diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 000000000..2676d177b --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,7 @@ +# Used by the OpenBSD CI job only. OpenBSD 8.0 can lose the wakeup of a +# blocking loopback connect() or accept() after the handshake completes, so a +# test can hang forever there: kill it after two minutes and retry it. +[profile.openbsd] +slow-timeout = { period = "60s", terminate-after = 2 } +retries = 2 +fail-fast = false diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..ab3f0503d --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,220 @@ +# Pure move commits (source layout cleanup). Moves across files still need `git blame -C -C`. + +# refactor(core): split resources.rs into resources/ (move) +6897ad0aa0df0d727b74a36ba841e08c6814f5f4 + +# refactor(core): move process_request.rs tests out of line (move) +c0bf9a8a8988a75d16707ac875b06282a126cb27 + +# refactor(kms): move render/backend.rs tests out of line (move) +1c0c7af185feed7303e0b987bb5c00303f02440b + +# refactor(kms): move render/engine.rs tests out of line (move) +3009e6525145e2cae4b9044784cbf6166d8a6469 + +# refactor(kms): move render/scene.rs tests out of line (move) +b1fc252a0b1b26d240ba9d3140e77df967a88396 + +# refactor(kms): move render/platform.rs tests out of line (move) +3d2c7807e25f6fc659621ab533bb112c4fbe3ca4 + +# refactor(kms): move vk/scanout.rs tests out of line (move) +ca4e05f8f6e65728b9eb920d8a9e622ce17924e6 + +# refactor(core): move core_loop/pointer_fanout.rs tests out of line (move) +5f4f3f545d162a6c345db72b0791cde344fb2c46 + +# refactor(core): move core_loop/run.rs tests out of line (move) +46864d2e4814d67d7bc1404794b16b611c9ec9ca + +# refactor(core): move server.rs tests out of line (move) +b34bb685edbac5b0fa940985f5309eafdfb9f55a + +# refactor(protocol): move x11/mod.rs tests out of line (move) +dd5ba5da6c7d0e29907d35dad8e95eca8415d60d + +# refactor(core): split process_request tests into topic modules (move) +c16e8fb7d44c68acfea96420a935c77f3f60bae8 + +# refactor(kms): split backend tests into topic modules (move) +5a9b1ad6fc80e92b3fce1b7daa9b37518ae458e9 + +# refactor(tests): split render_acceptance into one binary with topic modules (move) +90c712ddffa3897dc30f94ec6adf8f72e9e967d0 + +# refactor(kms): split scene tests into topic modules (move) +5b041d1913d05c6df6b4906533a999121cc34663 + +# refactor(kms): split engine tests into topic modules (move) +c85d9b2fe615d725ae0763d96075576a08e2aefc + +# refactor(core): qualify process_request tests' super::super paths (prep) +0960ff995512ab134c5c840a9929dee7326a9fac + +# refactor(kms): qualify backend tests' super:: paths (prep) +eca005eb64a454f0b36ec2ff1c6011e7a2898148 + +# refactor(kms): qualify scene tests' super::super paths (prep) +4c80b03030dcc2d27c535ab43d640de1a8e3cc30 + +# refactor(kms): qualify engine tests' super:: paths (prep) +57c2cb097c4ea2acbff1f83c38ad9e2dd1540f76 + +# refactor(core): qualify process_request super:: paths (prep) +1684ccdf9261079955766e2a29c05256ddbed3fd + +# refactor(core): split process_request into request-family modules (move) +8153b67438fc3b5ce431670a6ebab99d7b800734 + +# refactor(kms): qualify backend super:: paths (prep) +6b6e20a0e95f3b6d77e125cc3c59af78f7841ce7 + +# refactor(kms): split backend into portable/kms/trait_impl modules (move) +777758f4727f4bb88f0e580851b9bb1b8dd8a7f0 + +# refactor(kms): delegate window trait methods to portable/windows helpers +3d4037314accf85aeb9cdb0f51ec9d911ca687d4 + +# refactor(kms): delegate redirect, backing and pixmap trait methods to portable/redirect helpers +f74c626fcfacf21f7148d615dcab47a78eda801d + +# refactor(kms): delegate GC, clip and core drawing trait methods to portable/draw and clip helpers +5da4011b5da2ee9995932c5c426d781d1a069621 + +# refactor(kms): delegate RENDER trait methods to portable/render_ops, clip and text helpers +d4d6ffc6472f7e8c4446ad5699bba2541dce1668 + +# refactor(kms): delegate core text and font trait methods to portable/draw and text helpers +08b63c594c07c7bafa5146e643fca487de1c6c75 + +# refactor(kms): delegate cursor trait methods to kms/cursor helpers +7dfe88fd6a2da09c375114e9f4a91f47f6a7626f + +# refactor(kms): delegate Present trait methods to kms/present helpers +caf1a33bc4f451217cfc306492df73151a441805 + +# refactor(kms): delegate DRI3 and export trait methods to kms/export helpers +d88bab96a1cdf17d62ac28dde4075c5849aab436 + +# refactor(kms): delegate RANDR, gamma and crtc-config trait methods to kms/randr helpers +9bcff23aee85d5ea6b495125be6c8012c5c5d176 + +# refactor(kms): delegate frame loop, COW and dump trait methods to kms/scanout, readback and dump helpers +192b77239f5bd7bba0a794f9be3612089b4586cb + +# refactor(kms): delegate input, VT and DPMS trait methods to devices, pointer and kms/session helpers +8b7b9145d677ff3954ae4bbe9170e9d7265c2e7c + +# refactor(kms): delegate XKB and keymap trait methods to portable/keyboard helpers +43e9ffe1d722efc6cba018d11bb4a61dbba14d54 + +# refactor(kms): qualify engine super:: paths (prep) +399b91f42e43e9c3d82b2fed1a8e365675d5ff86 + +# refactor(kms): split engine into lifecycle/frame/op modules (move) +3ae1f634d1b2f782d3d55d26fcd7c04b7c2b084b + +# refactor(kms): qualify scene super:: paths (prep) +40d5f0a4825de9994371d31e15cb6a7c579df842 + +# refactor(kms): split scene into lifecycle/tick/compose/walk modules (move) +f18205508691f53edd12399564661e9932da1ad1 + +# refactor(kms): qualify platform super:: paths (prep) +525636c2eb914745b2c343502afb41f1ab9267e3 + +# refactor(kms): split platform into fence/submit/init/connectors modules (move) +13703cade2961301e591a1e4ea8e2e3fa08f92d4 + +# refactor(kms): qualify scanout super:: paths (prep) +edbf67665bd10b3eb0fdf8191a3e86dbbe33af76 + +# refactor(kms): split scanout into bo/copied/probe/image_alloc modules (move) +83693c2d565229ef216be8b918e57b5a4c295c2a + +# refactor(xi): hoist handle_xi2_request's fn-local import (prep) +e4552e7184276d32ae6447561c82aa8790dc3fca + +# refactor(xi): one fn per XI minor (extract) +a0cc43da481e46469a07d64c0c2359adf39822a0 + +# refactor(xi): split XI dispatch into devices/control/events/grabs/props/focus (move) +ea82d0095f7c3274d179d2c91b932740cea033cf + +# refactor(randr): hoist handle_randr_request's fn-local items (prep) +cd5d7798c3641cfda20b3fa7ca9b9bb17b8d1129 + +# refactor(randr): one fn per RANDR minor (extract) +9dfcc2e63fa8c1284eb2eca3af97ad1568bb4206 + +# refactor(randr): split randr_ext into screen/output/crtc/provider/monitor/xinerama (move) +e35594e1451aea8cfa71115dbcc12d2ba586463d + +# refactor(kms): allow the session and present re-exports to go unused until the import rewrite (prep) +de1ff506cf1da0dd6f0f4da169d2ae10c69ab711 + +# refactor(kms): delegate on_vt_acquire / arm_present_absolute_vblank to kms/session and kms/present (delegate) +f49fbaefa62c5006340748b504296330e01ee705 + +# refactor(kms): allow the crtc_config re-export to go unused until the import rewrite (prep) +9c5df20961e2dd698cb2a0c15767b828b4405d1e + +# refactor(kms): move crtc-config lifecycle from kms/randr into kms/crtc_config (move) +26c69786b51b121cca9fe269160be2d0b68217eb + +# refactor(kms): allow the portable text re-export to go unused until the import rewrite (prep) +f3f4cff724c1aac41e2826c784d3e3dab959296a + +# refactor(kms): move core text requests from portable/draw into portable/text (move) +638eed09099e41650f46b39836181771a8943394 + +# refactor(core): explicit imports in process_request/* +175f9a2948c4a58dac58ba2cec4dfd28cf592cf4 + +# refactor(core): explicit imports in xi/*, xi/dispatch/*, randr_ext.rs and randr_ext/* +85139673e25b63c31274d87ceb882a4555fae1bb + +# refactor(core): explicit imports in resources/* +b302a721d59bff83e8b37ca0115bcb2f11c9b4e4 + +# refactor(kms): explicit imports in backend/{portable,kms}/*, trait_impl, for_tests +ab09f18414afabdda6bd1303c7840dc0a8b5bd51 + +# refactor(kms): explicit imports in engine/* +5d8a43af43b202904fb6f34e613e0714ea841db1 + +# refactor(kms): explicit imports in scene/* +08daa62f3ba55c66bcea881af53f1f91586fb731 + +# refactor(kms): explicit imports in platform/* +2fe04de18ba994b0e4e512a215dfddbb9c9b0c9f + +# refactor(kms): explicit imports in vk/scanout/* +58c2baf483a5c3773e9999cf7824966efc390b8a + +# refactor(core): explicit child imports in the process_request, xi/dispatch, randr_ext dispatchers +934a8dfae9b3489d55eb6a7eee10000498b5c2f3 + +# refactor(kms): explicit child imports in the backend root +3d036fd4fdb682ebb41574bae730ba95f94692aa + +# refactor(kms): narrow scene visibility to private / pub(super) +34f3b7de197d0bd1a7e94a0ed321643797807cae + +# refactor(kms): narrow engine visibility to private / pub(super) +61719b412fc586cb07a9252f1b5594215bbd613f + +# refactor(kms): narrow platform visibility to private / pub(super) +cbba672aad4f07faddf28aeeef686b2a693b42ee + +# refactor(kms): narrow scanout visibility to private / pub(super) +6a4656ada5d1bda5e1f538794913ef0acb0757a0 + +# refactor(kms): narrow backend visibility to private / pub(super) +7b65740d4247955e6faa739146b09e005f2373ed + +# refactor(core): narrow process_request visibility to private / pub(super) +ad41c5c6203c8ae9ddc43a83b9455e774b31ebdd + +# refactor(core): narrow resources visibility to private / pub(super) +f61f26bf7545a2ad17f2ed1f327054093d2de4f8 diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..4d2c805a8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,62 @@ +name: Bug report +description: Something renders wrong, crashes, or behaves differently from Xorg +labels: ["bug"] +body: + - type: textarea + id: what-happened + attributes: + label: What happened? + description: Include what you expected instead. For visual problems, a photo or video helps. + validations: + required: true + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + description: The applications and commands involved, and how often it happens. + placeholder: | + 1. Start the session with `starty` + 2. Open ... + 3. ... + validations: + required: true + - type: dropdown + id: xorg + attributes: + label: Does the same setup work on Xorg? + options: + - "Yes, it only fails on yserver" + - "No, it also fails on Xorg" + - "Not tested" + validations: + required: true + - type: input + id: version + attributes: + label: yserver version + description: The output of `yserver --version`, or the commit you built. + validations: + required: true + - type: textarea + id: environment + attributes: + label: Environment + description: Leave out what does not apply. + value: | + OS and kernel: + GPU and driver version: + Monitors (count, resolution, refresh rate): + Desktop or window manager: + Compositor: + validations: + required: true + - type: textarea + id: logs + attributes: + label: Server log + description: | + Run `RUST_LOG=debug starty`, reproduce the problem, exit, then attach `~/.local/state/yserver/yserver.log`. See [docs/setup.md](https://github.com/joske/yserver/blob/master/docs/setup.md) for other ways to capture it. + + On macOS, run `just macos-run 1 1280x800 debug` and attach `yserver-mac.log`. The app started from Finder logs to `~/Library/Logs/yserver.log`. + + Drag the file here rather than pasting it, and check it first for anything you do not want public. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..c2b07f652 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Questions and ideas + url: https://github.com/joske/yserver/discussions + about: Ask about using yserver or discuss an idea before opening an issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 000000000..d00fac464 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,23 @@ +name: Feature request +description: Suggest something yserver should support +labels: ["enhancement"] +body: + - type: textarea + id: problem + attributes: + label: Problem + description: What are you trying to do, and what stops you today? + validations: + required: true + - type: textarea + id: solution + attributes: + label: Solution + description: What you would like to happen. If Xorg or another project already does this, say how. + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives + description: Workarounds or other approaches you have considered. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27f382f59..4e0174b85 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,7 @@ on: pull_request: branches: [master] workflow_call: + workflow_dispatch: env: CARGO_TERM_COLOR: always jobs: @@ -32,7 +33,12 @@ jobs: flags: "--features xdmcp" steps: - uses: actions/checkout@v7 + - name: Configure apt (mirror, retries) + run: | + printf 'http://mirrors.edge.kernel.org/ubuntu/\tpriority:1\nhttp://archive.ubuntu.com/ubuntu/\tpriority:2\n' | sudo tee /etc/apt/apt-mirrors.txt + printf 'Acquire::Retries "3";\nAcquire::http::Timeout "20";\n' | sudo tee /etc/apt/apt.conf.d/80-ci-retries - name: Install packages needed for build + timeout-minutes: 5 run: sudo apt-get update && sudo apt-get install -y build-essential just gcc libxshmfence-dev libxkbcommon-dev libinput-dev glslc libudev-dev libgbm-dev libfontconfig-dev xfonts-base xfonts-100dpi xfonts-75dpi mesa-vulkan-drivers vulkan-tools scdoc man-db shellcheck dash - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v2 @@ -66,12 +72,17 @@ jobs: # tcp_tests module, cfg'd on `feature = "tcp-transport"`); without it # this leg would build the gated code but never execute it. run: cargo test --all-targets ${{ matrix.flags }} --locked + - name: Check the source layout rules + # File-size ceilings, the backend/portable seam and yserver-render's + # dependencies (tools/check-layout.sh). Feature-independent; run once. + if: matrix.name == 'unix-only' + run: sh tools/check-layout.sh - name: Lint the shell scripts # starty is installed on every supported platform, so it must work # beyond bash. No cargo involved, so feature-independent; run once. if: matrix.name == 'unix-only' run: | - shellcheck -s sh starty tools/install-smoke.sh + shellcheck -s sh starty tools/install-smoke.sh tools/check-layout.sh tools/windows/build-xkb-data.sh dash ./starty --help > /dev/null - name: Render man pages # scdoc only — feature-independent. Kept on the same leg as the two @@ -117,18 +128,246 @@ jobs: ./target/debug/yserver --version | grep -q feedfacefeed \ || { echo "stale stamp — rerun-if-env-changed missing:"; \ ./target/debug/yserver --version; exit 1; } - - name: Run software-Vulkan render tests (lavapipe) - # GPU-less runner: Mesa's lavapipe is the only Vulkan ICD, so - # the `#[ignore = "needs live Vulkan ICD"]` render tests run on - # it. They self-skip if no Vulkan device is present. KMS/scanout - # tests aren't in this set (no /dev/dri on the runner). - # - # On the xdmcp leg, with --features xdmcp, for the same reason as the - # step above: rendering is orthogonal to TCP and XDMCP, but these are - # the heaviest code CI actually executes and they ran on the full - # build before the default set was emptied. The leg has already - # compiled that lib, so this costs nothing extra. - if: matrix.name == 'xdmcp' + lavapipe: + # The `#[ignore = "needs live Vulkan ICD"]` render tests on Mesa's + # lavapipe, in an Arch container: the KMS scanout tests (commit identity, + # unflip, tearing, cursor sprites) need SYNC_FD export and DRM format + # modifiers, which Ubuntu's lavapipe lacks; without them they report `ok` + # while skipping. lavapipe offers modifiers only with /dev/udmabuf, which + # must be loaded on the host, hence docker run rather than `container:`. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Configure apt (mirror, retries) + run: | + printf 'http://mirrors.edge.kernel.org/ubuntu/\tpriority:1\nhttp://archive.ubuntu.com/ubuntu/\tpriority:2\n' | sudo tee /etc/apt/apt-mirrors.txt + printf 'Acquire::Retries "3";\nAcquire::http::Timeout "20";\n' | sudo tee /etc/apt/apt.conf.d/80-ci-retries + - name: Open /dev/udmabuf + timeout-minutes: 5 + run: | + if [ ! -e /dev/udmabuf ]; then + sudo modprobe udmabuf \ + || { sudo apt-get update && sudo apt-get install -y "linux-modules-extra-$(uname -r)" && sudo modprobe udmabuf; } + fi + ls -la /dev/udmabuf + - name: Run software-Vulkan render tests (lavapipe, Arch) + run: | + docker run --rm --device /dev/udmabuf -v "$PWD:/src" -w /src archlinux:latest bash -euc ' + pacman -Syu --noconfirm --needed base-devel rustup libxshmfence libxkbcommon libinput \ + shaderc systemd-libs fontconfig pkgconf mesa vulkan-swrast vulkan-tools \ + xorg-fonts-misc xorg-fonts-75dpi xorg-fonts-100dpi >/dev/null + rustup default stable >/dev/null + vulkaninfo 2>/dev/null > /tmp/vulkaninfo.txt || true + grep -m1 deviceName /tmp/vulkaninfo.txt || true + # Fail here instead of letting those tests pass vacuously. + for ext in VK_KHR_external_semaphore_fd VK_EXT_image_drm_format_modifier; do + grep -q "$ext" /tmp/vulkaninfo.txt || { echo "lavapipe lacks $ext"; exit 1; } + done + YSERVER_ALLOW_SOFTWARE_VULKAN=1 cargo test --workspace --locked --features xdmcp --no-fail-fast -- --ignored + ' + freebsd: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Clippy and tests on FreeBSD + uses: vmactions/freebsd-vm@v1 + with: + release: "15" + mem: 12288 + cache-after-prepare: true + # Package list from docs/setup.md plus fonts (the font tests need them, as on + # Linux); rustup tracks stable like the Linux legs. + prepare: | + pkg install -y rustup-init just pkgconf shaderc fontconfig freetype2 libudev-devd libinput \ + libxkbcommon libxshmfence libdrm mesa-libs vulkan-loader scdoc \ + mkfontscale xorg-fonts + rustup-init -y --profile minimal -c clippy + run: | + set -e + . "$HOME/.cargo/env" + rustup update stable + cargo clippy --all-targets -- -D warnings + cargo clippy --all-targets --features xdmcp -- -D warnings + cargo test --all-targets --features xdmcp --locked + openbsd: + runs-on: ubuntu-latest + # Normally 8-12 minutes; a hang must not hold a release for six hours. + timeout-minutes: 45 + steps: + - uses: actions/checkout@v7 + - name: Clippy and tests on OpenBSD + uses: vmactions/openbsd-vm@v1 + with: + release: "8.0" + mem: 12288 + cache-after-prepare: true + # Package list from docs/setup.md. Mesa, libgbm, fontconfig and the + # fonts come from the X sets, fetched if the image lacks them. Rust + # is OpenBSD's package; rustup does not support OpenBSD. + prepare: | + pkg_add rust rust-clippy just shaderc vulkan-loader libinput-openbsd \ + libudev-openbsd libxkbcommon scdoc + (ulimit -d "$(ulimit -Hd)"; cargo install cargo-nextest --locked --version 0.9.149) + if [ ! -e /usr/X11R6/lib/pkgconfig/gbm.pc ]; then + v=$(uname -r | tr -d .) + for set in xbase xfont xshare; do + ftp -o - "$(cat /etc/installurl)/$(uname -r)/$(machine)/$set$v.tgz" | tar xzphf - -C / + done + fi + # The default data size limit is too small for rustc, the default + # open-files limit for the accept-flood tests, and debug info would + # not fit the disk. nextest kills and retries a hung test: see + # .config/nextest.toml. + run: | + set -e + ulimit -d "$(ulimit -Hd)" + ulimit -n "$(ulimit -Hn)" + export CARGO_PROFILE_DEV_DEBUG=0 + cargo clippy --all-targets -- -D warnings + cargo clippy --all-targets --features xdmcp -- -D warnings + cargo nextest run --all-targets --features xdmcp --locked --profile openbsd + macos: + # KosmicKrisp (Mesa Vulkan on Metal) needs macOS 26+; Apple Silicon only. + runs-on: macos-26 + steps: + - uses: actions/checkout@v7 + - name: Install packages + run: brew install mesa vulkan-loader vulkan-tools shaderc libxkbcommon fontconfig freetype pkgconf + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v2 + with: + components: clippy + toolchain: stable + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + - name: Vulkan environment + # The loader and the KosmicKrisp ICD come from Homebrew, off dyld's + # default search path. + run: | + prefix=$(brew --prefix) + echo "DYLD_FALLBACK_LIBRARY_PATH=$prefix/lib" >> "$GITHUB_ENV" + echo "VK_ICD_FILENAMES=$prefix/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json" >> "$GITHUB_ENV" + - name: Probe for a Vulkan device + # Hosted runners are VMs and may expose no Metal device. Logged, + # never fatal; the ignored (GPU) suite below runs only if it finds one. + id: probe + run: | + out=$(vulkaninfo --summary 2>&1) || true + echo "$out" + if echo "$out" | grep -q deviceName; then + echo "device=true" >> "$GITHUB_OUTPUT" + else + echo "device=false" >> "$GITHUB_OUTPUT" + fi + - name: Build + run: cargo build --workspace --locked + - name: Clippy + run: cargo clippy --workspace --all-targets -- -D warnings + - name: Run tests + run: cargo test --workspace --all-targets --locked + - name: Run Vulkan tests on KosmicKrisp + if: steps.probe.outputs.device == 'true' env: YSERVER_ALLOW_SOFTWARE_VULKAN: "1" - run: cargo test -p yserver --lib --locked --features xdmcp -- --ignored + run: cargo test --workspace --locked --no-fail-fast -- --ignored + xkb-data: + # The XKB data the Windows zip ships, from a pinned xkeyboard-config + # release: its rules files are generated at build time (meson, python, + # perl), so build it once here and hand it to both Windows legs. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Configure apt (mirror, retries) + run: | + printf 'http://mirrors.edge.kernel.org/ubuntu/\tpriority:1\nhttp://archive.ubuntu.com/ubuntu/\tpriority:2\n' | sudo tee /etc/apt/apt-mirrors.txt + printf 'Acquire::Retries "3";\nAcquire::http::Timeout "20";\n' | sudo tee /etc/apt/apt.conf.d/80-ci-retries + - name: Install meson + timeout-minutes: 5 + run: sudo apt-get update && sudo apt-get install -y meson ninja-build + - name: Build the XKB data + run: sh tools/windows/build-xkb-data.sh target/xkb-data + - uses: actions/upload-artifact@v7 + with: + name: xkb-data + path: target/xkb-data + if-no-files-found: error + windows: + needs: xkb-data + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + target: x86_64-pc-windows-msvc + - os: windows-11-arm + target: aarch64-pc-windows-msvc + runs-on: ${{ matrix.os }} + env: + # Keep vcpkg's binary packages between runs: a files cache, saved by + # actions/cache. + VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}\vcpkg-cache,readwrite + # vcpkg 2026.10.16. Pinned rather than the image's checkout, which + # moves with the image and would invalidate the cache. + VCPKG_COMMIT: 9eec002df1cd109f8f104cd966a763daf9751489 + steps: + - uses: actions/checkout@v7 + - name: Fetch vcpkg + shell: pwsh + run: | + $root = "$env:RUNNER_TEMP\vcpkg" + git init --quiet $root + git -C $root fetch --quiet --depth 1 https://github.com/microsoft/vcpkg $env:VCPKG_COMMIT + if ($LASTEXITCODE -ne 0) { throw 'vcpkg fetch failed' } + git -C $root checkout --quiet FETCH_HEAD + & "$root\bootstrap-vcpkg.bat" -disableMetrics + if ($LASTEXITCODE -ne 0) { throw 'vcpkg bootstrap failed' } + "VCPKG_ROOT=$root" >> $env:GITHUB_ENV + New-Item -ItemType Directory -Force vcpkg-cache | Out-Null + - name: Restore vcpkg packages + # Keyed on the vcpkg commit, which pins every port's version. + id: vcpkg-cache + uses: actions/cache/restore@v6 + with: + path: vcpkg-cache + key: vcpkg-v3-${{ matrix.target }}-${{ env.VCPKG_COMMIT }}-${{ hashFiles('tools/windows/vcpkg-*/**', 'tools/windows/build-env.ps1') }} + restore-keys: vcpkg-v3-${{ matrix.target }}- + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v2 + with: + components: clippy + toolchain: stable + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + - name: Cache glslc + # From the Vulkan SDK installer (tools/windows/build-env.ps1). + uses: actions/cache@v6 + with: + path: target/tools + key: glslc-${{ matrix.os }}-${{ hashFiles('tools/windows/build-env.ps1') }} + - name: Install the C libraries (vcpkg) and glslc + shell: pwsh + run: tools/windows/build-env.ps1 -Target ${{ matrix.target }} + - name: Save vcpkg packages + # Here rather than at job end, so a later failing step keeps them. + if: steps.vcpkg-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v6 + with: + path: vcpkg-cache + key: ${{ steps.vcpkg-cache.outputs.cache-primary-key }} + - name: Clippy + # Not --all-targets: the test code does not build on Windows yet. + run: cargo clippy --workspace -- -D warnings + - uses: actions/download-artifact@v8 + with: + name: xkb-data + path: target/xkb-data + - name: Build the zip + id: package + shell: pwsh + run: tools/windows/package.ps1 -Target ${{ matrix.target }} -XkbData target/xkb-data + - uses: actions/upload-artifact@v7 + with: + # The zip itself, not zipped again; the artifact takes its name. + path: ${{ steps.package.outputs.zip }} + archive: false + if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b5a1583f3..392f04341 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,7 +19,8 @@ name: Release # failed distro build would strand a public release, so the order is # deliberately inverted.) # -# The release ships the distro packages and nothing else. It used to upload its +# The release ships the distro packages and the Windows zips, which ci.yml's +# `windows` job builds inside the `ci` stage. It used to upload its # own git-archive tarball plus SHA256SUMS/SHA512SUMS, on the grounds that # GitHub's auto-generated /archive/ tarballs are produced on demand and are not # guaranteed byte-stable (they changed once in 2023, invalidating pinned @@ -246,11 +247,17 @@ jobs: needs: checks uses: ./.github/workflows/ci.yml + vng: + needs: checks + uses: ./.github/workflows/vng-suite.yml + with: + scenarios: all + # Build the distro packages BEFORE anything is published, and fail the # release if they do not build. The packaging workflow takes the upstream ref # as an input and generates its own tarball, so it does not need the release. packages: - needs: [checks, ci] + needs: [checks, ci, vng] runs-on: ubuntu-latest # GITHUB_TOKEN is unused here; all cross-repo work uses the fine-grained PAT. permissions: {} @@ -341,6 +348,38 @@ jobs: ref: ${{ needs.checks.outputs.sha }} fetch-depth: 0 + # Built by ci.yml's `windows` job in this same run (the `ci` stage), so + # `release` never starts if either leg failed. Fetched before the draft + # exists so a missing zip fails with nothing created. + - uses: actions/download-artifact@v8 + with: + pattern: yserver-*-windows-*.zip + path: dist-windows + merge-multiple: true + # The artifacts are bare .zip files (`archive: false`); without this + # the action would unpack them. + skip-decompress: true + + - name: Check the Windows zips + env: + V: ${{ needs.checks.outputs.version }} + run: | + set -eu + # Exact names: package.ps1 takes the version from Cargo.toml, which + # `checks` matched against the tag. + printf 'yserver-%s-windows-%s.zip\n' "$V" aarch64 "$V" x86_64 \ + | LC_ALL=C sort > winnames + got=$(find dist-windows -type f -printf '%f\n' | LC_ALL=C sort) + if [ "$got" != "$(cat winnames)" ]; then + echo "::error::the Windows zips do not match version $V" + echo "expected:"; cat winnames + echo "got:"; printf '%s\n' "$got" + exit 1 + fi + while read -r z; do + unzip -tq "dist-windows/$z" || { echo "::error::$z is not a valid zip"; exit 1; } + done < winnames + - name: Create the release as a draft env: GH_TOKEN: ${{ github.token }} @@ -371,7 +410,7 @@ jobs: set -- --draft --verify-tag --title "yserver $V" --generate-notes [ -z "$PREV" ] || set -- "$@" --notes-start-tag "$PREV" # No files here: GitHub's own auto-generated source archives are the - # source download, and the distro packages are attached below. + # source download, and the packages and zips are attached below. gh release create "$TAG" "$@" - name: Attach the distro packages built for this tag @@ -439,6 +478,7 @@ jobs: # rather than fails. Reads the list rather than globbing: the Fedora # RPMs arrive nested under RPMS//. xargs -0 -a pkglist -- gh release upload "$TAG" --clobber + sed 's|^|dist-windows/|' winnames | xargs -d '\n' -- gh release upload "$TAG" --clobber - name: Verify the draft's assets before publishing env: @@ -459,14 +499,15 @@ jobs: # unrelated packaging run. # LC_ALL=C on both sides: collation of '-' vs '_' is locale-dependent, # and the two lists are sorted in different steps. - attached=$(printf '%s\n' "$names" | grep -E '\.(rpm|deb|apk)$' | LC_ALL=C sort || true) - if [ "$attached" != "$(cat pkgnames)" ]; then - echo "::error::attached packages do not match what was downloaded" - echo "expected:"; cat pkgnames + attached=$(printf '%s\n' "$names" | grep -E '\.(rpm|deb|apk|zip)$' | LC_ALL=C sort || true) + expected=$(cat pkgnames winnames | LC_ALL=C sort) + if [ "$attached" != "$expected" ]; then + echo "::error::attached assets do not match what was downloaded" + echo "expected:"; printf '%s\n' "$expected" echo "attached:"; printf '%s\n' "$attached" exit 1 fi - echo "package inventory matches." + echo "asset inventory matches." - name: Report the source-archive checksums for downstream recipes env: @@ -498,6 +539,12 @@ jobs: echo "sha512 $sha512" echo '```' echo + echo "Windows zips:" + echo + echo '```' + (cd dist-windows && xargs -a ../winnames sha256sum) + echo '```' + echo echo "For \`alpine/APKBUILD\` (or run \`abuild checksum\`):" echo echo '```sh' diff --git a/.github/workflows/vng-suite.yml b/.github/workflows/vng-suite.yml new file mode 100644 index 000000000..49b69c93e --- /dev/null +++ b/.github/workflows/vng-suite.yml @@ -0,0 +1,111 @@ +name: vng suite +# Real yserver in a KVM guest (2D virtio-gpu + lavapipe): tools/vng-suite.sh. +# PRs and pushes run the quick set; nightly, manual and release runs the whole suite. +on: + workflow_dispatch: + inputs: + scenarios: + description: scenario regex (all = everything) + default: all + workflow_call: + inputs: + scenarios: + description: scenario regex (all = everything) + type: string + default: all + pull_request: + push: + branches: [master] + schedule: + - cron: '17 3 * * *' +env: + CARGO_TERM_COLOR: always +jobs: + vng: + runs-on: ubuntu-26.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v7 + - name: Runner facts + run: | + uname -a + lscpu | grep -E 'Model name|^CPU\(s\)|Virtualization|Hypervisor' + grep -o -w -E 'vmx|svm' /proc/cpuinfo | sort | uniq -c || echo "no vmx/svm flag" + ls -la /dev/kvm /dev/udmabuf || true + lsmod | grep -E 'kvm|udmabuf' || true + - name: Configure apt (mirror, retries) + run: | + printf 'http://mirrors.edge.kernel.org/ubuntu/\tpriority:1\nhttp://archive.ubuntu.com/ubuntu/\tpriority:2\n' | sudo tee /etc/apt/apt-mirrors.txt + printf 'Acquire::Retries "3";\nAcquire::http::Timeout "20";\n' | sudo tee /etc/apt/apt.conf.d/80-ci-retries + - name: Open /dev/kvm and /dev/udmabuf + timeout-minutes: 5 + run: | + if [ ! -e /dev/udmabuf ]; then + sudo modprobe udmabuf \ + || { sudo apt-get update && sudo apt-get install -y "linux-modules-extra-$(uname -r)" && sudo modprobe udmabuf; } \ + || echo "udmabuf unavailable" + fi + printf '%s\n' 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \ + 'KERNEL=="udmabuf", MODE="0666"' | sudo tee /etc/udev/rules.d/99-vng.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + sudo udevadm trigger --name-match=udmabuf + ls -la /dev/kvm /dev/udmabuf + - name: Install packages + # A stalled Ubuntu mirror otherwise eats the whole 60-minute job. + timeout-minutes: 5 + run: | + sudo apt-get update + sudo apt-get install -y build-essential gcc libxshmfence-dev libxkbcommon-dev libinput-dev glslc libudev-dev libgbm-dev libfontconfig-dev xfonts-base xfonts-100dpi xfonts-75dpi \ + qemu-system-x86 busybox-static mesa-vulkan-drivers xterm x11-xserver-utils x11-utils xdotool python3-xlib python3-pil imagemagick dbus \ + libx11-dev libxcb1-dev libxcb-composite0-dev libxcb-damage0-dev libxcb-dri3-dev libxcb-present-dev libxcb-shape0-dev libxcb-xfixes0-dev libxcb-record0-dev libxcb-render0-dev libxcb-shm0-dev libxcb-xinput-dev libxcb-xkb-dev libxcb-xtest0-dev libxkbcommon-x11-dev \ + wmctrl xinput x11-xkb-utils xserver-xorg-core xserver-xorg-input-libinput \ + x11-apps libmotif-dev motif-clients libxcb-screensaver0-dev libxext-dev libxcomposite-dev libxdamage-dev + # virtme-ng with virtiofsd: memfd guest RAM, needed for blob=on. + sudo apt-get install -y virtme-ng virtiofsd + - name: Guest kernel + timeout-minutes: 5 + # A generic kernel carries virtio-gpu/drm; the runner's own azure one may not. + # Unpacked, not installed: vng boots vmlinuz directly, so no postinst/initramfs. + run: | + img=$(apt-cache depends linux-image-generic | awk '/Depends: linux-image-[0-9]/{print $2; exit}') + ver=${img#linux-image-} + cd "$RUNNER_TEMP" + apt-get download "$img" "linux-modules-$ver" + apt-get download "linux-modules-extra-$ver" 2>/dev/null || true + for d in ./*.deb; do sudo dpkg -x "$d" /; done + sudo depmod "$ver" + sudo chmod 0644 "/boot/vmlinuz-$ver" + echo "KERNEL=/boot/vmlinuz-$ver" >> "$GITHUB_ENV" + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + - name: Build yserver + run: cargo build --locked --bin yserver + - name: Versions + run: | + echo "guest kernel: $KERNEL" + qemu-system-x86_64 --version | head -1 + vng --version + dpkg-query -W mesa-vulkan-drivers + ls /usr/share/vulkan/icd.d/ + - name: vng suite (gpu none) + env: + QUICK: '^(xterm|span-paint|pixel-oracle|xrandr-(scale|scale-crop|dpi|monitors|monitors-2|orientation|scale-cursor)|xmodmap-caps-control|xkbcomp-upload|subwindow-move|child-clip|draw-clip|redirected-backing)$' + SCENARIOS: ${{ inputs.scenarios }} + run: | + if [ -n "$SCENARIOS" ]; then filter=$SCENARIOS + elif [ "${{ github.event_name }}" = schedule ]; then filter=all + else filter=$QUICK; fi + SPAN_ROUNDS=3 tools/vng-suite.sh --gpu none --binary target/debug/yserver --out target/vng-suite/ci "$filter" + - name: Drop sockets before upload + if: always() + run: find target/vng-suite -type s -delete 2>/dev/null || true + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@v7 + with: + name: vng-suite + path: target/vng-suite/** + if-no-files-found: warn diff --git a/.gitignore b/.gitignore index 92116dfb5..3c7ff8d74 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,7 @@ PXL_* *.jpg *.jpeg *.png +!/assets/*.png *.heic # perf data captures (binary, can be large) diff --git a/AGENTS.md b/AGENTS.md index c32bd37e7..e96180d72 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,10 +1,10 @@ # yserver -A modern X11 server written from scratch in Rust. +A modern X11 server written from scratch in Rust. Supports linux/FreeBSD/OpenBSD on DRM/KMS. macOS/windows in nested mode. Info about the project is in README.md Current status is in docs/status.md and should be kept up to date -focus is on yserver (KMS) now +focus is on yserver (KMS) ## Instructions @@ -15,14 +15,13 @@ focus is on yserver (KMS) now - design docs (specs) go in docs/superpowers/specs - impl plans go in docs/superpowers/plans - work on feature branch for phases -- squash merge when ready (ask confirmation) +- squash merge when ready (ask confirmation); PRs with multiple commits serving distinct purposes are fast-forward merged instead, so each commit stays bisectable - Spec compliance is the goal, but if Xorg deviates from spec (unlikely), we need to follow Xorg, clients are tested for 40+ years on Xorg. ## environment -- you are most likely running in a bwrap sandbox, if you see /home/jos/realhome, you are. -- the project dir is rw mounted -- in /home/jos/Projects/xserver/hw/kdrive/ephyr/ you can find the source to Xephyr for reference -- in /home/jos/Projects/xserver/hw/xnest/ you can find the sources to Xnest for reference -- to test you can run ynest with RUST_LOG=debug, capture its output -- x11trace is available if you want to trace how Xephyr/Xnest does things, x11trace always needs -n flag +following extra folders should be in your sandbox, ask if not available +- /home/jos/Projects/xserver +- /home/jos/Projects/wlroots +- /home/jos/Projects/xts +- /home/jos/Projects/yserver-packaging diff --git a/Cargo.lock b/Cargo.lock index 561672610..dac6bbb9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.5" @@ -78,18 +84,22 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "bit-set" -version = "0.8.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" dependencies = [ "bit-vec", ] [[package]] name = "bit-vec" -version = "0.8.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] [[package]] name = "bitflags" @@ -103,6 +113,39 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "bytemuck" version = "1.25.2" @@ -120,14 +163,20 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.9", ] +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" -version = "1.4.6" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" dependencies = [ "find-msvc-tools", "shlex", @@ -135,9 +184,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" @@ -145,12 +194,47 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + [[package]] name = "colorchoice" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -168,9 +252,9 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -178,25 +262,37 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror", ] +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + [[package]] name = "dlib" version = "0.5.3" @@ -207,18 +303,10 @@ dependencies = [ ] [[package]] -name = "drm" -version = "0.14.1" +name = "downcast-rs" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "drm-ffi", - "drm-fourcc", - "libc", - "rustix 0.38.44", -] +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" [[package]] name = "drm" @@ -232,7 +320,7 @@ dependencies = [ "drm-ffi", "drm-fourcc", "libc", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -242,7 +330,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" dependencies = [ "drm-sys", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -261,6 +349,20 @@ dependencies = [ "linux-raw-sys 0.9.4", ] +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml", + "vswhom", + "winreg", +] + [[package]] name = "env_filter" version = "2.0.0" @@ -284,6 +386,12 @@ dependencies = [ "log", ] +[[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" @@ -302,9 +410,20 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.12" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] [[package]] name = "fnv" @@ -350,7 +469,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" dependencies = [ "bitflags 2.13.2", - "drm 0.14.1", "drm-fourcc", "gbm-sys", "libc", @@ -365,18 +483,6 @@ dependencies = [ "libc", ] -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - [[package]] name = "getrandom" version = "0.4.3" @@ -385,20 +491,15 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", - "r-efi 6.0.0", + "r-efi", + "rand_core", ] [[package]] -name = "gpu-allocator" -version = "0.28.0" +name = "hashbrown" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" -dependencies = [ - "ash", - "log", - "presser", - "thiserror", -] +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "hermit-abi" @@ -406,6 +507,16 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "input" version = "0.10.0" @@ -442,11 +553,17 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "jiff" -version = "0.2.37" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c" dependencies = [ "defmt", "jiff-core", @@ -459,9 +576,9 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93" dependencies = [ "defmt", "log", @@ -469,9 +586,9 @@ dependencies = [ [[package]] name = "jiff-static" -version = "0.2.37" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d" dependencies = [ "jiff-core", "proc-macro2", @@ -481,9 +598,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -507,9 +624,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.29" +version = "1.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2" dependencies = [ "cc", "libc", @@ -517,12 +634,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - [[package]] name = "linux-raw-sys" version = "0.9.4" @@ -537,9 +648,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "memchr" @@ -549,9 +660,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] @@ -565,11 +676,21 @@ dependencies = [ "autocfg", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "log", @@ -599,6 +720,198 @@ dependencies = [ "autocfg", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-security" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-service-management" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b213642d6959cc6023ceb1217aa595eaaf09b8094ce95127c103cab611fe65e8" +dependencies = [ + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-security", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -633,20 +946,14 @@ dependencies = [ ] [[package]] -name = "ppv-lite86" -version = "0.2.21" +name = "proc-macro-crate" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "zerocopy", + "toml_edit", ] -[[package]] -name = "presser" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" - [[package]] name = "proc-macro2" version = "1.0.107" @@ -658,16 +965,17 @@ dependencies = [ [[package]] name = "proptest" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ "bit-set", "bit-vec", "bitflags 2.13.2", + "chacha20", + "core_detect", "num-traits", "rand", - "rand_chacha", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -681,6 +989,15 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -690,12 +1007,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - [[package]] name = "r-efi" version = "6.0.0" @@ -704,38 +1015,25 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.9.5" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", + "getrandom", "rand_core", ] [[package]] name = "rand_core" -version = "0.9.5" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "rand_xorshift" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" dependencies = [ "rand_core", ] @@ -770,23 +1068,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] -name = "rustix" -version = "0.38.44" +name = "roxmltree" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "memchr", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", ] [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -807,6 +1110,22 @@ dependencies = [ "wait-timeout", ] +[[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", + "serde_derive", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -824,7 +1143,29 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", ] [[package]] @@ -835,9 +1176,9 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a0c28ca5908dbdbcd52e6fdaa00358ab88637f8ab33e1f188dd510eb44b53d" +checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74" dependencies = [ "libc", "signal-hook-registry", @@ -853,6 +1194,28 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "syn" version = "2.0.119" @@ -866,9 +1229,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.5" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -882,32 +1245,83 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom", "once_cell", - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] [[package]] name = "thiserror" -version = "2.0.20" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.20" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.9", +] + +[[package]] +name = "toml" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", ] +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "udev" version = "0.9.3" @@ -928,9 +1342,9 @@ checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "utf8parse" @@ -944,6 +1358,26 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + [[package]] name = "wait-timeout" version = "0.2.1" @@ -960,36 +1394,75 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" +name = "wayland-backend" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ - "wit-bindgen", + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", ] [[package]] -name = "windows-link" -version = "0.2.1" +name = "wayland-client" +version = "0.31.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix", + "wayland-backend", + "wayland-scanner", +] [[package]] -name = "windows-sys" -version = "0.48.0" +name = "wayland-protocols" +version = "0.32.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" dependencies = [ - "windows-targets 0.48.5", + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", ] +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + +[[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.59.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -1007,29 +1480,13 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -1038,78 +1495,36 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -1117,22 +1532,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" +name = "winnow" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] [[package]] -name = "wit-bindgen" -version = "0.57.1" +name = "winreg" +version = "0.56.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] [[package]] name = "xkbcommon" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" dependencies = [ "libc", "memmap2", @@ -1158,63 +1578,91 @@ dependencies = [ [[package]] name = "yserver" -version = "1.6.0" +version = "1.9.0" dependencies = [ "ash", + "block2", "crossbeam-channel", - "drm 0.15.0", + "dispatch2", + "drm", + "embed-resource", "env_logger", + "flate2", "fontconfig", "freetype-rs", "gbm", - "gpu-allocator", "input", "libc", "log", "nix", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-quartz-core", + "objc2-service-management", + "regex", + "roxmltree", + "serde_json", "signal-hook", + "socket2", "thiserror", "udev", + "wayland-client", + "wayland-protocols", + "windows-sys 0.61.2", "xkbcommon", "yserver-core", "yserver-protocol", + "yserver-render", ] [[package]] name = "yserver-core" -version = "1.6.0" +version = "1.9.0" dependencies = [ "crossbeam-channel", "libc", "log", "mio", "proptest", + "windows-sys 0.61.2", "yserver-protocol", ] [[package]] name = "yserver-protocol" -version = "1.6.0" +version = "1.9.0" dependencies = [ "proptest", ] [[package]] -name = "zerocopy" -version = "0.8.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +name = "yserver-render" +version = "1.9.0" dependencies = [ - "zerocopy-derive", + "ash", + "libc", + "log", + "nix", + "thiserror", + "yserver-protocol", ] [[package]] -name = "zerocopy-derive" -version = "0.8.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +name = "yserver-xauth" +version = "1.9.0" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "yserver-core", ] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 77b46d9ec..7b86c5c70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,16 @@ [workspace] resolver = "3" -members = ["crates/yserver", "crates/yserver-core", "crates/yserver-protocol"] +members = [ + "crates/yserver", + "crates/yserver-core", + "crates/yserver-protocol", + "crates/yserver-render", + "crates/yserver-xauth", +] +exclude = ["third_party"] [workspace.package] -version = "1.6.0" +version = "1.9.0" edition = "2024" repository = "https://github.com/joske/yserver" license = "MIT" @@ -14,13 +21,9 @@ crossbeam-channel = "0.5" drm = "0.15" env_logger = "0.11" freetype-rs = "0.38" -gbm = { version = "0.18", default-features = false, features = ["drm-support"] } -gpu-allocator = { version = "0.28", default-features = false, features = [ - "std", - "vulkan", -] } +gbm = { version = "0.18", default-features = false } input = "0.10" -libc = "0.2" +libc = "0.2.191" log = "0.4" mio = { version = "1", features = ["net", "os-ext", "os-poll"] } nix = { version = "0.31", features = [ @@ -33,12 +36,15 @@ nix = { version = "0.31", features = [ "socket", "term", ] } +roxmltree = "0.21" +serde_json = "1" signal-hook = "0.4" thiserror = "2" udev = "0.9" -xkbcommon = "0.9" +xkbcommon = { version = "0.9", default-features = false } yserver-core = { path = "crates/yserver-core", default-features = false } yserver-protocol = { path = "crates/yserver-protocol", default-features = false } +yserver-render = { path = "crates/yserver-render", default-features = false } [workspace.lints.clippy] # X11 protocol encoders and request handlers naturally take many @@ -53,6 +59,10 @@ too_many_arguments = "allow" # protocol-parsing paths for no behavioural or measured gain. chunks_exact_to_as_chunks = "allow" +# Explicit imports (docs/superpowers/plans/2026-10-12-explicit-imports.md); +# `use super::*` in test modules and `pub` re-export globs are exempt. +wildcard_imports = "warn" + # Keep DWARF unwind info in release builds so `perf record --call-graph # dwarf` can resolve Rust frames. Without this, ~65% of samples in a # release-build flamegraph land in [unknown] frames. Optimisation level @@ -71,3 +81,8 @@ chunks_exact_to_as_chunks = "allow" # (~1-2% runtime cost) make the unwind path infallible. [profile.release] debug = true + +# xkbcommon 0.9.0 with the Unix-only `OsStrExt` import in compose.rs replaced +# by `as_encoded_bytes`, so it builds on Windows. Drop once upstream has it. +[patch.crates-io] +xkbcommon = { path = "third_party/xkbcommon" } diff --git a/Justfile b/Justfile index ba113081d..6cf5b98bd 100644 --- a/Justfile +++ b/Justfile @@ -164,6 +164,69 @@ yserver-hw log="warn": kill -TERM $yserver_pid 2>/dev/null;\ wait $yserver_pid 2>/dev/null' +# macOS (Apple Silicon, KosmicKrisp): yserver in an AppKit window, DISPLAY=:; log in yserver-mac.log. +macos-run display="1" geometry="1280x800" log="info" scale="auto": + VK_ICD_FILENAMES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json \ + DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib RUST_LOG="{{log}}" \ + cargo run --release --bin yserver -- :{{display}} --geometry {{geometry}} --scale {{scale}} 2>&1 | tee yserver-mac.log + +# macOS rootless: one Mac window per X top-level, DISPLAY=:; log in yserver-mac.log. +macos-rootless display="1" log="info" scale="auto": + VK_ICD_FILENAMES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json \ + DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib RUST_LOG="{{log}}" \ + cargo run --release --bin yserver -- :{{display}} --rootless --scale {{scale}} 2>&1 | tee yserver-mac.log + +# macOS: target/yserver.app; uses the Homebrew packages at run time (README.md), no signing beyond the linker's ad-hoc one. +macos-bundle: + #!/usr/bin/env bash + set -euo pipefail + cargo build --release --bin yserver + version=$(cargo pkgid -p yserver | sed 's/.*[#@]//') + app=target/yserver.app + rm -rf "$app" + mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" + cp "{{TARGETDIR}}/yserver" "$app/Contents/MacOS/yserver" + iconset=target/yserver.iconset + rm -rf "$iconset" && mkdir -p "$iconset" + for size in 16 32 128 256 512; do + sips -z $size $size assets/yserver-icon.png --out "$iconset/icon_${size}x${size}.png" >/dev/null + sips -z $((size * 2)) $((size * 2)) assets/yserver-icon.png --out "$iconset/icon_${size}x${size}@2x.png" >/dev/null + done + iconutil -c icns "$iconset" -o "$app/Contents/Resources/yserver.icns" + cat > "$app/Contents/Info.plist" < + + + + CFBundleExecutable + yserver + CFBundleIdentifier + io.github.joske.yserver + CFBundleName + yserver + CFBundleDisplayName + yserver + CFBundleIconFile + yserver + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + CFBundleShortVersionString + $version + CFBundleVersion + $version + LSMinimumSystemVersion + 26.0 + LSApplicationCategoryType + public.app-category.developer-tools + NSHighResolutionCapable + + + + EOF + echo "macos-bundle: $app $version" + # Local TCP transport smoke. Creates a temporary FamilyInternet Xauthority # record for 127.0.0.1:7, starts yserver with TCP explicitly enabled, then # proves a real TCP client can complete setup. Requires a real KMS-capable @@ -464,7 +527,7 @@ yserver-mate-hw-release-trace log="warn": # # Also writes a per-vkQueueSubmit2 TSV to `yserver-${session}.submit.tsv` # (Stage 5 Task 3 paint-aggregation diagnostic, see -# crates/yserver/src/kms/render/submit_trace.rs). One row per submit: +# crates/yserver-render/src/kms/render/submit_trace.rs). One row per submit: # frame_id ns_mono kind target_kind target_id batch_size op \ # src_class mask_class pipeline_id readback alias zero_draws upload # Quick analyses: @@ -538,7 +601,6 @@ yserver-mate-hw-trace log="warn": yserver-mate-hw-vkdebug log="trace": cargo build --bin yserver bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ RUST_LOG="{{log}}" RUST_BACKTRACE=full \ YSERVER_VK_VALIDATION=1 \ VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation \ @@ -549,11 +611,10 @@ yserver-mate-hw-vkdebug log="trace": yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET DISPLAY=:7 GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ dbus-run-session mate-session --display :7 > mate-vkdebug.log 2>&1;\ kill -TERM $yserver_pid 2>/dev/null;\ wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;\ echo "yserver log: yserver-hw-mate-vkdebug.log";\ echo "mate log: mate-vkdebug.log";\ echo "radv dumps: ~/radv_dumps/ (if any)";' @@ -574,7 +635,7 @@ yserver-mate-hw-vkdebug log="trace": # Arguments are positional, as everywhere here: # just yserver-mate-hw-workload ~/clip.mp4 # ~90s, measure # just yserver-mate-hw-workload ~/clip.mp4 0.2 # ~20s, smoke -yserver-mate-hw-workload clip scale="1" log="warn,yserver::startup=info,yserver::kms::render::telemetry=info": +yserver-mate-hw-workload clip scale="1" log="warn,yserver::startup=info,yserver_render::kms::render::telemetry=info": RUSTFLAGS="-C debug-assertions=yes" cargo build --release --bin yserver bash -c '\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ @@ -670,6 +731,19 @@ yserver-plasma-hw log="info": kill -TERM $yserver_pid 2>/dev/null;\ wait $yserver_pid 2>/dev/null' +# KWin with buffer age off (full repaints): discriminates the Dolphin hover flicker (#100). +yserver-plasma-hw-no-buffer-age log="info": + cargo build --release --bin yserver + bash -c '\ + RUST_LOG="{{log}}" RUST_BACKTRACE=1 target/release/yserver > yserver-hw-plasma.log 2>&1 &\ + yserver_pid=$!;\ + sleep 2;\ + env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET DISPLAY=:7 GDK_BACKEND=x11 \ + XDG_SESSION_TYPE=x11 KWIN_USE_BUFFER_AGE=0 \ + dbus-run-session startplasma-x11 > plasma.log 2>&1;\ + kill -TERM $yserver_pid 2>/dev/null;\ + wait $yserver_pid 2>/dev/null' + yserver-plasma-hw-trace log="debug": cargo build --release --bin yserver rm -f plasma.xtrace @@ -777,7 +851,7 @@ yserver-e16-xterm-hw-trace log="debug": # For numbers comparable to the awesome/MATE runs, use the phased # `yserver-e16-hw-workload` below instead — a hand-driven session's content # load dominates and is not reproducible. -yserver-e16-hw-telemetry log="warn,yserver::startup=info,yserver::kms::render::telemetry=info": +yserver-e16-hw-telemetry log="warn,yserver::startup=info,yserver_render::kms::render::telemetry=info": RUSTFLAGS="-C debug-assertions=yes" cargo build --release --bin yserver bash -c '\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ @@ -826,7 +900,7 @@ yserver-e16-hw-telemetry log="warn,yserver::startup=info,yserver::kms::render::t # then compare with # tools/damage-phases.py -telemetry.log -phases.log \ # -telemetry.log -phases.log -yserver-e16-hw-workload clip scale="1" bin="" log="warn,yserver::startup=info,yserver::kms::render::telemetry=info": +yserver-e16-hw-workload clip scale="1" bin="" log="warn,yserver::startup=info,yserver_render::kms::render::telemetry=info": #!/usr/bin/env bash set -euo pipefail server='{{ bin }}' @@ -903,7 +977,6 @@ yserver-e27-hw-telemetry log="info": cargo build --release --bin yserver rm -f yserver-e27.submit.tsv bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ export GDK_BACKEND=x11;\ export XDG_SESSION_TYPE=x11;\ @@ -913,13 +986,12 @@ yserver-e27-hw-telemetry log="info": yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ DISPLAY=:7 enlightenment_start > e27-hw.log 2>&1 &\ sleep 2;\ DISPLAY=:7 wezterm ;\ kill -TERM $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' # ============================== openbox ============================== @@ -961,7 +1033,6 @@ yserver-openbox-picom-xrender-hw-telemetry log="info": cargo build --release --bin yserver rm -f yserver-openbox-picom.submit.tsv bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ export GDK_BACKEND=x11;\ export XDG_SESSION_TYPE=x11;\ @@ -971,15 +1042,41 @@ yserver-openbox-picom-xrender-hw-telemetry log="info": yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ DISPLAY=:7 openbox > openbox-picom.log 2>&1 &\ sleep 2;\ DISPLAY=:7 picom --backend xrender --log-level warn --log-file picom.log > picom.out 2>&1 &\ sleep 1;\ DISPLAY=:7 wezterm ;\ kill -TERM $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' + +# =========================== CDE =================================== +yserver-cde-hw log="info": + cargo build --release --bin yserver + bash -c '\ + unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ + export GDK_BACKEND=x11;\ + export XDG_SESSION_TYPE=x11;\ + RUST_LOG="{{log}}" RUST_BACKTRACE=1 target/release/yserver > yserver-hw-cde.log 2>&1 &\ + yserver_pid=$!;\ + sleep 2;\ + env PATH=$PATH:/usr/dt/bin DISPLAY=:7 /usr/dt/bin/Xsession > cde.log 2>&1 ;\ + kill -TERM $yserver_pid 2>/dev/null;\ + wait $yserver_pid 2>/dev/null;' + +yserver-cde-hw-trace log="info": + cargo build --release --bin yserver + bash -c '\ + unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ + export GDK_BACKEND=x11;\ + export XDG_SESSION_TYPE=x11;\ + RUST_LOG="{{log}}" RUST_BACKTRACE=1 target/release/yserver > yserver-hw-cde.log 2>&1 &\ + yserver_pid=$!;\ + sleep 2;\ + env PATH=$PATH:/usr/dt/bin DISPLAY=:7 x11trace -n -k -o cde.xtrace /usr/dt/bin/Xsession > cde.log 2>&1 ;\ + kill -TERM $yserver_pid 2>/dev/null;\ + wait $yserver_pid 2>/dev/null;' # ============================== awesome ============================== @@ -1059,11 +1156,10 @@ yserver-awesome-hw-audit log="info" interval="30" idle="5": # Long-run resource telemetry (vram / vram by use / gpu load / pixmap pool live) only, for # leaving a session up for a day; plain `log=info` recipes grow by GB/hour. # Contributors send the log (`gzip -k`), they don't read it. The last sample -# is post-teardown (pool drained): read the floor from `grep -v 'entries=0'`. +# is post-teardown; idle pool entries are trimmed after 60 s, so entries=0 mid-run is real. yserver-awesome-hw-resources: cargo build --release --bin yserver bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ export GDK_BACKEND=x11;\ export XDG_SESSION_TYPE=x11;\ @@ -1073,11 +1169,10 @@ yserver-awesome-hw-resources: yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ DISPLAY=:7 awesome > awesome.log 2>&1 ;\ kill -TERM $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' # Validation-layer session on yserver only (clients don't inherit it): # awesome + picom --backend glx + glxgears, stops itself after `seconds`. @@ -1091,7 +1186,6 @@ yserver-awesome-hw-validation bin="target/release/yserver" label="current" secon if [ "{{bin}}" = "target/release/yserver" ]; then cargo build --release --bin yserver || exit 1; fi log="$PWD/yserver-validation-{{label}}.vk.log" rm -f "$log" - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd" VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation \ VK_KHRONOS_VALIDATION_DEBUG_ACTION=VK_DBG_LAYER_ACTION_LOG_MSG \ VK_KHRONOS_VALIDATION_LOG_FILENAME="$log" \ @@ -1101,7 +1195,7 @@ yserver-awesome-hw-validation bin="target/release/yserver" label="current" secon ys=$! sleep 2 unset WAYLAND_DISPLAY WAYLAND_SOCKET - export DISPLAY=:7 GDK_BACKEND=x11 XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" + export DISPLAY=:7 GDK_BACKEND=x11 XDG_SESSION_TYPE=x11 awesome > awesome.log 2>&1 & aw=$! sleep 2 picom --backend glx > picom.log 2>&1 & pc=$! @@ -1110,7 +1204,6 @@ yserver-awesome-hw-validation bin="target/release/yserver" label="current" secon sleep {{seconds}} kill -TERM $gg $pc $aw 2>/dev/null; wait $gg $pc $aw 2>/dev/null kill -TERM $ys 2>/dev/null; wait $ys 2>/dev/null - rm -rf "$xdg_rd" echo "== {{label}}: $log" if [ -f "$log" ]; then grep -oE '\[ [A-Za-z0-9_-]+ \]' "$log" | sort | uniq -c | sort -rn; else echo " (no validation messages)"; fi @@ -1140,7 +1233,6 @@ yserver-awesome-hw-telemetry log="info": cargo build --release --bin yserver rm -f yserver-awesome.submit.tsv bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ export GDK_BACKEND=x11;\ export XDG_SESSION_TYPE=x11;\ @@ -1150,11 +1242,10 @@ yserver-awesome-hw-telemetry log="info": yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ DISPLAY=:7 awesome > awesome.log 2>&1 ;\ kill -TERM $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' # Deterministic phased workload for damage-repaint before/after measurement. # @@ -1180,10 +1271,9 @@ yserver-awesome-hw-telemetry log="info": # just yserver-awesome-hw-workload ~/clip.mp4 0.2 # ~20s, smoke the recipe # `clip` must be a video file. `scale` multiplies every phase duration; keep it # identical between the two branches being compared. -yserver-awesome-hw-workload clip scale="1" log="warn,yserver::startup=info,yserver::kms::render::telemetry=info": +yserver-awesome-hw-workload clip scale="1" log="warn,yserver::startup=info,yserver_render::kms::render::telemetry=info": RUSTFLAGS="-C debug-assertions=yes" cargo build --release --bin yserver bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ export GDK_BACKEND=x11 XDG_SESSION_TYPE=x11;\ YSERVER_LOOP_TELEMETRY=1 RUST_LOG="{{log}}" RUST_BACKTRACE=1 \ @@ -1191,17 +1281,16 @@ yserver-awesome-hw-workload clip scale="1" log="warn,yserver::startup=info,yserv yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ DISPLAY=:7 awesome > awesome.log 2>&1 &\ awesome_pid=$!;\ sleep 2;\ - DISPLAY=:7 XDG_RUNTIME_DIR="$xdg_rd" \ + DISPLAY=:7 \ tools/damage-workload.sh "{{clip}}" damage-phases.log "{{scale}}" \ > damage-workload.log 2>&1;\ kill -TERM $awesome_pid 2>/dev/null;\ kill -TERM $yserver_pid 2>/dev/null;\ wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;\ echo "workload done: yserver-hw-awesome.log + damage-phases.log";\ tail -5 damage-workload.log;\ echo "read it with: tools/damage-phases.py yserver-hw-awesome.log damage-phases.log"' @@ -1415,7 +1504,6 @@ yserver-fvwm3-hw-telemetry log="info": cargo build --release --bin yserver rm -f yserver-fvwm3.submit.tsv bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ unset WAYLAND_DISPLAY WAYLAND_SOCKET;\ export GDK_BACKEND=x11;\ export XDG_SESSION_TYPE=x11;\ @@ -1425,32 +1513,29 @@ yserver-fvwm3-hw-telemetry log="info": yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ DISPLAY=:7 fvwm3 > fvwm3-hw.log 2>&1 &\ sleep 1;\ DISPLAY=:7 wezterm ;\ kill -TERM $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' # ============================== WINDOW MAKER ============================== yserver-wmaker-xterm-hw log="info": cargo build --release --bin yserver bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ YSERVER_SCENE_WALK_ALL=1 \ RUST_LOG="{{log}}" RUST_BACKTRACE=1 target/release/yserver > yserver-hw-wmaker.log 2>&1 &\ yserver_pid=$!;\ sleep 2;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET DISPLAY=:7 GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ wmaker > wmaker-hw.log 2>&1 &\ sleep 2;\ DISPLAY=:7 wezterm;\ kill -TERM $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' # wmaker + wezterm on yserver with x11trace tunnelling. wmaker connects # to the fake display `:8`; x11trace forwards every request/event to @@ -1463,7 +1548,6 @@ yserver-wmaker-xterm-hw-trace log="debug": cargo build --release --bin yserver rm -f wmaker.xtrace bash -c '\ - xdg_rd=$(mktemp -d -t yserver-run.XXXXXX); chmod 700 "$xdg_rd";\ YSERVER_SCENE_WALK_ALL=1 \ RUST_LOG="{{log}}" RUST_BACKTRACE=1 target/release/yserver > yserver-hw-wmaker.log 2>&1 &\ yserver_pid=$!;\ @@ -1472,13 +1556,29 @@ yserver-wmaker-xterm-hw-trace log="debug": xtrace_pid=$!;\ sleep 1;\ env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET DISPLAY=:8 GDK_BACKEND=x11 \ - XDG_SESSION_TYPE=x11 XDG_RUNTIME_DIR="$xdg_rd" \ + XDG_SESSION_TYPE=x11 \ wmaker > wmaker-hw.log 2>&1 &\ sleep 2;\ DISPLAY=:8 wezterm;\ kill -TERM $xtrace_pid $yserver_pid 2>/dev/null;\ - wait $yserver_pid 2>/dev/null;\ - rm -rf "$xdg_rd" 2>/dev/null;' + wait $yserver_pid 2>/dev/null;' + +# ============================== VNG SUITE ============================== + +# Registered vng scenarios (tools/vng-scenarios/suite.list); filter is a name regex. +# just vng-suite just vng-suite span venus +vng-suite filter="all" gpu="none" binary="": + KERNEL={{KERNEL}} tools/vng-suite.sh --gpu {{gpu}} {{ if binary != "" { "--binary " + binary } else { "" } }} {{filter}} + +# Rewrite tools/vng-scenarios/goldens/ from Xorg 21.1 in the guest; review the diff like code. +# just vng-goldens xrandr-dpi +vng-goldens filter="all": + KERNEL={{KERNEL}} tools/vng-suite.sh --gpu none --regen-goldens {{filter}} + +# The runner's own self-test: fail, crash, timeout and SIGINT must all fail cleanly. +vng-suite-selftest gpu="none": + cargo build --bin yserver + KERNEL={{KERNEL}} tools/vng-scenarios/suite-selftest/run.sh {{gpu}} --binary target/debug/yserver # ============================== RENDERCHECK ============================== diff --git a/README.md b/README.md index 9bd4ce8e8..d2d7d4e4c 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,77 @@ See [`docs/extensions.txt`](docs/extensions.txt) for a list of all supported/imp ### Recent work +- Windows (x86_64 and aarch64): X clients from WSL or other machines show up + on the Windows desktop, each in its own window or in one rooted window, with + a shared clipboard, a Settings dialog and DPI awareness; `ssh -Y` from + Windows' own ssh client works with the bundled `xauth.exe` +- window operations 5-700x faster on slow machines: window clip regions are + computed in linear time +- compositors that Present their own buffers (marco, ...) get them flipped to + the screen instead of recomposited +- `xhost` access control (ChangeHosts, ListHosts, SetAccessControl) +- the first parts of an access control layer for client isolation (@ariel3259) +- Present keeps going when a monitor's vblank clock freezes (@ariel3259) +- TCP listens on IPv6 too +- shaped windows with many rectangles (xeyes) draw like on Xorg +- macOS: yserver runs in a window on Apple Silicon (Mesa KosmicKrisp), with a + Dock icon and a Settings window; rootless mode gives every X window its own + Mac window +- OpenBSD support +- variable refresh rate on the monitor a fullscreen client is scanned out to + (`--vrr`) (@ariel3259) +- `--vrr all`: VRR for NVIDIA clients too, honouring the NVIDIA and Mesa + application lists (@ariel3259) +- tearing on demand: fullscreen clients that ask for async flips get uncapped + direct scanout (@ariel3259) +- hardware cursor on atomic KMS: a cursor plane per CRTC, and cursor changes no + longer drop direct scanout (@ariel3259) +- gamma through atomic GAMMA_LUT (@ariel3259) +- multi-monitor: direct scanout across monitors whose refresh rates differ + slightly; switching off or unplugging one monitor no longer blanks the others; + `xrandr` changes to one output leave the others alone +- compositors: redirected windows keep their own and their subwindows' borders + (@SetZero), and draw at the right offset when resized; no more blank windows + after a workspace switch under picom; no more smudged decorations when + resizing under fvwm + xcompmgr +- less CPU in the core loop: a client's socket is only polled for writing while + output is waiting (@SetZero) +- XKB modifier locks apply and survive `setxkbmap` (@petrovo-as) +- RENDER text no longer loses glyphs after a long session +- no more crash when a window tree is destroyed while windows in it are still + in use (#297); window teardown follows Xorg's order for grabs, focus, + selections and Present +- clipboard and selection events go to the client that set the owner, as on + Xorg, and a second window manager is refused instead of fighting the first + +### Previously + +- CDE (the Common Desktop Environment) runs: dtsession, dtwm with its panel, + dtterm, dtfile, dtpad, and the Motif/Xaw apps around it +- old-style toolkits (Motif, Xaw, Tk, xterm) draw like on Xorg: lines, text and + clipping, exposures and GraphicsExpose, GetImage of windows with children +- CDE and Motif apps start as fast as on Xorg +- font lookups are indexed and cached +- compressed bitmap fonts now work as expected +- fractional scaling via RANDR transforms (Cinnamon 125%/150%, `xrandr --scale`), + screen rotation and reflection, virtual monitors (`xrandr --setmonitor`), and +- `xrandr --dpi` now works +- RECORD extension (pynput and other global input listeners) +- one XInput device per physical device (mouse, keyboard and touchpad, as on Xorg) (@ariel3259) +- runs on Vulkan 1.2 GPUs such as Intel Haswell and Ivy Bridge; older drivers get a + clear error naming what is missing +- XFCE dialogs under the compositor keep their button bar when scrolled; MATE tray + icons keep their pixels when moved +- the Cinnamon lock screen shows up again, and fullscreen windows can be + re-composited after leaving fullscreen +- fix slow VRAM growth: the cache of freed pixmaps is capped, and pixmaps held by + GCs and freed cursors are released +- window backgrounds no longer flash in odd colours (CDE with sloppy focus) +- lower CPU use with x11vnc and other screen grabbers +- xmodmap and xkbcomp changes reach XKB clients; XI2 raw key events +- a regression suite that runs the real server in a VM and compares it with Xorg, + in CI + - XDMCP session negotiation with a display manager, and a TCP listener — both optional Cargo build features, off by default; see [`docs/setup.md`](docs/setup.md) @@ -49,9 +120,6 @@ See [`docs/extensions.txt`](docs/extensions.txt) for a list of all supported/imp - multi-GPU: the render node is resolved on split display/render SoCs, and non-desktop connectors are ignored (touchbar on M2 macbook pro) - binary packages for aarch64 as well as x86_64 - -### Previously - - `starty` launcher (startx-style: display number picking, MIT-MAGIC-COOKIE-1, session teardown) - Present completions paced to the vblank, and the Present 1.4 acquire timeline honored (fixes free-running clients, fullscreen video, Plasma's spinner) @@ -89,7 +157,7 @@ See [`docs/extensions.txt`](docs/extensions.txt) for a list of all supported/imp - binary releases for Fedora/Debian/Ubuntu/Alpine - FreeBSD now works - Display hotplug now works -- xauth support (no xhost ACL support - not needed as we're unix socket only) +- xauth support, and xhost for local clients (`+si:localuser:`, `+local:`); over TCP only the cookie admits - XINERAMA support - RANDR gamma correction (redshift) - direct mode VT switch @@ -125,6 +193,7 @@ https://github.com/user-attachments/assets/dc266c55-e9ee-4649-a0c4-be3db2526713 - bspwm/sxhkd - i3/fastcompmgr - enlightenment e16 + e27 +- CDE (dtwm) ## Hardware tested @@ -170,6 +239,80 @@ sudo apk add --allow-untrusted ./yserver-*.apk # signed with a per-build key See also `yserver(1)` and `starty(1)`. +### macOS + +yserver runs in a window on macOS 26 or later on Apple Silicon, on Mesa's +KosmicKrisp Vulkan driver. Dependencies from Homebrew: + +```sh +brew install mesa vulkan-loader vulkan-tools shaderc libxkbcommon fontconfig freetype pkgconf +``` + +From a source checkout: + +```sh +just macos-run # :1, 1280x800, log in yserver-mac.log +just macos-run 2 1600x1000 # display, geometry (positional) +just macos-bundle # builds target/yserver.app +``` + +`target/yserver.app` uses the Homebrew libraries and the KosmicKrisp driver +from the Homebrew prefix; nothing is bundled. Started from Finder it takes +the lowest free display from `:1`, shows it in the window title +(`yserver DISPLAY=:N`) and logs to `~/Library/Logs/yserver.log`. + +`--scale` sets how many screen pixels one X pixel covers: `auto` (the +default; one X pixel per point, 2 on a Retina screen), `1` (full +resolution) or `2`. + +`just macos-rootless` runs it rootless instead: no desktop window, and every +X top-level window becomes its own Mac window. + +Text copied in X clients (CLIPBOARD) can be pasted in Mac apps, and the other +way round. PRIMARY (select / middle-click) stays within X. + +Clients connect with the display number, e.g. with XQuartz's clients: + +```sh +DISPLAY=:1 /opt/X11/bin/xterm +``` + +### Windows + +yserver runs on Windows 11 (x86_64 and aarch64) and needs a GPU driver +with Vulkan 1.3. Portable zips (`yserver--windows-.zip`, x86_64 +and aarch64) are attached to each GitHub release from 1.9.0 on; nothing needs +installing, the C runtime and libraries are linked in. The zip's `README.txt` +covers it in full. + +Run `start-yserver.cmd`: it starts display `:0`, creates a cookie in +`%LOCALAPPDATA%\yserver\Xauthority` on first use and prints it. Clients +connect over TCP only. yserver's icon in the notification area opens Settings +and quits it. + +- rootless (the default): every X top-level window is its own Windows window; + `--rooted` puts the whole X screen in one window instead +- text copied in X clients (CLIPBOARD) can be pasted in Windows apps, and the + other way round +- Scale works as on macOS: `auto` uses 1 X pixel per screen pixel up to 125% + and 2 from 150% + +From WSL2 (default NAT networking): + +```sh +export DISPLAY=$(ip route show default | awk '{print $3}'):0 +export XAUTHORITY=/mnt/c/Users//AppData/Local/yserver/Xauthority +xterm & +``` + +X11 forwarding with Windows' own ssh client works with `-Y`: the zip ships an +`xauth.exe`; point `XAuthLocation` in `%USERPROFILE%\.ssh\config` at it and +`set DISPLAY=127.0.0.1:0`. `-X` fails, because yserver has no SECURITY +extension for an untrusted cookie. + +To build it yourself, `tools/windows/package.ps1` installs the C libraries +with vcpkg, builds yserver and makes the zip. + ## Regression coverage with xts5 and rendercheck We run the X.Org X Test Suite (xts5) against `yserver` to gauge protocol completeness. diff --git a/assets/yserver-icon.png b/assets/yserver-icon.png new file mode 100644 index 000000000..6ad3f661e Binary files /dev/null and b/assets/yserver-icon.png differ diff --git a/assets/yserver-icon.svg b/assets/yserver-icon.svg new file mode 100644 index 000000000..476be5c0f --- /dev/null +++ b/assets/yserver-icon.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/assets/yserver.ico b/assets/yserver.ico new file mode 100644 index 000000000..9851771e7 Binary files /dev/null and b/assets/yserver.ico differ diff --git a/crates/yserver-core/Cargo.toml b/crates/yserver-core/Cargo.toml index b9fa23cb9..c304ad330 100644 --- a/crates/yserver-core/Cargo.toml +++ b/crates/yserver-core/Cargo.toml @@ -12,6 +12,9 @@ libc.workspace = true crossbeam-channel.workspace = true mio.workspace = true +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Networking_WinSock"] } + [dev-dependencies] proptest = "1" diff --git a/crates/yserver-core/src/access.rs b/crates/yserver-core/src/access.rs new file mode 100644 index 000000000..87990c4b1 --- /dev/null +++ b/crates/yserver-core/src/access.rs @@ -0,0 +1,280 @@ +//! Synchronous policy hooks for server access decisions. + +use std::ops::BitOr; + +use yserver_protocol::x11::{AtomId, ClientId, RequestHeader, ResourceId}; + +use crate::{peer::PeerIdentity, server::ServerState}; + +/// A policy's answer. `Allow` means this policy does not object. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Decision { + Allow, + Deny(DenyError), +} + +/// The X error a policy would like the checked site to report. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct DenyError { + pub code: u8, + pub value: u32, +} + +/// `BadAccess` with no associated value. +pub const ACCESS: DenyError = DenyError { + code: yserver_protocol::x11::error::BAD_ACCESS, + value: 0, +}; + +/// Server operation categories passed to policy hooks. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct AccessMode(u32); + +impl AccessMode { + pub const READ: Self = Self(1 << 0); + pub const MANAGE: Self = Self(1 << 1); + pub const WRITE: Self = Self(1 << 2); + pub const DESTROY: Self = Self(1 << 3); + pub const CREATE: Self = Self(1 << 4); + pub const GET_ATTR: Self = Self(1 << 5); + pub const SET_ATTR: Self = Self(1 << 6); + pub const LIST_PROP: Self = Self(1 << 7); + pub const GET_PROP: Self = Self(1 << 8); + pub const SET_PROP: Self = Self(1 << 9); + pub const LIST: Self = Self(1 << 10); + pub const ADD: Self = Self(1 << 11); + pub const REMOVE: Self = Self(1 << 12); + pub const HIDE: Self = Self(1 << 13); + pub const SHOW: Self = Self(1 << 14); + pub const BLEND: Self = Self(1 << 15); + pub const USE: Self = Self(1 << 16); + pub const RECEIVE: Self = Self(1 << 17); + pub const INSTALL: Self = Self(1 << 18); + pub const UNINSTALL: Self = Self(1 << 19); + + #[must_use] + pub const fn contains(self, other: Self) -> bool { + self.0 & other.0 == other.0 + } +} + +impl BitOr for AccessMode { + type Output = Self; + + fn bitor(self, rhs: Self) -> Self::Output { + Self(self.0 | rhs.0) + } +} + +/// X resource classes exposed to resource access policies. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum ResourceKind { + Window, + Pixmap, + Gc, + Font, + Cursor, + Colormap, + Picture, + GlyphSet, + Region, + PointerBarrier, + SyncCounter, + SyncAlarm, + SyncFence, + Damage, + PresentEventSelection, + ShmSegment, + GlxContext, + GlxDrawable, + Dri3Syncobj, + RecordContext, + RandrOutput, + RandrCrtc, + RandrMode, + RandrProvider, +} + +/// Resource ownership metadata supplied when a policy checks a creation. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Creation { + pub parent: Option, + pub owner: ClientId, +} + +/// The typed X resource a policy is asked about. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ResourceTarget { + pub id: ResourceId, + pub kind: ResourceKind, + pub creation: Option, +} + +/// The request opcodes active at an access check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RequestOpcodes { + pub major: u8, + pub minor: u8, +} + +impl RequestOpcodes { + /// The opcode pair Xorg exposes while dispatching this request. + /// Core requests use minor opcode zero; extension requests use the + /// request's data byte as their minor opcode. + pub const fn for_request(header: RequestHeader) -> Self { + Self { + major: header.opcode, + minor: if header.opcode < 128 { 0 } else { header.data }, + } + } +} + +/// The credential that admitted a client, without retaining its secret. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Admission { + Cookie { + credential: CredentialId, + source: CredentialSource, + }, + HostAccess, + Internal, +} + +/// Where an accepted cookie came from. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum CredentialSource { + File, + Session, +} + +/// An opaque process-local identifier for an accepted credential. +#[derive(Clone, Copy, Eq, Hash, PartialEq)] +pub struct CredentialId(u64); + +impl CredentialId { + pub(crate) const fn from_counter(value: u64) -> Self { + Self(value) + } +} + +impl std::fmt::Debug for CredentialId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +/// Facts available to a synchronous policy callback. +pub struct AccessContext<'a> { + state: &'a ServerState, + request: Option, +} + +impl<'a> AccessContext<'a> { + pub(crate) const fn new(state: &'a ServerState, request: Option) -> Self { + Self { state, request } + } + + #[must_use] + pub fn peer(&self, client: ClientId) -> Option<&PeerIdentity> { + self.state.clients.get(&client.0).map(|state| &state.peer) + } + + #[must_use] + pub fn admission(&self, client: ClientId) -> Option<&Admission> { + self.state + .clients + .get(&client.0) + .map(|state| &state.admission) + } + + /// Resolve the owner of an object of exactly this resource kind. + #[must_use] + pub fn owner(&self, id: ResourceId, kind: ResourceKind) -> Option { + self.state.access_resource_owner(id, kind) + } + + /// Whether `window` is this screen's root window. + #[must_use] + pub fn is_root(&self, window: ResourceId) -> bool { + window == crate::resources::ROOT_WINDOW + } + + /// Resolve an atom's current name without interning it. + #[must_use] + pub fn atom_name(&self, atom: AtomId) -> Option<&str> { + self.state.atoms.name(atom) + } + + #[must_use] + pub const fn request(&self) -> Option { + self.request + } +} + +/// An ordered, synchronous access policy. Methods run inline on the core loop +/// and must do no I/O or blocking wait. +pub trait AccessPolicy: Send + Sync { + fn server(&self, _ctx: &AccessContext<'_>, _client: ClientId, _mode: AccessMode) -> Decision { + Decision::Allow + } + + /// Decide whether an available extension is visible to a client during + /// `QueryExtension` or `ListExtensions` discovery. + fn extension_access( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _extension: &str, + ) -> Decision { + Decision::Allow + } + + /// Decide whether a request may be dispatched to an extension handler. + /// The request opcodes in `ctx` identify the operation being checked. + fn extension_dispatch( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _extension: &str, + ) -> Decision { + Decision::Allow + } + + /// Decide whether a client may perform `mode` on a typed resource. + fn resource( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _target: &ResourceTarget, + _mode: AccessMode, + ) -> Decision { + Decision::Allow + } + + /// Decide whether a client may perform `mode` on a window property. + fn property( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _window: ResourceId, + _property: AtomId, + _mode: AccessMode, + ) -> Decision { + Decision::Allow + } + + fn client_connected( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _peer: &PeerIdentity, + _admission: &Admission, + ) { + } + + fn connection_gone(&self, _ctx: &AccessContext<'_>, _client: ClientId) {} + + fn owner_gone(&self, _client: ClientId) {} + + fn generation_ended(&self) {} +} diff --git a/crates/yserver-core/src/anon_shm.rs b/crates/yserver-core/src/anon_shm.rs new file mode 100644 index 000000000..e406f7c83 --- /dev/null +++ b/crates/yserver-core/src/anon_shm.rs @@ -0,0 +1,133 @@ +//! Anonymous shared-memory file descriptors for MIT-SHM `CreateSegment`. +//! +//! Linux and FreeBSD use `memfd_create`. Targets without it get a POSIX +//! shared-memory object that is unlinked right after it is opened, so only +//! the descriptor keeps it alive. + +use std::{ + ffi::CStr, + io, + os::fd::{FromRawFd, OwnedFd}, +}; + +/// Create a close-on-exec anonymous shared-memory fd of size zero. +/// `name` is a debugging label only. +pub fn create_anon_shm(name: &CStr) -> io::Result { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + let fd = unsafe { libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd")))] + { + let _ = name; + create_unlinked_posix_shm() + } +} + +/// `shm_open(O_EXCL)` under a unique name, `shm_unlink`, then `FD_CLOEXEC`. +#[cfg_attr( + all(any(target_os = "linux", target_os = "freebsd"), not(test)), + allow(dead_code) +)] +fn create_unlinked_posix_shm() -> io::Result { + use std::{ + sync::atomic::{AtomicU32, Ordering}, + time::{SystemTime, UNIX_EPOCH}, + }; + static COUNTER: AtomicU32 = AtomicU32::new(0); + + for _ in 0..64 { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.subsec_nanos()); + let seq = COUNTER.fetch_add(1, Ordering::Relaxed); + // macOS limits POSIX shm names to 31 bytes (PSHMNAMLEN). + let name = format!( + "/ys{:x}.{seq:x}.{nanos:x}\0", + std::process::id() & 0xff_ffff + ); + let cname = CStr::from_bytes_with_nul(name.as_bytes()).map_err(io::Error::other)?; + // Apple declares shm_open variadic, so the mode is promoted to c_uint. + #[cfg(target_vendor = "apple")] + let mode: libc::c_uint = 0o600; + #[cfg(not(target_vendor = "apple"))] + let mode: libc::mode_t = 0o600; + let fd = unsafe { + libc::shm_open( + cname.as_ptr(), + libc::O_RDWR | libc::O_CREAT | libc::O_EXCL, + mode, + ) + }; + if fd < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::EEXIST) { + continue; + } + return Err(err); + } + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + unsafe { libc::shm_unlink(cname.as_ptr()) }; + set_cloexec(&fd)?; + return Ok(fd); + } + Err(io::Error::from(io::ErrorKind::AlreadyExists)) +} + +fn set_cloexec(fd: &OwnedFd) -> io::Result<()> { + use std::os::fd::AsRawFd; + let raw = fd.as_raw_fd(); + let flags = unsafe { libc::fcntl(raw, libc::F_GETFD) }; + if flags < 0 || unsafe { libc::fcntl(raw, libc::F_SETFD, flags | libc::FD_CLOEXEC) } < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{create_anon_shm, create_unlinked_posix_shm}; + use std::os::fd::{AsRawFd, OwnedFd}; + + fn assert_usable_shm(fd: &OwnedFd) { + let raw = fd.as_raw_fd(); + let flags = unsafe { libc::fcntl(raw, libc::F_GETFD) }; + assert!(flags & libc::FD_CLOEXEC != 0, "fd is close-on-exec"); + assert_eq!(unsafe { libc::ftruncate(raw, 4096) }, 0, "ftruncate"); + let map = unsafe { + libc::mmap( + std::ptr::null_mut(), + 4096, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + raw, + 0, + ) + }; + assert_ne!(map, libc::MAP_FAILED, "mmap"); + unsafe { + map.cast::().write(0x5a); + assert_eq!(map.cast::().read(), 0x5a); + libc::munmap(map, 4096); + } + } + + #[test] + fn anon_shm_is_cloexec_and_mappable() { + let fd = create_anon_shm(c"anon-shm-test").expect("create_anon_shm"); + assert_usable_shm(&fd); + } + + #[test] + fn posix_shm_fallback_is_cloexec_mappable_and_unique() { + let a = create_unlinked_posix_shm().expect("first shm_open fallback"); + let b = create_unlinked_posix_shm().expect("second shm_open fallback"); + assert_ne!(a.as_raw_fd(), b.as_raw_fd()); + assert_usable_shm(&a); + assert_usable_shm(&b); + } +} diff --git a/crates/yserver-core/src/backend/gamma.rs b/crates/yserver-core/src/backend/gamma.rs index bd1fc8d2f..29745d9d1 100644 --- a/crates/yserver-core/src/backend/gamma.rs +++ b/crates/yserver-core/src/backend/gamma.rs @@ -1,6 +1,7 @@ //! Pure gamma-LUT helpers shared by every backend: the linear identity -//! ramp used to seed a CRTC's cache, and the resample used when a -//! connector lands on a hardware CRTC of a different gamma size. +//! ramp used to seed a CRTC's cache, the resample used when a connector +//! lands on a hardware CRTC of a different gamma size, and the VidMode +//! gamma table that sits under every CRTC's RANDR ramp. /// A linear identity ramp of `size` entries: `entry[i] = i * 65535 / /// (size-1)`, so a fresh CRTC reports neutral gamma (matches Xorg's @@ -19,6 +20,187 @@ pub fn identity_ramp(size: u16) -> Vec { .collect() } +/// Significant bits of the VidMode gamma table, as modesetting asks of +/// `xf86HandleColormaps` (drmmode_display.c): `sigRGBbits` 10. +pub const VIDMODE_GAMMA_BITS: u32 = 10; + +/// Entries of the VidMode gamma table, `1 << VIDMODE_GAMMA_BITS`: Xorg's +/// `gammaElements`, which VidMode's `GetGammaRampSize` reports on +/// modesetting whatever the hardware LUT's size. +pub const VIDMODE_GAMMA_ENTRIES: u16 = 1 << VIDMODE_GAMMA_BITS; + +/// Entries per channel of the root visual's palette: the depth-24 +/// TrueColor visual has 8 bits per channel. +const PALETTE_ENTRIES: usize = 1 << 8; + +/// The screen's VidMode gamma table: Xorg's CMap gamma (`xf86cmap.c`) +/// on modesetting, `VIDMODE_GAMMA_ENTRIES` 10-bit values per channel. +/// `SetGamma` builds it from its three values, `SetGammaRamp` from a +/// client's ramp. It sits under each CRTC's RANDR ramp rather than +/// replacing it: [`Self::crtc_lut`] is what the hardware LUT gets. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct VidModeGammaTable { + pub red: Vec, + pub green: Vec, + pub blue: Vec, +} + +impl VidModeGammaTable { + /// The table before any VidMode write: `ComputeGamma` at 1.0. + #[must_use] + pub fn identity() -> Self { + Self::from_gamma([1.0; 3]) + } + + /// `ComputeGamma`: entry `i` is `i` at gamma 1.0, else + /// `(i / 1023)^(1/gamma) * 1023 + 0.5`, truncated. + #[must_use] + pub fn from_gamma(gamma: [f32; 3]) -> Self { + let channel = |gamma: f32| -> Vec { + let top = f64::from(VIDMODE_GAMMA_ENTRIES - 1); + let exponent = 1.0 / f64::from(gamma); + (0..VIDMODE_GAMMA_ENTRIES) + .map(|i| { + // Xorg compares the double exactly, and `i` differs from + // the power formula's rounding. + #[allow(clippy::float_cmp)] + if exponent == 1.0 { + return i; + } + let value = (f64::from(i) / top).powf(exponent) * top + 0.5; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let entry = value as u16; + entry + }) + .collect() + }; + Self { + red: channel(gamma[0]), + green: channel(gamma[1]), + blue: channel(gamma[2]), + } + } + + /// `ComputeGammaRamp`: a client's 16-bit ramp of + /// `VIDMODE_GAMMA_ENTRIES` entries, each kept to its top 10 bits. + #[must_use] + pub fn from_ramp(red: &[u16], green: &[u16], blue: &[u16]) -> Self { + let entries = usize::from(VIDMODE_GAMMA_ENTRIES); + debug_assert_eq!(red.len(), entries, "VidMode red ramp size"); + debug_assert_eq!(green.len(), entries, "VidMode green ramp size"); + debug_assert_eq!(blue.len(), entries, "VidMode blue ramp size"); + let channel = |ramp: &[u16]| -> Vec { + ramp.iter() + .map(|&value| value >> (16 - VIDMODE_GAMMA_BITS)) + .collect() + }; + Self { + red: channel(red), + green: channel(green), + blue: channel(blue), + } + } + + /// `xf86GetGammaRamp`: the table as a 16-bit ramp, each 10-bit value + /// shifted up and its top bits repeated below it. + #[must_use] + pub fn ramp(&self) -> (Vec, Vec, Vec) { + let channel = |table: &[u16]| -> Vec { + table + .iter() + .map(|&entry| { + let mut value = entry << (16 - VIDMODE_GAMMA_BITS); + let mut shift = VIDMODE_GAMMA_BITS; + while shift < 16 { + value |= value >> shift; + shift += VIDMODE_GAMMA_BITS; + } + value + }) + .collect() + }; + ( + channel(&self.red), + channel(&self.green), + channel(&self.blue), + ) + } + + /// A CRTC's hardware LUT of `size` entries for its RANDR ramp, as + /// modesetting loads it: the root TrueColor palette + /// (`CMapRefreshColors`, entry `i` the table's `i * 1023 / 255`), each + /// palette value looked up in the RANDR ramp, then spread over or + /// sampled down to the hardware size (`xf86RandR12CrtcComputeGamma`). + /// + /// Xorg's RANDR ramp has the table's 1024 entries, so a palette value + /// indexes it directly. Yserver's follows the hardware LUT's size, so + /// a ramp of any other size is first resampled to 1024 entries + /// ([`resample_channel`]) and then indexed the same way; that keeps a + /// no-op `SetGamma(1, 1, 1)` within one 8-bit step of the RANDR ramp, + /// where scaling the index down would truncate most levels a step + /// darker. An empty RANDR ramp is Xorg's absent one: the value shifted + /// to 16 bits. + #[must_use] + pub fn crtc_lut( + &self, + randr: (&[u16], &[u16], &[u16]), + size: usize, + ) -> (Vec, Vec, Vec) { + ( + crtc_channel(&self.red, randr.0, size), + crtc_channel(&self.green, randr.1, size), + crtc_channel(&self.blue, randr.2, size), + ) + } +} + +/// One channel of [`VidModeGammaTable::crtc_lut`]. +fn crtc_channel(table: &[u16], randr: &[u16], size: usize) -> Vec { + let top = usize::from(VIDMODE_GAMMA_ENTRIES - 1); + let palette: Vec = (0..PALETTE_ENTRIES) + .map(|i| { + table + .get(i * top / (PALETTE_ENTRIES - 1)) + .copied() + .unwrap_or(0) + }) + .collect(); + let resampled; + let randr = if randr.is_empty() || randr.len() == usize::from(VIDMODE_GAMMA_ENTRIES) { + randr + } else { + resampled = resample_channel(randr, usize::from(VIDMODE_GAMMA_ENTRIES)); + resampled.as_slice() + }; + let lookup = |value: u16| -> u16 { + if randr.is_empty() { + return value << (16 - VIDMODE_GAMMA_BITS); + } + randr[usize::from(value).min(randr.len() - 1)] + }; + if size == 0 { + return Vec::new(); + } + if size >= PALETTE_ENTRIES { + // Upsampling: each palette entry fills `size / 256` slots, and the + // last one the rest of a size that is not a multiple. + let slots = size / PALETTE_ENTRIES; + let mut lut = Vec::with_capacity(size); + for &value in &palette { + lut.extend(std::iter::repeat_n(lookup(value), slots)); + } + let last = lookup(palette[PALETTE_ENTRIES - 1]); + lut.resize(size, last); + lut + } else { + // Downsampling; a one-entry LUT takes the first palette entry. + let span = (size - 1).max(1); + (0..size) + .map(|i| lookup(palette[i * (PALETTE_ENTRIES - 1) / span])) + .collect() + } +} + /// Resample one channel from `src.len()` to `dst_len` entries by linear /// interpolation, preserving endpoints. `dst_len == 1` -> `[src[0]]`; /// `src.len() == 1` -> `dst_len` copies of `src[0]`; empty `src` -> empty. @@ -68,6 +250,162 @@ mod tests { assert_eq!(ramp[128], (128 * 65535 / 255) as u16); } + /// Xorg's RANDR ramp for a gamma, `init_one_component` + /// (xf86RandR12.c): the CRTC ramps the expected values below were + /// computed against. + fn xorg_randr_ramp(size: u32, gamma: f64) -> Vec { + let mut shift = 0; + while (size << shift) < (1 << 16) { + shift += 1; + } + let top = f64::from(size - 1); + (0..size) + .map(|i| { + if (gamma - 1.0).abs() < f64::EPSILON { + (i << shift) as u16 + } else { + ((f64::from(i) / top).powf(1.0 / gamma) * top * f64::from(1u32 << shift)) as u16 + } + }) + .collect() + } + + fn at(lut: &(Vec, Vec, Vec), i: usize) -> (u16, u16, u16) { + (lut.0[i], lut.1[i], lut.2[i]) + } + + /// Every expected value here was printed by Xorg's own `ComputeGamma`, + /// `ComputeGammaRamp`, `xf86GetGammaRamp` and + /// `xf86RandR12CrtcComputeGamma`, extracted from the xserver source + /// and compiled unchanged, over the TrueColor palette + /// `CMapRefreshColors` builds for a depth-24 root, against RANDR + /// ramps of 1024 entries at gamma 1.0, 1.25 and 1.0. + #[test] + fn vidmode_gamma_table_matches_xorgs_modesetting_path() { + let identity = VidModeGammaTable::identity(); + let ramp = identity.ramp(); + assert_eq!( + (ramp.0[0], ramp.0[1], ramp.0[512], ramp.0[1023]), + (0, 64, 32800, 65535) + ); + + let randr_red = xorg_randr_ramp(1024, 1.0); + let randr_green = xorg_randr_ramp(1024, 1.25); + let randr = ( + randr_red.as_slice(), + randr_green.as_slice(), + randr_red.as_slice(), + ); + + let table = VidModeGammaTable::from_gamma([2.0, 1.0, 0.5]); + assert_eq!((table.red[1], table.green[1], table.blue[1]), (32, 1, 0)); + assert_eq!( + (table.red[512], table.green[512], table.blue[512]), + (724, 512, 256) + ); + let lut = table.crtc_lut(randr, 256); + assert_eq!(at(&lut, 0), (0, 0, 0)); + assert_eq!(at(&lut, 1), (4096, 775, 0)); + assert_eq!(at(&lut, 2), (5760, 1350, 0)); + assert_eq!(at(&lut, 100), (40960, 30950, 10048)); + assert_eq!(at(&lut, 128), (46336, 37691, 16448)); + assert_eq!(at(&lut, 255), (65472, 65472, 65472)); + let lut = table.crtc_lut(randr, 1024); + assert_eq!(at(&lut, 3), (0, 0, 0)); + assert_eq!(at(&lut, 4), (4096, 775, 0)); + assert_eq!(at(&lut, 7), (4096, 775, 0)); + assert_eq!(at(&lut, 512), (46336, 37691, 16448)); + assert_eq!(at(&lut, 1023), (65472, 65472, 65472)); + let lut = table.crtc_lut(randr, 4096); + assert_eq!(at(&lut, 15), (0, 0, 0)); + assert_eq!(at(&lut, 16), (4096, 775, 0)); + assert_eq!(at(&lut, 2048), (46336, 37691, 16448)); + assert_eq!(at(&lut, 4095), (65472, 65472, 65472)); + let lut = table.crtc_lut(randr, 100); + assert_eq!(at(&lut, 1), (5760, 1350, 0)); + assert_eq!(at(&lut, 50), (46336, 37691, 16448)); + assert_eq!(at(&lut, 99), (65472, 65472, 65472)); + + let red: Vec = (0..1024).map(|i| 65535 - i * 64).collect(); + let green: Vec = (0..1024).map(|i| i * 64 + 63).collect(); + let blue: Vec = (0..1024u32).map(|i| (i * 37) as u16).collect(); + let table = VidModeGammaTable::from_ramp(&red, &green, &blue); + assert_eq!((table.red[0], table.green[0], table.blue[0]), (1023, 0, 0)); + assert_eq!( + (table.red[1023], table.green[1023], table.blue[1023]), + (0, 1023, 591) + ); + let ramp = table.ramp(); + assert_eq!(at(&ramp, 0), (65535, 0, 0)); + assert_eq!(at(&ramp, 1), (65471, 64, 0)); + assert_eq!(at(&ramp, 1023), (0, 65535, 37860)); + let lut = table.crtc_lut(randr, 256); + assert_eq!(at(&lut, 0), (65472, 0, 0)); + assert_eq!(at(&lut, 1), (65216, 775, 128)); + assert_eq!(at(&lut, 100), (39808, 30950, 14784)); + assert_eq!(at(&lut, 128), (32640, 37691, 18944)); + assert_eq!(at(&lut, 255), (0, 65472, 37824)); + } + + /// Yserver's RANDR ramp follows the hardware size, which KMS builds as + /// 256 entries on most hardware: the path that runs there resamples it + /// to 1024 entries and indexes that. A no-op `SetGamma(1, 1, 1)` then + /// stays within one 8-bit step of the RANDR ramp at every level, and + /// `SetGamma(2, 1, 0.5)` within one 8-bit step of what Xorg loads from + /// its 1024-entry ramp (the vectors of the test above). An empty ramp + /// is Xorg's absent one, the value shifted to 16 bits. + #[test] + fn vidmode_gamma_table_over_a_hardware_sized_randr_ramp() { + let randr = identity_ramp(256); + let randr3 = (randr.as_slice(), randr.as_slice(), randr.as_slice()); + let lut = VidModeGammaTable::identity().crtc_lut(randr3, 256); + for (level, (&got, &want)) in lut.0.iter().zip(&randr).enumerate() { + assert!( + got.abs_diff(want) < 257, + "level {level}: {got} against the RANDR ramp's {want}" + ); + assert_eq!(got >> 8, want >> 8, "level {level}"); + } + assert_eq!(at(&lut, 0), (0, 0, 0)); + assert_eq!(at(&lut, 1), (256, 256, 256)); + assert_eq!(at(&lut, 128), (32864, 32864, 32864)); + assert_eq!(at(&lut, 255), (65535, 65535, 65535)); + + let table = VidModeGammaTable::from_gamma([2.0, 1.0, 0.5]); + let lut = table.crtc_lut(randr3, 256); + let xorg_randr = xorg_randr_ramp(1024, 1.0); + let xorg = table.crtc_lut( + ( + xorg_randr.as_slice(), + xorg_randr.as_slice(), + xorg_randr.as_slice(), + ), + 256, + ); + for level in 0..256 { + let (got, want) = (at(&lut, level), at(&xorg, level)); + assert!( + got.0.abs_diff(want.0) < 257 + && got.1.abs_diff(want.1) < 257 + && got.2.abs_diff(want.2) < 257, + "level {level}: {got:?} against Xorg's {want:?}" + ); + } + assert_eq!(at(&lut, 1), (4100, 256, 0)); + assert_eq!(at(&lut, 100), (40999, 25689, 10058)); + assert_eq!(at(&lut, 128), (46381, 32864, 16464)); + assert_eq!(at(&lut, 255), (65535, 65535, 65535)); + + let lut = VidModeGammaTable::identity().crtc_lut((&[], &[], &[]), 256); + assert_eq!((lut.0[1], lut.0[255]), (4 << 6, 1023 << 6)); + assert!( + VidModeGammaTable::identity() + .crtc_lut(randr3, 0) + .0 + .is_empty() + ); + } + #[test] fn resample_preserves_endpoints_and_handles_degenerate() { let src = identity_ramp(256); diff --git a/crates/yserver-core/src/backend/mod.rs b/crates/yserver-core/src/backend/mod.rs index 28c8da433..16bd737a4 100644 --- a/crates/yserver-core/src/backend/mod.rs +++ b/crates/yserver-core/src/backend/mod.rs @@ -21,10 +21,11 @@ pub use params::{ }; pub use trait_def::{ ActiveCursorImage, Backend, BackendFdKind, CompletedPresentEvent, CrtcConfigApply, - CrtcConfigToken, DisplayedCursor, Dri3Caps, Dri3ImportModifier, Dri3PixmapExport, - HostSocketStatus, KeyboardMappingChange, KeymapLoad, ModeSpec, PresentCaps, PresentClockSample, - PresentClockSource, PresentScanoutCandidate, PresentSourceWait, PresentWake, SyncobjHandle, - XkbIndicatorMapsChange, XkbNewKeyboardInfo, XkbSetEvent, XkbSetOutcome, XshmfenceHandle, + CrtcConfigToken, DisplayedCursor, Dri3Caps, Dri3ExportBegin, Dri3ExportToken, + Dri3ImportModifier, Dri3PixmapExport, HostSocketStatus, KeyboardMappingChange, KeymapLoad, + ModeSpec, PresentCaps, PresentClockSample, PresentClockSource, PresentScanoutCandidate, + PresentSourceWait, PresentWake, RealizeBackground, SyncobjHandle, XkbIndicatorMapsChange, + XkbNewKeyboardInfo, XkbSetEvent, XkbSetOutcome, XshmfenceHandle, }; use yserver_protocol::x11::ClientId; @@ -108,6 +109,7 @@ pub struct BackendTopology { pub modes: Vec, pub providers: Vec, pub capabilities: BackendCapabilities, + pub limits: crate::randr::RandrLimits, } impl BackendTopology { @@ -122,6 +124,7 @@ impl BackendTopology { let (outputs, modes) = backend.randr_outputs_and_modes(); let providers = backend.randr_providers(); let capabilities = BackendCapabilities::from_backend(backend); + let limits = backend.randr_limits(); Self { width, height, @@ -129,6 +132,7 @@ impl BackendTopology { modes, providers, capabilities, + limits, } } @@ -145,6 +149,7 @@ impl BackendTopology { self.capabilities, ); state.randr.set_providers(self.providers); + state.randr.limits = self.limits; state } } diff --git a/crates/yserver-core/src/backend/params.rs b/crates/yserver-core/src/backend/params.rs index 6ed0cc818..78f8f75c7 100644 --- a/crates/yserver-core/src/backend/params.rs +++ b/crates/yserver-core/src/backend/params.rs @@ -8,84 +8,7 @@ use crate::backend::{FontHandle, PixmapHandle}; use yserver_protocol::x11::ClipRectangles; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum LineStyle { - Solid, - OnOffDash, - DoubleDash, -} - -impl LineStyle { - pub fn from_protocol(value: u8) -> Self { - match value { - 1 => Self::OnOffDash, - 2 => Self::DoubleDash, - _ => Self::Solid, - } - } - - pub fn protocol_value(self) -> u8 { - match self { - Self::Solid => 0, - Self::OnOffDash => 1, - Self::DoubleDash => 2, - } - } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum CapStyle { - NotLast, - Butt, - Round, - Projecting, -} - -impl CapStyle { - pub fn from_protocol(value: u8) -> Self { - match value { - 0 => Self::NotLast, - 2 => Self::Round, - 3 => Self::Projecting, - _ => Self::Butt, - } - } - - pub fn protocol_value(self) -> u8 { - match self { - Self::NotLast => 0, - Self::Butt => 1, - Self::Round => 2, - Self::Projecting => 3, - } - } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum JoinStyle { - Miter, - Round, - Bevel, -} - -impl JoinStyle { - pub fn from_protocol(value: u8) -> Self { - match value { - 1 => Self::Round, - 2 => Self::Bevel, - _ => Self::Miter, - } - } - - pub fn protocol_value(self) -> u8 { - match self { - Self::Miter => 0, - Self::Round => 1, - Self::Bevel => 2, - } - } -} +pub use yserver_protocol::x11::gc::{ArcMode, CapStyle, GcFunction, JoinStyle, LineStyle}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum FillStyle { @@ -137,70 +60,6 @@ impl FillRule { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum GcFunction { - Clear, - And, - AndReverse, - Copy, - AndInverted, - NoOp, - Xor, - Or, - Nor, - Equiv, - Invert, - OrReverse, - CopyInverted, - OrInverted, - Nand, - Set, -} - -impl GcFunction { - pub fn from_protocol(value: u8) -> Self { - match value { - 0 => Self::Clear, - 1 => Self::And, - 2 => Self::AndReverse, - 4 => Self::AndInverted, - 5 => Self::NoOp, - 6 => Self::Xor, - 7 => Self::Or, - 8 => Self::Nor, - 9 => Self::Equiv, - 10 => Self::Invert, - 11 => Self::OrReverse, - 12 => Self::CopyInverted, - 13 => Self::OrInverted, - 14 => Self::Nand, - 15 => Self::Set, - _ => Self::Copy, - } - } - - pub fn protocol_value(self) -> u8 { - match self { - Self::Clear => 0, - Self::And => 1, - Self::AndReverse => 2, - Self::Copy => 3, - Self::AndInverted => 4, - Self::NoOp => 5, - Self::Xor => 6, - Self::Or => 7, - Self::Nor => 8, - Self::Equiv => 9, - Self::Invert => 10, - Self::OrReverse => 11, - Self::CopyInverted => 12, - Self::OrInverted => 13, - Self::Nand => 14, - Self::Set => 15, - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SubwindowMode { ClipByChildren, @@ -223,28 +82,6 @@ impl SubwindowMode { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum ArcMode { - Chord, - PieSlice, -} - -impl ArcMode { - pub fn from_protocol(value: u8) -> Self { - match value { - 0 => Self::Chord, - _ => Self::PieSlice, - } - } - - pub fn protocol_value(self) -> u8 { - match self { - Self::Chord => 0, - Self::PieSlice => 1, - } - } -} - /// Effective clip-state of a GC at the moment a draw op runs. Either /// the GC has a `SetClipRectangles` list, a `ChangeGC(clip_mask=Pixmap)` /// host-mask, or no clip at all. `Rectangles.rects` carries the wire diff --git a/crates/yserver-core/src/backend/recording.rs b/crates/yserver-core/src/backend/recording.rs index e8e77ee8b..285d49e73 100644 --- a/crates/yserver-core/src/backend/recording.rs +++ b/crates/yserver-core/src/backend/recording.rs @@ -17,7 +17,7 @@ //! `nested::handle_request`'s ChangeWindowAttributes path on //! ROOT_WINDOW pokes the container). -use std::{io, sync::Mutex}; +use std::{collections::VecDeque, io, sync::Mutex}; use yserver_protocol::x11::{ClipRectangles, FontMetrics, ResourceId, glx, xfixes}; @@ -34,6 +34,8 @@ use crate::{ /// assert against `Vec` snapshots. #[derive(Debug, Clone, PartialEq, Eq)] pub enum RecordedCall { + /// The backend input-session cleanup hook ran at a generation boundary. + ResetInputSession, /// A key event handed to `on_host_input`; `repeat` distinguishes /// `HostInputEvent::KeyRepeat` from device `HostInputEvent::Key`. HostKey { @@ -41,6 +43,14 @@ pub enum RecordedCall { pressed: bool, repeat: bool, }, + /// Pointer motion or a button handed to `on_host_input`; `button` 0 is + /// a motion to `(x, y)`. + HostPointer { + x: i32, + y: i32, + button: u16, + pressed: bool, + }, CreateSubwindow { parent: u32, x: i16, @@ -55,6 +65,10 @@ pub enum RecordedCall { MapSubwindow(u32), UnmapSubwindow(u32), RealizeWindowStorage(u32), + /// `realize_window_storage` with the background paint inhibited. + RealizeWindowStorageUnpainted(u32), + /// `realize_window_storage` with the background paint left to the core. + RealizeWindowStorageDeferred(u32), ReleaseWindowStorage(u32), ConfigureSubwindow { host_xid: u32, @@ -85,6 +99,8 @@ pub enum RecordedCall { host_xid: u32, }, UnregisterHostWindow(u32), + /// `retire_overlay_window`: the COW's backend step of a destroy. + RetireOverlayWindow, CreatePixmap { depth: u8, width: u16, @@ -99,6 +115,21 @@ pub enum RecordedCall { ReleaseRedirectedBacking(u32), RetainBackingStorage(u32), DropBackingStorage(u32), + PaintWindowBorderRects { + host_xid: u32, + rects: Vec, + }, + ReallocateRedirectedBacking { + host_window: u32, + old: u32, + width: u16, + height: u16, + depth: u8, + }, + MoveSubwindowsForGravity { + moves: Vec<(u32, i16, i16)>, + carry_from: Option, + }, AllocateRedirectedBacking { host_window: u32, width: u16, @@ -126,6 +157,25 @@ pub enum RecordedCall { RenderCreatePicture { host_drawable: AnyHandle, host_pic: u32, + value_mask: u32, + values: Vec, + }, + RenderChangePicture { + host_pic: u32, + body: Vec, + }, + RenderCompositeGlyphs { + minor: u8, + op: u8, + host_src: u32, + host_dst: u32, + mask_fmt: u32, + host_gs: u32, + src_x: i16, + src_y: i16, + items: Vec, + x_off: i16, + y_off: i16, }, RenderFreePicture { host_pic: u32, @@ -142,6 +192,11 @@ pub enum RecordedCall { dst_host_xid: u32, plane: u32, }, + PolyText8 { + host_xid: u32, + foreground: u32, + body: Vec, + }, PaintWindowBackgroundRect { host_xid: u32, x: i16, @@ -154,6 +209,7 @@ pub enum RecordedCall { new_host_xid: u32, }, SetCursorHidden(bool), + FreeCursor(u32), DefineCursor { host_window_xid: u32, cursor_host_xid: u32, @@ -204,6 +260,14 @@ pub enum RecordedCall { height: u16, }, ApplyClipState(ClipState), + /// `poly_fill_rectangle(host_xid, ..)` called. + PolyFillRectangle { + host_xid: u32, + }, + /// `poly_point(host_xid, ..)` called. + PolyPoint { + host_xid: u32, + }, PutImage { host_xid: u32, depth: u8, @@ -231,6 +295,8 @@ pub enum RecordedCall { /// can pin this running strictly after `maybe_composite` (the KMS gate /// this arm hides behind only clears post-compose). ArmPresentCompletionIdleVblanks, + /// `on_rootless_events()` called with a non-empty batch. + RootlessEvents(Vec), } type GammaTriplet = (Vec, Vec, Vec); @@ -243,6 +309,8 @@ pub struct RecordingBackend { /// `take_displayed_cursor_change`. Tests set it to stand in for a KMS /// sprite change. pub displayed_cursor_change: Option, + /// What `displayed_cursor_hidden` answers. + pub displayed_cursor_hidden: bool, next_handle: Mutex, fake_window_id: u32, fake_root_visual_xid: u32, @@ -261,6 +329,8 @@ pub struct RecordingBackend { pub scanout_render_completion_count: std::sync::atomic::AtomicU32, /// Stable test-owned fd inventory returned by `poll_fds`. poll_sources: Vec<(std::os::fd::RawFd, crate::backend::BackendFdKind)>, + /// A host display connection's output, flushed as a rootless host's is. + pub host_display_out: Option, /// Optional test notification sent after a DRM fd is dispatched, /// allowing a test thread to wait without timing-dependent sleeps. page_flip_ready_tx: Option>, @@ -271,18 +341,23 @@ pub struct RecordingBackend { /// page-flip ever occurs (project_reclamation_starvation_leak). pub before_block_count: std::sync::atomic::AtomicU32, /// COW: whether the backend currently owns a materialized overlay. - /// A plain bool, not a count — core owns the claim list and this - /// backend is only ever driven on the 0 → 1 and 1 → 0 edges. Plain + /// A plain bool, not a count — core owns the claim list. Plain /// `bool` not `AtomicBool` — `Backend` methods take `&mut self`, so /// the test thread already has exclusive access. pub cow_materialized: bool, /// Failure injection: `get_overlay_window` returns `Err` instead of /// materializing, so tests can drive the claim-rollback path. pub cow_materialize_fails: bool, - /// Failure injection: `release_overlay_window` returns `Err` with the + /// Failure injection: `prepare_overlay_release` returns `Err` with the /// overlay left up, modelling `KmsBackend`'s - /// `materialize_direct_shadow_for_unflip` failing on the 1 → 0 edge. + /// `materialize_direct_shadow_for_unflip` failing. pub cow_teardown_fails: bool, + /// `retire_overlay_window` defers, as `KmsBackend` does behind direct + /// scanout: the COW stays materialized with `cow_release_deferred` set + /// until a test clears it or `get_overlay_window` re-adopts it. + pub cow_release_defers: bool, + /// A retirement deferred by `cow_release_defers` is outstanding. + pub cow_release_deferred: bool, /// Phase 2 (reparent reconciliation): lets tests opt in to /// claiming `supports_redirect_activation = true` so the /// production reconciliation block in `handle_reparent_window` @@ -328,11 +403,23 @@ pub struct RecordingBackend { /// Test controls and observations for asynchronous CRTC configuration. /// `None` preserves the synchronous `apply_crtc_config` path. pub pending_crtc_config: Option, + /// When set, a synchronous `apply_crtc_config` reports a change and the + /// following `refresh_randr_state_set_time` installs it into + /// `state.randr`, carrying client-owned state as the KMS rebuild does. + pub apply_crtc_configs: bool, + applied_crtc_config: Option<(u32, Option, i32, i32)>, pub ready_crtc_configs: Vec, pub crtc_config_results: std::collections::HashMap>, pub finished_crtc_configs: Vec, pub cancelled_crtc_configs: Vec, + /// When set, the next DRI3 export begins deferred under this token. + pub pending_dri3_export: Option, + pub ready_dri3_exports: Vec, + pub finished_dri3_exports: Vec, + pub released_dri3_exports: Vec, + /// Deferred exports that finish with an error. + pub failed_dri3_exports: Vec, /// Startup input-probe model. Each inner `Vec` is one "dispatch /// round" the fake libinput would yield; `probe_input_devices` /// consumes the front round per iteration and seeds the registry, @@ -350,6 +437,8 @@ pub struct RecordingBackend { pub warped_to: Option<(i32, i32)>, /// In-memory per-RANDR-CRTC gamma LUT for unit tests (size 256). pub gamma: std::cell::RefCell>, + /// The VidMode gamma table last handed to `set_vidmode_gamma`. + pub vidmode_gamma: Option, /// Active RMLVO `[rules, model, layout, variant, options]` returned by /// `current_xkb_rules_names`. `None` (the default) models a backend /// without a real keymap; tests that exercise `_XKB_RULES_NAMES` @@ -388,6 +477,8 @@ pub struct RecordingBackend { /// `(xid, triggered)` of each shared-memory fence `dri3_destroy_fence` /// unmapped, with its in-memory state at unmap time. pub destroyed_shm_fences: Vec<(u32, bool)>, + /// `dri3_fence_from_fd` fails, as for a fd that isn't an xshmfence. + pub refuse_fence_fds: bool, /// `(syncobj_xid, value)` passed to `dri3_signal_syncobj`, in call /// order — Task 8: lets a `PixmapSynced` supersession/copy-failure /// release be asserted the same way `triggered_dri3_fences` covers @@ -478,18 +569,11 @@ pub struct RecordingBackend { /// Task 7: canned return for `present_scanout_blackout`. Default /// `false` matches the trait default. pub present_scanout_blackout: bool, - /// Controls what `arm_present_absolute_vblank` returns. `None` - /// (default) mimics a real always-succeeds arm: covers every target - /// it's given. `Some(Ok(n))` / `Some(Err(kind))` let a test pin the - /// `Ok(0)` / `Err` idle_fallback paths (spec §msc-due future-target - /// rung 1). - pub arm_present_absolute_vblank_result: Option>, - /// `targets` recorded per `arm_present_absolute_vblank` call, in call - /// order, so a test can assert exactly what was armed — the `-1` from - /// `eff` is core-side (Task 7), so this should read `eff - 1`, never - /// the raw `effective_target_msc`. - pub armed_absolute_vblank_targets: Vec>, - pub armed_absolute_vblank_crtcs: Vec, + /// Controls what `arm_present_shared_wake` returns. `None` (default) + /// mimics an available tagged next-vblank arm. + pub arm_present_shared_wake_result: Option>, + /// CRTC IDs passed to `arm_present_shared_wake`, in call order. + pub armed_shared_wake_crtcs: Vec, /// Domain-qualified calls made by the two idle-arm paths. pub armed_idle_vblank_targets: Vec<(u32, Vec)>, pub armed_completion_idle_vblank_targets: Vec<(u32, Vec)>, @@ -500,9 +584,18 @@ pub struct RecordingBackend { /// `execute_present_pixmap_copy_or_reroute`'s failure arm. Default /// `false` matches today's always-succeeds behavior. pub fail_copy_area: bool, + /// When `true`, `fill_rectangle` records the call but returns `Err`. + pub fail_fill_rectangle: bool, + /// Failure injection for GLX pbuffer backing allocation tests. + pub create_pixmap_fails: bool, + /// The next `open_font` records its call and returns this error kind. + /// Used to drive reset's fatal default-font reinstall boundary. + pub fail_open_font: Option, /// Canned direct-Present result plus observed candidates. A successful /// result lets request-layer tests prove M2b bypasses Copy entirely. pub present_direct_result: bool, + /// `reallocate_redirected_backing` fails (after recording the call). + pub reallocate_fails: bool, pub present_direct_candidates: Vec, /// `(event, dst_host_xid)` passed to `enqueue_present_completion`, in call order. pub enqueued_present_completions: Vec<(CompletedPresentEvent, u32)>, @@ -518,11 +611,48 @@ pub struct RecordingBackend { /// one per pending Present scrapped by same-target supersession. /// Lets a test assert exactly one call per victim. pub present_skip_count: u32, - /// `(device_node, change)` pairs passed to `apply_device_config`, in - /// call order, so xinput property-write tests can assert exactly what - /// reached the backend (the trait's default impl is a no-op and - /// doesn't record anything). - pub applied_device_configs: Vec<(String, crate::xinput::libinput_props::DeviceConfigChange)>, + /// Source/change pairs passed to `start_device_config`, in call order. + pub started_device_configs: Vec<( + crate::xinput::InputSourceId, + crate::xinput::libinput_props::DeviceConfigChange, + )>, + /// Shared cancellation handles passed with submitted input commands. + pub device_config_cancel_tokens: Vec, + /// Results returned by successive `start_device_config` calls. Empty + /// means each setting is confirmed synchronously. + pub device_config_start_results: VecDeque< + Result< + crate::xinput::libinput_props::DeviceConfigStart, + crate::xinput::libinput_props::DeviceConfigError, + >, + >, + /// Whether this recording backend should exercise VT lifecycle dispatch. + pub vt_switching_armed: bool, + /// `on_platform_event` calls seen. + pub platform_events: usize, + /// The last `note_client_count`, shared so a test can watch a core + /// loop running on another thread. + pub client_count: std::sync::Arc, + /// Returned by `glx_available`. + pub glx_available: bool, + /// Let request-path tests create a glyphset without a host renderer. + pub render_create_glyphset_returns_handle: bool, + /// Whether the test backend simulates queueing the input pause barrier. + pub vt_release_pause_queued: bool, + /// Set when the release has crossed the test backend's yield boundary. + pub vt_release_finished: std::sync::Arc, + /// Test probe: capture output already written when the VT release finishes. + #[cfg(test)] + pub vt_release_probe_client: Option, + /// Whether the probe client had reply bytes written before release finished. + #[cfg(test)] + pub vt_release_wire_visible_before_finish: bool, + /// Test probe: source whose config inventory value is sampled at release. + #[cfg(test)] + pub vt_release_probe_source: Option, + /// The probe source's inventory accel speed observed at release finish. + #[cfg(test)] + pub vt_release_inventory_accel_before_finish: Option, } impl Default for RecordingBackend { @@ -536,6 +666,7 @@ impl RecordingBackend { Self { calls: Mutex::new(Vec::new()), displayed_cursor_change: None, + displayed_cursor_hidden: false, next_handle: Mutex::new(0x0001_0000), fake_window_id: 0x0000_0100, fake_root_visual_xid: 0x0000_0021, @@ -544,12 +675,15 @@ impl RecordingBackend { page_flip_fds: Mutex::new(Vec::new()), scanout_render_completion_count: std::sync::atomic::AtomicU32::new(0), poll_sources: Vec::new(), + host_display_out: None, page_flip_ready_tx: None, scanout_render_completion_tx: None, before_block_count: std::sync::atomic::AtomicU32::new(0), cow_materialized: false, cow_materialize_fails: false, cow_teardown_fails: false, + cow_release_defers: false, + cow_release_deferred: false, redirect_activation_supported: false, composite_opcode: None, query_pointer_mask: 0, @@ -563,14 +697,22 @@ impl RecordingBackend { provider_output_source_changed: true, provider_output_source_error: None, pending_crtc_config: None, + apply_crtc_configs: false, + applied_crtc_config: None, ready_crtc_configs: Vec::new(), crtc_config_results: std::collections::HashMap::new(), finished_crtc_configs: Vec::new(), cancelled_crtc_configs: Vec::new(), + pending_dri3_export: None, + ready_dri3_exports: Vec::new(), + finished_dri3_exports: Vec::new(), + released_dri3_exports: Vec::new(), + failed_dri3_exports: Vec::new(), probe_rounds: std::collections::VecDeque::new(), probe_rounds_run: std::cell::Cell::new(0), warped_to: None, gamma: std::cell::RefCell::new(std::collections::HashMap::new()), + vidmode_gamma: None, xkb_rules_names: None, keymap_rmlvo_result: None, kbd_by_name_result: None, @@ -585,6 +727,7 @@ impl RecordingBackend { triggered_dri3_fences: Vec::new(), shm_fences: std::collections::HashMap::new(), destroyed_shm_fences: Vec::new(), + refuse_fence_fds: false, signalled_dri3_syncobjs: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())), dri3_syncobj_owners: std::collections::HashMap::new(), dri3_caps: crate::backend::Dri3Caps::unsupported(), @@ -608,19 +751,39 @@ impl RecordingBackend { present_absolute_vblank_arm_supported: false, present_absolute_vblank_arm_supported_by_crtc: std::collections::HashMap::new(), present_scanout_blackout: false, - arm_present_absolute_vblank_result: None, - armed_absolute_vblank_targets: Vec::new(), - armed_absolute_vblank_crtcs: Vec::new(), + arm_present_shared_wake_result: None, + armed_shared_wake_crtcs: Vec::new(), armed_idle_vblank_targets: Vec::new(), armed_completion_idle_vblank_targets: Vec::new(), arm_idle_vblanks_result: None, fail_copy_area: false, + fail_fill_rectangle: false, + create_pixmap_fails: false, + fail_open_font: None, present_direct_result: false, + reallocate_fails: false, present_direct_candidates: Vec::new(), enqueued_present_completions: Vec::new(), arm_present_syncobj_wait_result: None, present_skip_count: 0, - applied_device_configs: Vec::new(), + started_device_configs: Vec::new(), + device_config_cancel_tokens: Vec::new(), + device_config_start_results: VecDeque::new(), + vt_switching_armed: false, + platform_events: 0, + client_count: std::sync::Arc::default(), + glx_available: true, + render_create_glyphset_returns_handle: false, + vt_release_pause_queued: false, + vt_release_finished: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + #[cfg(test)] + vt_release_probe_client: None, + #[cfg(test)] + vt_release_wire_visible_before_finish: false, + #[cfg(test)] + vt_release_probe_source: None, + #[cfg(test)] + vt_release_inventory_accel_before_finish: None, } } @@ -739,6 +902,10 @@ impl crate::backend::SyncobjHandle for RecordingSyncobjHandle { } impl Backend for RecordingBackend { + fn displayed_cursor_hidden(&self) -> bool { + self.displayed_cursor_hidden + } + // State accessors — return fixed sentinels so the call sites that // need a real number get a real number; record nothing. @@ -746,6 +913,62 @@ impl Backend for RecordingBackend { self.fake_window_id } + fn vt_switching_armed(&self) -> bool { + self.vt_switching_armed + } + + fn on_platform_event(&mut self, _state: &mut crate::server::ServerState) { + self.platform_events += 1; + } + + fn on_rootless_events( + &mut self, + _state: &crate::server::ServerState, + events: &[crate::rootless::RootlessEvent], + ) { + self.record(RecordedCall::RootlessEvents(events.to_vec())); + } + + fn note_client_count(&mut self, count: usize) { + self.client_count + .store(count, std::sync::atomic::Ordering::Release); + } + + fn begin_vt_release(&mut self) -> bool { + self.vt_release_pause_queued + } + + fn finish_vt_release( + &mut self, + state: &mut crate::server::ServerState, + input_inventory: &crate::core_loop::input_inventory::InputInventory, + ) { + #[cfg(test)] + { + self.vt_release_wire_visible_before_finish = self + .vt_release_probe_client + .and_then(|client_id| state.clients.get(&client_id)) + .and_then(|client| { + let writer = client.writer.lock().ok()?; + match &*writer { + crate::transport::Transport::Capture(bytes) => { + Some(!bytes.lock().ok()?.is_empty()) + } + _ => None, + } + }) + .unwrap_or(false); + self.vt_release_inventory_accel_before_finish = self + .vt_release_probe_source + .and_then(|source| input_inventory.get(source)) + .map(|entry| entry.config.accel.current); + } + #[cfg(not(test))] + let _ = (state, input_inventory); + self.vt_release_finished + .store(true, std::sync::atomic::Ordering::SeqCst); + } + fn root_visual_xid(&self) -> u32 { self.fake_root_visual_xid } @@ -795,6 +1018,17 @@ impl Backend for RecordingBackend { self.released_present_sources.push(pin_id); } + fn dri3_fence_from_fd( + &mut self, + _fence_xid: u32, + _fd: crate::fd::OwnedFd, + ) -> std::io::Result<()> { + if self.refuse_fence_fds { + return Err(std::io::Error::other("not an xshmfence")); + } + Ok(()) + } + fn dri3_trigger_fence(&mut self, fence_xid: u32) -> std::io::Result<()> { self.triggered_dri3_fences.push(fence_xid); if let Some(triggered) = self.shm_fences.get_mut(&fence_xid) { @@ -832,6 +1066,10 @@ impl Backend for RecordingBackend { self.dri3_caps } + fn glx_available(&self) -> bool { + self.glx_available + } + fn dri3_import_syncobj( &mut self, client_id: yserver_protocol::x11::ClientId, @@ -894,14 +1132,20 @@ impl Backend for RecordingBackend { .is_some_and(|(owner, _)| *owner == client_id) } - fn apply_device_config( + fn start_device_config( &mut self, - device_node: &str, + source: crate::xinput::InputSourceId, change: crate::xinput::libinput_props::DeviceConfigChange, - ) -> Result<(), crate::xinput::libinput_props::DeviceConfigError> { - self.applied_device_configs - .push((device_node.to_owned(), change)); - Ok(()) + cancel: crate::xinput::libinput_props::DeviceConfigCancelToken, + ) -> Result< + crate::xinput::libinput_props::DeviceConfigStart, + crate::xinput::libinput_props::DeviceConfigError, + > { + self.started_device_configs.push((source, change)); + self.device_config_cancel_tokens.push(cancel); + self.device_config_start_results.pop_front().unwrap_or(Ok( + crate::xinput::libinput_props::DeviceConfigStart::Applied, + )) } fn signal_present_wake(&mut self, present_id: u64) { @@ -958,12 +1202,11 @@ impl Backend for RecordingBackend { .unwrap_or(self.present_absolute_vblank_arm_supported) } - fn arm_present_absolute_vblank(&mut self, crtc_id: u32, targets: &[u64]) -> io::Result { - self.armed_absolute_vblank_crtcs.push(crtc_id); - self.armed_absolute_vblank_targets.push(targets.to_vec()); - match self.arm_present_absolute_vblank_result { - None => Ok(targets.len()), - Some(Ok(n)) => Ok(n), + fn arm_present_shared_wake(&mut self, crtc_id: u32) -> io::Result { + self.armed_shared_wake_crtcs.push(crtc_id); + match self.arm_present_shared_wake_result { + None => Ok(true), + Some(Ok(armed)) => Ok(armed), Some(Err(kind)) => Err(io::Error::from(kind)), } } @@ -1067,6 +1310,12 @@ impl Backend for RecordingBackend { None } + fn set_locked_mods(&mut self, affect: u8, values: u8) { + let (_, base, latched, locked) = self.xkb_mods; + let locked = (locked & !affect) | values; + self.xkb_mods = (base | latched | locked, base, latched, locked); + } + fn current_xkb_mods(&self) -> (u8, u8, u8, u8) { self.xkb_mods } @@ -1111,6 +1360,10 @@ impl Backend for RecordingBackend { Ok(()) } + fn reset_input_session(&mut self, _old_state: &mut crate::server::ServerState) { + self.record(RecordedCall::ResetInputSession); + } + fn on_host_input( &mut self, _state: &mut crate::server::ServerState, @@ -1120,6 +1373,26 @@ impl Backend for RecordingBackend { let (key, repeat) = match ev { HostInputEvent::Key(key) => (key, false), HostInputEvent::KeyRepeat(key) => (key, true), + HostInputEvent::PointerMotion { x, y, .. } => { + self.record(RecordedCall::HostPointer { + x, + y, + button: 0, + pressed: false, + }); + return; + } + HostInputEvent::PointerButton { + button, pressed, .. + } => { + self.record(RecordedCall::HostPointer { + x: 0, + y: 0, + button, + pressed, + }); + return; + } _ => return, }; self.record(RecordedCall::HostKey { @@ -1153,6 +1426,22 @@ impl Backend for RecordingBackend { fn before_block(&mut self) { self.before_block_count .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if let Some(out) = self.host_display_out.as_mut() { + out.flush(); + } + } + + fn on_host_display_ready(&mut self, _state: &mut crate::server::ServerState) -> bool { + if let Some(out) = self.host_display_out.as_mut() { + out.flush(); + } + true + } + + fn host_display_wants_writable(&self) -> bool { + self.host_display_out + .as_ref() + .is_some_and(|out| !out.pending.is_empty()) } fn set_provider_output_source( @@ -1190,7 +1479,57 @@ impl Backend for RecordingBackend { x, y, }); - Ok(false) + if self.apply_crtc_configs { + self.applied_crtc_config = Some((output_id, mode, x, y)); + } + Ok(self.apply_crtc_configs) + } + + fn refresh_randr_state_set_time( + &mut self, + state: &mut crate::server::ServerState, + set_time: u32, + ) { + let Some((output_id, mode, x, y)) = self.applied_crtc_config.take() else { + return; + }; + let prev = &state.randr; + let mut outputs = prev.outputs.clone(); + if let Some(output) = outputs.iter_mut().find(|o| o.output_id == output_id) { + let resolved = mode.and_then(|m| { + prev.mode_table.iter().find(|t| { + output.mode_ids.contains(&t.mode_id) + && (t.width, t.height, t.vrefresh) == (m.width, m.height, m.vrefresh) + }) + }); + // An off KMS output reports mode 0 at 0,0 with no size. + let (mode_id, width, height, vrefresh) = + resolved.map_or((0, 0, 0, 0), |m| (m.mode_id, m.width, m.height, m.vrefresh)); + let (x, y) = if resolved.is_some() { (x, y) } else { (0, 0) }; + output.mode_id = mode_id; + output.width = width; + output.height = height; + output.vrefresh = vrefresh; + output.x = i16::try_from(x).unwrap_or(i16::MAX); + output.y = i16::try_from(y).unwrap_or(i16::MAX); + } + let screen = ( + prev.screen_width, + prev.screen_height, + prev.width_mm, + prev.height_mm, + ); + let transforms = prev.crtc_transforms(); + let mode_table = prev.mode_table.clone(); + state.randr = + crate::randr::RandrState::from_outputs_with_modes(set_time, outputs, mode_table); + state.randr.restore_crtc_transforms(transforms); + ( + state.randr.screen_width, + state.randr.screen_height, + state.randr.width_mm, + state.randr.height_mm, + ) = screen; } fn begin_crtc_config( @@ -1233,6 +1572,47 @@ impl Backend for RecordingBackend { self.crtc_config_results.remove(&token); } + fn dri3_begin_export_pixmap_buffers( + &mut self, + host_xid: u32, + ) -> io::Result { + match self.pending_dri3_export.take() { + Some(token) => Ok(crate::backend::Dri3ExportBegin::Pending(token)), + None => self + .dri3_export_pixmap_buffers(host_xid) + .map(crate::backend::Dri3ExportBegin::Ready), + } + } + + fn drain_ready_dri3_exports(&mut self) -> Vec { + std::mem::take(&mut self.ready_dri3_exports) + } + + fn finish_dri3_export( + &mut self, + token: crate::backend::Dri3ExportToken, + ) -> io::Result { + self.finished_dri3_exports.push(token); + if self.failed_dri3_exports.contains(&token) { + return Err(io::Error::other("scripted deferred export failure")); + } + Ok(crate::backend::Dri3PixmapExport { + size: 64 * 4 * 16, + width: 64, + height: 16, + stride: 64 * 4, + offset: 0, + depth: 24, + bpp: 32, + modifier: 0, + fd: std::fs::File::open("/dev/null")?.into(), + }) + } + + fn release_dri3_export(&mut self, token: crate::backend::Dri3ExportToken) { + self.released_dri3_exports.push(token); + } + fn set_crtc_gamma( &mut self, crtc: u32, @@ -1254,6 +1634,14 @@ impl Backend for RecordingBackend { (ramp.clone(), ramp.clone(), ramp) } + fn set_vidmode_gamma( + &mut self, + table: Option<&crate::backend::gamma::VidModeGammaTable>, + ) -> io::Result<()> { + self.vidmode_gamma = table.cloned(); + Ok(()) + } + fn probe_input_devices(&mut self, state: &mut crate::server::ServerState) -> usize { // Mirror the KMS backend's bounded-drain contract over the // test-configured `probe_rounds`: at most `PROBE_MAX_ROUNDS` @@ -1278,7 +1666,7 @@ impl Backend for RecordingBackend { empty_rounds = 0; for info in batch { seeded += 1; - state.xi_seed_touchpad(&info); + state.xi_register_source(&info); } } self.probe_rounds_run.set(rounds_run); @@ -1349,8 +1737,19 @@ impl Backend for RecordingBackend { &mut self, _origin: Option, host_xid: u32, + background: crate::backend::RealizeBackground, ) -> io::Result<()> { - self.record(RecordedCall::RealizeWindowStorage(host_xid)); + self.record(match background { + crate::backend::RealizeBackground::Paint => { + RecordedCall::RealizeWindowStorage(host_xid) + } + crate::backend::RealizeBackground::Deferred => { + RecordedCall::RealizeWindowStorageDeferred(host_xid) + } + crate::backend::RealizeBackground::Inhibited => { + RecordedCall::RealizeWindowStorageUnpainted(host_xid) + } + }); Ok(()) } @@ -1480,6 +1879,55 @@ impl Backend for RecordingBackend { Ok(()) } + fn reallocate_redirected_backing( + &mut self, + _origin: Option, + host_window: WindowHandle, + old: PixmapHandle, + width: u16, + height: u16, + depth: u8, + ) -> io::Result { + self.record(RecordedCall::ReallocateRedirectedBacking { + host_window: host_window.as_raw(), + old: old.as_raw(), + width, + height, + depth, + }); + if self.reallocate_fails { + return Err(io::Error::other("reallocate_fails")); + } + let xid = self.allocate_handle(); + Ok(PixmapHandle::from_raw_panicking(xid)) + } + + fn paint_window_border_rects( + &mut self, + _origin: Option, + host_xid: u32, + rects: &[yserver_protocol::x11::xfixes::RegionRect], + ) -> io::Result<()> { + self.record(RecordedCall::PaintWindowBorderRects { + host_xid, + rects: rects.to_vec(), + }); + Ok(()) + } + + fn move_subwindows_for_gravity( + &mut self, + _origin: Option, + moves: &[(u32, i16, i16)], + carry_from: Option, + ) -> io::Result<()> { + self.record(RecordedCall::MoveSubwindowsForGravity { + moves: moves.to_vec(), + carry_from: carry_from.map(PixmapHandle::as_raw), + }); + Ok(()) + } + fn retain_backing_storage( &mut self, _origin: Option, @@ -1543,13 +1991,16 @@ impl Backend for RecordingBackend { width: u16, height: u16, ) -> io::Result { - let xid = self.allocate_handle(); - self.live_pixmaps.insert(xid); self.record(RecordedCall::CreatePixmap { depth, width, height, }); + if self.create_pixmap_fails { + return Err(io::Error::other("create_pixmap failure injected")); + } + let xid = self.allocate_handle(); + self.live_pixmaps.insert(xid); Ok(PixmapHandle::from_raw_panicking(xid)) } @@ -1564,8 +2015,11 @@ impl Backend for RecordingBackend { _origin: Option, name: &str, ) -> io::Result<(FontHandle, FontMetrics)> { - let xid = self.allocate_handle(); self.record(RecordedCall::OpenFont(name.to_string())); + if let Some(kind) = self.fail_open_font.take() { + return Err(io::Error::from(kind)); + } + let xid = self.allocate_handle(); // FontMetrics is private to the protocol crate; return a Default-ish // value via Default::default(). If FontMetrics has no Default we fall // back to a zero-initialised one in the unimplemented branch below. @@ -1620,6 +2074,11 @@ impl Backend for RecordingBackend { Ok(()) } + fn free_cursor(&mut self, _origin: Option, host_xid: u32) -> io::Result<()> { + self.record(RecordedCall::FreeCursor(host_xid)); + Ok(()) + } + fn define_cursor( &mut self, _origin: Option, @@ -1866,21 +2325,23 @@ impl Backend for RecordingBackend { fn poly_point( &mut self, _origin: Option, - _host_xid: u32, + host_xid: u32, _foreground: u32, _coordinate_mode: u8, _points: &[u8], ) -> io::Result<()> { - unimplemented!("RecordingBackend: poly_point") + self.record(RecordedCall::PolyPoint { host_xid }); + Ok(()) } fn poly_fill_rectangle( &mut self, _origin: Option, - _host_xid: u32, + host_xid: u32, _foreground: u32, _rectangles: &[u8], ) -> io::Result<()> { + self.record(RecordedCall::PolyFillRectangle { host_xid }); Ok(()) } @@ -1927,17 +2388,25 @@ impl Backend for RecordingBackend { width, height, }); + if self.fail_fill_rectangle { + return Err(io::Error::other("fill_rectangle failure injected")); + } Ok(()) } fn poly_text8( &mut self, _origin: Option, - _host_xid: u32, - _foreground: u32, - _body: &[u8], + host_xid: u32, + foreground: u32, + body: &[u8], ) -> io::Result<()> { - unimplemented!("RecordingBackend: poly_text8") + self.record(RecordedCall::PolyText8 { + host_xid, + foreground, + body: body.to_vec(), + }); + Ok(()) } fn poly_text16( @@ -1982,8 +2451,8 @@ impl Backend for RecordingBackend { _origin: Option, host_drawable: AnyHandle, _ynest_format: u32, - _value_mask: u32, - _values: &[u8], + value_mask: u32, + values: &[u8], ) -> io::Result> { if self.render_create_picture_fails { return Ok(None); @@ -1992,6 +2461,8 @@ impl Backend for RecordingBackend { self.record(RecordedCall::RenderCreatePicture { host_drawable, host_pic, + value_mask, + values: values.to_vec(), }); Ok(PictureHandle::from_raw(host_pic)) } @@ -1999,9 +2470,13 @@ impl Backend for RecordingBackend { fn render_change_picture( &mut self, _origin: Option, - _host_pic: u32, - _body: &[u8], + host_pic: u32, + body: &[u8], ) -> io::Result<()> { + self.record(RecordedCall::RenderChangePicture { + host_pic, + body: body.to_vec(), + }); Ok(()) } @@ -2019,7 +2494,9 @@ impl Backend for RecordingBackend { _origin: Option, _ynest_format: u32, ) -> io::Result> { - Ok(None) + Ok(self + .render_create_glyphset_returns_handle + .then(|| GlyphSetHandle::from_raw_panicking(self.allocate_handle()))) } fn render_free_glyphset( @@ -2071,18 +2548,31 @@ impl Backend for RecordingBackend { fn render_composite_glyphs( &mut self, _origin: Option, - _minor: u8, - _op: u8, - _host_src: u32, - _host_dst: u32, - _mask_fmt: u32, - _host_gs: u32, - _src_x: i16, - _src_y: i16, - _items: &[u8], - _x_off: i16, - _y_off: i16, + minor: u8, + op: u8, + host_src: u32, + host_dst: u32, + mask_fmt: u32, + host_gs: u32, + src_x: i16, + src_y: i16, + items: &[u8], + x_off: i16, + y_off: i16, ) -> io::Result> { + self.record(RecordedCall::RenderCompositeGlyphs { + minor, + op, + host_src, + host_dst, + mask_fmt, + host_gs, + src_x, + src_y, + items: items.to_vec(), + x_off, + y_off, + }); Ok(self.render_return_region.clone()) } @@ -2315,12 +2805,17 @@ impl Backend for RecordingBackend { Ok((0, Vec::new())) } - /// COW materialize edge (core 0 → 1). Core guarantees no COW is live - /// when this runs, so it is an unconditional materialize. + /// COW materialize: core calls this only with no core COW record, so + /// a live COW here must be a deferred retirement, which is re-adopted. fn get_overlay_window(&mut self, _origin: Option) -> io::Result { if self.cow_materialize_fails { return Err(io::Error::other("test-injected COW materialize failure")); } + assert!( + !self.cow_materialized || self.cow_release_deferred, + "get_overlay_window with a live, undeferred COW: core and backend drifted" + ); + self.cow_release_deferred = false; self.cow_materialized = true; Ok(true) } @@ -2337,21 +2832,30 @@ impl Backend for RecordingBackend { } } - /// COW teardown edge (core 1 → 0). Always a final teardown; clears - /// `cow_materialized` so `cow_host_xid` reverts to `None`. On - /// injected failure the overlay stays up, as `KmsBackend`'s does when - /// the unflip shadow cannot be allocated. - fn release_overlay_window(&mut self, _origin: Option) -> io::Result { + /// The fallible half of the COW teardown. On injected failure the + /// overlay stays up, as `KmsBackend`'s does when the unflip shadow + /// cannot be made. + fn prepare_overlay_release(&mut self, _origin: Option) -> io::Result { if !self.cow_materialized { return Ok(false); } if self.cow_teardown_fails { return Err(io::Error::other("test-injected COW teardown failure")); } - self.cow_materialized = false; Ok(true) } + /// Retire now (`cow_host_xid` reverts to `None`), or defer when + /// `cow_release_defers` is set. + fn retire_overlay_window(&mut self, _origin: Option) { + self.record(RecordedCall::RetireOverlayWindow); + if self.cow_release_defers { + self.cow_release_deferred = true; + } else { + self.cow_materialized = false; + } + } + fn dpms_capable(&self) -> bool { // Test default: pretend we can drive DPMS so tests can // exercise the wake/transition path. Individual tests @@ -2410,6 +2914,34 @@ impl Backend for RecordingBackend { } } +/// A rootless host's display connection, for loop tests: what is `pending` +/// goes to `stream` (non-blocking) as far as it takes at each flush, before +/// the loop blocks and when the connection is ready, as a host's flush does. +#[derive(Debug)] +pub struct HostDisplayOut { + pub stream: std::os::unix::net::UnixStream, + pub pending: Vec, + /// Flushes so far. + pub flushes: std::sync::Arc, +} + +impl HostDisplayOut { + fn flush(&mut self) { + use std::io::Write as _; + self.flushes + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + while !self.pending.is_empty() { + match self.stream.write(&self.pending) { + Ok(n) => { + self.pending.drain(..n); + } + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(_) => break, + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/yserver-core/src/backend/trait_def.rs b/crates/yserver-core/src/backend/trait_def.rs index a558db069..a3aa557a9 100644 --- a/crates/yserver-core/src/backend/trait_def.rs +++ b/crates/yserver-core/src/backend/trait_def.rs @@ -42,6 +42,19 @@ pub struct ModeSpec { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct CrtcConfigToken(pub u64); +/// What `Backend::realize_window_storage` does about the background. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RealizeBackground { + /// Paint it now (`miPaintWindow` on realize). + Paint, + /// The core paints it once the redirect backing the window paints into + /// exists; until then the storage shows what is underneath. + Deferred, + /// Never: Xorg's `inhibitBGPaint` (`mi/miexpose.c:435`). The storage shows + /// what is underneath, as for a None background. + Inhibited, +} + /// Initial disposition of a client-driven CRTC configuration request. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CrtcConfigApply { @@ -81,6 +94,10 @@ pub enum BackendFdKind { /// fences which gate a copied scanout path. Readiness means work rendered /// on the source GPU may advance to the sink-GPU copy. ScanoutRenderCompletion, + /// A rootless host's connection to its window system, served on the + /// core thread (a Wayland compositor's socket). Readiness drives + /// `Backend::on_host_display_ready`. + HostDisplay, } /// Result of arming the implicit producer fence for a `PresentPixmap` @@ -101,6 +118,8 @@ pub enum PresentSourceWait { #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct PresentScanoutCandidate { pub client_id: u32, + /// Local peer PID for the Presenting X client, when the platform exposes it. + pub client_pid: Option, pub present_id: u64, /// RANDR CRTC XID selected for this Present. `0` is the synthetic /// headless domain used when no output is enabled. @@ -108,6 +127,9 @@ pub struct PresentScanoutCandidate { pub crtc_epoch: u64, pub src_pixmap_xid: u32, pub dst_window_xid: u32, + /// The presented window has `_VARIABLE_REFRESH` as CARDINAL/32 with + /// at least one item and a first value of 1. + pub variable_refresh: bool, pub src_host_xid: u32, pub paint_dst_host_xid: u32, pub completion_dst_host_xid: u32, @@ -176,6 +198,9 @@ pub struct PresentCaps { /// false, the path selector short-circuits to `Copy` regardless /// of pixmap/window match per design §3.3.1. pub flip_path: bool, + /// The window's KMS device supports `DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP`. + /// Advertises Present's Async capability independently of `flip_path`. + pub async_flip: bool, /// `DRM_MODE_ATOMIC_NONBLOCK` accepted by the kernel — the /// `PresentOptionAsyncMayTear` bit is honourable. When false, /// the bit is **silently cleared** on incoming requests (per @@ -191,7 +216,7 @@ pub struct PresentCaps { impl PresentCaps { /// Encode as a `u32` for the `QueryCapabilities` reply. /// `presentproto` bit assignments: - /// - `Async` (0x1) — Phase 4.2 advertises if `flip_path`. + /// - `Async` (0x1) — advertised if `flip_path` or `async_flip`. /// - `Fence` (0x2) — XSync `Fence` always supported once /// DRI3 fence_fd cap is true; Phase 4.2 always advertises. /// - `UST` (0x4) — vblank UST timestamps; Phase 4.1's @@ -206,7 +231,7 @@ impl PresentCaps { const ASYNC_MAY_TEAR: u32 = 0x8; const SYNCOBJ: u32 = 0x10; let mut out = FENCE | UST; - if self.flip_path { + if self.flip_path || self.async_flip { out |= ASYNC; } if self.async_may_tear { @@ -331,11 +356,26 @@ mod present_caps_tests { fn full_caps_set_all_bits() { let caps = PresentCaps { flip_path: true, + async_flip: true, async_may_tear: true, syncobj: true, }; assert_eq!(caps.encode(), 0x1 | 0x2 | 0x4 | 0x8 | 0x10); } + + #[test] + fn present_caps_encode_async_bit_from_async_flip() { + // Mutation killed: dropping `async_flip` from `encode` leaves Async unset. + let caps = PresentCaps { + flip_path: false, + async_flip: true, + async_may_tear: false, + syncobj: false, + }; + + assert_eq!(caps.encode() & 0x1, 0x1, "Async advertised for async flip"); + assert_eq!(caps.encode() & 0x8, 0, "AsyncMayTear stays unset"); + } } /// DRI3 capability surface. Phase 4.2 design §4. `version == (0, 0)` @@ -427,7 +467,24 @@ pub struct Dri3PixmapExport { pub depth: u8, pub bpp: u8, pub modifier: u64, - pub fd: std::os::fd::OwnedFd, + pub fd: crate::fd::OwnedFd, +} + +/// Opaque identity of a DRI3 export the backend deferred. +/// +/// Tokens stay unique until the core calls [`Backend::release_dri3_export`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Dri3ExportToken(pub u64); + +/// How a DRI3 pixmap export began. +#[derive(Debug)] +pub enum Dri3ExportBegin { + /// Exported now. + Ready(Dri3PixmapExport), + /// The pixmap's storage is still scanned out. The core parks the client + /// and finishes the token once [`Backend::drain_ready_dri3_exports`] + /// returns it. + Pending(Dri3ExportToken), } /// Stage 5 Task 6.1: opaque handle to a DRI3 xshmfence's underlying @@ -461,11 +518,7 @@ pub trait SyncobjHandle: std::fmt::Debug + Send + Sync { /// completes. This is the PresentPixmapSynced Copy-path operation used /// by Xorg/Xwayland: clients may queue dependent work without reusing the /// pixmap before the server's GPU read has retired. - fn import_sync_file( - &self, - _value: u64, - _fd: std::os::fd::BorrowedFd<'_>, - ) -> std::io::Result<()> { + fn import_sync_file(&self, _value: u64, _fd: crate::fd::BorrowedFd<'_>) -> std::io::Result<()> { Err(std::io::Error::new( std::io::ErrorKind::Unsupported, "sync_file import unsupported", @@ -634,6 +687,10 @@ pub trait Backend { /// The live RandR provider set (`RRGetProviders`). Empty for /// backends that expose no provider topology. fn randr_providers(&mut self) -> Vec; + /// What the CRTCs can do and the screen size range. + fn randr_limits(&self) -> crate::randr::RandrLimits { + crate::randr::RandrLimits::default() + } fn render_opcode(&self) -> Option; fn xkb_opcode(&self) -> Option; fn xkb_info(&self) -> Option<(u8, u8, u8)>; @@ -645,6 +702,17 @@ pub trait Backend { fn current_group(&self) -> u8 { 0 } + /// Lock or unlock the real modifiers named by `affect` to the matching + /// bits of `values` — `XkbLatchLockState`'s affectModLocks/modLocks, + /// which is how `numlockx` (`XkbLockModifiers`) turns NumLock on. + /// + /// `values` has no bits outside `affect` (the request is BadMatch + /// otherwise), so implementations merge with `(old & !affect) | values`. + /// They own the lock-LED side effect too: locking Num_Lock/Caps_Lock + /// this way must light the keyboard LED exactly as pressing the key does. + /// + /// Default no-op for backends without an XKB state machine. + fn set_locked_mods(&mut self, _affect: u8, _values: u8) {} /// The current real-modifier state as `(effective, base, latched, /// locked)` masks, read from the live xkb state. Drives /// `XkbStateNotify` so libxkbcommon clients track modifier changes. @@ -652,6 +720,11 @@ pub trait Backend { fn current_xkb_mods(&self) -> (u8, u8, u8, u8) { (0, 0, 0, 0) } + /// The core keyboard's lit XKB indicators and the defined ones, `(Xorg + /// sli->effectiveState, namesPresent | mapsPresent)`. Default none. + fn xkb_indicators(&mut self) -> (u32, u32) { + (0, 0) + } fn composite_opcode(&self) -> Option; fn render_format_for_ynest_id(&self, ynest_fmt: u32) -> Option; fn ping(&mut self, origin: Option) -> io::Result<()>; @@ -666,10 +739,25 @@ pub trait Backend { /// (KMS) and F2 (host-X11); inert until then. fn on_host_input(&mut self, state: &mut ServerState, ev: HostInputEvent); + /// Reconcile backend-owned per-device state after XI slave attachment + /// changes. XKB implementations use this to create a floating slave's + /// independent state or retire it when the slave is attached again. + /// Backends without per-device keyboard state need no work. + fn sync_floating_keyboard_states(&mut self, _state: &ServerState) {} + + /// Release holds owned by one still-enabled physical XI facet before a + /// client-driven Device Enabled disable is committed. Backends without + /// host-device state have no cleanup to perform. + fn disable_xi_facet(&mut self, _state: &mut ServerState, _device_id: u16) {} + + /// Reconcile backend-owned state after a client-driven XI facet enable. + /// The core has already restored the facet's role-derived home master. + fn enable_xi_facet(&mut self, _state: &mut ServerState, _device_id: u16) {} + /// `drm_fd` is readable. The backend should drain completion events from /// that exact DRM device and submit the next composite/flip. The fd is one /// returned by [`Backend::poll_fds`] with [`BackendFdKind::Drm`]. - fn on_page_flip_ready(&mut self, state: &mut ServerState, drm_fd: std::os::fd::RawFd); + fn on_page_flip_ready(&mut self, state: &mut ServerState, drm_fd: crate::fd::RawFd); /// The DRM hotplug monitor is readable. Default: no-op. fn on_display_hotplug(&mut self, _state: &mut ServerState) {} @@ -809,13 +897,35 @@ pub trait Backend { (Vec::new(), Vec::new(), Vec::new()) } + /// The screen's VidMode gamma table, under every CRTC's RANDR ramp + /// (Xorg's CMap gamma on modesetting): each CRTC's hardware LUT becomes + /// [`VidModeGammaTable::crtc_lut`] of its RANDR ramp, now, whenever + /// that ramp changes and whenever the CRTC is lit. `None` loads the + /// RANDR ramps alone. `get_crtc_gamma` keeps reporting the RANDR ramp. + /// Default: Ok(()) no-op, for a backend without gamma. + /// + /// [`VidModeGammaTable::crtc_lut`]: crate::backend::gamma::VidModeGammaTable::crtc_lut + fn set_vidmode_gamma( + &mut self, + _table: Option<&crate::backend::gamma::VidModeGammaTable>, + ) -> io::Result<()> { + Ok(()) + } + /// Refresh RANDR state after a successful `RRSetCrtcConfig`, setting /// `lastSetTime` to the client's request timestamp (0/CurrentTime /// already resolved to `now` by the caller). A CRTC set bumps /// `lastSetTime` but NOT `lastConfigTime` (the available config did - /// not change). Default no-op for nested/recording backends. + /// not change). Also after a host resize (`host_screen_resized`), with + /// the resize's timestamp. Default no-op for nested/recording backends. fn refresh_randr_state_set_time(&mut self, _state: &mut ServerState, _set_time: u32) {} + /// The RANDR layout changed (a CRTC set, a screen resize or a server + /// reset): take the CRTC transforms and root extent from `state.randr` + /// and move the pointer onto a CRTC (`RRPointerScreenConfigured`). + /// Default no-op. + fn randr_layout_changed(&mut self, _state: &mut ServerState) {} + /// Resize the logical (virtual) screen to `w`×`h`: reallocate the /// root + Composite-overlay backing storage and update the pointer /// clamp / logical extent. Default no-op `Ok(())` for nested @@ -833,6 +943,23 @@ pub trait Backend { /// Direct-mode VT release signal. Default no-op. fn on_vt_release(&mut self, _state: &mut ServerState) {} + /// Begin a direct-mode VT release before the core drains input-thread + /// configuration results. Return true only when a FIFO pause barrier was + /// queued; the core waits for its acknowledgement only in that case. + fn begin_vt_release(&mut self) -> bool { + false + } + + /// Finish the release after the core has consumed the input pause barrier. + /// Backends that only implement `on_vt_release` retain their old behavior. + fn finish_vt_release( + &mut self, + state: &mut ServerState, + _input_inventory: &crate::core_loop::input_inventory::InputInventory, + ) { + self.on_vt_release(state); + } + /// Direct-mode VT acquire signal. Default no-op. fn on_vt_acquire(&mut self, _state: &mut ServerState) {} @@ -845,6 +972,26 @@ pub trait Backend { /// input thread and never registers this fd. fn on_libinput_ready(&mut self, _state: &mut ServerState) {} + /// The rootless host's display connection is readable + /// ([`BackendFdKind::HostDisplay`]), or writable while + /// [`Backend::host_display_wants_writable`]: send what is queued, read + /// its events and act on them with `state` in hand. `false` when the window system closed the + /// connection, which ends the server as the loss of its only display + /// would. Default: `true`; only a host that registers the fd sees this. + fn on_host_display_ready(&mut self, _state: &mut ServerState) -> bool { + true + } + + /// The rootless host's display connection holds output its last flush + /// could not send, the socket being full. Asked each loop iteration + /// after [`Backend::before_block`]: while it is true the loop watches the + /// [`BackendFdKind::HostDisplay`] fd for writable as well as readable, + /// and its readiness comes as [`Backend::on_host_display_ready`], which + /// flushes. A client's output is watched the same way. Default: `false`. + fn host_display_wants_writable(&self) -> bool { + false + } + /// Called once per core-loop iteration (with `state`) so a backend can /// service time-based backend work that isn't tied to an fd readiness /// edge. The backend reports any deadline via [`Backend::next_wakeup`] so @@ -876,9 +1023,9 @@ pub trait Backend { /// from the main loop. On real hardware the desktop's clients can /// enumerate devices (`XIQueryDevice` / `XListInputDevices`) seconds /// before that burst lands, so they cache a plain pointer and never - /// recognise the touchpad (observed on M2/Asahi MATE: all four - /// libinput devices first processed ~2s AFTER the clients queried - /// device 4). + /// recognise the physical touchpad facet (observed on M2/Asahi MATE: + /// all four libinput devices first processed ~2s after clients queried + /// the registry's initial devices). /// /// Implementations MUST be bounded and non-blocking: if libinput has /// nothing yet, return immediately rather than waiting. Backends without @@ -890,10 +1037,9 @@ pub trait Backend { 0 } - /// Apply a decoded touchpad config change to the live input device - /// identified by `device_node`. `Ok` = applied (or nothing to apply - /// on this backend). `Err(Unsupported)` → BadMatch, `Err(Invalid)` - /// → BadValue. + /// Start applying a decoded libinput config change to the live input + /// source. `Applied` confirms synchronous application; `Pending(token)` + /// means the backend will report the actual setter result later. /// /// Default: no-op success — only backends that own a live libinput /// context write through to a device. @@ -903,12 +1049,16 @@ pub trait Backend { /// Returns `DeviceConfigError::Unsupported` when the setting isn't /// available on the addressed device, or `Invalid` when the value /// is out of range / not a legal one-hot. - fn apply_device_config( + fn start_device_config( &mut self, - _device_node: &str, + _source: crate::xinput::InputSourceId, _change: crate::xinput::libinput_props::DeviceConfigChange, - ) -> Result<(), crate::xinput::libinput_props::DeviceConfigError> { - Ok(()) + _cancel: crate::xinput::libinput_props::DeviceConfigCancelToken, + ) -> Result< + crate::xinput::libinput_props::DeviceConfigStart, + crate::xinput::libinput_props::DeviceConfigError, + > { + Ok(crate::xinput::libinput_props::DeviceConfigStart::Applied) } /// Hand the backend a core-channel sender so backend-originated shutdowns @@ -916,15 +1066,16 @@ pub trait Backend { /// Default: no-op. fn set_input_sender(&mut self, _sender: crate::core_loop::CoreSender) {} - /// Tell the backend that something that could affect on-screen - /// pixels has changed since the last composite. KMS uses this to - /// gate `composite_and_flip` so an idle server doesn't burn - /// vsync-paced composite cycles. Default is a no-op for backends - /// (e.g. host-X11) that don't drive their own composite loop. + /// Ask the next composite to re-inspect the scene after core-driven + /// paint outside request handling (Present execution, server reset). + /// Not called per request: backend calls that change on-screen pixels + /// or scene structure raise their own wake. Default is a no-op for + /// backends (e.g. host-X11) that don't drive their own composite loop. fn mark_dirty(&mut self) {} - /// Submit drawing that precedes a queued DamageNotify. The core invokes - /// this before the notification can drain to an external compositor. + /// Submit drawing before exposing its damage to an external compositor, + /// through DamageNotify or the Subtract/FetchRegion requests that retrieve + /// coalesced damage without another notification. /// Immediate-rendering backends keep the default no-op. fn flush_before_damage_notify(&mut self) {} @@ -950,6 +1101,23 @@ pub trait Backend { Ok(()) } + /// The platform posted `Message::PlatformEvent`: drain its queue. + /// Default no-op for backends whose platform never posts one. + fn on_platform_event(&mut self, _state: &mut ServerState) {} + + /// Rootless top-level events of this iteration (spec §4.1, §4.2), after the + /// Present drain and before `maybe_composite`. Default no-op. + fn on_rootless_events( + &mut self, + _state: &ServerState, + _events: &[crate::rootless::RootlessEvent], + ) { + } + + /// `state.clients` gained or lost an established client; `count` is + /// its new size. Default no-op. + fn note_client_count(&mut self, _count: usize) {} + /// Dump the current scanout buffer to a file in the process's /// cwd. Diagnostic-only — fired from `Message::DumpScanout` /// (Ctrl-Alt-Enter on KMS). Default no-op for backends that don't @@ -972,9 +1140,8 @@ pub trait Backend { false } - /// Notify the backend that a window property changed or was - /// deleted. KMS uses this to re-evaluate EWMH stack hints - /// (`_NET_WM_WINDOW_TYPE`, `_NET_WM_STATE`, `WM_TRANSIENT_FOR`). + /// Notify the backend that a window property changed or was deleted. + /// Platforms may use it to refresh policy tied to a live window. /// Default no-op. fn on_window_property_changed( &mut self, @@ -1111,6 +1278,20 @@ pub trait Backend { /// the destination disappeared). fn finish_present_source_wait(&mut self, _wait_id: u64) {} + /// Whether a Present that is not yet executed is scrapped (completed as + /// Skip) by a later one for the same window and target MSC, as Xorg's + /// `present_scmd.c` does ("don't bother doing the previous one if this + /// one will overwrite it in the same frame"). Default true. A backend + /// whose windows are another window system's says false, since that + /// window system -- not the X server -- decides which frame a refresh + /// shows, and copies each present in turn. Xwayland scraps no copy at + /// arrival (`xwl_present_pixmap`); what it does scrap is a flip queued + /// behind a pending one (`xwl_present_execute`'s mailbox handling), and + /// such a backend has no flips. + fn present_supersedes_same_msc(&self) -> bool { + true + } + /// A scanout pageflip is submitted and not yet retired. Used ONLY by /// the immediate-target arrival rule (spec §msc-due). Default false: /// non-KMS backends execute everything at arrival. @@ -1131,28 +1312,20 @@ pub trait Backend { fn present_crtc_clock_epoch(&self, _crtc_id: u32) -> u64 { 0 } - /// Kernel accepts absolute CRTC_QUEUE_SEQUENCE arming. Gates the - /// idle-display fallback to flip-driven-clock drivers. Default false. + /// Kernel accepts CRTC_QUEUE_SEQUENCE arming. Gates the idle-display + /// fallback to flip-driven-clock drivers. Default false. fn present_absolute_vblank_arm_supported(&self, _crtc_id: u32) -> bool { false } - /// Arm absolute vblank sequences for parked future-target presents. - /// Own per-CRTC target set; must not consume or suppress the - /// relative-1 idle arm. + /// Keep one tagged next-vblank wake outstanding for Present work on a + /// CRTC. The wake covers every Present target on that CRTC and is + /// independent of the untagged idle-vblank arm. /// - /// Returns the number of targets now **covered** by an in-flight arm - /// — newly issued or already armed from a prior call — not just - /// newly issued arms: the caller re-arms every iteration, and a - /// still-parked already-armed target must not read as failure. `0` - /// or `Err` means the caller must not park on this mechanism (no - /// targets, no outputs, arming unsupported/failed) and should fall - /// through to another due-execution trigger. Default `Ok(0)`. - fn arm_present_absolute_vblank( - &mut self, - _crtc_id: u32, - _targets: &[u64], - ) -> std::io::Result { - Ok(0) + /// Returns `true` when the tagged wake is already outstanding or was + /// newly armed. `false` means no wake is available; `Err` reports an + /// arming failure. Default `Ok(false)`. + fn arm_present_shared_wake(&mut self, _crtc_id: u32) -> std::io::Result { + Ok(false) } /// Display cannot scan out at all (VT-away OR DPMS-off). Gates the /// blackout flush. Default false. @@ -1172,7 +1345,7 @@ pub trait Backend { /// Raw fds the core's poller should watch on this backend's behalf. The /// core gives every entry a unique token and retains both the fd and its /// `BackendFdKind` for readiness dispatch. - fn poll_fds(&self) -> Vec<(std::os::fd::RawFd, BackendFdKind)>; + fn poll_fds(&self) -> Vec<(crate::fd::RawFd, BackendFdKind)>; /// Downcast to `Any` for backend-specific operations (e.g. KMS composite). fn as_any(&self) -> &dyn Any; @@ -1210,8 +1383,9 @@ pub trait Backend { &mut self, origin: Option, host_xid: u32, + background: RealizeBackground, ) -> io::Result<()> { - let _ = (origin, host_xid); + let _ = (origin, host_xid, background); Ok(()) } @@ -1345,6 +1519,80 @@ pub trait Backend { )) } + /// `miPaintWindow(PW_BORDER)` over `rects` of `host_xid`'s border, in + /// its content space (`mi/miexpose.c:445-470`). Default no-op. + /// + /// # Errors + /// + /// A failed fill. + fn paint_window_border_rects( + &mut self, + origin: Option, + host_xid: u32, + rects: &[yserver_protocol::x11::xfixes::RegionRect], + ) -> io::Result<()> { + let _ = (origin, host_xid, rects); + Ok(()) + } + + /// `compReallocPixmap` (composite/compalloc.c:670-712): give + /// `host_window` a new backing of `width x height`, seeded from its + /// parent, and move its route and reason-1 hold off `old`. The caller + /// keeps `old` retained; nothing is read back from window leaves. + /// + /// # Errors + /// + /// `Unsupported` by default. On error the window stays on `old`. + fn reallocate_redirected_backing( + &mut self, + origin: Option, + host_window: WindowHandle, + old: PixmapHandle, + width: u16, + height: u16, + depth: u8, + ) -> io::Result { + let _ = (origin, host_window, old, width, height, depth); + Err(io::Error::new( + io::ErrorKind::Unsupported, + "reallocate_redirected_backing not supported", + )) + } + + /// Move children repositioned by `win_gravity` (`(host_xid, x, y)`). + /// With `carry_from`, a child sharing its parent's backing takes its + /// pixels from that old backing (`compCopyWindow` from `pOldPixmap`, + /// composite/compwindow.c:489-528); otherwise each child moves as a + /// plain `configure_subwindow`. + /// + /// # Errors + /// + /// The first failing move. + fn move_subwindows_for_gravity( + &mut self, + origin: Option, + moves: &[(u32, i16, i16)], + carry_from: Option, + ) -> io::Result<()> { + let _ = carry_from; + for &(host_xid, x, y) in moves { + self.configure_subwindow( + origin, + host_xid, + crate::host_x11::HostSubwindowConfig { + x: Some(x), + y: Some(y), + width: None, + height: None, + border_width: None, + sibling: None, + stack_mode: None, + }, + )?; + } + Ok(()) + } + /// L2 plan B.6c: release a redirect's reason-1 hold on a /// backing pixmap. The backend decrements the alias registry's /// refcount and frees the underlying pixmap if no @@ -1574,14 +1822,14 @@ pub trait Backend { Ok(()) } - /// Composite Overlay Window materialization — the **0 → 1 claim - /// edge**, and nothing else. + /// Composite Overlay Window materialization. /// /// Core owns the claim list ([`crate::server::ServerState::cow_claims`]) /// and is the single authority on how many holds the overlay has; /// **the backend must not count**. Two counters that can disagree is /// what leaked the overlay across a compositor crash. Core calls this - /// only when the claim list goes empty → non-empty, so an + /// from GetOverlayWindow whenever the core COW record is absent, + /// whatever the claim count (Xorg `compext.c:303`), so an /// implementation may assume no COW of its own is live (bar a /// physical teardown it deferred behind direct scanout, which it /// re-adopts here). @@ -1620,40 +1868,43 @@ pub trait Backend { Ok(false) } - /// Composite Overlay Window teardown — the **1 → 0 claim edge**, and - /// nothing else. + /// Composite Overlay Window teardown, part 1: everything that can fail. /// - /// The mirror of [`Backend::get_overlay_window`]: core calls this - /// only when the last claim is about to go, so this is always a final - /// teardown. Non-final Releases never reach the backend, and the - /// backend keeps no count of its own. + /// Core calls this when a destroy plan contains the COW (the last + /// ReleaseOverlayWindow, `DestroyWindow(COW)`, `DestroySubwindows(root)`), + /// before anything of the destroy happens, and follows `Ok(true)` with + /// [`Backend::retire_overlay_window`] in the same request. /// - /// Free the storage and unregister the `windows` entry plus the COW's - /// slot in `top_level_order` — the mirror of what the materialize - /// edge installs. Single hook owns the lifecycle in both directions; - /// there is no separate `destroy_cow` API. + /// Returns `Ok(false)` when this backend has no materialized COW (v1, + /// ynest, the trait default): core then gives the COW the ordinary + /// backend teardown. /// - /// Returns `Ok(true)` when the backend tore a COW down, so core - /// mirrors it with `destroy_cow_resource()`: the resources-side - /// Window record and its slot in `root.children` come down together - /// with the backend storage. `Ok(false)` means this backend has no - /// COW implementation (v1, ynest, the trait default) or had nothing - /// materialized, so there is nothing for core to mirror down. - /// - /// On `Err` **the overlay is still up**, and core keeps the caller's - /// claim: the claim is what keeps the overlay alive, so dropping it - /// before the overlay is gone is precisely the leak. + /// On `Err` nothing changed: the overlay is still up, and core answers + /// `BadAlloc` or keeps the caller's claim. An `Ok` that is never + /// followed by the retirement must leave nothing that needs undoing. /// /// # Errors /// - /// Backend-internal failures — on `KmsBackend`, the shadow-buffer - /// allocation that must succeed before a scanned-out buffer can be - /// released. - fn release_overlay_window(&mut self, origin: Option) -> io::Result { + /// Backend-internal failures — on `KmsBackend`, the unflip shadow + /// (`materialize_direct_shadow_for_unflip`) that must exist before a + /// scanned-out buffer can be released. + fn prepare_overlay_release(&mut self, origin: Option) -> io::Result { let _ = origin; Ok(false) } + /// Composite Overlay Window teardown, part 2: cannot fail. + /// + /// Called by the destroy executor in place of `destroy_subwindow` for + /// the COW, after its children's backend teardown and only after + /// [`Backend::prepare_overlay_release`] returned `Ok(true)`. Frees the + /// storage and the `windows` entry, or defers both behind direct + /// scanout until the composed replacement retires; a + /// [`Backend::get_overlay_window`] before then re-adopts them. + fn retire_overlay_window(&mut self, origin: Option) { + let _ = origin; + } + /// Stage 4e — return the host xid the backend has assigned to the /// COW, or `None` if the COW is not currently materialized. The /// core handler reads this to populate the resources COW record's @@ -2129,6 +2380,13 @@ pub trait Backend { None } + /// Whether a Picture's subwindow mode is IncludeInferiors, which + /// keeps a destination's children inside its clip + /// (`miValidatePicture`, `render/mipict.c:114-118`). + fn picture_includes_inferiors(&self, _host_pic: u32) -> bool { + false + } + fn render_change_picture( &mut self, origin: Option, @@ -2312,7 +2570,7 @@ pub trait Backend { /// /// `_drawable` is currently unused (single-GPU only — the fd is /// the same regardless of which drawable triggered the request). - fn dri3_open(&mut self, _drawable: u32) -> io::Result { + fn dri3_open(&mut self, _drawable: u32) -> io::Result { Err(io::Error::other("DRI3 unsupported on this backend")) } @@ -2326,6 +2584,12 @@ pub trait Backend { Dri3Caps::unsupported() } + /// Whether GLX (indirect, server-synthesised) is advertised. A platform + /// without a GL client stack to talk to turns it off. + fn glx_available(&self) -> bool { + true + } + /// Import a client-supplied dma-buf as a server-owned pixmap and /// return the host xid the dispatcher should bind. The `fd` /// ownership transfers into the backend on success; on Err the @@ -2343,7 +2607,7 @@ pub trait Backend { #[allow(clippy::too_many_arguments)] fn dri3_import_pixmap( &mut self, - _fd: std::os::fd::OwnedFd, + _fd: crate::fd::OwnedFd, _width: u16, _height: u16, _stride: u32, @@ -2378,7 +2642,7 @@ pub trait Backend { fn dri3_export_pixmap( &mut self, _host_xid: u32, - ) -> io::Result<(u32, u16, u16, u16, u8, u8, std::os::fd::OwnedFd)> { + ) -> io::Result<(u32, u16, u16, u16, u8, u8, crate::fd::OwnedFd)> { Err(io::Error::other("DRI3 export unsupported on this backend")) } @@ -2395,12 +2659,35 @@ pub trait Backend { )) } - /// Import a `sync_file` fd as the backing of an XSync `Fence` - /// resource. The fd ownership transfers into the backend; on - /// success the backend owns a `VkSemaphore` keyed by `fence_xid`. + /// Begin a DRI3 export for `BufferFromPixmap` / `BuffersFromPixmap`. + /// A backend may defer it while the pixmap is on a CRTC. + fn dri3_begin_export_pixmap_buffers(&mut self, host_xid: u32) -> io::Result { + self.dri3_export_pixmap_buffers(host_xid) + .map(Dri3ExportBegin::Ready) + } + + /// Deferred DRI3 exports whose result is ready for + /// [`Backend::finish_dri3_export`]. + fn drain_ready_dri3_exports(&mut self) -> Vec { + Vec::new() + } + + /// The result of a ready deferred DRI3 export. + fn finish_dri3_export(&mut self, _token: Dri3ExportToken) -> io::Result { + Err(io::Error::other("unknown deferred DRI3 export token")) + } + + /// The core is done with `token`: after its reply or error, or because + /// its client went away. + fn release_dri3_export(&mut self, _token: Dri3ExportToken) {} + + /// Import a DRI3 FenceFromFD fd (an xshmfence, or a `sync_file`) as + /// the backing of an XSync `Fence` resource keyed by `fence_xid`. The + /// fd ownership transfers into the backend. An error is the client's + /// BadValue, and no fence is made. /// /// Default impl is unsupported. - fn dri3_fence_from_fd(&mut self, _fence_xid: u32, _fd: std::os::fd::OwnedFd) -> io::Result<()> { + fn dri3_fence_from_fd(&mut self, _fence_xid: u32, _fd: crate::fd::OwnedFd) -> io::Result<()> { Err(io::Error::other("DRI3 FenceFromFD unsupported")) } @@ -2409,7 +2696,7 @@ pub trait Backend { /// caller. /// /// Default impl is unsupported. - fn dri3_fd_from_fence(&mut self, _fence_xid: u32) -> io::Result { + fn dri3_fd_from_fence(&mut self, _fence_xid: u32) -> io::Result { Err(io::Error::other("DRI3 FDFromFence unsupported")) } @@ -2422,7 +2709,7 @@ pub trait Backend { &mut self, _client_id: yserver_protocol::x11::ClientId, _syncobj_xid: u32, - _fd: std::os::fd::OwnedFd, + _fd: crate::fd::OwnedFd, ) -> io::Result<()> { Err(io::Error::other("DRI3 ImportSyncobj unsupported")) } @@ -2531,8 +2818,9 @@ pub trait Backend { /// Per-window Present capability surface. Default impl: all-false /// (Copy-only, no syncobj). KmsBackend overrides; - /// `HostX11Backend` and `RecordingBackend` keep the default. - fn present_capabilities(&self, _window: u32) -> PresentCaps { + /// `HostX11Backend` and `RecordingBackend` keep the default. Non-KMS + /// backends ignore `crtc_id`. + fn present_capabilities(&self, _window: u32, _crtc_id: u32) -> PresentCaps { PresentCaps::default() } @@ -2663,6 +2951,13 @@ pub trait Backend { /// contribution here. Default no-op. fn client_disconnected(&mut self, _client_id: yserver_protocol::x11::ClientId) {} + /// Retire state held by the old input session immediately before a + /// server-generation reset destroys its clients and replaces its XI + /// registry. Backends whose input state lives entirely in `ServerState` + /// need no extra work; stateful backends can route releases while the old + /// facets and resources are still present. Default no-op. + fn reset_input_session(&mut self, _old_state: &mut ServerState) {} + /// GLX-TFP Task 3.5: promote the backing for `host_xid` to /// dma-buf-exportable storage (idempotent) WITHOUT touching the /// lifetime refcount (`glx_refs`) or allocating/exporting a dmabuf fd. @@ -2763,6 +3058,13 @@ pub trait Backend { /// Default no-op for backends that draw no sprite of their own. fn set_cursor_hidden(&mut self, _hidden: bool) {} + /// Whether the cursor the user sees shows nothing: the `None` cursor, + /// XFIXES `HideCursor`, or a cursor whose every pixel is transparent. + /// Rootless mode's pointer lock reads it (`rootless/lock.rs`). + fn displayed_cursor_hidden(&self) -> bool { + false + } + /// Take the pending "the effective cursor changed" report, if the sprite /// switched to a different cursor since the last call. Drained by the /// core after every request and loop iteration to send XFIXES @@ -2831,13 +3133,20 @@ pub trait Backend { /// its test window ("Expected event not received" en masse). fn warp_pointer_root(&mut self, _state: &mut ServerState, _x: i32, _y: i32) {} + /// The window tree changed under a pointer that did not move: a map, + /// unmap, configure, restack, reparent, shape change or a destroy (called + /// before the dying windows leave the tree). Re-resolve the window under + /// the pointer and fan out the crossings within the request, as Xorg's + /// `WindowsRestructured` does (`dix/events.c:3269`). Default no-op: a + /// host-forwarding backend gets these crossings from the host. + fn windows_restructured(&mut self, _state: &mut ServerState) {} + /// After the server moved the pointer on its own (XTEST fake motion), - /// hand the new position to whatever tracks physical pointer input, so - /// the next real motion continues from there instead of jumping back. - /// The KMS backend's direct-mode input thread accumulates relative - /// deltas from its own copy of the position ([`Self::warp_pointer_root`] - /// resyncs it the same way). Default no-op: host-forwarding backends get - /// their position from the host. + /// hand the new position to backends that keep a producer-side pointer + /// position, so the next real motion continues from there. KMS integrates + /// physical relative deltas from its current cursor and needs no resync. + /// Default no-op: host-forwarding backends get their position from the + /// host. fn resync_input_position(&mut self) {} fn query_pointer(&mut self, origin: Option) -> io::Result; @@ -2909,6 +3218,13 @@ pub trait Backend { None } + /// `(numGroups, enabledControls)` of the backend's XKB keyboard, as its + /// GetControls reply carries them, for the `XkbControlsNotify` the core + /// loop sends. `None` = no XKB keymap here. + fn xkb_controls_base(&self) -> Option<(u8, u32)> { + None + } + /// RANDR per-output identity for the read-only output properties /// `EDID` / `EDID_DATA` / `ConnectorType`: returns `(raw EDID blob, /// ConnectorType name)` for the given RANDR output id, or `None` diff --git a/crates/yserver-core/src/composite_redirects.rs b/crates/yserver-core/src/composite_redirects.rs new file mode 100644 index 000000000..01ae32c8e --- /dev/null +++ b/crates/yserver-core/src/composite_redirects.rs @@ -0,0 +1,394 @@ +//! COMPOSITE redirect bookkeeping, ported from Xorg's +//! `composite/compalloc.c`. +//! +//! Xorg keeps two per-window lists of per-client records +//! (`CompClientWindowRec`): `cw->clients`, the redirects that apply to the +//! window itself, and `csw->clients`, the `RedirectSubwindows` records that +//! apply to its children. A subwindows redirect is not inherited at lookup +//! time: it adds one record per child to that child's own list +//! (`compRedirectSubwindows`, and `compCreateWindow` / +//! `compReparentWindow` for later children), owned by the same client with +//! the same update mode. So `UnredirectWindow(child)` under a +//! `RedirectSubwindows(parent)` frees that record and the child is no +//! longer redirected; a later `RedirectWindow(child, Manual)` then succeeds. +//! +//! This type is the bookkeeping only. Callers compare +//! [`CompositeRedirects::window_mode`] before and after a change to drive +//! the window's backing (Xorg `compCheckRedirect`). + +use std::collections::HashMap; + +use yserver_protocol::x11::{ClientId, ResourceId}; + +use crate::server::{CompositeRedirectMode, RedirectRecord}; + +/// A redirect that Xorg refuses with `BadAccess`: a second Manual +/// redirect, whichever client asks (`compalloc.c:155-158`, `:336-339`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ManualTaken; + +#[derive(Debug, Default)] +pub struct CompositeRedirects { + /// `cw->clients`, newest first. + windows: HashMap>, + /// `csw->clients`, newest first. + subwindows: HashMap>, +} + +fn update_of(records: &[RedirectRecord]) -> Option { + if records.is_empty() { + None + } else if records + .iter() + .any(|r| r.mode == CompositeRedirectMode::Manual) + { + Some(CompositeRedirectMode::Manual) + } else { + Some(CompositeRedirectMode::Automatic) + } +} + +fn remove_one( + map: &mut HashMap>, + window: ResourceId, + owner: ClientId, + mode: CompositeRedirectMode, +) -> bool { + let Some(list) = map.get_mut(&window) else { + return false; + }; + let Some(at) = list.iter().position(|r| r.owner == owner && r.mode == mode) else { + return false; + }; + list.remove(at); + if list.is_empty() { + map.remove(&window); + } + true +} + +impl CompositeRedirects { + /// The window's effective update mode (`cw->update`), `None` when it + /// is not redirected (`cw == NULL`): Manual while any record is Manual. + #[must_use] + pub fn window_mode(&self, window: ResourceId) -> Option { + self.windows.get(&window).and_then(|l| update_of(l)) + } + + /// The `RedirectSubwindows` mode on `parent` (`csw->update`). + #[must_use] + pub fn subwindows_mode(&self, parent: ResourceId) -> Option { + self.subwindows.get(&parent).and_then(|l| update_of(l)) + } + + #[must_use] + pub fn window_records(&self, window: ResourceId) -> &[RedirectRecord] { + self.windows.get(&window).map_or(&[], Vec::as_slice) + } + + #[must_use] + pub fn subwindows_records(&self, parent: ResourceId) -> &[RedirectRecord] { + self.subwindows.get(&parent).map_or(&[], Vec::as_slice) + } + + /// The parents whose subwindows list holds a record of `owner`. + #[must_use] + pub fn subwindows_parents_of(&self, owner: ClientId) -> Vec { + let mut parents: Vec = self + .subwindows + .iter() + .filter(|(_, list)| list.iter().any(|r| r.owner == owner)) + .map(|(parent, _)| *parent) + .collect(); + parents.sort_unstable_by_key(|p| p.0); + parents + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.windows.is_empty() && self.subwindows.is_empty() + } + + /// Xorg `compRedirectWindow` (`compalloc.c:133-230`), minus the + /// overlay and root checks the caller makes. + /// + /// # Errors + /// + /// [`ManualTaken`] for a Manual redirect on a window that already has + /// one, from any client. + pub fn redirect_window( + &mut self, + window: ResourceId, + record: RedirectRecord, + ) -> Result<(), ManualTaken> { + let list = self.windows.entry(window).or_default(); + if record.mode == CompositeRedirectMode::Manual + && list.iter().any(|r| r.mode == CompositeRedirectMode::Manual) + { + if list.is_empty() { + self.windows.remove(&window); + } + return Err(ManualTaken); + } + list.insert(0, record); + Ok(()) + } + + /// Xorg `compUnredirectWindow` (`compalloc.c:313-326`): frees one of + /// `owner`'s records with that mode, whether `RedirectWindow` or a + /// subwindows redirect created it. `false` is Xorg's `BadValue`. + pub fn unredirect_window( + &mut self, + window: ResourceId, + owner: ClientId, + mode: CompositeRedirectMode, + ) -> bool { + remove_one(&mut self.windows, window, owner, mode) + } + + /// Xorg `compRedirectSubwindows` (`compalloc.c:328-399`): a record on + /// `parent`'s subwindows list plus one on each child's own list, + /// `children` top first (`lastChild` → `prevSib`). A child that refuses + /// rolls back the ones already done. + /// + /// # Errors + /// + /// [`ManualTaken`] for a second Manual subwindows redirect on `parent`, + /// or a Manual one when a child already has a Manual redirect. + pub fn redirect_subwindows( + &mut self, + parent: ResourceId, + children: &[ResourceId], + record: RedirectRecord, + ) -> Result<(), ManualTaken> { + if record.mode == CompositeRedirectMode::Manual + && self + .subwindows_records(parent) + .iter() + .any(|r| r.mode == CompositeRedirectMode::Manual) + { + return Err(ManualTaken); + } + for (done, child) in children.iter().enumerate() { + if let Err(err) = self.redirect_window(*child, record) { + for undo in &children[..done] { + self.unredirect_window(*undo, record.owner, record.mode); + } + return Err(err); + } + } + self.subwindows.entry(parent).or_default().insert(0, record); + Ok(()) + } + + /// Xorg `compUnredirectSubwindows` → `compFreeClientSubwindows` + /// (`compalloc.c:405-475`): drops `owner`'s subwindows record and frees + /// one of `owner`'s same-mode records on every child — including one a + /// later `RedirectWindow(child)` made. `false` is Xorg's `BadValue`. + pub fn unredirect_subwindows( + &mut self, + parent: ResourceId, + children: &[ResourceId], + owner: ClientId, + mode: CompositeRedirectMode, + ) -> bool { + if !remove_one(&mut self.subwindows, parent, owner, mode) { + return false; + } + for child in children { + self.unredirect_window(*child, owner, mode); + } + true + } + + /// A child created under `parent` gets a record per subwindows record + /// of `parent`, refusals ignored (Xorg `compCreateWindow`, + /// `compwindow.c:579-589`). + pub fn redirect_new_subwindow(&mut self, parent: ResourceId, child: ResourceId) { + for record in self.subwindows_records(parent).to_vec() { + let _ = self.redirect_window(child, record); + } + } + + /// Reparent: `compUnredirectOneSubwindow(old)` then + /// `compRedirectOneSubwindow(new)` (`compwindow.c:453-454`, + /// `compalloc.c:500-529`); each stops at its first failure. + pub fn reparent_subwindow( + &mut self, + old_parent: ResourceId, + new_parent: ResourceId, + child: ResourceId, + ) { + for record in self.subwindows_records(old_parent).to_vec() { + if !self.unredirect_window(child, record.owner, record.mode) { + break; + } + } + for record in self.subwindows_records(new_parent).to_vec() { + if self.redirect_window(child, record).is_err() { + break; + } + } + } + + /// Drop every record on the destroyed `windows` (Xorg + /// `compDestroyWindow`). + pub fn forget_windows(&mut self, windows: &[ResourceId]) { + for window in windows { + self.windows.remove(window); + self.subwindows.remove(window); + } + } + + /// Free every record `owner` holds, as its resources go with it. + /// Returns each window whose own list changed with its mode before, so + /// its backing can be re-checked. + pub fn forget_client( + &mut self, + owner: ClientId, + ) -> Vec<(ResourceId, Option)> { + let mut changed = Vec::new(); + self.windows.retain(|window, list| { + let before = update_of(list.as_slice()); + let len = list.len(); + list.retain(|r| r.owner != owner); + if list.len() != len { + changed.push((*window, before)); + } + !list.is_empty() + }); + self.subwindows.retain(|_, list| { + list.retain(|r| r.owner != owner); + !list.is_empty() + }); + changed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ROOT: ResourceId = ResourceId(0x0000_0001); + const W: ResourceId = ResourceId(0x0020_0001); + const V: ResourceId = ResourceId(0x0020_0002); + const FRAME: ResourceId = ResourceId(0x0020_0003); + const WM: ClientId = ClientId(1); + const OTHER: ClientId = ClientId(2); + const MANUAL: CompositeRedirectMode = CompositeRedirectMode::Manual; + const AUTOMATIC: CompositeRedirectMode = CompositeRedirectMode::Automatic; + + fn rec(owner: ClientId, mode: CompositeRedirectMode) -> RedirectRecord { + RedirectRecord { mode, owner } + } + + // Measured on Xvfb 21.1: the compositor's fullscreen round. + #[test] + fn child_unredirected_under_subwindows_redirect_can_be_redirected_again() { + let mut r = CompositeRedirects::default(); + r.redirect_subwindows(ROOT, &[W], rec(WM, MANUAL)).unwrap(); + assert_eq!(r.window_mode(W), Some(MANUAL)); + assert_eq!( + r.redirect_window(W, rec(WM, MANUAL)), + Err(ManualTaken), + "muffin's probe: a second Manual redirect, same client" + ); + assert!(r.unredirect_window(W, WM, MANUAL)); + assert_eq!(r.window_mode(W), None); + assert!( + !r.unredirect_window(W, WM, MANUAL), + "BadValue the second time" + ); + assert_eq!(r.redirect_window(W, rec(WM, MANUAL)), Ok(())); + assert_eq!(r.window_mode(W), Some(MANUAL)); + assert_eq!(r.subwindows_mode(ROOT), Some(MANUAL)); + } + + #[test] + fn manual_is_exclusive_automatic_is_shared() { + let mut r = CompositeRedirects::default(); + r.redirect_window(W, rec(WM, MANUAL)).unwrap(); + assert_eq!(r.redirect_window(W, rec(OTHER, MANUAL)), Err(ManualTaken)); + assert_eq!(r.redirect_window(W, rec(OTHER, AUTOMATIC)), Ok(())); + assert_eq!(r.window_mode(W), Some(MANUAL)); + assert!(r.unredirect_window(W, WM, MANUAL)); + assert_eq!( + r.window_mode(W), + Some(AUTOMATIC), + "compFreeClientWindow falls back to Automatic" + ); + assert!( + !r.unredirect_window(W, WM, AUTOMATIC), + "owner and mode must match" + ); + assert!(r.unredirect_window(W, OTHER, AUTOMATIC)); + assert!(r.is_empty()); + } + + #[test] + fn second_manual_subwindows_redirect_is_refused() { + let mut r = CompositeRedirects::default(); + r.redirect_subwindows(ROOT, &[W], rec(WM, MANUAL)).unwrap(); + assert_eq!( + r.redirect_subwindows(ROOT, &[W], rec(OTHER, MANUAL)), + Err(ManualTaken) + ); + assert_eq!(r.window_records(W), &[rec(WM, MANUAL)]); + } + + #[test] + fn subwindows_redirect_refused_by_a_child_rolls_back() { + let mut r = CompositeRedirects::default(); + r.redirect_window(V, rec(OTHER, MANUAL)).unwrap(); + assert_eq!( + r.redirect_subwindows(ROOT, &[W, V], rec(WM, MANUAL)), + Err(ManualTaken) + ); + assert_eq!(r.window_mode(W), None); + assert_eq!(r.subwindows_mode(ROOT), None); + assert_eq!(r.window_records(V), &[rec(OTHER, MANUAL)]); + } + + #[test] + fn unredirect_subwindows_frees_a_later_redirect_window_of_that_client() { + // compFreeClientSubwindows calls compUnredirectWindow on every child, + // which frees whichever same-client, same-mode record it finds. + let mut r = CompositeRedirects::default(); + r.redirect_subwindows(ROOT, &[W, V], rec(WM, MANUAL)) + .unwrap(); + assert!(r.unredirect_window(W, WM, MANUAL)); + r.redirect_window(W, rec(WM, MANUAL)).unwrap(); + r.redirect_window(V, rec(OTHER, AUTOMATIC)).unwrap(); + assert!(r.unredirect_subwindows(ROOT, &[W, V], WM, MANUAL)); + assert_eq!(r.window_mode(W), None); + assert_eq!(r.window_mode(V), Some(AUTOMATIC)); + assert!(!r.unredirect_subwindows(ROOT, &[W, V], WM, MANUAL)); + } + + #[test] + fn new_and_reparented_children_follow_the_subwindows_records() { + let mut r = CompositeRedirects::default(); + r.redirect_subwindows(ROOT, &[], rec(WM, MANUAL)).unwrap(); + r.redirect_new_subwindow(ROOT, W); + assert_eq!(r.window_mode(W), Some(MANUAL)); + // Into a frame nobody redirects: the root's record goes. + r.reparent_subwindow(ROOT, FRAME, W); + assert_eq!(r.window_mode(W), None); + r.reparent_subwindow(FRAME, ROOT, W); + assert_eq!(r.window_mode(W), Some(MANUAL)); + // An own RedirectWindow by another client survives the round. + r.redirect_window(W, rec(OTHER, AUTOMATIC)).unwrap(); + r.reparent_subwindow(ROOT, FRAME, W); + assert_eq!(r.window_records(W), &[rec(OTHER, AUTOMATIC)]); + } + + #[test] + fn forget_client_reports_the_windows_it_changed() { + let mut r = CompositeRedirects::default(); + r.redirect_subwindows(ROOT, &[W], rec(WM, MANUAL)).unwrap(); + r.redirect_window(V, rec(OTHER, AUTOMATIC)).unwrap(); + assert_eq!(r.forget_client(WM), vec![(W, Some(MANUAL))]); + assert_eq!(r.subwindows_mode(ROOT), None); + assert_eq!(r.window_mode(V), Some(AUTOMATIC)); + } +} diff --git a/crates/yserver-core/src/core_loop/auth.rs b/crates/yserver-core/src/core_loop/auth.rs index 528ead80c..70b768874 100644 --- a/crates/yserver-core/src/core_loop/auth.rs +++ b/crates/yserver-core/src/core_loop/auth.rs @@ -2,7 +2,8 @@ //! //! Faithful to X.Org's `os/auth.c` + `os/mitauth.c`: honor an auth file, //! validate each client's SetupRequest cookie, reject mismatches. No auth -//! file (or zero cookies loaded) keeps local access open. See +//! file (or zero cookies loaded) keeps local access open, except under XDMCP, +//! where cookie-less local access is never opened (os/access.c:387). See //! docs/superpowers/specs/2026-06-25-xauth-server-auth-design.md. //! //! Beside the file cookies sits **one** in-memory *session credential*: the @@ -28,8 +29,19 @@ use std::{ time::SystemTime, }; -use super::generation::Generation; -use crate::xauth::{self, MIT_MAGIC_COOKIE}; +use super::{ + generation::Generation, + host_access::{ + BadValue, FAMILY_INTERNET, FAMILY_INTERNET6, FAMILY_LOCAL_HOST, FAMILY_SERVER_INTERPRETED, + HostEntry, HostList, NameResolver, SiEntry, SiType, SystemResolver, check_addr, + si_matches_local, + }, +}; +use crate::{ + access::{Admission, CredentialId, CredentialSource}, + peer::{PeerCred, PeerIdentity, own_interface_addrs}, + xauth::{self, MIT_MAGIC_COOKIE}, +}; // Reject reason strings — byte-for-byte X.Org. Note the trailing newline // on two of them and its absence on the cookie one. @@ -61,11 +73,63 @@ pub struct AuthState { /// `-auth` file at startup (the cookie arrives later, in an `Accept`), /// and a TCP client is then authorized by the session credential /// **alone** — a cookie sitting in a local file must not admit a client - /// to a session it has nothing to do with. Unix clients are unaffected. + /// to a session it has nothing to do with. Unix clients still take file + /// cookies, but never the cookie-less local-open fallback (Xorg + /// `AccessUsingXdmcp`). xdmcp: bool, + /// A TCP listener is configured. Without one Xorg's `selfhosts` is + /// empty (os/connection.c:287-288), so no list entry stands for this + /// host and admits a local client. + tcp_listen: bool, + /// Our own interface addresses, the interface part of Xorg's + /// `selfhosts`. Production: [`own_interface_addrs`], queried per use + /// like `address_is_ours`. A seam so tests do not depend on the host's + /// interfaces. + own_addrs: fn() -> Vec, inner: Mutex, } +/// The core thread's handle on the process-lifetime [`AuthState`], for +/// `ChangeHosts`, `ListHosts` and `SetAccessControl`, with the generation the +/// core is running. Every `AuthState` call from the core passes +/// `generation`. `run_core` installs the real one; a reset carries `auth` +/// into the fresh state with the new generation. +#[derive(Clone)] +pub struct HostAccessHandle { + pub auth: Arc, + pub generation: Generation, + pub policies: Vec>, +} + +impl Default for HostAccessHandle { + /// A private `AuthState` with no `-auth` file, for states that never + /// run under `run_core` (unit tests, before installation). + fn default() -> Self { + Self { + auth: AuthState::new(None), + generation: Generation::default(), + policies: Vec::new(), + } + } +} + +impl std::fmt::Debug for HostAccessHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HostAccessHandle") + .field("generation", &self.generation) + .finish_non_exhaustive() + } +} + +/// Why a `ChangeHosts` failed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum HostChangeError { + /// `BadAccess`: the write came from an older, quarantined generation. + Access, + /// `BadValue`, carrying the length or the family as [`BadValue`] says. + Value(BadValue), +} + /// The cookie from one accepted XDMCP offer, bound to the generation that /// offer belongs to. struct SessionCredential { @@ -73,6 +137,7 @@ struct SessionCredential { /// MIT-MAGIC-COOKIE-1 data. Never empty — see /// [`AuthState::install_session_cookie`]. cookie: Vec, + credential: CredentialId, } struct Inner { @@ -80,16 +145,35 @@ struct Inner { last_mtime: Option, /// Latches true once ≥1 cookie has loaded (X.Org `loaded`). ever_loaded: bool, - /// Host-ACL local-access toggle (collapsed to a bool on unix-only). + /// Xorg's `LocalHostEnabled`: admits every cookie-less Unix client. Three + /// writers, as in Xorg: the auth-file load outcome, `ChangeHosts` of + /// `FamilyLocalHost` (`xhost ±local:`), and the reset (`ResetHosts`, via + /// [`Inner::enter`]). Only meaningful for `generation`. local_open: bool, - /// MIT-MAGIC-COOKIE-1 data blobs. ADDITIVE — never cleared. - cookies: Vec>, + /// Xorg's `validhosts` and `AccessEnabled`. Reset with `local_open`. + hosts: HostList, + /// The generation `local_open` and `hosts` belong to. `AuthState` + /// outlives a reset, so the reset is applied by the first access from a + /// newer generation ([`Inner::enter`]), never by a call at the boundary. + generation: Generation, + /// MIT-MAGIC-COOKIE-1 data blobs. Additive within a generation; a reset + /// clears them (`MitResetCookie`, os/mitauth.c:87-97). + cookies: Vec<(CredentialId, Vec)>, + /// Next process-lifetime id. It is preserved across generation resets. + next_credential_id: u64, /// The XDMCP session credential. ONE slot: a new `Accept` replaces it, /// an abandoned offer clears it. Deliberately not merged into `cookies`, - /// which is additive and process-lifetime — the opposite lifetime. + /// which is additive and only cleared by a reset. session: Option, } +fn reject_reason(name: &[u8]) -> &'static str { + match Inner::reject(name) { + AuthVerdict::Reject(reason) => reason, + AuthVerdict::Allow => unreachable!("reject always returns Reject"), + } +} + /// Reproduce X.Org's reload trigger (os/auth.c:166-175), updating /// `last_mtime`. `stat_mtime == None` means the stat failed. Returns /// true iff a load should run now. @@ -118,6 +202,18 @@ fn should_reload(stat_mtime: Option, last_mtime: &mut Option>), @@ -128,25 +224,70 @@ enum LoadOutcome { } impl Inner { - fn apply_load_outcome(&mut self, outcome: LoadOutcome) { + /// `xdmcp` mirrors Xorg's `UsingXdmcp`: `EnableLocalHost` is then a no-op + /// (os/access.c:273-279), so a load may close local access but never open it. + fn apply_load_outcome(&mut self, outcome: LoadOutcome, xdmcp: bool) { match outcome { - LoadOutcome::Loaded(mut cookies) => { - self.cookies.append(&mut cookies); // additive — os/auth.c never clears + LoadOutcome::Loaded(cookies) => { + // Additive — a reload never clears (os/auth.c). Skip + // cookies already held, so a reload of an unchanged file + // does not grow the list. + for cookie in cookies { + if !self.cookies.iter().any(|(_, loaded)| loaded == &cookie) { + let credential = self.allocate_credential_id(); + self.cookies.push((credential, cookie)); + } + } self.local_open = false; // DisableLocalAccess self.ever_loaded = true; } LoadOutcome::OpenedEmpty => { // EnableLocalAccess, even if previously loaded (os/auth.c:197 quirk). - self.local_open = true; + if !xdmcp { + self.local_open = true; + } } LoadOutcome::OpenFailed => { // loadauth == -1: open only if never loaded; else unchanged. - if !self.ever_loaded { + if !self.ever_loaded && !xdmcp { self.local_open = true; } } } } + + /// Bring the state into `generation`. The first access from a newer + /// generation applies Xorg's reset: `ResetHosts` closes local access + /// and empties the enabled host list (os/access.c:956-962), and + /// `ResetAuthorization` drops every cookie and forces the next auth load + /// (os/auth.c:225-233, os/mitauth.c:87-97), whose outcome may open it again. With no auth + /// file that load finds zero cookies (`LoadAuthorization` returns 0, + /// os/auth.c:117-119), so the reset value is `!xdmcp`. An access from an + /// older generation changes nothing. + fn enter(&mut self, generation: Generation, file: Option<&Path>, xdmcp: bool) -> Access { + if generation < self.generation { + return Access::Stale; + } + if generation > self.generation { + self.local_open = false; + self.hosts = HostList::default(); + self.cookies.clear(); + match file { + Some(path) => AuthState::reload_if_needed(self, path, true, xdmcp), + None => self.apply_load_outcome(LoadOutcome::OpenedEmpty, xdmcp), + } + self.generation = generation; + } + Access::Current + } + + fn allocate_credential_id(&mut self) -> CredentialId { + let value = self.next_credential_id; + self.next_credential_id = value + .checked_add(1) + .expect("credential id counter exhausted"); + CredentialId::from_counter(value) + } } /// Constant-time byte equality (mirrors X.Org's timingsafe_memcmp). @@ -210,6 +351,11 @@ impl Inner { AuthVerdict::Reject(REASON_BAD_PROTO) } + /// The cookie verdict, then the parts of Xorg's `InvalidHost` + /// (os/access.c:1529-1555) that need no lookup: access control disabled + /// (`xhost +`) or local access open. Both only for Unix: the host list + /// never admits a TCP client. The selfhost and SI rules run in + /// [`AuthState::admit`] with the lock released. fn verdict( &self, transport: AuthTransport, @@ -218,50 +364,115 @@ impl Inner { name: &[u8], data: &[u8], ) -> AuthVerdict { - if self.session_authorizes(setup_generation, name, data) { + let verdict = self.cookie_verdict(transport, xdmcp, setup_generation, name, data); + if verdict != AuthVerdict::Allow + && transport == AuthTransport::Unix + && (!self.hosts.access_enabled || self.local_open) + { + return AuthVerdict::Allow; + } + verdict + } + + /// [`Inner::verdict`] without the local-open fallback. + fn cookie_verdict( + &self, + transport: AuthTransport, + xdmcp: bool, + setup_generation: Generation, + name: &[u8], + data: &[u8], + ) -> AuthVerdict { + if self + .cookie_match(transport, xdmcp, setup_generation, name, data) + .is_some() + { return AuthVerdict::Allow; } + Self::reject(name) + } + + /// Return the credential that matched, preserving session-before-file + /// ordering and XDMCP's TCP-only-session rule. + fn cookie_match( + &self, + transport: AuthTransport, + xdmcp: bool, + setup_generation: Generation, + name: &[u8], + data: &[u8], + ) -> Option<(CredentialId, CredentialSource)> { + if self.session_authorizes(setup_generation, name, data) { + return self + .session + .as_ref() + .map(|session| (session.credential, CredentialSource::Session)); + } // In XDMCP mode the session credential is the ONLY thing that // authorizes TCP: stop before the file cookies and before the // local-open fallback. Before the first `Accept` there is no // credential at all, so this is also where TCP fails closed. if xdmcp && transport == AuthTransport::Tcp { - return Self::reject(name); + return None; } - // Cookie match OR local-open admits (mirrors CheckAuthorization + - // host-ACL fallthrough, os/connection.c:536-560). - if name == MIT_MAGIC_COOKIE.as_bytes() && self.cookies.iter().any(|c| ct_eq(c, data)) { - return AuthVerdict::Allow; - } - if transport == AuthTransport::Unix && self.local_open { - return AuthVerdict::Allow; + // Cookie match; `verdict` adds the local-open fallback (mirrors + // CheckAuthorization + host-ACL fallthrough, + // os/connection.c:536-560). + if name == MIT_MAGIC_COOKIE.as_bytes() { + return self + .cookies + .iter() + .find(|(_, cookie)| ct_eq(cookie, data)) + .map(|(credential, _)| (*credential, CredentialSource::File)); } - Self::reject(name) + None } } impl AuthState { /// Build from `LaunchOptions.auth_file`. `None` ⇒ permanently open. pub fn new(file: Option) -> Arc { - Self::new_with_xdmcp(file, false) + Self::new_with(file, false, false) } /// Build from `LaunchOptions.auth_file` and whether `LaunchOptions.xdmcp` /// is set. See [`AuthState::xdmcp`] for what the flag changes. pub fn new_with_xdmcp(file: Option, xdmcp: bool) -> Arc { + Self::new_with(file, xdmcp, false) + } + + /// Build from `LaunchOptions.auth_file`, whether `LaunchOptions.xdmcp` + /// is set, and whether a TCP listener is configured + /// (`LaunchOptions.tcp_listen`, see [`AuthState::tcp_listen`]). + pub fn new_with(file: Option, xdmcp: bool, tcp_listen: bool) -> Arc { + Arc::new(Self::build(file, xdmcp, tcp_listen, own_interface_addrs)) + } + + fn build( + file: Option, + xdmcp: bool, + tcp_listen: bool, + own_addrs: fn() -> Vec, + ) -> Self { // Start open; the first successful load flips this to false (Xorg ShouldLoadAuth=TRUE → never-loaded+unopenable stays open). - let local_open = true; - Arc::new(Self { + // XDMCP starts closed and stays closed: AccessUsingXdmcp (os/access.c:387-391). + let local_open = !xdmcp; + Self { file, xdmcp, + tcp_listen, + own_addrs, inner: Mutex::new(Inner { last_mtime: None, ever_loaded: false, local_open, + hosts: HostList::default(), + generation: Generation::default(), cookies: Vec::new(), + next_credential_id: 1, session: None, }), - }) + } } /// Install the credential from an accepted XDMCP offer, bound to @@ -289,9 +500,11 @@ impl AuthState { inner.session = None; return false; } + let credential = inner.allocate_credential_id(); inner.session = Some(SessionCredential { generation, cookie: data.to_vec(), + credential, }); true } @@ -326,18 +539,18 @@ impl AuthState { // load even when `stat` fails so startup and runtime share precisely // the same load outcome. let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - Self::reload_if_needed(&mut inner, path, true); + Self::reload_if_needed(&mut inner, path, true, self.xdmcp); if inner.cookies.is_empty() { return Err("-listen tcp requires -auth with a MIT-MAGIC-COOKIE-1 cookie".into()); } Ok(()) } - fn reload_if_needed(inner: &mut Inner, path: &Path, force: bool) { + fn reload_if_needed(inner: &mut Inner, path: &Path, force: bool, xdmcp: bool) { let stat_mtime = fs::metadata(path).ok().and_then(|m| m.modified().ok()); let changed = should_reload(stat_mtime, &mut inner.last_mtime); if force || changed { - inner.apply_load_outcome(load_outcome(path)); + inner.apply_load_outcome(load_outcome(path), xdmcp); } } @@ -347,29 +560,246 @@ impl AuthState { /// bound to at accept (`BoundSender::generation`), never the counter's /// current value: reading the counter here would re-admit a client of the /// destroyed session the instant a reset installed a new credential. + /// + /// The cookie decides first; the host list is consulted only when it + /// fails (os/connection.c:533-560), so the list only adds admissions. + /// It is consulted for Unix peers only, never for TCP. pub fn check( &self, - transport: AuthTransport, + peer: &PeerIdentity, setup_generation: Generation, proto_name: &[u8], proto_data: &[u8], ) -> AuthVerdict { - // Poisoning recovery — same pattern as setup_thread.rs:66. - let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - // With no `-auth` file there is nothing to reload; the initial state - // (`local_open`, no file cookies) is already what such a server has, - // and is never mutated. The session credential still applies. - if let Some(path) = self.file.as_deref() { - Self::reload_if_needed(&mut inner, path, false); - } - inner.verdict( - transport, - self.xdmcp, + self.admit(peer, setup_generation, proto_name, proto_data) + .map_or_else(AuthVerdict::Reject, |_| AuthVerdict::Allow) + } + + /// Authorize a client and record the credential or fallback that admitted + /// it. Credential ids are allocated independently of cookie bytes. + pub fn admit( + &self, + peer: &PeerIdentity, + setup_generation: Generation, + proto_name: &[u8], + proto_data: &[u8], + ) -> Result { + self.admit_with( + peer, setup_generation, proto_name, proto_data, + &SystemResolver, ) } + + #[cfg(test)] + fn check_with( + &self, + peer: &PeerIdentity, + setup_generation: Generation, + proto_name: &[u8], + proto_data: &[u8], + resolver: &dyn NameResolver, + ) -> AuthVerdict { + self.admit_with(peer, setup_generation, proto_name, proto_data, resolver) + .map_or_else(AuthVerdict::Reject, |_| AuthVerdict::Allow) + } + + fn admit_with( + &self, + peer: &PeerIdentity, + setup_generation: Generation, + proto_name: &[u8], + proto_data: &[u8], + resolver: &dyn NameResolver, + ) -> Result { + let hosts = { + // Poisoning recovery — same pattern as setup_thread.rs:66. + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + // A newer generation first gets Xorg's reset state; a stale + // producer changes nothing, and neither the local-open fallback + // nor the host list applies to it. + let access = inner.enter(setup_generation, self.file.as_deref(), self.xdmcp); + if access == Access::Stale { + return match inner.cookie_match( + peer.transport, + self.xdmcp, + setup_generation, + proto_name, + proto_data, + ) { + Some((credential, source)) => Ok(Admission::Cookie { credential, source }), + None => Err(reject_reason(proto_name)), + }; + } + // With no `-auth` file there is nothing to reload: `local_open` + // then changes only through `enter` and `FamilyLocalHost`. The + // session credential still applies. + if let Some(path) = self.file.as_deref() { + Self::reload_if_needed(&mut inner, path, false, self.xdmcp); + } + if let Some((credential, source)) = inner.cookie_match( + peer.transport, + self.xdmcp, + setup_generation, + proto_name, + proto_data, + ) { + return Ok(Admission::Cookie { credential, source }); + } + if inner.verdict( + peer.transport, + self.xdmcp, + setup_generation, + proto_name, + proto_data, + ) == AuthVerdict::Allow + { + return Ok(Admission::HostAccess); + } + if peer.transport != AuthTransport::Unix { + return Err(reject_reason(proto_name)); + } + inner.hosts.hosts.clone() + }; + // The lock is released: the interface query and the NSS lookups run + // on this snapshot of the list. + if self.list_admits_unix(&hosts, peer.cred.as_ref(), resolver) { + return Ok(Admission::HostAccess); + } + Err(reject_reason(proto_name)) + } + + /// The rest of `InvalidHost` for a Unix peer (os/access.c:1540-1566): + /// one of our `selfhosts` is listed, or an SI entry matches the peer's + /// credentials. Non-SI entries never match a Unix peer (`addr` is NULL). + fn list_admits_unix( + &self, + hosts: &[HostEntry], + cred: Option<&PeerCred>, + resolver: &dyn NameResolver, + ) -> bool { + if hosts.is_empty() { + return false; + } + let selfhosts = self.selfhosts(); + hosts.iter().any(|host| selfhosts.contains(host)) + || hosts + .iter() + .any(|host| si_matches_local(host, cred, resolver)) + } + + /// Xorg's `selfhosts`: every interface address plus `{FamilyLocalHost, + /// len 0}` (`DefineSelf`, os/access.c:793-818, :874-886), and nothing + /// without a TCP listener (os/connection.c:287-288). + fn selfhosts(&self) -> Vec { + if !self.tcp_listen { + return Vec::new(); + } + let mut selfhosts = (self.own_addrs)(); + selfhosts.push(HostEntry { + family: FAMILY_LOCAL_HOST, + addr: Vec::new(), + }); + selfhosts + } + + /// `ChangeHosts` after the mode and access checks: Xorg's `AddHost` + /// (`insert`) or `RemoveHost` (os/access.c:1313-1446). `FamilyLocalHost` + /// takes any length and opens or closes local access, then is stored + /// like any entry. Every other family is validated first; deleting an + /// absent entry is fine. Names resolve through `resolver` on the calling + /// thread, as Xorg does on its only one. + pub fn change_hosts( + &self, + generation: Generation, + insert: bool, + family: u8, + addr: &[u8], + resolver: &dyn NameResolver, + ) -> Result<(), HostChangeError> { + if family != FAMILY_LOCAL_HOST { + check_addr(family, addr, resolver).map_err(HostChangeError::Value)?; + } + let entry = HostEntry { + family, + addr: addr.to_vec(), + }; + let inert = if insert { + self.inert_reason(&entry) + } else { + None + }; + { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + // Cannot happen for a live client; fails closed. + if inner.enter(generation, self.file.as_deref(), self.xdmcp) == Access::Stale { + return Err(HostChangeError::Access); + } + if family == FAMILY_LOCAL_HOST { + inner.local_open = insert; + } + if insert { + inner.hosts.insert(entry); + } else { + inner.hosts.delete(&entry); + } + } + if let Some(reason) = inert { + log::warn!("xhost: added a host entry (family {family}) that admits nobody: {reason}"); + } + Ok(()) + } + + /// Why an inserted entry can never admit anyone here, if it cannot. The + /// list never admits TCP, so an address entry only counts as one of our + /// own `selfhosts`, and an SI `hostname`/`ipv6` entry only ever matches + /// Internet peers (os/access.c:1819-1846, :1970-1994). + fn inert_reason(&self, entry: &HostEntry) -> Option<&'static str> { + match entry.family { + FAMILY_INTERNET | FAMILY_INTERNET6 if !self.tcp_listen => Some( + "no TCP listener, so it is not one of our addresses, and the list never \ + admits a TCP client", + ), + FAMILY_INTERNET | FAMILY_INTERNET6 if !(self.own_addrs)().contains(entry) => { + Some("not one of our addresses, and the list never admits a TCP client") + } + FAMILY_SERVER_INTERPRETED => SiEntry::parse(&entry.addr) + .filter(|si| matches!(si.kind, SiType::Hostname | SiType::Ipv6)) + .map(|_| "SI hostname/ipv6 entries only match TCP clients, which the list never admits"), + _ => None, + } + } + + /// `SetAccessControl` after the mode and access checks: Xorg's + /// `ChangeAccessControl` (os/access.c:1616-1623). Connected clients are + /// not touched. + pub fn set_access_enabled( + &self, + generation: Generation, + enabled: bool, + ) -> Result<(), HostChangeError> { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if inner.enter(generation, self.file.as_deref(), self.xdmcp) == Access::Stale { + return Err(HostChangeError::Access); + } + inner.hosts.access_enabled = enabled; + Ok(()) + } + + /// `ListHosts`' `enabled` flag and entries, newest first. An older + /// generation reads the reset state. + pub fn list_hosts(&self, generation: Generation) -> (bool, Vec) { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + match inner.enter(generation, self.file.as_deref(), self.xdmcp) { + Access::Current => (inner.hosts.access_enabled, inner.hosts.hosts.clone()), + Access::Stale => { + let reset = HostList::default(); + (reset.access_enabled, reset.hosts) + } + } + } } #[cfg(test)] @@ -377,6 +807,17 @@ mod tests { use super::*; use std::time::Duration; + const UNIX: PeerIdentity = PeerIdentity { + transport: AuthTransport::Unix, + addr: None, + cred: None, + }; + const TCP: PeerIdentity = PeerIdentity { + transport: AuthTransport::Tcp, + addr: None, + cred: None, + }; + fn t(secs: u64) -> SystemTime { SystemTime::UNIX_EPOCH + Duration::from_secs(secs) } @@ -418,20 +859,29 @@ mod tests { } fn enforcing_with(cookies: Vec>) -> Inner { - Inner { - last_mtime: Some(t(1)), - ever_loaded: true, - local_open: false, - cookies, - session: None, - } + let mut inner = fresh_open(); + inner.last_mtime = Some(t(1)); + inner.apply_load_outcome(LoadOutcome::Loaded(cookies), false); + inner + } + + fn cookie_bytes(inner: &Inner) -> Vec> { + inner + .cookies + .iter() + .map(|(_, cookie)| cookie.clone()) + .collect() } + fn fresh_open() -> Inner { Inner { last_mtime: None, ever_loaded: false, local_open: true, + hosts: HostList::default(), + generation: Generation::default(), cookies: Vec::new(), + next_credential_id: 1, session: None, } } @@ -439,22 +889,22 @@ mod tests { #[test] fn loaded_enforces_and_appends() { let mut i = fresh_open(); - i.apply_load_outcome(LoadOutcome::Loaded(vec![vec![1u8; 16]])); + i.apply_load_outcome(LoadOutcome::Loaded(vec![vec![1u8; 16]]), false); assert!(!i.local_open); assert!(i.ever_loaded); - assert_eq!(i.cookies, vec![vec![1u8; 16]]); + assert_eq!(cookie_bytes(&i), vec![vec![1u8; 16]]); // A second load APPENDS (additive — Xorg never clears on reload). - i.apply_load_outcome(LoadOutcome::Loaded(vec![vec![2u8; 16]])); - assert_eq!(i.cookies, vec![vec![1u8; 16], vec![2u8; 16]]); + i.apply_load_outcome(LoadOutcome::Loaded(vec![vec![2u8; 16]]), false); + assert_eq!(cookie_bytes(&i), vec![vec![1u8; 16], vec![2u8; 16]]); } #[test] fn empty_file_reopens_even_after_load() { let mut i = enforcing_with(vec![vec![1u8; 16]]); - i.apply_load_outcome(LoadOutcome::OpenedEmpty); + i.apply_load_outcome(LoadOutcome::OpenedEmpty, false); assert!(i.local_open, "empty file reopens local access (Xorg quirk)"); assert_eq!( - i.cookies, + cookie_bytes(&i), vec![vec![1u8; 16]], "cookies retained (additive)" ); @@ -463,9 +913,9 @@ mod tests { #[test] fn open_failed_after_load_keeps_enforcing() { let mut i = enforcing_with(vec![vec![1u8; 16]]); - i.apply_load_outcome(LoadOutcome::OpenFailed); + i.apply_load_outcome(LoadOutcome::OpenFailed, false); assert!(!i.local_open, "stays enforcing — does NOT reopen"); - assert_eq!(i.cookies, vec![vec![1u8; 16]]); + assert_eq!(cookie_bytes(&i), vec![vec![1u8; 16]]); } #[test] @@ -476,10 +926,13 @@ mod tests { last_mtime: None, ever_loaded: false, local_open: false, + hosts: HostList::default(), + generation: Generation::default(), cookies: Vec::new(), + next_credential_id: 1, session: None, }; - i.apply_load_outcome(LoadOutcome::OpenFailed); + i.apply_load_outcome(LoadOutcome::OpenFailed, false); assert!( i.local_open, "OpenFailed before any load must enable local access" @@ -579,6 +1032,128 @@ mod tests { std::env::temp_dir().join(format!("yserver-auth-test-{}-{tag}", std::process::id())) } + // Mutation: exposing the cookie bytes from `Admission`'s Debug output makes this assertion fail. + #[test] + fn admission_debug_never_shows_the_cookie() { + let cookie = [0xABu8; 16]; + let path = temp_path("admission-debug"); + fs::write(&path, xauth_bytes(b"7", &cookie)).unwrap(); + let auth = AuthState::new(Some(path.clone())); + + let admission = auth + .admit( + &UNIX, + Generation::default(), + MIT_MAGIC_COOKIE.as_bytes(), + &cookie, + ) + .unwrap(); + let debug = format!("{admission:?}"); + let hex = cookie + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let decimal = cookie + .iter() + .map(u8::to_string) + .collect::>() + .join(", "); + assert!(!debug.contains(&hex)); + assert!(!debug.contains(&decimal)); + fs::remove_file(path).unwrap(); + } + + // Mutation: derive CredentialId from cookie bytes; reloading C1 after a + // reset makes `assert_ne!(c1_after_reset_id, c1_id)` fail. + #[test] + fn credential_ids_are_kept_while_loaded_and_never_reused() { + fn file_id(auth: &AuthState, generation: Generation, cookie: &[u8]) -> CredentialId { + match auth + .admit(&UNIX, generation, MIT, cookie) + .expect("file cookie must be admitted") + { + Admission::Cookie { + credential, + source: CredentialSource::File, + } => credential, + other => panic!("expected file-cookie admission, got {other:?}"), + } + } + + fn session_id(auth: &AuthState, generation: Generation, cookie: &[u8]) -> CredentialId { + match auth + .admit(&TCP, generation, MIT, cookie) + .expect("session cookie must be admitted") + { + Admission::Cookie { + credential, + source: CredentialSource::Session, + } => credential, + other => panic!("expected session-cookie admission, got {other:?}"), + } + } + + let path = temp_path("allocated-credential-ids"); + let c1 = [0xD1u8; 16]; + fs::write(&path, xauth_bytes(b"1", &c1)).unwrap(); + let auth = AuthState::new(Some(path.clone())); + let counter = GenerationCounter::new(); + let mut generation = counter.current(); + let mut seen = std::collections::HashSet::new(); + + let c1_id = file_id(&auth, generation, &c1); + assert!(seen.insert(c1_id), "first credential id must be new"); + + // The file reload is additive. Removing C1 from the file does not + // remove the already-loaded credential or change its id. + fs::write(&path, b"").unwrap(); + touch_later(&path); + // Mutation: reallocating IDs for retained credentials on every reload + // makes this keep-after-removal assertion fail. + assert_eq!(file_id(&auth, generation, &c1), c1_id); + + // Putting C1 back and reloading still refers to the same loaded + // lifetime. The file contents do not remove/recreate loaded cookies. + fs::write(&path, xauth_bytes(b"1", &c1)).unwrap(); + touch_later(&path); + assert_eq!(file_id(&auth, generation, &c1), c1_id); + + // A reset drops the loaded cookie list, then the forced reload + // allocates a fresh id for the same bytes. + generation = counter.bump(); + let c1_after_reset_id = file_id(&auth, generation, &c1); + assert_ne!(c1_after_reset_id, c1_id); + assert!( + seen.insert(c1_after_reset_id), + "post-reset C1 id must be new" + ); + + let session1 = [0xE1u8; 16]; + let session2 = [0xE2u8; 16]; + assert!(auth.install_session_cookie(generation, MIT, &session1)); + let session1_id = session_id(&auth, generation, &session1); + assert!(seen.insert(session1_id), "session id must be new"); + + assert!(auth.install_session_cookie(generation, MIT, &session2)); + let session2_id = session_id(&auth, generation, &session2); + assert_ne!(session2_id, session1_id); + assert!( + seen.insert(session2_id), + "replacement session id must be new" + ); + + auth.clear_session_cookie(); + assert!(auth.install_session_cookie(generation, MIT, &session2)); + let session2_reinstalled_id = session_id(&auth, generation, &session2); + assert_ne!(session2_reinstalled_id, session2_id); + assert!( + seen.insert(session2_reinstalled_id), + "cleared session id must never be reused" + ); + + fs::remove_file(path).unwrap(); + } + #[test] fn check_enforces_against_file_cookie() { let cookie = [0xABu8; 16]; @@ -588,7 +1163,7 @@ mod tests { assert_eq!( auth.check( - AuthTransport::Unix, + &UNIX, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &cookie @@ -597,7 +1172,7 @@ mod tests { ); assert_eq!( auth.check( - AuthTransport::Unix, + &UNIX, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &[0u8; 16] @@ -605,7 +1180,7 @@ mod tests { AuthVerdict::Reject(REASON_BAD_COOKIE) ); assert_eq!( - auth.check(AuthTransport::Unix, Generation::default(), b"", b""), + auth.check(&UNIX, Generation::default(), b"", b""), AuthVerdict::Reject(REASON_NO_PROTO) ); @@ -614,7 +1189,7 @@ mod tests { fs::remove_file(&path).unwrap(); assert_eq!( auth.check( - AuthTransport::Unix, + &UNIX, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &cookie @@ -623,7 +1198,7 @@ mod tests { ); assert_eq!( auth.check( - AuthTransport::Unix, + &UNIX, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &[0u8; 16] @@ -637,11 +1212,11 @@ mod tests { fn check_no_auth_file_is_open() { let auth = AuthState::new(None); assert_eq!( - auth.check(AuthTransport::Unix, Generation::default(), b"", b""), + auth.check(&UNIX, Generation::default(), b"", b""), AuthVerdict::Allow ); assert_eq!( - auth.check(AuthTransport::Tcp, Generation::default(), b"", b""), + auth.check(&TCP, Generation::default(), b"", b""), AuthVerdict::Reject(REASON_NO_PROTO), "TCP must never inherit Unix local-open access" ); @@ -653,11 +1228,11 @@ mod tests { fs::write(&path, b"").unwrap(); let auth = AuthState::new(Some(path.clone())); assert_eq!( - auth.check(AuthTransport::Unix, Generation::default(), b"", b""), + auth.check(&UNIX, Generation::default(), b"", b""), AuthVerdict::Allow ); assert_eq!( - auth.check(AuthTransport::Tcp, Generation::default(), b"", b""), + auth.check(&TCP, Generation::default(), b"", b""), AuthVerdict::Reject(REASON_NO_PROTO), "an empty -auth file cannot authorize TCP" ); @@ -673,12 +1248,12 @@ mod tests { let _ = fs::remove_file(&path); // ensure absent let auth = AuthState::new(Some(path)); assert_eq!( - auth.check(AuthTransport::Unix, Generation::default(), b"", b""), + auth.check(&UNIX, Generation::default(), b"", b""), AuthVerdict::Allow ); assert_eq!( auth.check( - AuthTransport::Tcp, + &TCP, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &[0u8; 16] @@ -697,7 +1272,7 @@ mod tests { assert_eq!( auth.check( - AuthTransport::Tcp, + &TCP, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &cookie @@ -706,7 +1281,7 @@ mod tests { ); assert_eq!( auth.check( - AuthTransport::Tcp, + &TCP, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &[0u8; 16] @@ -726,7 +1301,7 @@ mod tests { assert!(auth.require_tcp_auth_at_startup().is_ok()); assert_eq!( auth.check( - AuthTransport::Tcp, + &TCP, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &cookie @@ -736,7 +1311,7 @@ mod tests { ); let inner = auth.inner.lock().unwrap(); assert_eq!( - inner.cookies, + cookie_bytes(&inner), vec![cookie.to_vec()], "runtime must see the startup load rather than append a second load" ); @@ -777,11 +1352,11 @@ mod tests { // 1. No -auth file at all: Unix open, TCP closed. let none = AuthState::new(None); assert_eq!( - none.check(AuthTransport::Unix, Generation::default(), b"", b""), + none.check(&UNIX, Generation::default(), b"", b""), AuthVerdict::Allow ); assert_eq!( - none.check(AuthTransport::Tcp, Generation::default(), b"", b""), + none.check(&TCP, Generation::default(), b"", b""), AuthVerdict::Reject(REASON_NO_PROTO) ); @@ -791,12 +1366,12 @@ mod tests { let _ = fs::remove_file(&missing); let unreadable = AuthState::new(Some(missing)); assert_eq!( - unreadable.check(AuthTransport::Unix, Generation::default(), b"", b""), + unreadable.check(&UNIX, Generation::default(), b"", b""), AuthVerdict::Allow ); assert_eq!( unreadable.check( - AuthTransport::Tcp, + &TCP, Generation::default(), MIT_MAGIC_COOKIE.as_bytes(), &[7u8; 16] @@ -810,7 +1385,7 @@ mod tests { let path = temp_path("fence-loaded"); fs::write(&path, xauth_bytes(b"7", &cookie)).unwrap(); let loaded = AuthState::new(Some(path.clone())); - for transport in [AuthTransport::Unix, AuthTransport::Tcp] { + for transport in [&UNIX, &TCP] { assert_eq!( loaded.check( transport, @@ -852,7 +1427,7 @@ mod tests { let old_client = sender.bind(); assert!(auth.install_session_cookie(rx.current_generation(), MIT, &first)); assert_eq!( - auth.check(AuthTransport::Tcp, old_client.generation(), MIT, &first), + auth.check(&TCP, old_client.generation(), MIT, &first), AuthVerdict::Allow ); @@ -865,7 +1440,7 @@ mod tests { // A client of the new session presenting the PREVIOUS session's // cookie is refused. assert_eq!( - auth.check(AuthTransport::Tcp, new_client.generation(), MIT, &first), + auth.check(&TCP, new_client.generation(), MIT, &first), AuthVerdict::Reject(REASON_BAD_COOKIE) ); @@ -876,7 +1451,7 @@ mod tests { // `generation::should_dispatch`; all this asserts is which comparison // produced the refusal above.) assert_eq!( - auth.check(AuthTransport::Tcp, old_client.generation(), MIT, &first), + auth.check(&TCP, old_client.generation(), MIT, &first), AuthVerdict::Allow, "the refusal must come from the generation comparison, not from an \ empty slot — otherwise this test passes for the wrong reason" @@ -887,20 +1462,20 @@ mod tests { let second = [0xC2u8; 16]; assert!(auth.install_session_cookie(new_generation, MIT, &second)); assert_eq!( - auth.check(AuthTransport::Tcp, new_client.generation(), MIT, &second), + auth.check(&TCP, new_client.generation(), MIT, &second), AuthVerdict::Allow ); assert_eq!( - auth.check(AuthTransport::Tcp, new_client.generation(), MIT, &first), + auth.check(&TCP, new_client.generation(), MIT, &first), AuthVerdict::Reject(REASON_BAD_COOKIE) ); assert_eq!( - auth.check(AuthTransport::Tcp, old_client.generation(), MIT, &first), + auth.check(&TCP, old_client.generation(), MIT, &first), AuthVerdict::Reject(REASON_BAD_COOKIE), "one slot: the previous session's cookie is gone once replaced" ); assert_eq!( - auth.check(AuthTransport::Tcp, old_client.generation(), MIT, &second), + auth.check(&TCP, old_client.generation(), MIT, &second), AuthVerdict::Reject(REASON_BAD_COOKIE), "nor may an old client borrow the new session's cookie" ); @@ -919,7 +1494,7 @@ mod tests { assert!(auth.install_session_cookie(generation, MIT, &refused)); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &refused), + auth.check(&TCP, generation, MIT, &refused), AuthVerdict::Allow ); @@ -931,7 +1506,7 @@ mod tests { // long. auth.clear_session_cookie(); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &refused), + auth.check(&TCP, generation, MIT, &refused), AuthVerdict::Reject(REASON_BAD_COOKIE), "the refused offer's cookie must stop authorizing immediately, not \ merely once a replacement arrives" @@ -940,11 +1515,11 @@ mod tests { // The replacement offer, in the same generation. assert!(auth.install_session_cookie(generation, MIT, &accepted)); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &accepted), + auth.check(&TCP, generation, MIT, &accepted), AuthVerdict::Allow ); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &refused), + auth.check(&TCP, generation, MIT, &refused), AuthVerdict::Reject(REASON_BAD_COOKIE) ); } @@ -957,23 +1532,151 @@ mod tests { let generation = Generation::default(); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &[0x11u8; 16]), + auth.check(&TCP, generation, MIT, &[0x11u8; 16]), AuthVerdict::Reject(REASON_BAD_COOKIE) ); assert_eq!( - auth.check(AuthTransport::Tcp, generation, b"", b""), + auth.check(&TCP, generation, b"", b""), AuthVerdict::Reject(REASON_NO_PROTO) ); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, b""), + auth.check(&TCP, generation, MIT, b""), AuthVerdict::Reject(REASON_BAD_COOKIE), "an empty presentation must not match an empty slot" ); - // Unix is unaffected: no -auth file, so local access is open as ever. + // Nor a cookie-less Unix client: XDMCP never opens local access. assert_eq!( - auth.check(AuthTransport::Unix, generation, b"", b""), + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + } + + /// Bump `path`'s mtime so the next `check` reloads it. + /// Push the file's mtime past every earlier `touch_later`: a rewrite in + /// the same clock tick gets the same mtime, so "mtime + 10 s" alone is + /// not strictly newer on coarse-clock systems (OpenBSD). + fn touch_later(path: &Path) { + static STEP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let step = STEP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let later = + fs::metadata(path).unwrap().modified().unwrap() + Duration::from_secs(10 * step); + fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(later) + .unwrap(); + } + + #[test] + fn xdmcp_load_closes_local_access_but_never_opens_it() { + let mut i = fresh_open(); + i.local_open = false; + i.apply_load_outcome(LoadOutcome::OpenedEmpty, true); + assert!(!i.local_open, "EnableLocalHost is a no-op under XDMCP"); + i.apply_load_outcome(LoadOutcome::OpenFailed, true); + assert!(!i.local_open, "EnableLocalHost is a no-op under XDMCP"); + i.local_open = true; + i.apply_load_outcome(LoadOutcome::Loaded(vec![vec![1u8; 16]]), true); + assert!(!i.local_open, "DisableLocalHost still applies"); + } + + #[test] + fn xdmcp_without_auth_file_refuses_cookieless_unix() { + let auth = AuthState::new_with_xdmcp(None, true); + let generation = Generation::default(); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + assert_eq!( + auth.check(&UNIX, generation, MIT, &[0u8; 16]), + AuthVerdict::Reject(REASON_BAD_COOKIE) + ); + } + + #[test] + fn xdmcp_empty_auth_file_refuses_cookieless_unix_across_reloads() { + let path = temp_path("xdmcp-empty"); + fs::write(&path, b"").unwrap(); + let generation = Generation::default(); + let auth = AuthState::new_with_xdmcp(Some(path.clone()), true); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO), + "empty file at startup" + ); + + // A later reload of the still-empty file. + touch_later(&path); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO), + "reload of the still-empty file" + ); + + // A loaded cookie, then the file emptied: Xorg's reopen quirk must + // not apply under XDMCP; the loaded cookie keeps working. + let cookie = [0x3Cu8; 16]; + fs::write(&path, xauth_bytes(b"7", &cookie)).unwrap(); + touch_later(&path); + assert_eq!( + auth.check(&UNIX, generation, MIT, &cookie), AuthVerdict::Allow ); + fs::write(&path, b"").unwrap(); + touch_later(&path); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO), + "emptied after a load" + ); + assert_eq!( + auth.check(&UNIX, generation, MIT, &cookie), + AuthVerdict::Allow + ); + let _ = fs::remove_file(path); + } + + #[test] + fn xdmcp_unreadable_auth_file_refuses_cookieless_unix() { + let generation = Generation::default(); + + // stat succeeds, read fails: the never-loaded OpenFailed path. + let dir = temp_path("xdmcp-unreadable-dir"); + let _ = fs::remove_dir(&dir); + fs::create_dir(&dir).unwrap(); + let auth = AuthState::new_with_xdmcp(Some(dir.clone()), true); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + let _ = fs::remove_dir(dir); + + // Missing entirely. + let missing = temp_path("xdmcp-missing"); + let _ = fs::remove_file(&missing); + let auth = AuthState::new_with_xdmcp(Some(missing), true); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + } + + #[test] + fn xdmcp_session_cookie_admits_unix() { + let auth = AuthState::new_with_xdmcp(None, true); + let generation = Generation::default(); + let session = [0x4Du8; 16]; + assert!(auth.install_session_cookie(generation, MIT, &session)); + assert_eq!( + auth.check(&UNIX, generation, MIT, &session), + AuthVerdict::Allow + ); + assert_eq!( + auth.check(&UNIX, generation, b"", b""), + AuthVerdict::Reject(REASON_NO_PROTO) + ); } #[test] @@ -985,12 +1688,12 @@ mod tests { let auth = AuthState::new_with_xdmcp(Some(path.clone()), true); assert_eq!( - auth.check(AuthTransport::Unix, generation, MIT, &file_cookie), + auth.check(&UNIX, generation, MIT, &file_cookie), AuthVerdict::Allow, "Unix clients are unaffected by XDMCP mode" ); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &file_cookie), + auth.check(&TCP, generation, MIT, &file_cookie), AuthVerdict::Reject(REASON_BAD_COOKIE), "a cookie in a local file must not authorize a client into an \ XDMCP session it has nothing to do with" @@ -1000,11 +1703,11 @@ mod tests { let session_cookie = [0x6Bu8; 16]; assert!(auth.install_session_cookie(generation, MIT, &session_cookie)); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &session_cookie), + auth.check(&TCP, generation, MIT, &session_cookie), AuthVerdict::Allow ); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &file_cookie), + auth.check(&TCP, generation, MIT, &file_cookie), AuthVerdict::Reject(REASON_BAD_COOKIE), "installing a session cookie does not un-shadow the file ones" ); @@ -1013,7 +1716,7 @@ mod tests { // file or the cookie. let plain = AuthState::new(Some(path.clone())); assert_eq!( - plain.check(AuthTransport::Tcp, generation, MIT, &file_cookie), + plain.check(&TCP, generation, MIT, &file_cookie), AuthVerdict::Allow ); @@ -1030,19 +1733,14 @@ mod tests { // admit precisely this client — an open display dressed as an // authenticated one. assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, b""), + auth.check(&TCP, generation, MIT, b""), AuthVerdict::Reject(REASON_BAD_COOKIE) ); // An authorization name this layer cannot check is refused too. assert!(!auth.install_session_cookie(generation, b"XDM-AUTHORIZATION-1", &[1u8; 8])); assert_eq!( - auth.check( - AuthTransport::Tcp, - generation, - b"XDM-AUTHORIZATION-1", - &[1u8; 8] - ), + auth.check(&TCP, generation, b"XDM-AUTHORIZATION-1", &[1u8; 8]), AuthVerdict::Reject(REASON_BAD_PROTO) ); @@ -1052,7 +1750,7 @@ mod tests { assert!(auth.install_session_cookie(generation, MIT, &good)); assert!(!auth.install_session_cookie(generation, MIT, b"")); assert_eq!( - auth.check(AuthTransport::Tcp, generation, MIT, &good), + auth.check(&TCP, generation, MIT, &good), AuthVerdict::Reject(REASON_BAD_COOKIE) ); } @@ -1073,4 +1771,653 @@ mod tests { .is_err() ); } + + // ---- the reset: generation-tagged `local_open` ---- + + use crate::core_loop::generation::GenerationCounter; + + /// Stand-in for `xhost ±local:` until `ChangeHosts` exists. + fn set_local_open(auth: &AuthState, open: bool) { + auth.inner.lock().unwrap().local_open = open; + } + + fn cookieless_unix(auth: &AuthState, generation: Generation) -> AuthVerdict { + auth.check(&UNIX, generation, b"", b"") + } + + /// Rewrite `path` without moving its mtime, so only a forced load can + /// see the new contents. + fn rewrite_keeping_mtime(path: &Path, bytes: &[u8]) { + let mtime = fs::metadata(path).unwrap().modified().unwrap(); + fs::write(path, bytes).unwrap(); + fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(mtime) + .unwrap(); + } + + #[test] + fn a_reset_without_auth_file_reopens_local_access() { + let counter = GenerationCounter::new(); + let auth = AuthState::new(None); + let g0 = counter.current(); + set_local_open(&auth, false); + assert_eq!( + cookieless_unix(&auth, g0), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + // ResetHosts closes it, and the forced load of no file reopens it. + assert_eq!(cookieless_unix(&auth, counter.bump()), AuthVerdict::Allow); + } + + #[test] + fn a_reset_under_xdmcp_closes_local_access() { + let counter = GenerationCounter::new(); + let auth = AuthState::new_with_xdmcp(None, true); + let g0 = counter.current(); + set_local_open(&auth, true); + assert_eq!(cookieless_unix(&auth, g0), AuthVerdict::Allow); + assert_eq!( + cookieless_unix(&auth, counter.bump()), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + } + + #[test] + fn a_reset_forces_the_auth_reload_even_with_an_unchanged_mtime() { + let counter = GenerationCounter::new(); + let path = temp_path("reset-forced-reload"); + let (first, second) = ([0x31u8; 16], [0x32u8; 16]); + fs::write(&path, xauth_bytes(b"0", &first)).unwrap(); + let auth = AuthState::new(Some(path.clone())); + let g0 = counter.current(); + assert_eq!(auth.check(&UNIX, g0, MIT, &first), AuthVerdict::Allow); + rewrite_keeping_mtime(&path, &xauth_bytes(b"0", &second)); + assert_eq!( + auth.check(&UNIX, g0, MIT, &second), + AuthVerdict::Reject(REASON_BAD_COOKIE), + "same mtime: no lazy reload within G0" + ); + + // An open local access from G0 (`xhost +local:`) does not survive. + set_local_open(&auth, true); + let g1 = counter.bump(); + assert_eq!( + auth.check(&UNIX, g1, MIT, &second), + AuthVerdict::Allow, + "the reset forced the reload" + ); + assert_eq!( + auth.check(&UNIX, g1, MIT, &first), + AuthVerdict::Reject(REASON_BAD_COOKIE), + "the reset dropped the cookie the file no longer holds" + ); + assert_eq!( + cookieless_unix(&auth, g1), + AuthVerdict::Reject(REASON_NO_PROTO), + "a loaded cookie leaves local access closed" + ); + let _ = fs::remove_file(path); + } + + #[test] + fn a_reset_with_an_emptied_auth_file_opens_local_access() { + let counter = GenerationCounter::new(); + let path = temp_path("reset-emptied"); + fs::write(&path, xauth_bytes(b"0", &[0x33u8; 16])).unwrap(); + let auth = AuthState::new(Some(path.clone())); + let g0 = counter.current(); + assert_eq!( + cookieless_unix(&auth, g0), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + rewrite_keeping_mtime(&path, b""); + assert_eq!( + cookieless_unix(&auth, g0), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + assert_eq!(cookieless_unix(&auth, counter.bump()), AuthVerdict::Allow); + let _ = fs::remove_file(path); + } + + #[test] + fn a_reset_with_a_deleted_auth_file_keeps_the_reset_value() { + // `loaded` stays TRUE and `loadauth == -1` changes nothing, so the + // value is ResetHosts' closed one. + let counter = GenerationCounter::new(); + let path = temp_path("reset-deleted"); + fs::write(&path, xauth_bytes(b"0", &[0x34u8; 16])).unwrap(); + let auth = AuthState::new(Some(path.clone())); + let g0 = counter.current(); + assert_eq!( + cookieless_unix(&auth, g0), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + set_local_open(&auth, true); + fs::remove_file(&path).unwrap(); + let g1 = counter.bump(); + assert_eq!( + cookieless_unix(&auth, g1), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + assert_eq!( + auth.check(&UNIX, g1, MIT, &[0x34u8; 16]), + AuthVerdict::Reject(REASON_BAD_COOKIE), + "no file to reload, and the reset dropped the old cookie" + ); + } + + #[test] + fn an_older_generation_writes_nothing_and_gets_no_local_fallback() { + let counter = GenerationCounter::new(); + let auth = AuthState::new(None); + let g1 = counter.bump(); + let g2 = counter.bump(); + assert_eq!(cookieless_unix(&auth, g1), AuthVerdict::Allow); + assert_eq!(cookieless_unix(&auth, g2), AuthVerdict::Allow); + assert_eq!( + cookieless_unix(&auth, g1), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + let inner = auth.inner.lock().unwrap(); + assert_eq!(inner.generation, g2); + assert!(inner.local_open); + } + + #[test] + fn reset_reloads_do_not_duplicate_cookies() { + let counter = GenerationCounter::new(); + let path = temp_path("reset-dedup"); + let cookie = [0x35u8; 16]; + fs::write(&path, xauth_bytes(b"0", &cookie)).unwrap(); + let auth = AuthState::new(Some(path.clone())); + let mut generation = counter.current(); + for _ in 0..4 { + assert_eq!( + auth.check(&UNIX, generation, MIT, &cookie), + AuthVerdict::Allow + ); + generation = counter.bump(); + } + assert_eq!(auth.inner.lock().unwrap().cookies.len(), 1); + let _ = fs::remove_file(path); + } + + // ---- the host list: admission through `InvalidHost` ---- + + use crate::core_loop::host_access::{FAMILY_DECNET, HostEntry}; + use std::{ + ffi::CStr, + net::{IpAddr, Ipv4Addr, Ipv6Addr}, + sync::mpsc, + time::Duration as StdDuration, + }; + + const BOB: PeerCred = PeerCred { + uid: 1000, + gid: 100, + pid: None, + }; + const HOST_COOKIE: [u8; 16] = [0x51; 16]; + const WRONG_COOKIE: [u8; 16] = [0x52; 16]; + + /// `bob` is uid 1000, group `staff` gid 100; nothing else resolves. + struct Names; + + impl NameResolver for Names { + fn uid(&self, name: &CStr) -> Option { + (name.to_bytes() == b"bob").then_some(1000) + } + fn gid(&self, name: &CStr) -> Option { + (name.to_bytes() == b"staff").then_some(100) + } + } + + fn unix_peer(cred: Option) -> PeerIdentity { + PeerIdentity { + transport: AuthTransport::Unix, + addr: None, + cred, + } + } + + fn tcp_peer() -> PeerIdentity { + PeerIdentity { + transport: AuthTransport::Tcp, + addr: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)), + cred: None, + } + } + + fn v6_own() -> [u8; 16] { + Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).octets() + } + + fn fake_own_addrs() -> Vec { + vec![ + HostEntry { + family: FAMILY_INTERNET, + addr: vec![127, 0, 0, 1], + }, + HostEntry { + family: FAMILY_INTERNET6, + addr: v6_own().to_vec(), + }, + ] + } + + fn si(kind: &str, value: &str) -> Vec { + let mut addr = kind.as_bytes().to_vec(); + addr.push(0); + addr.extend_from_slice(value.as_bytes()); + addr + } + + /// `-auth` with one cookie, already loaded, so `local_open` is false. + fn enforcing_state(tag: &str, tcp_listen: bool) -> (AuthState, PathBuf) { + let path = temp_path(tag); + fs::write(&path, xauth_bytes(b"0", &HOST_COOKIE)).unwrap(); + let auth = AuthState::build(Some(path.clone()), false, tcp_listen, fake_own_addrs); + assert_eq!( + auth.check_with( + &unix_peer(Some(BOB)), + Generation::default(), + MIT, + &HOST_COOKIE, + &Names + ), + AuthVerdict::Allow + ); + assert!(!auth.inner.lock().unwrap().local_open); + (auth, path) + } + + fn add(auth: &AuthState, family: u8, addr: &[u8]) { + auth.change_hosts(Generation::default(), true, family, addr, &Names) + .unwrap(); + } + + fn cookieless(auth: &AuthState, peer: &PeerIdentity) -> AuthVerdict { + auth.check_with(peer, Generation::default(), b"", b"", &Names) + } + + #[derive(Clone, Copy, Debug)] + enum Source { + AccessDisabled, + LocalOpen, + LocalUserId(&'static str), + LocalUserName(&'static str), + LocalGroupId(&'static str), + LocalGroupName(&'static str), + SelfLocalHost, + } + + fn apply(auth: &AuthState, source: Source) { + match source { + Source::AccessDisabled => auth + .set_access_enabled(Generation::default(), false) + .unwrap(), + Source::LocalOpen => set_local_open(auth, true), + Source::LocalUserId(v) | Source::LocalUserName(v) => { + add(auth, FAMILY_SERVER_INTERPRETED, &si("localuser", v)); + } + Source::LocalGroupId(v) | Source::LocalGroupName(v) => { + add(auth, FAMILY_SERVER_INTERPRETED, &si("localgroup", v)); + } + Source::SelfLocalHost => { + add(auth, FAMILY_LOCAL_HOST, &[]); + set_local_open(auth, false); + } + } + } + + const ADMITTING: [Source; 7] = [ + Source::AccessDisabled, + Source::LocalOpen, + Source::LocalUserId("#1000"), + Source::LocalUserName("bob"), + Source::LocalGroupId("#100"), + Source::LocalGroupName("staff"), + Source::SelfLocalHost, + ]; + + #[test] + fn each_host_source_alone_admits_a_cookieless_unix_peer() { + for (n, source) in ADMITTING.into_iter().enumerate() { + let (auth, path) = enforcing_state(&format!("h-admit-{n}"), true); + let bob = unix_peer(Some(BOB)); + assert_eq!( + cookieless(&auth, &bob), + AuthVerdict::Reject(REASON_NO_PROTO), + "{source:?}: refused before" + ); + apply(&auth, source); + assert_eq!(cookieless(&auth, &bob), AuthVerdict::Allow, "{source:?}"); + assert_eq!( + auth.check_with(&bob, Generation::default(), MIT, &WRONG_COOKIE, &Names), + AuthVerdict::Allow, + "{source:?}: a wrong cookie falls through to the list too" + ); + let _ = fs::remove_file(path); + } + } + + #[test] + fn non_matching_host_entries_refuse() { + let cases: [(Source, Option); 5] = [ + (Source::LocalUserId("#1001"), Some(BOB)), + (Source::LocalGroupId("#101"), Some(BOB)), + // A supplementary group of the peer: credentials carry the + // primary gid only, as on Xorg's SO_PEERCRED/getpeereid paths. + (Source::LocalGroupId("#27"), Some(BOB)), + (Source::LocalUserId("#1000"), None), + (Source::LocalGroupId("#100"), None), + ]; + for (n, (source, cred)) in cases.into_iter().enumerate() { + let (auth, path) = enforcing_state(&format!("h-refuse-{n}"), true); + apply(&auth, source); + assert_eq!( + cookieless(&auth, &unix_peer(cred)), + AuthVerdict::Reject(REASON_NO_PROTO), + "{source:?} against {cred:?}" + ); + let _ = fs::remove_file(path); + } + } + + #[test] + fn no_host_source_admits_tcp() { + for (n, source) in ADMITTING.into_iter().enumerate() { + let (auth, path) = enforcing_state(&format!("h-tcp-{n}"), true); + apply(&auth, source); + assert_eq!( + auth.check_with( + &tcp_peer(), + Generation::default(), + MIT, + &WRONG_COOKIE, + &Names + ), + AuthVerdict::Reject(REASON_BAD_COOKIE), + "{source:?}" + ); + assert_eq!( + auth.check_with(&tcp_peer(), Generation::default(), b"", b"", &Names), + AuthVerdict::Reject(REASON_NO_PROTO), + "{source:?}" + ); + assert_eq!( + auth.check_with( + &tcp_peer(), + Generation::default(), + MIT, + &HOST_COOKIE, + &Names + ), + AuthVerdict::Allow, + "{source:?}: the file cookie still admits TCP" + ); + let _ = fs::remove_file(path); + } + } + + #[test] + fn xdmcp_tcp_needs_the_session_credential_whatever_the_list_says() { + let auth = AuthState::build(None, true, true, fake_own_addrs); + let generation = Generation::default(); + let session = [0x53u8; 16]; + assert!(auth.install_session_cookie(generation, MIT, &session)); + auth.set_access_enabled(generation, false).unwrap(); + add(&auth, FAMILY_LOCAL_HOST, &[]); + assert_eq!( + auth.check_with(&tcp_peer(), generation, MIT, &session, &Names), + AuthVerdict::Allow + ); + assert_eq!( + auth.check_with(&tcp_peer(), generation, MIT, &WRONG_COOKIE, &Names), + AuthVerdict::Reject(REASON_BAD_COOKIE) + ); + } + + #[test] + fn a_valid_cookie_admits_with_an_enabled_empty_list() { + let (auth, path) = enforcing_state("h-cookie", false); + assert_eq!(auth.list_hosts(Generation::default()), (true, Vec::new())); + assert_eq!( + auth.check_with( + &unix_peer(None), + Generation::default(), + MIT, + &HOST_COOKIE, + &Names + ), + AuthVerdict::Allow + ); + let _ = fs::remove_file(path); + } + + /// `+local:` and then a cookie reload: `DisableLocalHost` closes local + /// access, the entry stays listed (os/access.c:300-311, :1322-1325). + fn local_host_then_reload(auth: &AuthState, path: &Path, addr: &[u8]) { + add(auth, FAMILY_LOCAL_HOST, addr); + assert!(auth.inner.lock().unwrap().local_open); + fs::write(path, xauth_bytes(b"0", &[0x54u8; 16])).unwrap(); + touch_later(path); + // Any connection triggers the lazy reload. + assert_eq!( + auth.check_with( + &unix_peer(None), + Generation::default(), + MIT, + &HOST_COOKIE, + &Names + ), + AuthVerdict::Allow + ); + assert!(!auth.inner.lock().unwrap().local_open); + } + + #[test] + fn a_cookie_reload_closes_local_host_but_keeps_the_entry() { + let (auth, path) = enforcing_state("h-local-reload", false); + local_host_then_reload(&auth, &path, &[]); + assert_eq!( + auth.list_hosts(Generation::default()), + ( + true, + vec![HostEntry { + family: FAMILY_LOCAL_HOST, + addr: Vec::new(), + }] + ) + ); + let _ = fs::remove_file(path); + } + + #[test] + fn a_listed_selfhost_admits_unix_only_with_a_tcp_listener() { + for tcp_listen in [true, false] { + let expected = if tcp_listen { + AuthVerdict::Allow + } else { + AuthVerdict::Reject(REASON_NO_PROTO) + }; + let (auth, path) = enforcing_state(&format!("h-self-local-{tcp_listen}"), tcp_listen); + local_host_then_reload(&auth, &path, &[]); + assert_eq!( + cookieless(&auth, &unix_peer(None)), + expected, + "{{252, []}}, tcp_listen {tcp_listen}" + ); + let _ = fs::remove_file(path); + + let (auth, path) = enforcing_state(&format!("h-self-v4-{tcp_listen}"), tcp_listen); + add(&auth, FAMILY_INTERNET, &[127, 0, 0, 1]); + assert_eq!( + cookieless(&auth, &unix_peer(None)), + expected, + "127.0.0.1, tcp_listen {tcp_listen}" + ); + let _ = fs::remove_file(path); + } + } + + #[test] + fn a_nonzero_length_local_host_entry_is_not_a_selfhost() { + let (auth, path) = enforcing_state("h-self-local-len", true); + local_host_then_reload(&auth, &path, &[1]); + assert_eq!( + cookieless(&auth, &unix_peer(None)), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + let _ = fs::remove_file(path); + } + + #[test] + fn ipv6_selfhosts_come_from_the_own_address_list() { + let other = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2).octets(); + for tcp_listen in [true, false] { + let (auth, path) = enforcing_state(&format!("h-self-v6-{tcp_listen}"), tcp_listen); + add(&auth, FAMILY_INTERNET6, &other); + assert_eq!( + cookieless(&auth, &unix_peer(None)), + AuthVerdict::Reject(REASON_NO_PROTO), + "2001:db8::2 is not ours" + ); + add(&auth, FAMILY_INTERNET6, &v6_own()); + let expected = if tcp_listen { + AuthVerdict::Allow + } else { + AuthVerdict::Reject(REASON_NO_PROTO) + }; + assert_eq!( + cookieless(&auth, &unix_peer(None)), + expected, + "2001:db8::1, tcp_listen {tcp_listen}" + ); + let _ = fs::remove_file(path); + } + } + + #[test] + fn the_host_list_does_not_survive_a_reset() { + let counter = GenerationCounter::new(); + let (auth, path) = enforcing_state("h-reset", false); + let g0 = counter.current(); + add(&auth, FAMILY_SERVER_INTERPRETED, &si("localuser", "#1000")); + auth.set_access_enabled(g0, false).unwrap(); + let bob = unix_peer(Some(BOB)); + assert_eq!(cookieless(&auth, &bob), AuthVerdict::Allow); + let g1 = counter.bump(); + assert_eq!( + auth.check_with(&bob, g1, b"", b"", &Names), + AuthVerdict::Reject(REASON_NO_PROTO) + ); + assert_eq!(auth.list_hosts(g1), (true, Vec::new())); + let _ = fs::remove_file(path); + } + + #[test] + fn a_stale_generation_cannot_write_the_list() { + let counter = GenerationCounter::new(); + let auth = AuthState::new(None); + let g0 = counter.current(); + let g1 = counter.bump(); + assert_eq!(auth.list_hosts(g1), (true, Vec::new())); + assert_eq!( + auth.change_hosts(g0, true, FAMILY_LOCAL_HOST, &[], &Names), + Err(HostChangeError::Access) + ); + assert_eq!( + auth.set_access_enabled(g0, false), + Err(HostChangeError::Access) + ); + assert_eq!(auth.list_hosts(g1), (true, Vec::new())); + } + + #[test] + fn change_hosts_validates_before_storing() { + let auth = AuthState::new(None); + let g = Generation::default(); + assert_eq!( + auth.change_hosts(g, true, FAMILY_DECNET, &[1, 2], &Names), + Err(HostChangeError::Value(BadValue::Length)) + ); + assert_eq!( + auth.change_hosts(g, true, 7, &[], &Names), + Err(HostChangeError::Value(BadValue::Family)) + ); + assert_eq!( + auth.change_hosts( + g, + true, + FAMILY_SERVER_INTERPRETED, + &si("localuser", "nobody_here"), + &Names + ), + Err(HostChangeError::Value(BadValue::Length)) + ); + assert_eq!(auth.list_hosts(g), (true, Vec::new())); + } + + /// Blocks inside `uid` until released, after announcing it got there. + struct BlockingNames { + entered: mpsc::Sender<()>, + release: Mutex>, + } + + impl NameResolver for BlockingNames { + fn uid(&self, name: &CStr) -> Option { + self.entered.send(()).unwrap(); + self.release.lock().unwrap().recv().unwrap(); + Names.uid(name) + } + fn gid(&self, name: &CStr) -> Option { + Names.gid(name) + } + } + + #[test] + fn name_lookups_at_check_run_with_the_lock_released() { + let (auth, path) = enforcing_state("h-unlocked", false); + let auth = Arc::new(auth); + add(&auth, FAMILY_SERVER_INTERPRETED, &si("localuser", "bob")); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let checker = { + let auth = Arc::clone(&auth); + std::thread::spawn(move || { + let resolver = BlockingNames { + entered: entered_tx, + release: Mutex::new(release_rx), + }; + auth.check_with( + &unix_peer(Some(BOB)), + Generation::default(), + b"", + b"", + &resolver, + ) + }) + }; + entered_rx + .recv_timeout(StdDuration::from_secs(10)) + .expect("check reached the resolver"); + let (done_tx, done_rx) = mpsc::channel(); + let writer = { + let auth = Arc::clone(&auth); + std::thread::spawn(move || { + add(&auth, FAMILY_SERVER_INTERPRETED, &si("localuser", "#1")); + done_tx.send(()).unwrap(); + }) + }; + let completed = done_rx.recv_timeout(StdDuration::from_secs(10)).is_ok(); + release_tx.send(()).unwrap(); + assert!(completed, "change_hosts blocked behind a check in NSS"); + writer.join().unwrap(); + assert_eq!(checker.join().unwrap(), AuthVerdict::Allow); + let _ = fs::remove_file(path); + } } diff --git a/crates/yserver-core/src/core_loop/client_io.rs b/crates/yserver-core/src/core_loop/client_io.rs index 2ca8ed076..1a1ec0ced 100644 --- a/crates/yserver-core/src/core_loop/client_io.rs +++ b/crates/yserver-core/src/core_loop/client_io.rs @@ -4,30 +4,70 @@ //! `write_or_buffer`. It tries a direct non-blocking `write(2)` first; //! on `EAGAIN`/partial write it buffers the remainder on //! `ClientState::outbound` and returns `WouldBlock` so the caller can -//! arrange `WRITABLE` interest in the poller (I2). When the buffer is -//! about to exceed `OUTBOUND_CAP` we return `Disconnect` and let the -//! caller tear the client down. +//! arrange `WRITABLE` interest in the poller (I2). The buffer grows as +//! Xorg's does (`FlushClient`, `os/io.c`), up to `INT_MAX`; only past +//! that do we return `Disconnect`. +//! +//! Every failed write also marks the client `write_failed`: later writes +//! to it are refused without touching the socket, and the core loop +//! disconnects it through the normal path (`failed_writers`). Callers may +//! act on the outcome, but ignoring it can no longer keep the client. //! //! Today's `ClientState::writer` is still `Arc>` //! (A1 left it untouched; D2 demotes it). The helper transparently //! locks the mutex; once D2 lands we strip the lock without touching //! call sites. -use std::io::{self, ErrorKind, Write}; +use std::{ + collections::VecDeque, + io::{self, ErrorKind, Write}, +}; + +use yserver_protocol::x11::ClientId; -use crate::server::ClientState; +use crate::{ + fd::{OwnedFd, RawFd}, + server::ClientState, + transport::Transport, +}; /// Maximum bytes queued per client before we treat the peer as -/// unrecoverably slow and disconnect. +/// unrecoverably slow and disconnect: Xorg's, whose `FlushClient` +/// (`os/io.c`) grows a client's output buffer for as long as +/// `notWritten + BUFSIZE <= INT_MAX` and aborts the client only past it. /// -/// Sized to fit a single legitimate large reply with headroom for -/// additional traffic. The motivating case is a QueryFont reply for an -/// ISO10646 host font (`-Misc-Fixed-*-ISO10646-1`): m=65536 CHAR_INFOs -/// ⇒ 32 + 4·(7 + 2n + 3·65536) ≈ 786 KB. With Linux's default -/// 208 KB unix-socket send buffer the partial-write tail is ~578 KB, -/// so a smaller cap would force a spurious slow-client disconnect on a -/// fast client that simply hasn't read the reply yet. -pub const OUTBOUND_CAP: usize = 4 * 1024 * 1024; +/// It was 4 MiB, sized to one large QueryFont reply. A client that +/// stopped reading for a while was dropped at that cap, where Xorg would +/// have kept its output. +pub const OUTBOUND_CAP: usize = i32::MAX as usize; + +/// Queued output this large is logged, and each doubling past it: a +/// client that stopped reading, and what it is sent. +const BACKLOG_REPORT: usize = 1024 * 1024; + +#[cfg(test)] +thread_local! { + /// The cap tests saturate, a test thread's own: 4 MiB unless a test + /// sets it, so a saturated client costs no more than that. + static TEST_CAP: std::cell::Cell = const { std::cell::Cell::new(4 * 1024 * 1024) }; +} + +/// The cap in force: [`OUTBOUND_CAP`], or a test thread's. +pub fn outbound_cap() -> usize { + #[cfg(test)] + return TEST_CAP.with(std::cell::Cell::get); + #[cfg(not(test))] + OUTBOUND_CAP +} + +/// Test support: run `f` with the production cap in force on this thread. +#[cfg(test)] +pub(crate) fn with_production_cap(f: impl FnOnce() -> T) -> T { + let before = TEST_CAP.with(|cap| cap.replace(OUTBOUND_CAP)); + let out = f(); + TEST_CAP.with(|cap| cap.set(before)); + out +} #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum WriteOutcome { @@ -36,17 +76,168 @@ pub enum WriteOutcome { /// Some bytes are buffered on `client.outbound`. Caller should /// register `WRITABLE` interest if not already. WouldBlock, - /// Peer is gone or buffer exceeded `OUTBOUND_CAP`. Caller must - /// drop the client. + /// Peer is gone or buffer exceeded `OUTBOUND_CAP`. The client is + /// marked `write_failed`, so the core loop drops it. Disconnect, } +/// Descriptors waiting in `ClientState::outbound`, each with the offset and +/// length there of its reply. A descriptor goes in the `SCM_RIGHTS` of a +/// `sendmsg` of its reply's bytes, as Xorg's `WriteFdToClient` (`os/io.c`) +/// leaves it to xtrans's next flush: queued with the output, never waited +/// for. +#[derive(Debug, Default)] +pub struct OutboundFds(VecDeque); + +#[derive(Debug)] +struct QueuedFd { + at: usize, + len: usize, + fd: OwnedFd, +} + +impl OutboundFds { + fn next_at(&self) -> Option { + self.0.front().map(|queued| queued.at) + } + + /// `n` bytes went, with the front descriptor when `with_front`. + fn sent(&mut self, n: usize, with_front: bool) { + if with_front { + self.0.pop_front(); + } + for queued in &mut self.0 { + queued.at -= n; + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + +/// Queue `bytes` behind the client's output with `fd`, which their first +/// byte carries, and write what the socket takes now. The descriptor is +/// duplicated: the caller keeps and closes its own. +pub fn write_with_fd( + client: &mut ClientState, + bytes: &[u8], + fd: RawFd, +) -> io::Result { + if client.gone { + return Ok(WriteOutcome::Done); + } + if client.write_failed { + return Ok(WriteOutcome::Disconnect); + } + let outcome = write_with_fd_inner(client, bytes, fd); + note_failure(client, outcome) +} + +fn write_with_fd_inner( + client: &mut ClientState, + bytes: &[u8], + fd: RawFd, +) -> io::Result { + if !client.outbound.is_empty() && client.outbound.len() + bytes.len() > outbound_cap() { + log::warn!( + "client_io: client 0x{:x}: outbound cap exceeded -- {} bytes unread, +{} new with a descriptor; disconnecting", + client.resource_id_base, + client.outbound.len(), + bytes.len(), + ); + return Ok(WriteOutcome::Disconnect); + } + let fd = duplicate(fd)?; + let at = client.outbound.len(); + client.outbound_fds.0.push_back(QueuedFd { + at, + len: bytes.len(), + fd, + }); + client.outbound.extend(bytes.iter().copied()); + drain_outbound_inner(client) +} + +#[cfg(unix)] +fn duplicate(fd: RawFd) -> io::Result { + // SAFETY: the caller's descriptor is open for the call. + unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }.try_clone_to_owned() +} + +/// No Windows transport passes descriptors, so `fd_passing` is never set. +#[cfg(windows)] +fn duplicate(_fd: RawFd) -> io::Result { + Err(unsupported()) +} + +fn unsupported() -> io::Error { + io::Error::new( + ErrorKind::Unsupported, + "file descriptor passing is unavailable on this transport", + ) +} + +/// One `sendmsg` of `chunk` with `fd`: the bytes it took. +#[cfg(unix)] +fn send_with_fd(writer: &mut Transport, chunk: &[u8], fd: &OwnedFd) -> io::Result { + let Transport::Unix(stream) = writer else { + return Err(unsupported()); + }; + match crate::unix_fd::send_with_fd(stream, chunk, std::os::fd::AsRawFd::as_raw_fd(fd)) { + // The BSDs' unix stream socket (macOS's among them) shrinks the + // sender's limit as the peer's buffer fills, and refuses a message + // whose descriptor no longer fits with EMSGSIZE rather than EAGAIN. + // It fits once the client reads. + Err(e) if e.raw_os_error() == Some(libc::EMSGSIZE) => Err(ErrorKind::WouldBlock.into()), + other => other, + } +} + +#[cfg(windows)] +fn send_with_fd(_writer: &mut Transport, _chunk: &[u8], fd: &OwnedFd) -> io::Result { + match *fd {} +} + /// Write `bytes` to the client. Drains any already-buffered outbound /// first so wire ordering is preserved. pub fn write_or_buffer(client: &mut ClientState, bytes: &[u8]) -> io::Result { + // Xorg `WriteToClient` drops output to a gone client (`os/io.c:700`). + if client.gone { + return Ok(WriteOutcome::Done); + } + if client.write_failed { + return Ok(WriteOutcome::Disconnect); + } + let outcome = write_or_buffer_inner(client, bytes); + note_failure(client, outcome) +} + +/// Clients whose writes failed and that the core loop must disconnect. +pub fn failed_writers(clients: &std::collections::HashMap) -> Vec { + let mut failed: Vec = clients + .iter() + .filter(|(_, client)| client.write_failed && !client.gone) + .map(|(id, _)| ClientId(*id)) + .collect(); + failed.sort_unstable_by_key(|id| id.0); + failed +} + +fn note_failure( + client: &mut ClientState, + outcome: io::Result, +) -> io::Result { + if !matches!(outcome, Ok(WriteOutcome::Done | WriteOutcome::WouldBlock)) { + client.write_failed = true; + } + outcome +} + +fn write_or_buffer_inner(client: &mut ClientState, bytes: &[u8]) -> io::Result { // Drain pending bytes first. if !client.outbound.is_empty() { - match drain_outbound(client)? { + match drain_outbound_inner(client)? { WriteOutcome::Done => {} // fall through to write `bytes` WriteOutcome::WouldBlock => { return Ok(buffer_or_disconnect(client, bytes)); @@ -60,7 +251,7 @@ pub fn write_or_buffer(client: &mut ClientState, bytes: &[u8]) -> io::Result Ok(WriteOutcome::Done), - Ok(0) => Ok(WriteOutcome::Disconnect), + Ok(0) => Ok(peer_gone(client, "write returned 0")), Ok(n) => { drop(writer); Ok(buffer_or_disconnect(client, &bytes[n..])) @@ -69,61 +260,138 @@ pub fn write_or_buffer(client: &mut ClientState, bytes: &[u8]) -> io::Result Ok(WriteOutcome::Disconnect), + Err(e) if disconnect_kind(e.kind()) => Ok(peer_gone(client, &e.to_string())), Err(e) => Err(e), } } /// Push `bytes` onto `client.outbound`, or return `Disconnect` if -/// doing so would exceed `OUTBOUND_CAP`. +/// doing so would exceed the cap ([`OUTBOUND_CAP`]). fn buffer_or_disconnect(client: &mut ClientState, bytes: &[u8]) -> WriteOutcome { - if !client.outbound.is_empty() && client.outbound.len() + bytes.len() > OUTBOUND_CAP { + let before = client.outbound.len(); + if before != 0 && before + bytes.len() > outbound_cap() { log::warn!( - "client_io: outbound cap exceeded — outbound={} bytes pending, +{} new ⇒ Disconnect", - client.outbound.len(), + "client_io: client 0x{:x}: outbound cap exceeded -- {} bytes unread, +{} new; disconnecting", + client.resource_id_base, + before, bytes.len(), ); return WriteOutcome::Disconnect; } - let was_empty = client.outbound.is_empty(); client.outbound.extend(bytes.iter().copied()); - if was_empty { - log::trace!( - "client_io: starting to buffer outbound — {} bytes (kernel buffer full)", - client.outbound.len(), + let after = client.outbound.len(); + if before == 0 { + log::trace!("client_io: starting to buffer outbound -- {after} bytes (kernel buffer full)"); + } + if crossed_report(before, after) { + log::info!( + "client_io: client 0x{:x} reads slowly: {} bytes unread; the newest message {}", + client.resource_id_base, + after, + describe(bytes), ); } WriteOutcome::WouldBlock } +/// Whether the backlog went past [`BACKLOG_REPORT`] or one of its +/// doublings. +fn crossed_report(before: usize, after: usize) -> bool { + let mut mark = BACKLOG_REPORT; + while mark <= after { + if before < mark { + return true; + } + match mark.checked_mul(2) { + Some(next) => mark = next, + None => return false, + } + } + false +} + +/// An outgoing message by its header, for the backlog log: a reply, an +/// error, an event by code, a GenericEvent by extension and type. +fn describe(bytes: &[u8]) -> String { + match bytes { + [] => "(none)".into(), + [0, code, ..] => format!("is error {code} ({} bytes)", bytes.len()), + [1, ..] => format!("is a reply ({} bytes)", bytes.len()), + [35, extension, _, _, _, _, _, _, low, high, ..] => format!( + "is GenericEvent of extension {extension}, type {} ({} bytes)", + u16::from_le_bytes([*low, *high]), + bytes.len() + ), + [code, ..] => format!("is event {} ({} bytes)", code & 0x7f, bytes.len()), + } +} + /// Push as much of `client.outbound` to the wire as possible without /// blocking. Returns `Done` if the queue is now empty, `WouldBlock` if /// some bytes remain, `Disconnect` if the peer is gone. pub fn drain_outbound(client: &mut ClientState) -> io::Result { + if client.gone { + client.outbound.clear(); + client.outbound_fds.clear(); + return Ok(WriteOutcome::Done); + } + if client.write_failed { + return Ok(WriteOutcome::Disconnect); + } + let outcome = drain_outbound_inner(client); + note_failure(client, outcome) +} + +fn drain_outbound_inner(client: &mut ClientState) -> io::Result { let writer_arc = client.writer.clone(); let mut writer = writer_arc.lock().unwrap(); while !client.outbound.is_empty() { + // A descriptor goes with its reply's bytes alone, and any other + // chunk ends where the next descriptor's reply begins. + let with_fd = client.outbound_fds.next_at() == Some(0); + let end = if with_fd { + client.outbound_fds.0.front().map(|queued| queued.len) + } else { + client.outbound_fds.next_at() + } + .unwrap_or(usize::MAX); // VecDeque can wrap; iterate over the contiguous front slice // first. `as_slices().0` is the front; `.1` is everything past // the wrap point. Copy out a small chunk to dodge a borrow // conflict with the subsequent `drain` call. let chunk: Vec = { let (front, _) = client.outbound.as_slices(); - front[..front.len().min(8 * 1024)].to_vec() + front[..front.len().min(8 * 1024).min(end)].to_vec() }; - match writer.write(&chunk) { - Ok(0) => return Ok(WriteOutcome::Disconnect), + let written = match client.outbound_fds.0.front() { + Some(queued) if with_fd => send_with_fd(&mut writer, &chunk, &queued.fd), + _ => writer.write(&chunk), + }; + match written { + Ok(0) => return Ok(peer_gone(client, "write returned 0")), Ok(n) => { client.outbound.drain(..n); + client.outbound_fds.sent(n, with_fd); } Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(WriteOutcome::WouldBlock), - Err(e) if disconnect_kind(e.kind()) => return Ok(WriteOutcome::Disconnect), + Err(e) if disconnect_kind(e.kind()) => return Ok(peer_gone(client, &e.to_string())), Err(e) => return Err(e), } } Ok(WriteOutcome::Done) } +/// The peer went: said once, since the client's writes stop here, so the +/// disconnect that follows says why. +fn peer_gone(client: &ClientState, why: &str) -> WriteOutcome { + log::info!( + "client_io: client 0x{:x}: the peer is gone ({why}), {} bytes unread", + client.resource_id_base, + client.outbound.len(), + ); + WriteOutcome::Disconnect +} + fn disconnect_kind(k: ErrorKind) -> bool { matches!( k, @@ -131,6 +399,20 @@ fn disconnect_kind(k: ErrorKind) -> bool { ) } +/// Test support: fill `client`'s socket, then its outbound buffer to +/// the cap ([`outbound_cap`]), so its next write overflows. +#[cfg(test)] +pub(crate) fn saturate_for_test(client: &mut ClientState) { + client.writer.lock().unwrap().set_nonblocking(true).unwrap(); + client + .outbound + .extend(std::iter::repeat_n(0u8, outbound_cap())); + let _ = drain_outbound(client); + let missing = outbound_cap() - client.outbound.len(); + client.outbound.extend(std::iter::repeat_n(0u8, missing)); + assert!(!client.write_failed); +} + #[cfg(test)] mod tests { use super::*; @@ -145,6 +427,7 @@ mod tests { fn make_client(writer: UnixStream) -> ClientState { ClientState { + admission: crate::access::Admission::Internal, writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(writer))), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -157,11 +440,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ResourceId(0), reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), } } @@ -200,7 +488,7 @@ mod tests { let payload = vec![0xABu8; 32 * 1024]; let outcome = write_or_buffer(&mut c, &payload).unwrap(); // Either WouldBlock (some buffered) or Disconnect (overflowed cap). - // For 32 KiB <= OUTBOUND_CAP (64 KiB), it should be WouldBlock. + // For 32 KiB <= outbound_cap(), it should be WouldBlock. assert_eq!(outcome, WriteOutcome::WouldBlock); assert!(!c.outbound.is_empty(), "remainder should be buffered"); // Drain the peer; outbound should now drain to empty. @@ -229,17 +517,137 @@ mod tests { let mut c = make_client(a); // Fill the kernel buffer first so the next call must buffer. let _ = write_or_buffer(&mut c, &vec![0u8; 8 * 1024]).unwrap(); - // Now hand it more than OUTBOUND_CAP — must Disconnect. - let huge = vec![0u8; OUTBOUND_CAP + 1]; + // Now hand it more than the cap — must Disconnect. + let huge = vec![0u8; outbound_cap() + 1]; let outcome = write_or_buffer(&mut c, &huge).unwrap(); assert_eq!(outcome, WriteOutcome::Disconnect); } + /// An overflow marks the client failed; nothing more reaches its socket + /// or buffer, even after its peer catches up, and `failed_writers` + /// names it for the core loop. + #[test] + fn overflow_marks_client_failed_and_refuses_later_writes() { + let (a, mut b) = UnixStream::pair().unwrap(); + let mut c = make_client(a); + saturate_for_test(&mut c); + assert_eq!( + write_or_buffer(&mut c, &[1u8; 32]).unwrap(), + WriteOutcome::Disconnect + ); + assert!(c.write_failed); + assert_eq!(c.outbound.len(), outbound_cap()); + + b.set_nonblocking(true).unwrap(); + let mut sink = vec![0u8; 1 << 20]; + while b.read(&mut sink).is_ok_and(|n| n > 0) {} + assert_eq!( + write_or_buffer(&mut c, &[1u8; 32]).unwrap(), + WriteOutcome::Disconnect + ); + assert_eq!(drain_outbound(&mut c).unwrap(), WriteOutcome::Disconnect); + assert_eq!(c.outbound.len(), outbound_cap()); + assert!(b.read(&mut sink).is_err(), "no byte after the failure"); + + let mut clients = HashMap::new(); + clients.insert(9, c); + let (ok, _ok_peer) = UnixStream::pair().unwrap(); + clients.insert(3, make_client(ok)); + assert_eq!(failed_writers(&clients), [ClientId(9)]); + } + + /// A peer that hung up marks the client failed too. + #[test] + fn peer_gone_marks_client_failed() { + let (a, b) = UnixStream::pair().unwrap(); + drop(b); + let mut c = make_client(a); + assert_eq!( + write_or_buffer(&mut c, &[1u8; 32]).unwrap(), + WriteOutcome::Disconnect + ); + assert!(c.write_failed); + } + + /// A gone client's output is dropped (Xorg `WriteToClient`, `os/io.c:700`; + /// `output_pending_clear`, `dix/dispatch.c:3522`): a write to its + /// shut-down socket neither fails nor queues it for another disconnect. + #[test] + fn gone_client_drops_output_and_is_not_queued_for_disconnect() { + let (a, b) = UnixStream::pair().unwrap(); + drop(b); + let mut c = make_client(a); + c.outbound.extend([0u8; 32]); + c.gone = true; + assert_eq!( + write_or_buffer(&mut c, &[1u8; 32]).unwrap(), + WriteOutcome::Done + ); + assert_eq!(drain_outbound(&mut c).unwrap(), WriteOutcome::Done); + assert!(c.outbound.is_empty()); + assert!(!c.write_failed); + c.write_failed = true; + let mut clients = HashMap::new(); + clients.insert(9, c); + assert!(failed_writers(&clients).is_empty()); + } + + /// A reply with a descriptor to a client that is not reading is queued + /// at once, as Xorg's `WriteFdToClient` queues it: the core thread never + /// waits for the client. Once the client reads, each descriptor arrives + /// with its own reply's first byte, two replies in a row included. + #[test] + fn an_fd_reply_to_a_full_socket_is_queued_and_each_fd_goes_with_its_reply() { + let (a, mut b) = pair_with_small_sndbuf(); + let mut c = make_client(a); + let filler = vec![7u8; 64 * 1024]; + assert_eq!( + write_or_buffer(&mut c, &filler).unwrap(), + WriteOutcome::WouldBlock + ); + let null = std::fs::File::open("/dev/null").unwrap(); + let null_fd = std::os::fd::AsRawFd::as_raw_fd(&null); + let started = std::time::Instant::now(); + for reply in [[1u8; 32], [2u8; 32]] { + assert_eq!( + write_with_fd(&mut c, &reply, null_fd).unwrap(), + WriteOutcome::WouldBlock + ); + } + assert!(started.elapsed() < std::time::Duration::from_millis(50)); + drop(null); + + b.set_nonblocking(true).unwrap(); + let total = filler.len() + 64; + let mut received = Vec::new(); + let mut fd_offsets = Vec::new(); + let mut buf = [0u8; 4096]; + while received.len() < total { + let _ = drain_outbound(&mut c).unwrap(); + match crate::unix_fd::recv_with_fds(&mut b, &mut buf) { + Ok((n, fds)) => { + for fd in fds { + fd_offsets.push(received.len()); + // SAFETY: received for this test, closed once. + unsafe { libc::close(fd) }; + } + received.extend_from_slice(&buf[..n]); + } + Err(e) if e.kind() == ErrorKind::WouldBlock => {} + Err(e) => panic!("recvmsg: {e}"), + } + } + assert_eq!(fd_offsets, [filler.len(), filler.len() + 32]); + assert_eq!(&received[filler.len()..filler.len() + 32], &[1u8; 32]); + assert_eq!(&received[filler.len() + 32..], &[2u8; 32]); + assert!(c.outbound.is_empty() && c.outbound_fds.0.is_empty()); + } + #[test] fn single_oversized_reply_buffers_when_outbound_empty() { let (a, _b) = pair_with_small_sndbuf(); let mut c = make_client(a); - let big = vec![0u8; OUTBOUND_CAP + 1_000_000]; + let big = vec![0u8; outbound_cap() + 1_000_000]; let outcome = buffer_or_disconnect(&mut c, &big); assert_eq!(outcome, WriteOutcome::WouldBlock); assert_eq!(c.outbound.len(), big.len()); @@ -250,7 +658,7 @@ mod tests { let (a, _b) = pair_with_small_sndbuf(); let mut c = make_client(a); c.outbound - .extend(std::iter::repeat_n(0u8, OUTBOUND_CAP - 10)); + .extend(std::iter::repeat_n(0u8, outbound_cap() - 10)); let outcome = buffer_or_disconnect(&mut c, &[0u8; 1000]); assert_eq!(outcome, WriteOutcome::Disconnect); } @@ -290,6 +698,88 @@ mod tests { assert!(c.outbound.is_empty(), "buffer should drain to empty"); } + /// A client that stopped reading was dropped once 4 MiB were queued + /// for it. Xorg keeps buffering (`FlushClient`, up to `INT_MAX`): so does the core now. + /// What that could cost instead: a writer stalled on the client that + /// does not read, or bytes out of order. Neither: each write returns at + /// once, a client that reads is served meanwhile, and the slow one gets + /// every byte in order once it reads. + #[test] + fn a_client_that_stops_reading_keeps_its_output_as_xorg_does() { + with_production_cap(|| { + let (a, mut slow_peer) = pair_with_small_sndbuf(); + let mut slow = make_client(a); + let (b, mut fast_peer) = UnixStream::pair().unwrap(); + b.set_nonblocking(true).unwrap(); + let mut fast = make_client(b); + let event = |n: u32| { + let mut bytes = [0u8; 32]; + bytes[0] = 6; // MotionNotify + bytes[4..8].copy_from_slice(&n.to_le_bytes()); + bytes + }; + // 16 MiB of events, four times the old cap, the peer reading + // nothing (a write that waited would hang here); another + // client's write between every 4096. + let count = 16 * 1024 * 1024 / 32; + for n in 0..count { + let outcome = write_or_buffer(&mut slow, &event(n)).unwrap(); + assert_ne!(outcome, WriteOutcome::Disconnect, "event {n}"); + if n % 4096 == 0 { + assert_eq!( + write_or_buffer(&mut fast, &event(n)).unwrap(), + WriteOutcome::Done + ); + let mut got = [0u8; 32]; + fast_peer.read_exact(&mut got).unwrap(); + assert_eq!(got, event(n)); + } + } + assert!(!slow.write_failed); + assert!(slow.outbound.len() > 4 * 1024 * 1024); + // The peer reads; every event arrives, in order. + slow_peer.set_nonblocking(true).unwrap(); + let mut next = 0u32; + let mut pending = Vec::new(); + let mut sink = vec![0u8; 64 * 1024]; + while next < count { + let _ = drain_outbound(&mut slow).unwrap(); + match slow_peer.read(&mut sink) { + Ok(n) => pending.extend_from_slice(&sink[..n]), + Err(e) if e.kind() == ErrorKind::WouldBlock => {} + Err(e) => panic!("read: {e}"), + } + let whole = pending.len() / 32 * 32; + for chunk in pending[..whole].chunks_exact(32) { + assert_eq!(chunk, event(next)); + next += 1; + } + pending.drain(..whole); + } + assert!(slow.outbound.is_empty()); + }); + } + + #[test] + fn a_backlog_is_reported_at_a_mebibyte_and_each_doubling() { + let mib = 1024 * 1024; + assert!(!crossed_report(0, mib - 1)); + assert!(crossed_report(mib - 1, mib)); + assert!(!crossed_report(mib, mib + 32)); + assert!(crossed_report(3 * mib, 4 * mib + 1)); + assert!(!crossed_report(4 * mib + 1, 5 * mib)); + assert!(!crossed_report(usize::MAX - 1, usize::MAX)); + let mut generic = [0u8; 32]; + generic[0] = 35; + generic[1] = 131; + generic[8] = 17; + assert_eq!( + describe(&generic), + "is GenericEvent of extension 131, type 17 (32 bytes)" + ); + assert_eq!(describe(&[0x86, 0, 0, 0]), "is event 6 (4 bytes)"); + } + #[test] fn disconnect_with_pending_outbound_no_panic() { // The caller drops a ClientState whose outbound still has diff --git a/crates/yserver-core/src/core_loop/client_reader.rs b/crates/yserver-core/src/core_loop/client_reader.rs index 6b5fe01cc..398af5439 100644 --- a/crates/yserver-core/src/core_loop/client_reader.rs +++ b/crates/yserver-core/src/core_loop/client_reader.rs @@ -29,21 +29,20 @@ //! dropping its `reader_control`, so a reader parked on a barrier //! also exits. -use std::{ - io::{self, ErrorKind}, - os::fd::{FromRawFd, RawFd}, -}; +use std::io::{self, ErrorKind}; use crossbeam_channel::{Receiver, TryRecvError}; use log::warn; use yserver_protocol::x11::{self, ClientByteOrder, ClientId, SequenceNumber}; +#[cfg(unix)] +use crate::unix_fd::FdReader; use crate::{ core_loop::{message::Message, sender::BoundSender}, + fd::RawSocket, server::ReaderControl, transport::Transport, - unix_fd::FdReader, }; /// X11 BigRequests `Enable` minor opcode (always 0 — see X.Org spec). @@ -193,21 +192,7 @@ fn run( // xcb-dri3 hits this every time. Now we peek at the (major, // minor[, body]) and pop exactly the right count. let fd_count = expected_fd_count(header.opcode, header.data, &body); - let mut attached_fd: Option = None; - for _ in 0..fd_count { - // First fd → attached_fd; any extras (PixmapFromBuffers - // num_buffers > 1) are closed because Phase 4.2 only - // accepts num_buffers == 1 — the dispatcher rejects - // larger requests with BadAlloc anyway. - match reader.pop_fd() { - Some(raw) if attached_fd.is_none() => attached_fd = Some(raw), - Some(raw) => { - // SAFETY: own the raw fd; close to avoid leak. - unsafe { libc::close(raw) }; - } - None => break, - } - } + let attached_fd = reader.take_attached_fd(fd_count); let is_enable = header.opcode == big_requests_major && header.data == BIG_REQUESTS_ENABLE_MINOR; @@ -219,11 +204,7 @@ fn run( accepted_at: telemetry_enabled.then(std::time::Instant::now), header, body, - attached_fd: attached_fd.map(|raw| { - // SAFETY: FdReader hands us an fd it received via SCM_RIGHTS; - // there's no other owner. - unsafe { std::os::fd::OwnedFd::from_raw_fd(raw) } - }), + attached_fd, })?; if is_enable { @@ -292,11 +273,41 @@ impl BlockingFdReader { Self { inner } } - fn pop_fd(&mut self) -> Option { - self.inner.pop_fd() + /// The descriptor of a request expecting `fd_count`. + #[cfg(unix)] + fn take_attached_fd(&mut self, fd_count: usize) -> Option { + use std::os::fd::FromRawFd; + + let mut attached_fd: Option = None; + for _ in 0..fd_count { + // First fd → attached_fd; any extras (PixmapFromBuffers + // num_buffers > 1) are closed because Phase 4.2 only + // accepts num_buffers == 1 — the dispatcher rejects + // larger requests with BadAlloc anyway. + match self.inner.pop_fd() { + Some(raw) if attached_fd.is_none() => attached_fd = Some(raw), + Some(raw) => { + // SAFETY: own the raw fd; close to avoid leak. + unsafe { libc::close(raw) }; + } + None => break, + } + } + attached_fd.map(|raw| { + // SAFETY: FdReader hands us an fd it received via SCM_RIGHTS; + // there's no other owner. + unsafe { std::os::fd::OwnedFd::from_raw_fd(raw) } + }) + } + + /// No descriptors arrive over a Windows socket. + #[cfg(windows)] + #[allow(clippy::unused_self)] + fn take_attached_fd(&mut self, _fd_count: usize) -> Option { + None } - fn fd(&self) -> RawFd { + fn fd(&self) -> RawSocket { self.inner.fd() } } @@ -315,10 +326,38 @@ impl io::Read for BlockingFdReader { } } +/// Client ingress on Windows: a plain TCP stream, which carries no +/// descriptors. +#[cfg(windows)] +struct FdReader(std::net::TcpStream); + +#[cfg(windows)] +impl FdReader { + fn new(stream: Transport) -> Self { + match stream { + Transport::Tcp(stream) => Self(stream), + #[cfg(test)] + Transport::Capture(_) => panic!("test capture transport cannot read client requests"), + } + } + + fn fd(&self) -> RawSocket { + std::os::windows::io::AsRawSocket::as_raw_socket(&self.0) + } +} + +#[cfg(windows)] +impl io::Read for FdReader { + fn read(&mut self, dst: &mut [u8]) -> io::Result { + self.0.read(dst) + } +} + /// Block until `fd` is readable (or `poll(2)` errors). POLLHUP is /// also surfaced as readable so the caller observes EOF on the next /// `read`. -pub(crate) fn wait_readable(fd: RawFd) -> io::Result<()> { +#[cfg(unix)] +pub(crate) fn wait_readable(fd: RawSocket) -> io::Result<()> { use std::time::Duration; let mut pfd = libc::pollfd { fd, @@ -342,6 +381,30 @@ pub(crate) fn wait_readable(fd: RawFd) -> io::Result<()> { } } +/// Block until `socket` is readable (or `WSAPoll` errors). Hangup and +/// error are reported readable, so the caller observes them on the next +/// `read`. +#[cfg(windows)] +pub(crate) fn wait_readable(socket: RawSocket) -> io::Result<()> { + use windows_sys::Win32::Networking::WinSock::{POLLRDNORM, SOCKET, WSAPOLLFD, WSAPoll}; + + let mut pfd = WSAPOLLFD { + fd: socket as SOCKET, + events: POLLRDNORM, + revents: 0, + }; + loop { + // SAFETY: one valid WSAPOLLFD, for the duration of the call. + let n = unsafe { WSAPoll(&raw mut pfd, 1, -1) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + if pfd.revents != 0 { + return Ok(()); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/yserver-core/src/core_loop/clip_list.rs b/crates/yserver-core/src/core_loop/clip_list.rs new file mode 100644 index 000000000..e681d0934 --- /dev/null +++ b/crates/yserver-core/src/core_loop/clip_list.rs @@ -0,0 +1,1006 @@ +//! Xorg's per-window clip regions, computed from the window tree on demand: +//! the clip list (what of a window shows, its children out) and the +//! universe its children are cut from (`NotClippedByChildren`), as +//! `miComputeClips` keeps them (`mi/mivaltree.c:194-470`). Graphics +//! exposures (`miHandleExposures`) and the Expose events of a map or an +//! unmap (`miHandleValidateExposures`) are made of them. +//! +//! Regions are in a window's content space and in pixman's canonical form +//! ([`canonical`]), so the rects a client is sent match Xorg's one for one. + +use std::collections::{HashMap, HashSet}; + +use yserver_protocol::x11::{ResourceId, xfixes::RegionRect}; + +use crate::{ + region::Region, + resources::{MapState, ROOT_WINDOW, WindowClass}, + server::{CompositeRedirectMode, ServerState}, +}; + +/// Xorg's `RECTLIMIT` (`mi/miexpose.c:107`): past this many rects an +/// exposure is sent as its extents. +pub(crate) const RECTLIMIT: usize = 25; + +/// pixman's canonical form of the union of `rects`: y-x banded, each band +/// split only where the set of x spans changes, adjacent bands with the +/// same spans merged. Unique for a region, so two servers that agree on +/// the region agree on the rects. +pub(crate) fn canonical(rects: Vec) -> Vec { + let banded = crate::nested::normalize_region_rects(rects); + let mut out: Vec = Vec::with_capacity(banded.len()); + // The previous band: its index range in `out`. + let mut prev: Option<(usize, usize)> = None; + let mut i = 0; + while i < banded.len() { + let y = banded[i].y; + let mut j = i; + while j < banded.len() && banded[j].y == y { + j += 1; + } + let band = &banded[i..j]; + let merged = prev.is_some_and(|(s, e)| { + let p = &out[s..e]; + i32::from(p[0].y) + i32::from(p[0].height) == i32::from(y) + && p.len() == band.len() + && p.iter() + .zip(band) + .all(|(a, b)| a.x == b.x && a.width == b.width) + }); + if merged { + let (s, e) = prev.expect("merged implies a previous band"); + for r in &mut out[s..e] { + r.height = r.height.saturating_add(band[0].height); + } + } else { + let s = out.len(); + out.extend_from_slice(band); + prev = Some((s, out.len())); + } + i = j; + } + out +} + +/// `a ∩ b`, canonical. +pub(crate) fn intersect(a: &[RegionRect], b: &[RegionRect]) -> Vec { + Region::from_rects(a) + .intersect(&Region::from_rects(b)) + .to_rects() +} + +/// `a − b`, canonical. +pub(crate) fn subtract(a: &[RegionRect], b: &[RegionRect]) -> Vec { + Region::from_rects(a) + .subtract(&Region::from_rects(b)) + .to_rects() +} + +/// `rects` moved by `(dx, dy)`, saturating at the wire's range. +pub(crate) fn translate(mut rects: Vec, dx: i32, dy: i32) -> Vec { + for r in &mut rects { + r.x = (i32::from(r.x) + dx).clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16; + r.y = (i32::from(r.y) + dy).clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16; + } + rects +} + +/// Whether `rect` lies wholly inside `region` (`RegionContainsRect == rgnIN`). +pub(crate) fn contains(region: &[RegionRect], rect: RegionRect) -> bool { + rect.width == 0 + || rect.height == 0 + || Region::from_rects(&[rect]) + .subtract(&Region::from_rects(region)) + .is_empty() +} + +/// A viewable `InputOutput` window: what takes part in clipping. An +/// `InputOnly` window is never viewable (`RealizeTree`, `dix/window.c`). +fn viewable(state: &ServerState, w: ResourceId) -> bool { + w == ROOT_WINDOW + || state.resources.window(w).is_some_and(|win| { + win.map_state == MapState::Viewable && win.class == WindowClass::InputOutput + }) +} + +/// A Manual-redirected window clips neither its siblings nor its parent +/// (`TreatAsTransparent`, `mi/mivaltree.c:171`). +fn transparent(state: &ServerState, w: ResourceId) -> bool { + state.composite_redirects.window_mode(w) == Some(CompositeRedirectMode::Manual) +} + +/// Xorg's `borderSize` of `w` in its parent's content space: its outer +/// rect, cut to its bounding shape (`SetBorderSize`, `dix/window.c:1747`). +pub(crate) fn border_size_in_parent(state: &ServerState, w: ResourceId) -> Vec { + border_size(state, w).to_rects() +} + +fn border_size(state: &ServerState, w: ResourceId) -> Region { + let Some(win) = state.resources.window(w) else { + return Region::default(); + }; + let bw2 = win.border_width.saturating_mul(2); + let outer = Region::rect(RegionRect { + x: win.x, + y: win.y, + width: win.width.saturating_add(bw2), + height: win.height.saturating_add(bw2), + }); + match state + .shape_windows + .get(&w) + .and_then(|s| s.bounding_region()) + { + Some(shape) => { + let bw = i32::from(win.border_width); + let shape = shape + .clone() + .translate(i32::from(win.x) + bw, i32::from(win.y) + bw); + outer.intersect(&shape) + } + None => outer, + } +} + +/// Xorg's `winSize` of `w` in its own content space, short of its +/// parent's: its content rect cut to its bounding and clip shapes +/// (`SetWinSize`, `dix/window.c:1710`). +fn win_size(state: &ServerState, w: ResourceId) -> Region { + let Some(win) = state.resources.window(w) else { + return Region::default(); + }; + let mut region = Region::rect(RegionRect { + x: 0, + y: 0, + width: win.width, + height: win.height, + }); + if let Some(shape) = state.shape_windows.get(&w) { + for s in [shape.bounding_region(), shape.clip_region()] + .into_iter() + .flatten() + { + region = region.intersect(s); + } + } + region +} + +/// `w`'s offset from its parent's content origin to its own: its position +/// plus its border. +fn content_offset(state: &ServerState, w: ResourceId) -> Option<(i32, i32, i32)> { + state.resources.window(w).map(|c| { + let bw = i32::from(c.border_width); + (i32::from(c.x) + bw, i32::from(c.y) + bw, bw) + }) +} + +/// What of `w` shows, its inferiors included, in its content space: +/// Xorg's `borderClip ∩ winSize`, which `NotClippedByChildren` returns and +/// its children's universes are cut from. A redirected window's is its own +/// shape, not clipped by its parent or the screen (`mi/mivaltree.c:233- +/// 239`); every other window's is its parent's less the windows stacked +/// above it there. +pub(crate) fn not_clipped_by_children(state: &ServerState, w: ResourceId) -> Vec { + universe(state, w).to_rects() +} + +fn universe(state: &ServerState, w: ResourceId) -> Region { + if !viewable(state, w) { + return Region::default(); + } + if w == ROOT_WINDOW { + return state + .resources + .window(ROOT_WINDOW) + .map_or_else(Region::default, |r| { + Region::rect(RegionRect { + x: 0, + y: 0, + width: r.width, + height: r.height, + }) + }); + } + if state.composite_redirects.window_mode(w).is_some() { + return win_size(state, w); + } + let Some(parent) = state.resources.window(w).map(|win| win.parent) else { + return Region::default(); + }; + let universe = universe(state, parent); + child_universe(state, &universe, parent, w, &[]) +} + +/// [`not_clipped_by_children`] of `w` while the `still_redirected` windows, +/// Manual redirects not yet released, stay transparent: the clip of +/// `compRestoreWindow` when `compFreeClientSubwindows` unredirects one +/// child at a time (`composite/compalloc.c:450-452`). +pub(crate) fn not_clipped_by_children_while( + state: &ServerState, + w: ResourceId, + still_redirected: &[ResourceId], +) -> Vec { + let Some(parent) = state.resources.window(w).map(|win| win.parent) else { + return Vec::new(); + }; + if w == ROOT_WINDOW || state.composite_redirects.window_mode(w).is_some() { + return not_clipped_by_children(state, w); + } + let universe = universe(state, parent); + child_universe(state, &universe, parent, w, still_redirected).to_rects() +} + +/// The universe of the single `child` from its parent's: the parent's less +/// `child`'s higher siblings, one subtraction per sibling. A whole layer +/// goes through [`split_universe`] instead. +fn child_universe( + state: &ServerState, + parent_universe: &Region, + parent: ResourceId, + child: ResourceId, + also_transparent: &[ResourceId], +) -> Region { + if !viewable(state, child) { + return Region::default(); + } + if state.composite_redirects.window_mode(child).is_some() { + return win_size(state, child); + } + if parent_universe.is_empty() { + return Region::default(); + } + uncovered_in_child_space(state, parent_universe, parent, child, also_transparent) + .intersect(&win_size(state, child)) +} + +/// `parent_universe` less `child`'s higher siblings, in `child`'s content +/// space: what its `borderSize` is cut to (`miComputeClips`). +fn uncovered_in_child_space( + state: &ServerState, + parent_universe: &Region, + parent: ResourceId, + child: ResourceId, + also_transparent: &[ResourceId], +) -> Region { + let Some((dx, dy, _)) = content_offset(state, child) else { + return Region::default(); + }; + let mut universe = parent_universe.clone(); + let siblings = state.resources.children(parent); + if let Some(at) = siblings.iter().position(|s| *s == child) { + for s in &siblings[at + 1..] { + if universe.is_empty() { + break; + } + if viewable(state, *s) && !transparent(state, *s) && !also_transparent.contains(s) { + universe = universe.subtract(&border_size(state, *s)); + } + } + } + universe.translate(-dx, -dy) +} + +/// The visible part of `w`'s border, in its content space: Xorg's +/// `borderClip − winSize` (`mi/mivaltree.c:362-380`). A redirected window's +/// `borderClip` is its own `borderSize` (`mi/mivaltree.c:233-239`). Empty +/// without a border (`HasBorder`). +#[cfg(test)] +pub(crate) fn border_ring_clip(state: &ServerState, w: ResourceId) -> Vec { + border_ring(state, w).to_rects() +} + +fn border_ring(state: &ServerState, w: ResourceId) -> Region { + if w == ROOT_WINDOW || !viewable(state, w) { + return Region::default(); + } + let Some(parent) = state.resources.window(w).map(|c| c.parent) else { + return Region::default(); + }; + let Some((dx, dy, bw)) = content_offset(state, w) else { + return Region::default(); + }; + if bw == 0 { + return Region::default(); + } + let own = border_size(state, w).translate(-dx, -dy); + let clip = if state.composite_redirects.window_mode(w).is_some() { + own + } else { + let universe = universe(state, parent); + uncovered_in_child_space(state, &universe, parent, w, &[]).intersect(&own) + }; + clip.subtract(&win_size(state, w)) +} + +/// One viewable child's share of its parent's universe, from +/// [`split_universe`]: its own universe and visible border ring, both in +/// its content space. +struct ChildClip { + window: ResourceId, + universe: Region, + ring: Region, +} + +/// `miComputeClips` over `parent`'s children: walk them once, top-most +/// first, carrying what of `universe` (the parent's) they leave uncovered. +/// Each viewable child for which `want` (its index in `children`, its id +/// and its `borderSize`) holds gets its universe, `borderClip ∩ winSize`, +/// and, with `borders`, its ring, `borderClip − winSize`. A redirected +/// child's are its own (`mi/mivaltree.c:233-239`). A child then covers the +/// rest of the parent unless it is Manual-redirected. What is left at the +/// end is the parent's clip list. +fn split_universe( + state: &ServerState, + parent: ResourceId, + universe: Region, + borders: bool, + mut want: impl FnMut(usize, ResourceId, &Region) -> bool, +) -> (Region, Vec) { + let mut uncovered = universe; + let mut wanted = Vec::new(); + let children = state.resources.children(parent); + for (i, &c) in children.iter().enumerate().rev() { + if !viewable(state, c) { + continue; + } + let Some((dx, dy, bw)) = content_offset(state, c) else { + continue; + }; + let size = border_size(state, c); + if want(i, c, &size) { + let win = win_size(state, c); + let redirected = state.composite_redirects.window_mode(c).is_some(); + // `borderClip`, in the child's content space. + let border_clip = if redirected { + size.clone() + } else { + uncovered.intersect(&size) + } + .translate(-dx, -dy); + let ring = if borders && bw != 0 { + border_clip.subtract(&win) + } else { + Region::default() + }; + let universe = if redirected { + win + } else { + border_clip.intersect(&win) + }; + wanted.push(ChildClip { + window: c, + universe, + ring, + }); + } + if !uncovered.is_empty() && !transparent(state, c) { + uncovered = uncovered.subtract(&size); + } + } + (uncovered, wanted) +} + +/// One window's clip list and visible border ring, for an exposure diff. +pub(crate) type ClipEntry = (ResourceId, Region, Region); + +/// What a change exposes of one window: `region` of its content and +/// `border` of its border (`after.exposed` and `after.borderExposed`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Exposure { + pub(crate) window: ResourceId, + pub(crate) region: Vec, + pub(crate) border: Vec, +} + +/// `w`'s clip list in its content space: what of it shows and is not under +/// a child (ClipByChildren). +pub(crate) fn clip_list(state: &ServerState, w: ResourceId) -> Vec { + let mut region = universe(state, w); + for c in state.resources.children(w) { + if region.is_empty() { + break; + } + if viewable(state, *c) && !transparent(state, *c) { + region = region.subtract(&border_size(state, *c)); + } + } + region.to_rects() +} + +/// The clip lists of `w` and every viewable window inside it, in the order +/// Xorg delivers exposures (`miHandleValidateExposures`, `mi/miwindow.c`): +/// a window before its children, children top-most first. +pub(crate) fn subtree_clip_lists( + state: &ServerState, + w: ResourceId, +) -> Vec<(ResourceId, Vec)> { + let mut out = Vec::new(); + walk( + state, + w, + universe(state, w), + Region::default(), + false, + &mut out, + ); + without_rings(out) +} + +/// [`subtree_clip_lists`] of each of `tops` in turn, siblings mapped +/// together (MapSubwindows): their parent's universe is split among them +/// once instead of once per window. +pub(crate) fn subtrees_clip_lists( + state: &ServerState, + tops: &[ResourceId], +) -> Vec<(ResourceId, Vec)> { + let parent = tops + .first() + .and_then(|t| state.resources.window(*t)) + .map(|w| w.parent); + let siblings = tops.len() > 1 + && tops + .iter() + .all(|t| *t != ROOT_WINDOW && state.resources.window(*t).map(|w| w.parent) == parent); + let (Some(parent), true) = (parent, siblings) else { + return tops + .iter() + .flat_map(|t| subtree_clip_lists(state, *t)) + .collect(); + }; + let members: HashSet = tops.iter().copied().collect(); + let (_, kids) = split_universe(state, parent, universe(state, parent), false, |_, c, _| { + members.contains(&c) + }); + let mut universes: HashMap = + kids.into_iter().map(|k| (k.window, k.universe)).collect(); + let mut out = Vec::new(); + for t in tops { + if let Some(u) = universes.remove(t) { + walk(state, *t, u, Region::default(), false, &mut out); + } + } + without_rings(out) +} + +fn without_rings(entries: Vec) -> Vec<(ResourceId, Vec)> { + entries + .into_iter() + .map(|(w, clip, _)| (w, clip.to_rects())) + .collect() +} + +/// Push the entries of `w` (its clip list, from `universe`, and `ring`) and +/// of its viewable inferiors in exposure order. +fn walk( + state: &ServerState, + w: ResourceId, + universe: Region, + ring: Region, + borders: bool, + out: &mut Vec, +) { + if !viewable(state, w) { + return; + } + let (clip, kids) = split_universe(state, w, universe, borders, |_, _, _| true); + out.push((w, clip, ring)); + for k in kids { + walk(state, k.window, k.universe, k.ring, borders, out); + } +} + +/// The clip lists and border rings unmapping `w` can grow, before or after +/// it: its parent's and those of the siblings stacked under it that it +/// overlaps, with their subtrees, in exposure order (`UnmapWindow` +/// validates and exposes from the parent, `dix/window.c:2856-2866`). +pub(crate) fn clip_entries_under(state: &ServerState, w: ResourceId) -> Vec { + let Some(parent) = state.resources.window(w).map(|win| win.parent) else { + return Vec::new(); + }; + let footprint = border_size(state, w); + let at = state + .resources + .children(parent) + .iter() + .position(|s| *s == w); + let (clip, kids) = split_universe( + state, + parent, + universe(state, parent), + true, + |i, _, size| at.is_some_and(|at| i < at) && !size.intersect(&footprint).is_empty(), + ); + let mut out = vec![(parent, clip, border_ring(state, parent))]; + for k in kids { + walk(state, k.window, k.universe, k.ring, true, &mut out); + } + out +} + +/// `w`'s outer rect in its parent's content space, border included. +fn outer_rect(state: &ServerState, w: ResourceId) -> Option { + let win = state.resources.window(w)?; + let bw2 = win.border_width.saturating_mul(2); + Some(RegionRect { + x: win.x, + y: win.y, + width: win.width.saturating_add(bw2), + height: win.height.saturating_add(bw2), + }) +} + +fn overlaps(a: RegionRect, b: RegionRect) -> bool { + let (ax, ay, bx, by) = ( + i32::from(a.x), + i32::from(a.y), + i32::from(b.x), + i32::from(b.y), + ); + ax < bx + i32::from(b.width) + && bx < ax + i32::from(a.width) + && ay < by + i32::from(b.height) + && by < ay + i32::from(a.height) +} + +/// The clip lists and rings of `parent` and of those of its children in +/// `members` with their subtrees, in exposure order +/// (`miHandleValidateExposures` from the layer's parent): the parent, then +/// the members top-most first. +fn clip_entries_of( + state: &ServerState, + parent: ResourceId, + members: &HashSet, +) -> Vec { + let (clip, kids) = split_universe(state, parent, universe(state, parent), true, |_, c, _| { + members.contains(&c) + }); + let mut out = vec![(parent, clip, border_ring(state, parent))]; + for k in kids { + walk(state, k.window, k.universe, k.ring, true, &mut out); + } + out +} + +/// A change to a viewable window's geometry, stacking or shape, as Xorg +/// validates one (`ValidateTree` + `HandleExposures` from the parent, +/// `dix/window.c:2149-2176`, `mi/miwindow.c`): the clip lists it can +/// alter, taken before the change, so that [`TreeChange::exposed`] can +/// diff them against the ones after. Those are the parent's and those of +/// the siblings (the window included) that meet the window's outer rect +/// before or after, with their subtrees; no other window's clip list +/// depends on the change. +pub(crate) struct TreeChange { + parent: ResourceId, + members: HashSet, + before: Vec, +} + +impl TreeChange { + /// Snapshot before changing `w`; `reach` is the outer rect (parent + /// content space) the change moves or sizes it to, if any. `None` for + /// a window that is not viewable: its change exposes nothing. + pub(crate) fn begin( + state: &ServerState, + w: ResourceId, + reach: Option, + ) -> Option { + if w == ROOT_WINDOW || !viewable(state, w) { + return None; + } + let parent = state.resources.window(w)?.parent; + let mut extent = vec![outer_rect(state, w)?]; + extent.extend(reach); + let members: HashSet = state + .resources + .children(parent) + .iter() + .copied() + .filter(|s| { + *s == w + || (viewable(state, *s) + && outer_rect(state, *s) + .is_some_and(|r| extent.iter().any(|e| overlaps(r, *e)))) + }) + .collect(); + let before = clip_entries_of(state, parent, &members); + Some(Self { + parent, + members, + before, + }) + } + + /// Per window, in exposure order, what it shows now that it did not + /// before (`miComputeClips`: the new clip list less the old one, both + /// in the window's own space, `mi/mivaltree.c:453-458`). `whole` gets + /// its entire clip list instead: a resized window's contents are + /// forfeit (`mi/miwindow.c:466-472`). + pub(crate) fn exposed(self, state: &ServerState, whole: Option) -> Vec { + let after = clip_entries_of(state, self.parent, &self.members); + newly_exposed(&self.before, after, whole) + } +} + +/// Per window, what `after` shows that `before` did not: the exposures a +/// change between the two makes, in `after`'s order. `whole`, if any, +/// gains its entire clip list; its border stays a diff (`borderVisible`, +/// `mi/miwindow.c:418-429`). The border gained is the visible ring less +/// the old one (`mi/mivaltree.c:362-380`). +pub(crate) fn newly_exposed( + before: &[ClipEntry], + after: Vec, + whole: Option, +) -> Vec { + let mut index: HashMap = HashMap::with_capacity(before.len()); + for (i, (w, _, _)) in before.iter().enumerate() { + index.entry(*w).or_insert(i); + } + after + .into_iter() + .filter_map(|(w, region, ring)| { + let old = index.get(&w).map(|i| &before[*i]); + let region = match old.filter(|_| Some(w) != whole) { + Some((_, old, _)) => region.subtract(old), + None => region, + }; + let border = match old { + Some((_, _, old_ring)) => ring.subtract(old_ring), + None => ring, + }; + (!region.is_empty() || !border.is_empty()).then(|| Exposure { + window: w, + region: region.to_rects(), + border: border.to_rects(), + }) + }) + .collect() +} + +#[cfg(test)] +mod equivalence; +#[cfg(test)] +mod oracle; + +#[cfg(test)] +mod tests { + use super::*; + + fn r(x: i16, y: i16, width: u16, height: u16) -> RegionRect { + RegionRect { + x, + y, + width, + height, + } + } + + /// pixman merges bands whose spans agree: the union of two stacked + /// rects with the same x range is one rect, and a rect minus an inner + /// one is four, top band, two sides, bottom band. + #[test] + fn canonical_coalesces_bands_like_pixman() { + assert_eq!( + canonical(vec![r(0, 0, 10, 5), r(0, 5, 10, 5)]), + vec![r(0, 0, 10, 10)] + ); + assert_eq!( + subtract(&[r(0, 0, 10, 10)], &[r(3, 3, 4, 4)]), + vec![r(0, 0, 10, 3), r(0, 3, 3, 4), r(7, 3, 3, 4), r(0, 7, 10, 3)] + ); + // UnmapSubwindows in draw-clip's expose-probe: P1 ∪ P5 seen on P. + assert_eq!( + canonical(vec![r(40, 10, 70, 50), r(40, 40, 40, 60)]), + vec![r(40, 10, 70, 50), r(40, 60, 40, 40)] + ); + } + + fn window( + state: &mut ServerState, + id: u32, + parent: ResourceId, + geom: (i16, i16, u16, u16), + class: u16, + ) { + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(id), + parent, + x: geom.0, + y: geom.1, + width: geom.2, + height: geom.3, + border_width: 0, + class, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(id)) + .unwrap() + .map_state = MapState::Viewable; + } + + /// MapWindow of tools/vng-scenarios/expose-probe.c's P, measured on + /// Xorg without a compositor: P at (-40,200) 300x200, children P1 + /// (10,10 100x50), P2 (50,40 100x80) above it, an InputOnly P3 over + /// all of P and P4 (200,150 150x100). P's exposure is its part on the + /// screen less P1, P2 and P4 in pixman's seven rects, P1's what P2 + /// leaves of it, and P3 none; children come top-most first. + #[test] + fn map_exposures_are_the_clip_lists_in_xorgs_order() { + let mut state = ServerState::with_geometry(1024, 768); + let (p, p1, p2, p3, p4) = ( + 0x0020_0100, + 0x0020_0101, + 0x0020_0102, + 0x0020_0103, + 0x0020_0104, + ); + window(&mut state, p, ROOT_WINDOW, (-40, 200, 300, 200), 1); + window(&mut state, p1, ResourceId(p), (10, 10, 100, 50), 1); + window(&mut state, p2, ResourceId(p), (50, 40, 100, 80), 1); + window(&mut state, p3, ResourceId(p), (0, 0, 300, 200), 2); + window(&mut state, p4, ResourceId(p), (200, 150, 150, 100), 1); + let got = subtree_clip_lists(&state, ResourceId(p)); + let ids: Vec = got.iter().map(|(w, _)| w.0).collect(); + assert_eq!(ids, vec![p, p4, p2, p1], "P3 is InputOnly"); + assert_eq!( + got[0].1, + vec![ + r(40, 0, 260, 10), + r(110, 10, 190, 30), + r(150, 40, 150, 20), + r(40, 60, 10, 60), + r(150, 60, 150, 60), + r(40, 120, 260, 30), + r(40, 150, 160, 50), + ] + ); + assert_eq!(got[1].1, vec![r(0, 0, 100, 50)]); + assert_eq!(got[2].1, vec![r(0, 0, 100, 80)]); + assert_eq!(got[3].1, vec![r(30, 0, 70, 30), r(30, 30, 10, 20)]); + } + + fn configure( + state: &mut ServerState, + id: u32, + geom: Option<(i16, i16, u16, u16)>, + stack: Option<(u8, Option)>, + ) { + state + .resources + .configure_window(yserver_protocol::x11::ConfigureWindowRequest { + window: ResourceId(id), + value_mask: 0, + x: geom.map(|g| g.0), + y: geom.map(|g| g.1), + width: geom.map(|g| g.2), + height: geom.map(|g| g.3), + border_width: None, + sibling: stack.and_then(|s| s.1).map(ResourceId), + stack_mode: stack.map(|s| s.0), + }); + } + + fn change( + state: &mut ServerState, + id: u32, + geom: Option<(i16, i16, u16, u16)>, + stack: Option<(u8, Option)>, + whole: bool, + ) -> Vec<(u32, Vec)> { + let reach = geom.map(|g| r(g.0, g.1, g.2, g.3)); + let change = TreeChange::begin(state, ResourceId(id), reach).unwrap(); + configure(state, id, geom, stack); + change + .exposed(state, whole.then_some(ResourceId(id))) + .into_iter() + .map(|e| (e.window.0, e.region)) + .collect() + } + + /// tools/vng-scenarios/restack-expose-probe.c's top-levels, measured + /// on Xorg without a compositor (goldens/restack-expose.txt): A and B + /// at (40,40) 200x150, A stacked under B, C at (180,120) 120x100 on + /// top. Each restack, move and resize exposes the new clip list less + /// the old one, a resized window its whole clip list, the higher + /// window first. + #[test] + fn tree_changes_expose_what_xorg_exposes() { + const ABOVE: u8 = 0; + const BELOW: u8 = 1; + let mut state = ServerState::with_geometry(1024, 768); + let (a, b, c) = (0x0020_0001, 0x0020_0002, 0x0020_0003); + window(&mut state, b, ROOT_WINDOW, (40, 40, 200, 150), 1); + window(&mut state, a, ROOT_WINDOW, (40, 40, 200, 150), 1); + configure(&mut state, a, None, Some((BELOW, None))); + let root = ROOT_WINDOW.0; + + let got = change(&mut state, a, None, Some((ABOVE, None)), false); + assert_eq!(got, vec![(a, vec![r(0, 0, 200, 150)])], "A raised"); + let got = change(&mut state, a, None, Some((BELOW, None)), false); + assert_eq!(got, vec![(b, vec![r(0, 0, 200, 150)])], "A lowered"); + + window(&mut state, c, ROOT_WINDOW, (180, 120, 120, 100), 1); + let got = change(&mut state, a, None, Some((BELOW, Some(c))), false); + assert_eq!( + got, + vec![(a, vec![r(0, 0, 200, 80), r(0, 80, 140, 70)])], + "A raised to just below C" + ); + let got = change(&mut state, a, None, Some((ABOVE, None)), false); + assert_eq!(got, vec![(a, vec![r(140, 80, 60, 70)])], "A raised over C"); + let got = change(&mut state, a, None, Some((BELOW, None)), false); + assert_eq!( + got, + vec![ + (c, vec![r(0, 0, 60, 70)]), + (b, vec![r(0, 0, 200, 80), r(0, 80, 140, 70)]), + ], + "A lowered under B and C" + ); + + let got = change(&mut state, b, Some((70, 60, 200, 150)), None, false); + assert_eq!( + got.iter() + .filter(|(w, _)| *w != root) + .cloned() + .collect::>(), + vec![(a, vec![r(0, 0, 200, 20), r(0, 20, 30, 130)])], + "B moved by 30,20" + ); + let got = change(&mut state, b, Some((70, 60, 230, 170)), None, true); + assert_eq!( + got, + vec![( + b, + vec![r(0, 0, 230, 60), r(0, 60, 110, 100), r(0, 160, 230, 10)] + )], + "B grown to 230x170" + ); + let got = change(&mut state, b, Some((70, 60, 150, 100)), None, true); + assert_eq!( + got.iter() + .filter(|(w, _)| *w != root) + .cloned() + .collect::>(), + vec![ + (b, vec![r(0, 0, 150, 60), r(0, 60, 110, 40)]), + (a, vec![r(180, 20, 20, 60), r(30, 120, 110, 30)]), + ], + "B shrunk to 150x100" + ); + } + + /// The same under an Automatic RedirectSubwindows of the root, measured + /// on Xorg: a redirected window's clip list is its own shape, so a + /// restack exposes nothing and a resize the whole window. + #[test] + fn redirected_top_levels_are_not_exposed_by_restacks() { + let mut state = ServerState::with_geometry(1024, 768); + let (a, b) = (0x0020_0001, 0x0020_0002); + window(&mut state, b, ROOT_WINDOW, (40, 40, 200, 150), 1); + window(&mut state, a, ROOT_WINDOW, (40, 40, 200, 150), 1); + configure(&mut state, a, None, Some((1, None))); + for w in [a, b] { + state + .composite_redirects + .redirect_window( + ResourceId(w), + crate::server::RedirectRecord { + owner: yserver_protocol::x11::ClientId(1), + mode: CompositeRedirectMode::Automatic, + }, + ) + .unwrap(); + } + let got = change(&mut state, a, None, Some((0, None)), false); + assert!( + got.iter().all(|(w, _)| *w == ROOT_WINDOW.0), + "A raised: {got:?}" + ); + let got = change(&mut state, b, Some((40, 40, 230, 170)), None, true); + assert_eq!( + got.iter() + .filter(|(w, _)| *w != ROOT_WINDOW.0) + .cloned() + .collect::>(), + vec![(b, vec![r(0, 0, 230, 170)])] + ); + } + + fn set_border(state: &mut ServerState, id: u32, bw: u16) { + state + .resources + .window_mut(ResourceId(id)) + .unwrap() + .border_width = bw; + } + + fn redirect_manual(state: &mut ServerState, id: u32) { + state + .composite_redirects + .redirect_window( + ResourceId(id), + crate::server::RedirectRecord { + owner: yserver_protocol::x11::ClientId(1), + mode: CompositeRedirectMode::Manual, + }, + ) + .unwrap(); + } + + fn borders(got: Vec) -> Vec<(u32, Vec)> { + got.into_iter() + .filter(|e| !e.border.is_empty()) + .map(|e| (e.window.0, e.border)) + .collect() + } + + /// `miComputeClips`' `borderExposed` (`mi/mivaltree.c:362-380`) for the + /// probe's C: a child at (80,80) 50x50 bw 4 in a redirected W that grows + /// from 100 to 200. Its extents match Xorg's border damage `80,80 58x58`. + #[test] + fn border_exposed_of_a_child_crossing_the_grown_edge() { + let mut state = ServerState::with_geometry(1024, 768); + let (w, c) = (0x0020_0201, 0x0020_0202); + window(&mut state, w, ROOT_WINDOW, (300, 300, 100, 100), 1); + redirect_manual(&mut state, w); + window(&mut state, c, ResourceId(w), (80, 80, 50, 50), 1); + set_border(&mut state, c, 4); + let reach = Some(r(300, 300, 200, 200)); + let change = TreeChange::begin(&state, ResourceId(w), reach).unwrap(); + configure(&mut state, w, Some((300, 300, 200, 200)), None); + let got = borders(change.exposed(&state, Some(ResourceId(w)))); + assert_eq!( + got, + vec![( + c, + vec![ + r(16, -4, 38, 4), + r(50, 0, 4, 16), + r(-4, 16, 4, 34), + r(50, 16, 4, 34), + r(-4, 50, 58, 4), + ] + )] + ); + } + + /// U: a sibling S (0,0) 30x30 over C (10,10) 50x50 bw 4 unmaps; the + /// part of C's ring S covered is exposed (Xorg damage `10,10 20x20`). + #[test] + fn border_exposed_when_an_occluding_sibling_unmaps() { + let mut state = ServerState::with_geometry(1024, 768); + let (w, c, sib) = (0x0020_0211, 0x0020_0212, 0x0020_0213); + window(&mut state, w, ROOT_WINDOW, (400, 300, 120, 120), 1); + redirect_manual(&mut state, w); + window(&mut state, c, ResourceId(w), (10, 10, 50, 50), 1); + set_border(&mut state, c, 4); + window(&mut state, sib, ResourceId(w), (0, 0, 30, 30), 1); + let before = clip_entries_under(&state, ResourceId(sib)); + let _ = state.resources.unmap_window(ResourceId(sib)); + let after = clip_entries_under(&state, ResourceId(sib)); + let got = borders(newly_exposed(&before, after, None)); + assert_eq!(got, vec![(c, vec![r(-4, -4, 20, 4), r(-4, 0, 4, 16)])]); + } + + /// `HasBorder` is false at `bw == 0`: no border is ever exposed. + #[test] + fn unbordered_windows_expose_no_border() { + let mut state = ServerState::with_geometry(1024, 768); + let (w, c, sib) = (0x0020_0221, 0x0020_0222, 0x0020_0223); + window(&mut state, w, ROOT_WINDOW, (0, 0, 120, 120), 1); + window(&mut state, c, ResourceId(w), (10, 10, 50, 50), 1); + window(&mut state, sib, ResourceId(w), (0, 0, 30, 30), 1); + let before = clip_entries_under(&state, ResourceId(sib)); + let _ = state.resources.unmap_window(ResourceId(sib)); + let after = clip_entries_under(&state, ResourceId(sib)); + assert!(borders(newly_exposed(&before, after, None)).is_empty()); + } +} diff --git a/crates/yserver-core/src/core_loop/clip_list/equivalence.rs b/crates/yserver-core/src/core_loop/clip_list/equivalence.rs new file mode 100644 index 000000000..ebdb864f8 --- /dev/null +++ b/crates/yserver-core/src/core_loop/clip_list/equivalence.rs @@ -0,0 +1,550 @@ +//! The clip-list traversal against [`super::oracle`], the traversal it +//! replaced: every query and every exposure diff must give the same rects +//! in the same order. + +use proptest::prelude::*; +use yserver_protocol::x11::{ + ClientId, ResourceId, + shape::{KIND_BOUNDING, KIND_CLIP}, + xfixes::RegionRect, +}; + +use super::oracle; +use crate::{ + resources::{MapState, ROOT_WINDOW}, + server::{CompositeRedirectMode, RedirectRecord, ServerState}, +}; + +type Rects = Vec; + +fn r(x: i16, y: i16, width: u16, height: u16) -> RegionRect { + RegionRect { + x, + y, + width, + height, + } +} + +const ABOVE: u8 = 0; +const BELOW: u8 = 1; + +/// One window of a generated tree: created in this order, so a later +/// window of the same parent stacks above an earlier one. +#[derive(Debug, Clone)] +struct Spec { + /// Index into the windows created before this one; out of range + /// means the root. + parent: usize, + geom: (i16, i16, u16, u16), + border: u16, + input_only: bool, + mapped: bool, + redirect: Option, + bounding: Option, + clip: Option, +} + +fn id(i: usize) -> ResourceId { + ResourceId(0x0020_0001 + u32::try_from(i).unwrap()) +} + +fn redirect(state: &mut ServerState, w: ResourceId, mode: CompositeRedirectMode) { + state + .composite_redirects + .redirect_window( + w, + RedirectRecord { + owner: ClientId(1), + mode, + }, + ) + .unwrap(); +} + +fn create(state: &mut ServerState, w: ResourceId, parent: ResourceId, s: &Spec) { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: w, + parent, + x: s.geom.0, + y: s.geom.1, + width: s.geom.2, + height: s.geom.3, + border_width: s.border, + class: if s.input_only { 2 } else { 1 }, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let parent_viewable = parent == ROOT_WINDOW + || state + .resources + .window(parent) + .is_some_and(|p| p.map_state == MapState::Viewable); + state.resources.window_mut(w).unwrap().map_state = match (s.mapped, parent_viewable) { + (false, _) => MapState::Unmapped, + (true, true) => MapState::Viewable, + (true, false) => MapState::Unviewable, + }; + if let Some(mode) = s.redirect { + redirect(state, w, mode); + } + if s.bounding.is_some() || s.clip.is_some() { + let shape = state.shape_windows.entry(w).or_default(); + shape.set_rects(KIND_BOUNDING, s.bounding.clone()); + shape.set_rects(KIND_CLIP, s.clip.clone()); + } +} + +fn build(specs: &[Spec]) -> (ServerState, Vec) { + let mut state = ServerState::with_geometry(64, 48); + let mut ids = Vec::new(); + for (i, s) in specs.iter().enumerate() { + let parent = ids.get(s.parent).copied().unwrap_or(ROOT_WINDOW); + create(&mut state, id(i), parent, s); + ids.push(id(i)); + } + (state, ids) +} + +// The traversal under test, reduced to rects so that it compares with the +// oracle's. + +fn new_entries_under(state: &ServerState, w: ResourceId) -> Vec<(ResourceId, Rects, Rects)> { + rings_as_rects(super::clip_entries_under(state, w)) +} + +fn rings_as_rects(entries: Vec) -> Vec<(ResourceId, Rects, Rects)> { + entries + .into_iter() + .map(|(w, clip, ring)| (w, clip.to_rects(), ring.to_rects())) + .collect() +} + +fn new_exposed( + change: super::TreeChange, + state: &ServerState, + whole: Option, +) -> Vec<(ResourceId, Rects, Rects)> { + change + .exposed(state, whole) + .into_iter() + .map(|e| (e.window, e.region, e.border)) + .collect() +} + +fn new_batch(state: &ServerState, tops: &[ResourceId]) -> Vec<(ResourceId, Rects)> { + super::subtrees_clip_lists(state, tops) +} + +fn old_exposed( + change: oracle::TreeChange, + state: &ServerState, + whole: Option, +) -> Vec<(ResourceId, Rects, Rects)> { + change + .exposed(state, whole) + .into_iter() + .map(|e| (e.window, e.region, e.border)) + .collect() +} + +fn old_entries_under(state: &ServerState, w: ResourceId) -> Vec<(ResourceId, Rects, Rects)> { + oracle::with_borders(state, oracle::clip_lists_under(state, w)) +} + +/// Every per-window query, the root included, old against new. +fn assert_queries_match(state: &ServerState, ids: &[ResourceId]) { + for w in std::iter::once(ROOT_WINDOW).chain(ids.iter().copied()) { + assert_eq!( + super::not_clipped_by_children(state, w), + oracle::not_clipped_by_children(state, w), + "not_clipped_by_children {w:?}" + ); + assert_eq!( + super::clip_list(state, w), + oracle::clip_list(state, w), + "clip_list {w:?}" + ); + assert_eq!( + super::border_ring_clip(state, w), + oracle::border_ring_clip(state, w), + "border_ring_clip {w:?}" + ); + assert_eq!( + super::border_size_in_parent(state, w), + oracle::border_size_in_parent(state, w), + "border_size_in_parent {w:?}" + ); + assert_eq!( + super::subtree_clip_lists(state, w), + oracle::subtree_clip_lists(state, w), + "subtree_clip_lists {w:?}" + ); + if w != ROOT_WINDOW { + assert_eq!( + new_entries_under(state, w), + old_entries_under(state, w), + "entries under {w:?}" + ); + let manual: Vec = state + .resources + .children(state.resources.window(w).unwrap().parent) + .to_vec(); + assert_eq!( + super::not_clipped_by_children_while(state, w, &manual), + oracle::not_clipped_by_children_while(state, w, &manual), + "not_clipped_by_children_while {w:?}" + ); + } + } + // MapSubwindows' batch: every child of a parent, top-most first. + for p in std::iter::once(ROOT_WINDOW).chain(ids.iter().copied()) { + let tops: Vec = state.resources.children(p).iter().rev().copied().collect(); + let want: Vec<(ResourceId, Rects)> = tops + .iter() + .flat_map(|t| oracle::subtree_clip_lists(state, *t)) + .collect(); + assert_eq!(new_batch(state, &tops), want, "batch under {p:?}"); + } +} + +/// A configure of `w` (geometry and/or stacking) through both +/// `TreeChange`s. +fn assert_change_matches( + state: &mut ServerState, + w: ResourceId, + geom: Option<(i16, i16, u16, u16)>, + stack: Option<(u8, Option)>, +) { + let bw = state.resources.window(w).map_or(0, |win| win.border_width); + let reach = geom.map(|g| r(g.0, g.1, g.2 + 2 * bw, g.3 + 2 * bw)); + let new = super::TreeChange::begin(state, w, reach); + let old = oracle::TreeChange::begin(state, w, reach); + assert_eq!(new.is_some(), old.is_some()); + state + .resources + .configure_window(yserver_protocol::x11::ConfigureWindowRequest { + window: w, + value_mask: 0, + x: geom.map(|g| g.0), + y: geom.map(|g| g.1), + width: geom.map(|g| g.2), + height: geom.map(|g| g.3), + border_width: None, + sibling: stack.and_then(|s| s.1), + stack_mode: stack.map(|s| s.0), + }); + let whole = geom.map(|_| w); + if let (Some(new), Some(old)) = (new, old) { + assert_eq!( + new_exposed(new, state, whole), + old_exposed(old, state, whole), + "configure {w:?} to {geom:?} {stack:?}" + ); + } +} + +/// An unmap of `w` diffed both ways, as UnmapWindow and DestroyWindow do. +fn assert_unmap_matches(state: &mut ServerState, w: ResourceId) { + let new_before = super::clip_entries_under(state, w); + let old_before = old_entries_under(state, w); + assert_eq!( + rings_as_rects(new_before.clone()), + old_before, + "before unmapping {w:?}" + ); + let _ = state.resources.unmap_window(w); + let new: Vec<(ResourceId, Rects, Rects)> = + super::newly_exposed(&new_before, super::clip_entries_under(state, w), None) + .into_iter() + .map(|e| (e.window, e.region, e.border)) + .collect(); + let old: Vec<(ResourceId, Rects, Rects)> = + oracle::newly_exposed(&old_before, old_entries_under(state, w), None) + .into_iter() + .map(|e| (e.window, e.region, e.border)) + .collect(); + assert_eq!(new, old, "unmapping {w:?}"); +} + +/// A bounding shape change of `w`, validated as ShapeRectangles does. +fn assert_shape_matches(state: &mut ServerState, w: ResourceId, bounding: Option) { + let new = super::TreeChange::begin(state, w, None); + let old = oracle::TreeChange::begin(state, w, None); + state + .shape_windows + .entry(w) + .or_default() + .set_rects(KIND_BOUNDING, bounding); + if let (Some(new), Some(old)) = (new, old) { + assert_eq!( + new_exposed(new, state, None), + old_exposed(old, state, None), + "reshaping {w:?}" + ); + } +} + +// Hand-written cases: the redirect rules of the design +// (docs/superpowers/specs/2026-10-28-cached-clip-lists-design.md, Phase 2). + +fn spec(parent: usize, geom: (i16, i16, u16, u16), border: u16) -> Spec { + Spec { + parent, + geom, + border, + input_only: false, + mapped: true, + redirect: None, + bounding: None, + clip: None, + } +} + +const ROOT: usize = usize::MAX; + +/// A redirected child under a higher sibling and one its parent clips +/// away, each Automatic and Manual, with and without borders. +#[test] +fn redirected_children_match_the_oracle() { + for mode in [ + CompositeRedirectMode::Automatic, + CompositeRedirectMode::Manual, + ] { + for border in [0, 3] { + // 0: a parent; 1: redirected child; 2: a sibling over it; + // 3: a redirected child outside the parent; 4: its child; + // 5: a sibling under them all. + let mut redirected = spec(0, (4, 4, 20, 16), border); + redirected.redirect = Some(mode); + let mut outside = spec(0, (30, 30, 20, 20), border); + outside.redirect = Some(mode); + let specs = vec![ + spec(ROOT, (2, 2, 40, 30), border), + spec(0, (0, 0, 40, 30), border), + redirected, + spec(0, (8, 6, 10, 10), border), + outside, + spec(4, (2, 2, 6, 6), border), + ]; + let (mut state, ids) = build(&specs); + assert_queries_match(&state, &ids); + assert_change_matches(&mut state, ids[3], None, Some((BELOW, None))); + assert_queries_match(&state, &ids); + assert_change_matches(&mut state, ids[2], Some((-3, -2, 30, 20)), None); + assert_change_matches(&mut state, ids[1], None, Some((ABOVE, None))); + assert_unmap_matches(&mut state, ids[3]); + assert_unmap_matches(&mut state, ids[1]); + assert_queries_match(&state, &ids); + } + } +} + +/// Bordered windows overlapping in a stack, and shaped siblings. +#[test] +fn bordered_and_shaped_siblings_match_the_oracle() { + let mut shaped = spec(ROOT, (10, 10, 30, 20), 2); + shaped.bounding = Some(vec![r(0, 0, 10, 10), r(20, 5, 10, 15), r(-2, 18, 40, 4)]); + let mut clipped = spec(ROOT, (5, 20, 20, 20), 1); + clipped.clip = Some(vec![r(2, 2, 8, 8)]); + let specs = vec![ + spec(ROOT, (0, 0, 40, 30), 4), + spec(ROOT, (20, 10, 30, 30), 2), + shaped, + clipped, + spec(2, (3, 3, 10, 10), 1), + ]; + let (mut state, ids) = build(&specs); + assert_queries_match(&state, &ids); + assert_change_matches(&mut state, ids[0], None, Some((ABOVE, None))); + assert_change_matches(&mut state, ids[2], Some((12, 8, 30, 20)), None); + assert_shape_matches(&mut state, ids[2], Some(vec![r(5, 5, 20, 10)])); + assert_shape_matches(&mut state, ids[2], None); + assert_unmap_matches(&mut state, ids[1]); + assert_queries_match(&state, &ids); +} + +/// A shape stored as the request path stores it (banded, bands with the +/// same spans not merged, so not canonical): the cached regions give the +/// clips the stored rects give, before and after a change. +#[test] +fn shapes_stored_by_the_request_path_match_the_oracle() { + let specs = vec![ + spec(ROOT, (0, 0, 40, 30), 1), + spec(ROOT, (10, 10, 30, 20), 2), + spec(1, (3, 3, 10, 10), 1), + ]; + let (mut state, ids) = build(&specs); + let bands = vec![ + r(0, 0, 10, 5), + r(0, 5, 10, 5), + r(12, 0, 4, 10), + r(-2, 12, 40, 4), + ]; + assert!(crate::nested::set_shape_rects( + &mut state, + ids[1], + KIND_BOUNDING, + bands.clone() + )); + let clip = vec![r(1, 1, 8, 3), r(1, 4, 8, 3), r(20, 1, 4, 6)]; + assert!(crate::nested::set_shape_rects( + &mut state, + ids[1], + KIND_CLIP, + clip.clone() + )); + let shape = &state.shape_windows[&ids[1]]; + let canonical = crate::region::Region::from_rects(&bands); + assert_ne!( + canonical.to_rects(), + bands, + "the rects given are meant to be non-canonical" + ); + assert_eq!(shape.bounding_region(), Some(&canonical)); + assert_eq!( + shape.clip_region(), + Some(&crate::region::Region::from_rects(&clip)) + ); + assert_queries_match(&state, &ids); + + let new = super::TreeChange::begin(&state, ids[1], None).unwrap(); + let old = oracle::TreeChange::begin(&state, ids[1], None).unwrap(); + crate::nested::set_shape_rects( + &mut state, + ids[1], + KIND_BOUNDING, + vec![r(0, 0, 6, 6), r(0, 6, 6, 6), r(8, 2, 20, 2)], + ); + assert_eq!( + new_exposed(new, &state, None), + old_exposed(old, &state, None) + ); + assert_queries_match(&state, &ids); + + let new = super::TreeChange::begin(&state, ids[1], None).unwrap(); + let old = oracle::TreeChange::begin(&state, ids[1], None).unwrap(); + crate::nested::clear_shape_rects(&mut state, ids[1], KIND_BOUNDING); + assert_eq!(state.shape_windows[&ids[1]].bounding_region(), None); + assert_eq!( + new_exposed(new, &state, None), + old_exposed(old, &state, None) + ); + assert_queries_match(&state, &ids); +} + +// Random trees. + +fn shape() -> impl Strategy> { + prop_oneof![ + 3 => Just(None), + 1 => prop::collection::vec((-3i16..20, -3i16..20, 0u16..14, 0u16..14), 0..4) + .prop_map(|v| Some(v.into_iter().map(|(x, y, w, h)| r(x, y, w, h)).collect())), + ] +} + +fn specs() -> impl Strategy> { + let one = ( + (0usize..12, prop::bool::weighted(0.3)), + (-8i16..50, -8i16..40, 1u16..36, 1u16..30), + prop_oneof![3 => Just(0u16), 1 => 1u16..4], + prop::bool::weighted(0.1), + prop::bool::weighted(0.85), + prop_oneof![ + 4 => Just(None), + 1 => Just(Some(CompositeRedirectMode::Automatic)), + 1 => Just(Some(CompositeRedirectMode::Manual)), + ], + shape(), + shape(), + ) + .prop_map( + |((parent, at_root), geom, border, input_only, mapped, redirect, bounding, clip)| { + Spec { + parent: if at_root { ROOT } else { parent }, + geom, + border, + input_only, + mapped, + redirect, + bounding, + clip, + } + }, + ); + prop::collection::vec(one, 1..12).prop_map(|mut v| { + // A parent is created before its children. + for (i, s) in v.iter_mut().enumerate() { + if s.parent >= i { + s.parent = ROOT; + } + } + v + }) +} + +#[derive(Debug, Clone)] +enum Op { + Configure { + pick: usize, + geom: Option<(i16, i16, u16, u16)>, + stack: Option<(u8, Option)>, + }, + Unmap(usize), + Reshape(usize, Option), +} + +fn ops() -> impl Strategy> { + let op = prop_oneof![ + 3 => ( + 0usize..12, + prop::option::of((-8i16..50, -8i16..40, 1u16..36, 1u16..30)), + prop::option::of((0u8..2, prop::option::of(0usize..12))), + ) + .prop_map(|(pick, geom, stack)| Op::Configure { pick, geom, stack }), + 1 => (0usize..12).prop_map(Op::Unmap), + 1 => (0usize..12, shape()).prop_map(|(p, s)| Op::Reshape(p, s)), + ]; + prop::collection::vec(op, 0..4) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(400))] + + #[test] + fn random_trees_match_the_oracle(specs in specs(), ops in ops()) { + let (mut state, ids) = build(&specs); + assert_queries_match(&state, &ids); + for op in ops { + match op { + Op::Configure { pick, geom, stack } => { + let w = ids[pick % ids.len()]; + // A sibling, if the pick names one of the same parent. + let parent = state.resources.window(w).unwrap().parent; + let stack = stack.map(|(mode, sib)| { + let sib = sib + .map(|s| ids[s % ids.len()]) + .filter(|s| *s != w && state.resources.window(*s) + .is_some_and(|win| win.parent == parent)); + (mode, sib) + }); + assert_change_matches(&mut state, w, geom, stack); + } + Op::Unmap(pick) => { + let w = ids[pick % ids.len()]; + if state.resources.window(w).unwrap().map_state == MapState::Viewable { + assert_unmap_matches(&mut state, w); + } + } + Op::Reshape(pick, bounding) => { + assert_shape_matches(&mut state, ids[pick % ids.len()], bounding); + } + } + assert_queries_match(&state, &ids); + } + } +} diff --git a/crates/yserver-core/src/core_loop/clip_list/oracle.rs b/crates/yserver-core/src/core_loop/clip_list/oracle.rs new file mode 100644 index 000000000..e721c1469 --- /dev/null +++ b/crates/yserver-core/src/core_loop/clip_list/oracle.rs @@ -0,0 +1,466 @@ +//! The clip-list traversal as it was before the single top-down pass: each +//! child's universe re-subtracts all of its higher siblings and every +//! border ring is computed from the root. Slow but verified against Xorg's +//! exposures, so the equivalence tests compare the new traversal to it. + +use yserver_protocol::x11::{ResourceId, xfixes::RegionRect}; + +use super::{intersect, subtract, translate}; +use crate::{ + resources::{MapState, ROOT_WINDOW, WindowClass}, + server::{CompositeRedirectMode, ServerState}, +}; + +/// A viewable `InputOutput` window: what takes part in clipping. An +/// `InputOnly` window is never viewable (`RealizeTree`, `dix/window.c`). +fn viewable(state: &ServerState, w: ResourceId) -> bool { + w == ROOT_WINDOW + || state.resources.window(w).is_some_and(|win| { + win.map_state == MapState::Viewable && win.class == WindowClass::InputOutput + }) +} + +/// A Manual-redirected window clips neither its siblings nor its parent +/// (`TreatAsTransparent`, `mi/mivaltree.c:171`). +fn transparent(state: &ServerState, w: ResourceId) -> bool { + state.composite_redirects.window_mode(w) == Some(CompositeRedirectMode::Manual) +} + +/// Xorg's `borderSize` of `w` in its parent's content space: its outer +/// rect, cut to its bounding shape (`SetBorderSize`, `dix/window.c:1747`). +pub(super) fn border_size_in_parent(state: &ServerState, w: ResourceId) -> Vec { + let Some(win) = state.resources.window(w) else { + return Vec::new(); + }; + let bw2 = win.border_width.saturating_mul(2); + let outer = RegionRect { + x: win.x, + y: win.y, + width: win.width.saturating_add(bw2), + height: win.height.saturating_add(bw2), + }; + match state + .shape_windows + .get(&w) + .and_then(crate::server::ShapeWindowState::bounding) + { + Some(shape) => { + let bw = i32::from(win.border_width); + let shape = translate(shape, i32::from(win.x) + bw, i32::from(win.y) + bw); + intersect(&[outer], &shape) + } + None => vec![outer], + } +} + +/// Xorg's `winSize` of `w` in its own content space, short of its +/// parent's: its content rect cut to its bounding and clip shapes +/// (`SetWinSize`, `dix/window.c:1710`). +fn win_size(state: &ServerState, w: ResourceId) -> Vec { + let Some(win) = state.resources.window(w) else { + return Vec::new(); + }; + let mut region = vec![RegionRect { + x: 0, + y: 0, + width: win.width, + height: win.height, + }]; + if let Some(shape) = state.shape_windows.get(&w) { + for s in [shape.bounding(), shape.clip()].into_iter().flatten() { + region = intersect(®ion, &s); + } + } + region +} + +/// What of `w` shows, its inferiors included, in its content space: +/// Xorg's `borderClip ∩ winSize`, which `NotClippedByChildren` returns and +/// its children's universes are cut from. A redirected window's is its own +/// shape, not clipped by its parent or the screen (`mi/mivaltree.c:233- +/// 239`); every other window's is its parent's less the windows stacked +/// above it there. +pub(super) fn not_clipped_by_children(state: &ServerState, w: ResourceId) -> Vec { + if !viewable(state, w) { + return Vec::new(); + } + if w == ROOT_WINDOW { + return state + .resources + .window(ROOT_WINDOW) + .map_or_else(Vec::new, |r| { + vec![RegionRect { + x: 0, + y: 0, + width: r.width, + height: r.height, + }] + }); + } + if state.composite_redirects.window_mode(w).is_some() { + return win_size(state, w); + } + let Some(parent) = state.resources.window(w).map(|win| win.parent) else { + return Vec::new(); + }; + let universe = not_clipped_by_children(state, parent); + child_universe(state, &universe, parent, w) +} + +/// [`not_clipped_by_children`] of `w` while the `still_redirected` windows, +/// Manual redirects not yet released, stay transparent: the clip of +/// `compRestoreWindow` when `compFreeClientSubwindows` unredirects one +/// child at a time (`composite/compalloc.c:450-452`). +pub(super) fn not_clipped_by_children_while( + state: &ServerState, + w: ResourceId, + still_redirected: &[ResourceId], +) -> Vec { + let Some(parent) = state.resources.window(w).map(|win| win.parent) else { + return Vec::new(); + }; + if w == ROOT_WINDOW || state.composite_redirects.window_mode(w).is_some() { + return not_clipped_by_children(state, w); + } + let universe = not_clipped_by_children(state, parent); + child_universe_with(state, &universe, parent, w, still_redirected) +} + +/// [`not_clipped_by_children`] of `child` from its parent's. +fn child_universe( + state: &ServerState, + parent_universe: &[RegionRect], + parent: ResourceId, + child: ResourceId, +) -> Vec { + child_universe_with(state, parent_universe, parent, child, &[]) +} + +fn child_universe_with( + state: &ServerState, + parent_universe: &[RegionRect], + parent: ResourceId, + child: ResourceId, + also_transparent: &[ResourceId], +) -> Vec { + if !viewable(state, child) { + return Vec::new(); + } + if state.composite_redirects.window_mode(child).is_some() { + return win_size(state, child); + } + if parent_universe.is_empty() { + return Vec::new(); + } + let universe = + uncovered_in_child_space(state, parent_universe, parent, child, also_transparent); + intersect(&universe, &win_size(state, child)) +} + +/// `parent_universe` less `child`'s higher siblings, in `child`'s content +/// space: what its `borderSize` is cut to (`miComputeClips`). +fn uncovered_in_child_space( + state: &ServerState, + parent_universe: &[RegionRect], + parent: ResourceId, + child: ResourceId, + also_transparent: &[ResourceId], +) -> Vec { + let Some((x, y, bw)) = state + .resources + .window(child) + .map(|c| (i32::from(c.x), i32::from(c.y), i32::from(c.border_width))) + else { + return Vec::new(); + }; + let mut universe = parent_universe.to_vec(); + let siblings = state.resources.children(parent); + if let Some(at) = siblings.iter().position(|s| *s == child) { + for s in &siblings[at + 1..] { + if viewable(state, *s) && !transparent(state, *s) && !also_transparent.contains(s) { + universe = subtract(&universe, &border_size_in_parent(state, *s)); + } + } + } + translate(universe, -(x + bw), -(y + bw)) +} + +/// The visible part of `w`'s border, in its content space: Xorg's +/// `borderClip − winSize` (`mi/mivaltree.c:362-380`). A redirected window's +/// `borderClip` is its own `borderSize` (`mi/mivaltree.c:233-239`). Empty +/// without a border (`HasBorder`). +pub(super) fn border_ring_clip(state: &ServerState, w: ResourceId) -> Vec { + if w == ROOT_WINDOW || !viewable(state, w) { + return Vec::new(); + } + let Some((x, y, bw, parent)) = state.resources.window(w).map(|c| { + ( + i32::from(c.x), + i32::from(c.y), + i32::from(c.border_width), + c.parent, + ) + }) else { + return Vec::new(); + }; + if bw == 0 { + return Vec::new(); + } + let own = translate(border_size_in_parent(state, w), -(x + bw), -(y + bw)); + let clip = if state.composite_redirects.window_mode(w).is_some() { + own + } else { + let universe = not_clipped_by_children(state, parent); + intersect( + &uncovered_in_child_space(state, &universe, parent, w, &[]), + &own, + ) + }; + subtract(&clip, &win_size(state, w)) +} + +/// One window's clip list and visible border ring, for an exposure diff. +pub(super) type ClipEntry = (ResourceId, Vec, Vec); + +/// `clips` with each window's [`border_ring_clip`] alongside. +pub(super) fn with_borders( + state: &ServerState, + clips: Vec<(ResourceId, Vec)>, +) -> Vec { + clips + .into_iter() + .map(|(w, clip)| { + let ring = border_ring_clip(state, w); + (w, clip, ring) + }) + .collect() +} + +/// What a change exposes of one window: `region` of its content and +/// `border` of its border (`after.exposed` and `after.borderExposed`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Exposure { + pub(super) window: ResourceId, + pub(super) region: Vec, + pub(super) border: Vec, +} + +/// `w`'s clip list in its content space: what of it shows and is not under +/// a child (ClipByChildren). +pub(super) fn clip_list(state: &ServerState, w: ResourceId) -> Vec { + clip_list_from(state, w, not_clipped_by_children(state, w)) +} + +fn clip_list_from( + state: &ServerState, + w: ResourceId, + universe: Vec, +) -> Vec { + let mut region = universe; + for c in state.resources.children(w) { + if region.is_empty() { + break; + } + if viewable(state, *c) && !transparent(state, *c) { + region = subtract(®ion, &border_size_in_parent(state, *c)); + } + } + region +} + +/// The clip lists of `w` and every viewable window inside it, in the order +/// Xorg delivers exposures (`miHandleValidateExposures`, `mi/miwindow.c`): +/// a window before its children, children top-most first. +pub(super) fn subtree_clip_lists( + state: &ServerState, + w: ResourceId, +) -> Vec<(ResourceId, Vec)> { + let mut out = Vec::new(); + let universe = not_clipped_by_children(state, w); + walk(state, w, universe, &mut out); + out +} + +fn walk( + state: &ServerState, + w: ResourceId, + universe: Vec, + out: &mut Vec<(ResourceId, Vec)>, +) { + if !viewable(state, w) { + return; + } + let children: Vec = state.resources.children(w).iter().rev().copied().collect(); + let child_universes: Vec<(ResourceId, Vec)> = children + .iter() + .map(|c| (*c, child_universe(state, &universe, w, *c))) + .collect(); + out.push((w, clip_list_from(state, w, universe))); + for (c, u) in child_universes { + walk(state, c, u, out); + } +} + +/// The clip lists unmapping `w` can grow, before or after it: its +/// parent's and those of the siblings stacked under it that it overlaps, +/// with their subtrees, in exposure order (`UnmapWindow` validates and +/// exposes from the parent, `dix/window.c:2856-2866`). +pub(super) fn clip_lists_under( + state: &ServerState, + w: ResourceId, +) -> Vec<(ResourceId, Vec)> { + let mut out = Vec::new(); + let Some(parent) = state.resources.window(w).map(|win| win.parent) else { + return out; + }; + let universe = not_clipped_by_children(state, parent); + out.push((parent, clip_list_from(state, parent, universe.clone()))); + let footprint = border_size_in_parent(state, w); + let siblings = state.resources.children(parent); + let Some(at) = siblings.iter().position(|s| *s == w) else { + return out; + }; + for s in siblings[..at].iter().rev() { + if intersect(&border_size_in_parent(state, *s), &footprint).is_empty() { + continue; + } + let u = child_universe(state, &universe, parent, *s); + walk(state, *s, u, &mut out); + } + out +} + +/// `w`'s outer rect in its parent's content space, border included. +fn outer_rect(state: &ServerState, w: ResourceId) -> Option { + let win = state.resources.window(w)?; + let bw2 = win.border_width.saturating_mul(2); + Some(RegionRect { + x: win.x, + y: win.y, + width: win.width.saturating_add(bw2), + height: win.height.saturating_add(bw2), + }) +} + +fn overlaps(a: RegionRect, b: RegionRect) -> bool { + let (ax, ay, bx, by) = ( + i32::from(a.x), + i32::from(a.y), + i32::from(b.x), + i32::from(b.y), + ); + ax < bx + i32::from(b.width) + && bx < ax + i32::from(a.width) + && ay < by + i32::from(b.height) + && by < ay + i32::from(a.height) +} + +/// The clip lists of `parent` and of those of its children in `members` +/// with their subtrees, in exposure order (`miHandleValidateExposures` +/// from the layer's parent): the parent, then the members top-most first. +fn clip_lists_of( + state: &ServerState, + parent: ResourceId, + members: &[ResourceId], +) -> Vec<(ResourceId, Vec)> { + let universe = not_clipped_by_children(state, parent); + let mut out = vec![(parent, clip_list_from(state, parent, universe.clone()))]; + for c in state.resources.children(parent).iter().rev() { + if members.contains(c) { + let u = child_universe(state, &universe, parent, *c); + walk(state, *c, u, &mut out); + } + } + out +} + +/// A change to a viewable window's geometry, stacking or shape, as Xorg +/// validates one (`ValidateTree` + `HandleExposures` from the parent, +/// `dix/window.c:2149-2176`, `mi/miwindow.c`): the clip lists it can +/// alter, taken before the change, so that [`TreeChange::exposed`] can +/// diff them against the ones after. Those are the parent's and those of +/// the siblings (the window included) that meet the window's outer rect +/// before or after, with their subtrees; no other window's clip list +/// depends on the change. +pub(super) struct TreeChange { + parent: ResourceId, + members: Vec, + before: Vec, +} + +impl TreeChange { + /// Snapshot before changing `w`; `reach` is the outer rect (parent + /// content space) the change moves or sizes it to, if any. `None` for + /// a window that is not viewable: its change exposes nothing. + pub(super) fn begin( + state: &ServerState, + w: ResourceId, + reach: Option, + ) -> Option { + if w == ROOT_WINDOW || !viewable(state, w) { + return None; + } + let parent = state.resources.window(w)?.parent; + let mut extent = vec![outer_rect(state, w)?]; + extent.extend(reach); + let members: Vec = state + .resources + .children(parent) + .iter() + .copied() + .filter(|s| { + *s == w + || (viewable(state, *s) + && outer_rect(state, *s) + .is_some_and(|r| extent.iter().any(|e| overlaps(r, *e)))) + }) + .collect(); + let before = with_borders(state, clip_lists_of(state, parent, &members)); + Some(Self { + parent, + members, + before, + }) + } + + /// Per window, in exposure order, what it shows now that it did not + /// before (`miComputeClips`: the new clip list less the old one, both + /// in the window's own space, `mi/mivaltree.c:453-458`). `whole` gets + /// its entire clip list instead: a resized window's contents are + /// forfeit (`mi/miwindow.c:466-472`). + pub(super) fn exposed(self, state: &ServerState, whole: Option) -> Vec { + let after = with_borders(state, clip_lists_of(state, self.parent, &self.members)); + newly_exposed(&self.before, after, whole) + } +} + +/// Per window, what `after` shows that `before` did not: the exposures a +/// change between the two makes, in `after`'s order. `whole`, if any, +/// gains its entire clip list; its border stays a diff (`borderVisible`, +/// `mi/miwindow.c:418-429`). The border gained is the visible ring less +/// the old one (`mi/mivaltree.c:362-380`). +pub(super) fn newly_exposed( + before: &[ClipEntry], + after: Vec, + whole: Option, +) -> Vec { + after + .into_iter() + .filter_map(|(w, region, ring)| { + let old = before.iter().find(|(b, _, _)| *b == w); + let region = match old.filter(|_| Some(w) != whole) { + Some((_, old, _)) => subtract(®ion, old), + None => region, + }; + let border = match old { + Some((_, _, old_ring)) => subtract(&ring, old_ring), + None => ring, + }; + (!region.is_empty() || !border.is_empty()).then_some(Exposure { + window: w, + region, + border, + }) + }) + .collect() +} diff --git a/crates/yserver-core/src/core_loop/composite_overlay.rs b/crates/yserver-core/src/core_loop/composite_overlay.rs index da197567b..e9ad56130 100644 --- a/crates/yserver-core/src/core_loop/composite_overlay.rs +++ b/crates/yserver-core/src/core_loop/composite_overlay.rs @@ -8,8 +8,11 @@ //! `CompOverlayClientRec` owned by the calling client //! (`composite/compoverlay.c`) and the resource system frees them all //! when that client goes away. We keep the equivalent list in -//! [`ServerState::cow_claims`] and the backend counts nothing: it sees -//! only the 0 → 1 materialize edge and the 1 → 0 teardown edge. +//! [`ServerState::cow_claims`] and the backend counts nothing. Existence +//! is separate, as in Xorg: the overlay exists while its core record does. +//! GetOverlayWindow materializes it whenever the record is absent, and it +//! is destroyed through a destroy plan, by the last release or by +//! `DestroyWindow` / `DestroySubwindows`, which leave the claims alone. //! //! Two things in the tree carry confusingly similar names and are **not** //! this: `scene.root_overlay` / `root_overlay_on_disconnect` @@ -20,12 +23,15 @@ use yserver_protocol::x11::ClientId; use crate::{ backend::{Backend, OriginContext}, - resources::COMPOSITE_OVERLAY_WINDOW, + core_loop::fanout::emit_window_event_to_state, + resources::{COMPOSITE_OVERLAY_WINDOW, ROOT_WINDOW}, server::ServerState, }; +const SUBSTRUCTURE_NOTIFY: u32 = 0x0008_0000; + /// Ask the backend to materialize the overlay, then mirror it on the -/// resources side. Called on the 0 → 1 claim edge only. +/// resources side. Called only while no core COW record exists. /// /// The caller must have already recorded the claim, and must roll it /// back if this returns `Err` — a claim recorded against an overlay that @@ -53,55 +59,81 @@ pub(crate) fn materialize_overlay( .materialize_cow_resource(crate::backend::WindowHandle::from_raw_panicking( cow_host_xid, )); - state.materialize_cow_input_shape(); + // Xorg compCreateOverlayWindow (composite/compoverlay.c:125-141) is a + // CreateWindow and a MapWindow of an override-redirect root child, so + // root's SubstructureNotify listeners see CreateNotify then MapNotify. + // It has no input shape: it takes the pointer until the compositor + // empties its input region. + if let Some(geometry) = + state + .resources + .window(COMPOSITE_OVERLAY_WINDOW) + .map(|w| yserver_protocol::x11::Geometry { + root: ROOT_WINDOW, + x: w.x, + y: w.y, + width: w.width, + height: w.height, + border_width: w.border_width, + depth: w.depth, + }) + { + let _dropped = + emit_window_event_to_state(state, ROOT_WINDOW, SUBSTRUCTURE_NOTIFY, |buf, seq, o| { + yserver_protocol::x11::encode_create_notify_event( + buf, + seq, + o, + ROOT_WINDOW, + COMPOSITE_OVERLAY_WINDOW, + geometry, + true, + ); + }); + let _dropped = + emit_window_event_to_state(state, ROOT_WINDOW, SUBSTRUCTURE_NOTIFY, |buf, seq, o| { + yserver_protocol::x11::encode_map_notify_event( + buf, + seq, + o, + ROOT_WINDOW, + COMPOSITE_OVERLAY_WINDOW, + true, + ); + }); + } // The COW is now a core root child (capped on top); reproject the // backend top-level order from core so it enters the projection at // the top. Must run AFTER materialize_cow_resource — the backend COW // hook no longer pushes to top_level_order itself. backend.sync_top_level_order(state); + // The MapWindow ends in WindowsRestructured (`dix/window.c:2695`). + backend.windows_restructured(state); Ok(()) } -/// Tear the overlay down: backend first, then the resources-side mirror. -/// -/// Called on the 1 → 0 claim edge only. Backend first is load-bearing: -/// the claim is the thing keeping the overlay alive, so a caller must not -/// drop the last claim unless this succeeded. +/// Destroy the overlay on the last claim's release: plan, prepare, +/// execute, as any destroy of the COW (Xorg `compDestroyOverlayWindow`, +/// `composite/compoverlay.c:167-173`, frees it through `DeleteWindow`). +/// A COW already destroyed by `DestroyWindow` / `DestroySubwindows` leaves +/// nothing to do (`FreeResource` of a freed id, `dix/resource.c:906-924`). /// /// # Errors /// -/// From the backend's teardown — on `KmsBackend` the -/// `materialize_direct_shadow_for_unflip` allocation that has to succeed -/// before a scanned-out buffer can be released. +/// From the plan's preparation — on `KmsBackend` the unflip shadow that +/// has to exist before a scanned-out buffer can be released. Nothing +/// changed: the overlay is still up. pub(crate) fn teardown_overlay( state: &mut ServerState, backend: &mut dyn Backend, origin: Option, ) -> std::io::Result<()> { - if !backend.release_overlay_window(origin)? { - // Backend never materialized a COW (v1, ynest, trait default): - // nothing to mirror down either, because nothing ever reached - // `materialize_cow_resource`. - return Ok(()); - } - // Xorg frees the overlay through DeleteWindow, so its Pictures die with it. - crate::core_loop::process_request::free_pictures_on_destroyed_windows( + crate::core_loop::process_request::destroy_window_subtree( state, backend, origin, - &[COMPOSITE_OVERLAY_WINDOW], - ); - crate::core_loop::process_request::purge_present_for_destroyed_windows( - state, - backend, - &[COMPOSITE_OVERLAY_WINDOW], - ); - state.resources.destroy_cow_resource(); - state.destroy_cow_input_shape(); - // The COW is no longer a core root child; reproject so it leaves the - // backend top-level order. - backend.sync_top_level_order(state); - Ok(()) + COMPOSITE_OVERLAY_WINDOW, + ) } /// Release **every** overlay claim held by `client`, and tear the overlay diff --git a/crates/yserver-core/src/core_loop/damage_fanout.rs b/crates/yserver-core/src/core_loop/damage_fanout.rs index e483649ba..81f6bd008 100644 --- a/crates/yserver-core/src/core_loop/damage_fanout.rs +++ b/crates/yserver-core/src/core_loop/damage_fanout.rs @@ -132,16 +132,8 @@ pub fn accumulate_damage_border_to_state( state: &mut ServerState, window: ResourceId, ) -> Vec { - let mut dropped: Vec = Vec::new(); - for rect in border_annulus_rects(state, window) { - for c in accumulate_damage_to_state(state, window, rect.x, rect.y, rect.width, rect.height) - { - if !dropped.contains(&c) { - dropped.push(c); - } - } - } - dropped + let ring = border_annulus_rects(state, window); + accumulate_damage_region_to_state(state, window, &ring) } /// Mapped `InputOutput` children of `drawable`, as rects in the @@ -163,11 +155,32 @@ pub fn mapped_child_clip_rects( w.class == crate::resources::WindowClass::InputOutput && w.map_state != crate::resources::MapState::Unmapped }) - .map(|w| xfixes::RegionRect { - x: w.x, - y: w.y, - width: w.width, - height: w.height, + .flat_map(|w| { + let rect = xfixes::RegionRect { + x: w.x, + y: w.y, + width: w.width, + height: w.height, + }; + // A shaped child covers only its bounding shape (Xorg's + // `borderSize`, `dix/window.c:1747-1770`); the shape is + // relative to its content origin. + match state + .shape_windows + .get(&w.id) + .and_then(|s| s.bounding_region()) + { + Some(shape) => { + let bw = i32::from(w.border_width); + let shape = shape + .clone() + .translate(i32::from(w.x) + bw, i32::from(w.y) + bw); + crate::region::Region::rect(rect) + .intersect(&shape) + .to_rects() + } + None => vec![rect], + } }) .collect() } @@ -274,17 +287,7 @@ pub fn accumulate_damage_clip_by_children_to_state( log_clip_by_children_debug(state, drawable, "damage", &[full], &visible); - let mut dropped: Vec = Vec::new(); - for rect in visible { - for c in - accumulate_damage_to_state(state, drawable, rect.x, rect.y, rect.width, rect.height) - { - if !dropped.contains(&c) { - dropped.push(c); - } - } - } - dropped + accumulate_damage_region_to_state(state, drawable, &visible) } pub fn accumulate_damage_to_state( @@ -295,7 +298,34 @@ pub fn accumulate_damage_to_state( width: u16, height: u16, ) -> Vec { - if width == 0 || height == 0 { + accumulate_damage_region_to_state( + state, + drawable, + &[xfixes::RegionRect { + x, + y, + width, + height, + }], + ) +} + +/// DAMAGE for one drawing op over `region` of `drawable` (its own +/// coordinates), as Xorg's `damageRegionAppend` + +/// `damageRegionProcessPending` (`miext/damage/damage.c:125-300`): every +/// damage object the op reaches gets the region clipped to its drawable, +/// and reports it whole, in damage-list order. +pub fn accumulate_damage_region_to_state( + state: &mut ServerState, + drawable: ResourceId, + region: &[xfixes::RegionRect], +) -> Vec { + let region: Vec = region + .iter() + .filter(|r| r.width != 0 && r.height != 0) + .copied() + .collect(); + if region.is_empty() { return Vec::new(); } // Nothing on screen ⇒ nothing damaged (issue #97). Xorg keeps @@ -327,89 +357,83 @@ pub fn accumulate_damage_to_state( if std::env::var_os("YSERVER_DAMAGE_BACKTRACE").is_some() { let bt = std::backtrace::Backtrace::force_capture(); log::info!( - "DIAG accumulate_damage: drawable=0x{:x} rect=({},{} {}x{})\n{}", + "DIAG accumulate_damage: drawable=0x{:x} region={}\n{}", drawable.0, - x, - y, - width, - height, + format_damage_rects(®ion), bt, ); } let timestamp = state.timestamp_now(); - let mut pending: Vec = Vec::new(); + let mut hits: Vec = Vec::new(); + + // The leaf level — pixmaps and windows alike. Pixmaps have no parent, + // so a `state.resources.window(drawable)` miss at the top of the loop + // ends the walk before the first step. + let mut level_region = crate::core_loop::clip_list::canonical(region); + collect_level(state, drawable, &level_region, &mut hits); - // Initial rect in the leaf drawable's coordinate space. Carry as - // i32 through the ancestor walk so translation + clip don't - // overflow when a child sits well past its parent's edge; - // saturate-cast back to i16/u16 only at emit time. - let mut rx = i32::from(x); - let mut ry = i32::from(y); - let mut rw = i32::from(width); - let mut rh = i32::from(height); - - // Process the leaf level — pixmaps and windows alike. Pixmaps - // have no parent so processing stops here; windows fall through - // to the ancestor walk below. - accumulate_at_level(state, drawable, rx, ry, rw, rh, &mut pending); - - // Ancestor walk — only meaningful for window drawables. Pixmaps - // exist outside the window tree per X11 spec (Composite spec's - // NameWindowPixmap aliases sit beside the window tree, not in - // it), so a `state.resources.window(drawable)` miss at the top - // of the loop terminates the walk before the first step. let mut current = drawable; for _ in 0..ANCESTOR_WALK_MAX_DEPTH { - // Look up the current window's own offset + parent. A - // missing window is the loop termination for pixmaps and - // for any path that strays off the tree. + // A redirected window draws into its own pixmap, whose damage list + // its ancestors are not on (`getDrawableDamageRef`, + // `miext/damage/damage.c:86-110`). + if state.composite_redirects.window_mode(current).is_some() { + break; + } let Some(current_win) = state.resources.window(current) else { break; }; - let cur_off_x = i32::from(current_win.x); - let cur_off_y = i32::from(current_win.y); - let parent = current_win.parent; + // The child's content origin in the parent: `x + bw` + // (`dix/window.c`, `drawable.x = parent.x + x + bw`). + let bw = i32::from(current_win.border_width); + let (off_x, off_y, parent) = ( + i32::from(current_win.x) + bw, + i32::from(current_win.y) + bw, + current_win.parent, + ); // Root self-parents (`parent == self`, see resources.rs - // ROOT_WINDOW initialiser). Other walks in the tree use - // the same sentinel for termination — propagating beyond - // root makes no sense. + // ROOT_WINDOW initialiser). if parent == current { break; } - // Translate the rect from `current`'s coord space into - // `parent`'s by adding `current`'s own (x, y). - rx += cur_off_x; - ry += cur_off_y; - // Clip the translated rect to `parent`'s extent. If the - // rect doesn't intersect this parent at all, it certainly - // won't intersect any higher ancestor either — terminate. let Some(parent_win) = state.resources.window(parent) else { - // Dangling parent xid (resources tree should keep this - // consistent; stay defensive — stop walking). break; }; - let parent_w = i32::from(parent_win.width); - let parent_h = i32::from(parent_win.height); - let x0 = rx.max(0); - let y0 = ry.max(0); - let x1 = (rx + rw).min(parent_w); - let y1 = (ry + rh).min(parent_h); - if x1 <= x0 || y1 <= y0 { + // Into the parent's coordinates, clipped to its extent: an ancestor + // sees the part of the paint that lies inside it. + let bounds = xfixes::RegionRect { + x: 0, + y: 0, + width: parent_win.width, + height: parent_win.height, + }; + level_region = crate::core_loop::clip_list::intersect( + &crate::core_loop::clip_list::translate(level_region, off_x, off_y), + &[bounds], + ); + if level_region.is_empty() { break; } - // Re-anchor the rect to its visible portion within - // `parent`. The clipped rect (in parent's coord space) is - // what higher ancestors will see, exactly mirroring the - // X11 spec rule "damage propagates the visible region - // through ancestors." - rx = x0; - ry = y0; - rw = x1 - x0; - rh = y1 - y0; current = parent; - accumulate_at_level(state, parent, rx, ry, rw, rh, &mut pending); + collect_level(state, parent, &level_region, &mut hits); } + if hits.is_empty() { + return Vec::new(); + } + // `damageRegionProcessPending` walks the list from its head. + hits.sort_by_key(|h| { + std::cmp::Reverse( + state + .damage_objects + .get(&h.damage_id) + .map_or((0, 0), |d| (d.list_pos, h.damage_id)), + ) + }); + let mut pending: Vec = Vec::new(); + for hit in hits { + commit_hit(state, hit, &mut pending); + } if pending.is_empty() { return Vec::new(); } @@ -435,6 +459,42 @@ pub fn accumulate_damage_to_state( dropped } +/// Xorg's `damageSetWindowPixmap` (`miext/damage/damage.c:1547-1575`) for +/// each window `compSetPixmap` visits from `window` +/// (`composite/compwindow.c:118-148`): a window's damage leaves the old +/// pixmap's list and is prepended to the new one's, newest first, so the +/// oldest ends at the head. Descendants with their own backing are skipped. +pub fn move_window_damage_to_list_head(state: &mut ServerState, window: ResourceId) { + let mut stack = vec![window]; + while let Some(w) = stack.pop() { + if w != window + && state + .resources + .window(w) + .is_some_and(|win| win.redirected_backing.is_some()) + { + continue; + } + let mut ids: Vec<(u64, u32)> = state + .damage_objects + .iter() + .filter(|(_, d)| d.drawable == w) + .map(|(id, d)| (d.created, *id)) + .collect(); + ids.sort_unstable_by(|a, b| b.cmp(a)); + for (_, id) in ids { + state.damage_list_clock += 1; + let tick = state.damage_list_clock; + if let Some(d) = state.damage_objects.get_mut(&id) { + d.list_pos = tick; + } + } + // `TraverseTree` visits firstChild first; children are stored + // bottom-most first. + stack.extend(state.resources.children(w).iter().copied()); + } +} + /// Re-report an already-accumulated damage object without appending a /// new rect. This mirrors Xorg's `ProcDamageSubtract` follow-up path: /// after subtracting a non-None repair region, any remaining damage is @@ -567,51 +627,41 @@ pub fn report_existing_damage_to_state(state: &mut ServerState, damage_id: u32) dropped } -/// Per-level helper: match damage objects keyed on `level_drawable`, -/// push the (clipped, i32 → i16/u16-saturated) rect into each, and -/// add a fire-once `PendingNotify` for any object that hasn't fired -/// in this cycle yet. Called once per level by the ancestor walk -/// (leaf + each ancestor up to root). -/// -/// `rx/ry/rw/rh` are in `level_drawable`'s coordinate space and -/// already clipped to its extent by the caller. They arrive as i32 -/// for safe walk-time arithmetic; the saturate-cast here is the -/// single conversion point. -fn accumulate_at_level( - state: &mut ServerState, +/// One damage object reached by a drawing op: its drawable's part of the +/// op's region, in that drawable's coordinates. +struct Hit { + damage_id: u32, + drawable: ResourceId, + rects: Vec, + /// The drawable's current geometry (`damageGetGeometry`). + geometry: x11damage::Rectangle, +} + +/// The damage objects keyed on `level_drawable` or one of its +/// NameWindowPixmap aliases, each given `rects` (already clipped to it). +fn collect_level( + state: &ServerState, level_drawable: ResourceId, - rx: i32, - ry: i32, - rw: i32, - rh: i32, - pending: &mut Vec, + rects: &[xfixes::RegionRect], + hits: &mut Vec, ) { // Resolve `level_drawable` through the NameWindowPixmap alias // indirection. Compositors such as picom subscribe DAMAGE on the // pixmap returned by `NameWindowPixmap`, not on the window itself. - // When damage is accumulated for a redirected window (either a - // ConfigureWindow-move emits `accumulate_damage_full(state, W)` or - // a descendant paint walks up to W as a redirected ancestor), the - // damage objects subscribed on W's `composite_named_pixmaps[*]` - // alias pixmaps MUST also fire here — otherwise the compositor - // never receives `DamageNotify` for redirected-window content - // (move: stale composite; child repaint: blank in the composited - // frame). - // // Xorg's `getDrawableDamageRef(&pWin->drawable)` resolves this // automatically via `GetWindowPixmap(pWin)` → backing pixmap → // that pixmap's damage list (miext/damage/damage.c:90-110). The // alias pixmap and the window share the backing pixmap's damage // list, so a single `DamageDamageRegion(&pWin->drawable, ...)` hits - // every alias subscription. yserver's per-xid `damage_objects` map - // has no such indirection, so we mirror it inline here. + // every alias subscription. let mut drawables = vec![level_drawable]; - if let Some(window) = state.resources.window(level_drawable) - && !window.composite_named_pixmaps.is_empty() - { - for alias in &window.composite_named_pixmaps { - drawables.push(alias.client_pixmap); - } + if let Some(window) = state.resources.window(level_drawable) { + drawables.extend( + window + .composite_named_pixmaps + .iter() + .map(|a| a.client_pixmap), + ); } let damage_ids: Vec = state .damage_objects @@ -619,69 +669,23 @@ fn accumulate_at_level( .filter(|(_, dmg)| drawables.contains(&dmg.drawable)) .map(|(id, _)| *id) .collect(); - // Stage 4d shadow-hunt diagnostic: surface every accumulate call - // with its target drawable + how many DAMAGE subscriptions matched - // + how many of those have `pending_notify_fired=true` (i.e. would - // skip the notify). Grep this in the broken-state run to find: - // - level_drawable=0x match_ids=0 (compositor never subscribed - // to W, or subscribed to a different xid — hypothesis 2); - // - level_drawable=0x match_ids>0 fired_count=match_ids (notify - // would fire but compositor isn't subtracting fast enough); - // - "no entry for W" (paint handler isn't calling accumulate at - // all for that path — hypothesis 1). - // Logged unconditionally at trace; enable with + // Logged at trace; enable with // `yserver_core::core_loop::damage_fanout=trace` in `RUST_LOG`. - let fired_count = damage_ids - .iter() - .filter(|id| { - state - .damage_objects - .get(id) - .is_some_and(|d| d.pending_notify_fired) - }) - .count(); log::trace!( - "damage_fanout: level_drawable=0x{:x} rect=({},{} {}x{}) match_ids={} fired_count={}", + "damage_fanout: level_drawable=0x{:x} region={} match_ids={}", level_drawable.0, - rx, - ry, - rw, - rh, + format_damage_rects(rects), damage_ids.len(), - fired_count, ); - if damage_ids.is_empty() { return; } - - // Saturate-cast i32 walk coords to the wire i16/u16 shape. - // Real window dimensions stay well under i16::MAX (32767); the - // saturate is defensive against runaway parent chains or - // corrupt tree state. - let rect_i16 = xfixes::RegionRect { - x: i16::try_from(rx).unwrap_or(i16::MAX), - y: i16::try_from(ry).unwrap_or(i16::MAX), - width: u16::try_from(rw).unwrap_or(u16::MAX), - height: u16::try_from(rh).unwrap_or(u16::MAX), - }; - let area = x11damage::Rectangle { - x: rect_i16.x, - y: rect_i16.y, - width: rect_i16.width, - height: rect_i16.height, - }; - // Per-level geometry — the damaged drawable's CURRENT geometry - // in its parent's coordinate space (X11 DAMAGE proto + Xorg - // damageext.c: fills from pDrawable->{x, y, width, height}; - // window drawables carry root-relative x/y, pixmaps are - // always (0, 0)). marco/picom/etc. use this geometry to map - // the damage rect back into screen space — if x/y stay - // hardcoded at (0, 0), the compositor recomposites at the - // wrong screen position after every move, observable as - // "top-left bits of CC stay rendered" after dragging. - let geom_full = drawable_full_rect(state, level_drawable); + // (X11 DAMAGE proto + Xorg damageext.c: fills from + // pDrawable->{x, y, width, height}; window drawables carry + // root-relative x/y, pixmaps are always (0, 0)). Compositors use it + // to map the damage rect back into screen space. + let full = drawable_full_rect(state, level_drawable); let (geom_x, geom_y) = if state.resources.window(level_drawable).is_some() { let (ax, ay) = state.resources.window_absolute_position(level_drawable); ( @@ -691,116 +695,109 @@ fn accumulate_at_level( } else { (0, 0) }; - let geom_rect = x11damage::Rectangle { + let geometry = x11damage::Rectangle { x: geom_x, y: geom_y, - width: geom_full.width, - height: geom_full.height, + width: full.width, + height: full.height, }; - for damage_id in damage_ids { - let (level, fired, owner, last_reported_geometry) = { - let dmg = state - .damage_objects - .get(&damage_id) - .expect("just enumerated"); - ( - dmg.level, - dmg.pending_notify_fired, - dmg.owner, - dmg.last_reported_geometry, - ) - }; - if let Some(d) = state.damage_objects.get_mut(&damage_id) { - d.rects.push(rect_i16); + hits.push(Hit { + damage_id, + drawable: level_drawable, + rects: rects.to_vec(), + geometry, + }); + } +} + +/// Add `hit` to its damage object and queue the notifies its level asks +/// for (`DamageReportDamage` + `DamageExtReport`, +/// `miext/damage/damage.c:1935-1975`, `damageext/damageext.c:86-153`). +fn commit_hit(state: &mut ServerState, hit: Hit, pending: &mut Vec) { + let Some(dmg) = state.damage_objects.get_mut(&hit.damage_id) else { + return; + }; + dmg.rects.extend(hit.rects.iter().copied()); + let (level, fired, owner, last_reported_geometry) = ( + dmg.level, + dmg.pending_notify_fired, + dmg.owner, + dmg.last_reported_geometry, + ); + let geometry_changed = last_reported_geometry.is_some_and(|prev| prev != hit.geometry); + let owner_alive = state.clients.contains_key(&owner.0); + let notify = |level: u8, area: x11damage::Rectangle| PendingNotify { + owner, + damage_id: hit.damage_id, + level, + drawable: hit.drawable.0, + area, + geometry: hit.geometry, + }; + // Raw / Delta / BoundingBox report every op; only NonEmpty has the + // one-shot-per-Subtract semantic, re-reported when the geometry the + // last notify carried is stale. + let queued = match level { + x11damage::report_level::RAW_RECTANGLES + | x11damage::report_level::DELTA_RECTANGLES + | x11damage::report_level::BOUNDING_BOX + if owner_alive => + { + // `DamageExtNotify` flags every rect but the last of a report + // with DamageNotifyMore (`damageext/damageext.c:103-115`). + let more = level != x11damage::report_level::BOUNDING_BOX; + let last = hit.rects.len() - 1; + for (i, r) in hit.rects.iter().enumerate() { + let level = if more && i < last { + level | x11damage::MORE_FLAG + } else { + level + }; + pending.push(notify( + level, + x11damage::Rectangle { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + }, + )); + } + true } - let geometry_changed = last_reported_geometry.is_some_and(|prev| prev != geom_rect); - // Per X11 DAMAGE proto + Xorg `damageext/damageext.c:136-153` - // (`DamageExtReport`): Raw / Delta / BoundingBox levels emit - // a `DamageNotify` on EVERY damage event; only NonEmpty has - // the one-shot-per-Subtract semantic (emit on empty→non-empty - // transition, silent until the client Subtracts). The - // `geometry_changed` re-report fallback survives for NonEmpty - // because the spec requires the geometry payload to be - // current. - let level_allows_emit = match level { - x11damage::report_level::RAW_RECTANGLES - | x11damage::report_level::DELTA_RECTANGLES - | x11damage::report_level::BOUNDING_BOX => true, - x11damage::report_level::NON_EMPTY => !fired || geometry_changed, - _ => false, - }; - if state.clients.contains_key(&owner.0) && level_allows_emit { - // Per X11 DAMAGE spec + Xorg `damageext/damageext.c:117-126` - // (`DamageExtNotify` with `pBoxes == NULL`): NonEmpty events - // carry the full drawable extent in `area`, not the actual - // damaged sub-rect. Compositors (marco, picom, …) treat - // `area` as the region to recomposite — passing the small - // rect makes them clip the next composite to it, leaving - // the rest of the offscreen stale (observed as shrinking / - // top-left-only CC content after small client updates on - // marco-with-compositing). Raw / Delta / BoundingBox keep - // the current rect. - let area_for_level = if level == x11damage::report_level::NON_EMPTY { + // NonEmpty events carry the drawable's full extent in `area` + // (`DamageExtNotify` with `pBoxes == NULL`, + // `damageext/damageext.c:117-126`). + x11damage::report_level::NON_EMPTY if owner_alive && (!fired || geometry_changed) => { + pending.push(notify( + level, x11damage::Rectangle { x: 0, y: 0, - width: geom_full.width, - height: geom_full.height, - } - } else { - area - }; - pending.push(PendingNotify { - owner, - damage_id, - level, - drawable: level_drawable.0, - geometry: geom_rect, - area: area_for_level, - }); - if let Some(d) = state.damage_objects.get(&damage_id) { - log::trace!( - "damage_notify_queue: damage=0x{:x} owner={} drawable=0x{:x} level={} \ - area=({},{} {}x{}) geom=({},{} {}x{}) rects_n={} rects={}", - damage_id, - owner.0, - level_drawable.0, - level, - area_for_level.x, - area_for_level.y, - area_for_level.width, - area_for_level.height, - geom_rect.x, - geom_rect.y, - geom_rect.width, - geom_rect.height, - d.rects.len(), - format_damage_rects(&d.rects), - ); - } - if let Some(d) = state.damage_objects.get_mut(&damage_id) { - d.pending_notify_fired = true; - d.last_reported_geometry = Some(geom_rect); - } - } else { - let owner_alive = state.clients.contains_key(&owner.0); - if let Some(d) = state.damage_objects.get(&damage_id) { - log::trace!( - "damage_notify_skip: damage=0x{:x} owner={} drawable=0x{:x} level={} \ - fired={} owner_alive={} geometry_changed={} rects_n={} rects={}", - damage_id, - owner.0, - level_drawable.0, - level, - fired, - owner_alive, - geometry_changed, - d.rects.len(), - format_damage_rects(&d.rects), - ); - } + width: hit.geometry.width, + height: hit.geometry.height, + }, + )); + true } + _ => false, + }; + log::trace!( + "damage_notify_{}: damage=0x{:x} owner={} drawable=0x{:x} level={} fired={} \ + owner_alive={} rects={}", + if queued { "queue" } else { "skip" }, + hit.damage_id, + owner.0, + hit.drawable.0, + level, + fired, + owner_alive, + format_damage_rects(&hit.rects), + ); + if queued && let Some(d) = state.damage_objects.get_mut(&hit.damage_id) { + d.pending_notify_fired = true; + d.last_reported_geometry = Some(hit.geometry); } } @@ -891,6 +888,7 @@ mod tests { state.clients.insert( client_id, ClientState { + admission: crate::access::Admission::Internal, writer: make_test_writer(), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -903,11 +901,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), }, ); } @@ -963,6 +966,8 @@ mod tests { rects: Vec::new(), pending_notify_fired: false, last_reported_geometry: None, + list_pos: 0, + created: 0, }, ); } @@ -977,6 +982,7 @@ mod tests { state.clients.insert( client_id, ClientState { + admission: crate::access::Admission::Internal, writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -989,11 +995,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), }, ); b @@ -1146,11 +1157,10 @@ mod tests { assert!(dmg.pending_notify_fired, "a notify must have been queued"); } - /// The ancestor walk translates a negative-origin ring rect by the - /// child's own (x, y) — which is exactly right, because a child's - /// x/y are its INNER origin in the parent and the ring hangs `bw` - /// outside it. A child at (100, 50) with `bw = 2` must therefore - /// damage its parent starting at (98, 48). + /// The ancestor walk translates by the child's content origin, `x + bw` + /// (`dix/window.c:888`): a child's x/y are its OUTER corner, so a + /// child at (100, 50) with `bw = 2` damages its parent from (100, 50) + /// (Xorg, redirected-backing probe: `80,80 58x58` for (80,80) bw 4). #[test] fn the_ring_translates_to_the_outer_origin_in_the_parent() { let mut state = ServerState::new(); @@ -1179,8 +1189,8 @@ mod tests { .rects; assert!( rects.contains(&xfixes::RegionRect { - x: 98, - y: 48, + x: 100, + y: 50, width: 1280, height: 2 }), @@ -1189,8 +1199,8 @@ mod tests { ); assert!( rects.contains(&xfixes::RegionRect { - x: 98, - y: 754, + x: 100, + y: 756, width: 1280, height: 2 }), @@ -1378,6 +1388,33 @@ mod tests { ); } + /// Damage family: a damage owner over `OUTBOUND_CAP` is flagged for + /// the core loop to disconnect, and another owner's damage on the same + /// window still reports. + #[test] + fn overflowing_damage_owner_is_flagged_for_disconnect() { + let mut state = ServerState::new(); + let _slow = add_client_with_reader(&mut state, 1, 0x0010_0000); + let mut fast = add_client_with_reader(&mut state, 2, 0x0020_0000); + let w_id = add_window(&mut state, 1, 0x0010_0001, ROOT_WINDOW, 0, 0, 500, 400); + for (client, damage) in [(1, 0x0010_0002), (2, 0x0020_0002)] { + add_damage_on_with_level( + &mut state, + client, + damage, + w_id, + x11damage::report_level::RAW_RECTANGLES, + ); + } + crate::core_loop::client_io::saturate_for_test(state.clients.get_mut(&1).unwrap()); + let _ = accumulate_damage_to_state(&mut state, w_id, 5, 5, 30, 40); + assert_eq!( + crate::core_loop::client_io::failed_writers(&state.clients), + [ClientId(1)] + ); + assert_eq!(count_damage_notify_events(&mut fast, &state, 2), 1); + } + /// Companion: NonEmpty (level 3) keeps its spec-correct one-shot /// semantics — emit once on empty→non-empty transition, silent /// until Subtract. Ensures the fix doesn't over-reach. @@ -1610,6 +1647,7 @@ mod tests { state.clients.insert( 1, ClientState { + admission: crate::access::Admission::Internal, writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(writer_end))), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -1622,11 +1660,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), }, ); @@ -1738,6 +1781,39 @@ mod tests { /// `InputOnly` and unmapped children never contribute to the /// ClipByChildren region (matching Xorg's clipList). A socket /// "covered" only by such children still damages in full. + /// A bounding-shaped child covers its parent with its shape only: + /// a RENDER paint on the parent under the child's rect but outside + /// its shape (xfce4-settings-manager's button bar below its shaped + /// socket) is damage the compositor must hear about. + #[test] + fn mapped_child_clip_rects_use_a_childs_bounding_shape() { + let mut state = ServerState::new(); + add_client(&mut state, 1, 0x0210_0000); + let parent = add_window(&mut state, 1, 0x0210_0030, ROOT_WINDOW, 0, 0, 746, 500); + let socket = add_window(&mut state, 1, 0x0210_0031, parent, 8, 8, 730, 531); + let _ = state.resources.map_window(socket); + crate::nested::set_shape_rects( + &mut state, + socket, + yserver_protocol::x11::shape::KIND_BOUNDING, + vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 730, + height: 450, + }], + ); + assert_eq!( + mapped_child_clip_rects(&state, parent), + vec![xfixes::RegionRect { + x: 8, + y: 8, + width: 730, + height: 450, + }] + ); + } + #[test] fn mapped_child_clip_rects_skips_inputonly_and_unmapped() { let mut state = ServerState::new(); diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 7a773d3fe..8d24ffcb7 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -6,9 +6,9 @@ //! client's `last_sequence`, encode against the client's //! `byte_order`, and push bytes through `client_io::write_or_buffer` //! — the same path opcode dispatch will use after the D3 lift. -//! Disconnect outcomes are reported back to the caller as a -//! `Vec` so the core's request-loop can issue -//! `Message::ClientDisconnected` for each one. +//! Clients whose write failed are returned as a `Vec` for +//! information only: `client_io` has already flagged them, and the core +//! loop disconnects them (`run::disconnect_failed_writers`). //! //! The pre-lift `EventTarget`-based helpers in `server.rs` remain in //! place; D3 migrates callers off them. @@ -251,16 +251,16 @@ pub fn client_target_id(state: &ServerState, client_id: ClientId) -> Optionclient`, `dix/selection.c:297-301`), which need not own the window. #[must_use] pub fn selection_owner_target_id( state: &ServerState, selection: yserver_protocol::x11::AtomId, ) -> Option<(ResourceId, ClientId)> { - let owner_window = state.selections.get(&selection)?.0; - let owner_client = state.resources.window_owner(owner_window)?; - let target = client_target_id(state, owner_client)?; - Some((owner_window, target)) + let owner = state.selections.get(&selection)?; + let target = client_target_id(state, owner.client?)?; + Some((owner.window, target)) } /// `encode(buf, sequence, byte_order)` writes a 32-byte (or larger) @@ -323,9 +323,9 @@ where /// State-borrowing replacement for `nested::emit_xi2_focus_event`. /// /// Emits an XI2 FocusIn / FocusOut on `window` to clients selecting -/// the matching XI2 evtype on `(window, deviceid)` for any of the -/// fallback device candidates `[5, 3, 1, 0]` (slave keyboard, then -/// master keyboard, then AllMasterDevices, then AllDevices). The +/// the matching XI2 evtype on the master keyboard or either wildcard +/// selector. Focus transitions carry master keyboard deviceid 3, so +/// the XTEST keyboard's exact-device selector is not eligible. The /// encoding is byte-order agnostic, matching the pre-lift helper. /// /// `xi2_major_opcode` is the XI extension's runtime-assigned major @@ -344,14 +344,15 @@ pub fn emit_xi2_focus_event_to_state( .clients .iter() .filter_map(|(id, client)| { - let mask = client - .xi2_masks - .get(&(window, 5)) - .or_else(|| client.xi2_masks.get(&(window, 3))) - .or_else(|| client.xi2_masks.get(&(window, 1))) - .or_else(|| client.xi2_masks.get(&(window, 0))) - .copied() - .unwrap_or(0); + let mask = [ + crate::xinput::DEVICEID_MASTER_KEYBOARD, + 1, // XIAllMasterDevices applies to this master device. + 0, // XIAllDevices applies to every device. + ] + .into_iter() + .filter_map(|device_id| client.xi2_masks.get(&(window, device_id))) + .copied() + .fold(0, |combined, selected| combined | selected); if mask & (1 << evtype) != 0 { Some(ClientId(*id)) } else { @@ -392,19 +393,14 @@ pub fn emit_xi2_focus_event_to_state( /// active slave swap). const XI_REASON_DEVICE_CHANGE: u8 = 2; -/// Emit an XI2 `XI_DeviceChanged` for the slave pointer (device 4) to -/// every client that selected `XI_DeviceChanged` on it. -/// -/// Called after `xi_seed_touchpad` / `xi_clear_touchpad` so a running -/// desktop re-reads device 4 (picking up the new name + libinput -/// properties when a touchpad appears, or the reverted defaults when it -/// disappears). The carried class set mirrors the device-4 classes the -/// XIQueryDevice handler reports (button + 4 valuators + 2 scroll), so a -/// client re-querying after the event sees a consistent device. +/// Emit an XI2 `XI_DeviceChanged` for the bootstrapped virtual XTEST +/// pointer to clients that selected that device or `XIAllDevices`. +/// Physical registry facets are never represented by device 4 here. +/// The carried class set keeps the query-compatible button + 4 valuator +/// + 2 scroll shape. /// -/// Selection matches device 4 explicitly, plus the `XIAllDevices` (0) -/// and `XIAllMasterDevices` (1) wildcards a client may have used. If no -/// client selected, this is a no-op. Returns clients whose outbound +/// `XIAllMasterDevices` does not select this slave event. If no client +/// selected, this is a no-op. Returns clients whose outbound /// buffer overflowed (for `ClientDisconnected` reporting). /// /// `xi2_major_opcode` is the XI extension's runtime-assigned major @@ -413,27 +409,23 @@ pub fn emit_xi2_device_changed_slave_pointer( state: &mut ServerState, xi2_major_opcode: u8, ) -> Vec { - const SLAVE_POINTER: u16 = 4; + const XTEST_POINTER: u16 = crate::xinput::DEVICEID_XTEST_POINTER; // Clients select on (window, deviceid). DeviceChanged is a // hierarchy-wide event clients select on the ROOT window (the same // window `process_request`'s XISelectEvents bootstrap requires before // it sends the initial DeviceChanged). Match the root window only — // matching any window would spuriously deliver to a client that - // selected DeviceChanged on some unrelated child. Device-id match - // covers device 4 plus the AllDevices(0)/AllMasterDevices(1) - // wildcards. + // selected DeviceChanged on some unrelated child. The XTEST device + // matches its exact selector and XIAllDevices(0); it is not a master, + // so XIAllMasterDevices(1) does not match. let targets: Vec = state .clients .iter() .filter_map(|(id, client)| { let selected = client.xi2_masks.iter().any(|(&(window, dev), &mask)| { window == ROOT_WINDOW - // NOTE: XIAllMasterDevices(1) technically covers - // masters only; device 4 is a slave. Kept for - // delivery breadth; real clients select via - // XIAllDevices(0). - && matches!(dev, SLAVE_POINTER | 0 | 1) + && matches!(dev, XTEST_POINTER | 0) && (mask & u64::from(XI2_DEVICE_CHANGED_MASK)) != 0 }); selected.then_some(ClientId(*id)) @@ -451,164 +443,78 @@ pub fn emit_xi2_device_changed_slave_pointer( order, seq, xi2_major_opcode, - SLAVE_POINTER, + XTEST_POINTER, time, num_classes, - SLAVE_POINTER, // sourceid = the device itself + XTEST_POINTER, // sourceid = the XTEST device itself XI_REASON_DEVICE_CHANGE, &classes, ); }) } -/// Build the XI2 device-class block for the slave pointer (device 4), -/// returning `(class_bytes, num_classes)`. -/// -/// This is the SINGLE source of truth for device 4's class shape: -/// Button(7) + Valuator×4 (X, Y, vert-scroll, horiz-scroll) + Scroll×2 -/// (vert, horiz). Both XIQueryDevice's device-4 path (opcode 48) and the -/// touchpad-add/remove `XI_DeviceChanged` fanout call it, so the bytes can -/// never drift apart (asserted byte-identical by -/// `query_device_4_matches_device_changed_block`). `num_classes` is -/// derived from the writes below, not hardcoded at the call sites. +/// Build the XI2 device-class block for the virtual XTEST pointer. /// -/// The scroll valuators MUST stay declared — dropping them fires a -/// Gdk-CRITICAL (`_gdk_x11_device_xi2_add_scroll_valuator` asserts the -/// scroll axis index is within the valuator count). +/// The query encoder owns the shared button/valuator/scroll class layout; +/// both XIQueryDevice and DeviceChanged use it so their class blocks remain +/// byte-identical for little-endian clients. pub(crate) fn build_slave_pointer_class_block(state: &mut ServerState) -> (Vec, u16) { - const DEVICEID: u16 = 4; - - fn write_button_class(buf: &mut Vec, sourceid: u16, label_atoms: &[x11::AtomId]) { - let le = ClientByteOrder::LittleEndian; - let num_buttons = u16::try_from(label_atoms.len()).unwrap_or(u16::MAX); - let state_words = num_buttons.div_ceil(32) as usize; - let byte_len = 8 + 4 * state_words + 4 * num_buttons as usize; - x11::write_u16(le, buf, 1); // type = Button - x11::write_u16(le, buf, (byte_len / 4) as u16); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, num_buttons); - buf.extend(std::iter::repeat_n(0u8, 4 * state_words)); - for atom in label_atoms { - x11::write_u32(le, buf, atom.0); - } - } + build_pointer_class_block_for_device(state, crate::xinput::DEVICEID_XTEST_POINTER) +} - fn write_valuator_class( - buf: &mut Vec, - sourceid: u16, - number: u16, - label_atom: x11::AtomId, - min_int: i32, - max_int: i32, - mode: u8, - value: i32, - ) { - let le = ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, 2); // type = Valuator - x11::write_u16(le, buf, 11); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, number); - x11::write_u32(le, buf, label_atom.0); - x11::write_u32(le, buf, min_int as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, max_int as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, value as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, 0); // resolution - buf.push(mode); - buf.extend_from_slice(&[0u8; 3]); - } +pub(crate) fn build_pointer_class_block_for_device( + state: &mut ServerState, + device_id: u16, +) -> (Vec, u16) { + let class_data = pointer_class_data_for_device(state, device_id); + crate::xinput::query::build_pointer_classes( + ClientByteOrder::LittleEndian, + device_id, + class_data, + ) +} - fn write_scroll_class(buf: &mut Vec, sourceid: u16, number: u16, scroll_type: u16) { - let le = ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, 3); // type = Scroll - x11::write_u16(le, buf, 6); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, number); - x11::write_u16(le, buf, scroll_type); - x11::write_u16(le, buf, 0); // pad - x11::write_u32(le, buf, 0); // flags - x11::write_u32(le, buf, 1); // increment = 1.0 - x11::write_u32(le, buf, 0); +pub(crate) fn pointer_class_data_for_device( + state: &mut ServerState, + device_id: u16, +) -> crate::xinput::query::XiQueryClassData { + crate::xinput::query::XiQueryClassData { + button_labels: [ + state.atoms.intern("Button Left", false), + state.atoms.intern("Button Middle", false), + state.atoms.intern("Button Right", false), + state.atoms.intern("Button Wheel Up", false), + state.atoms.intern("Button Wheel Down", false), + state.atoms.intern("Button Horiz Wheel Left", false), + state.atoms.intern("Button Horiz Wheel Right", false), + ], + button_state: if device_id == crate::xinput::DEVICEID_MASTER_POINTER { + state.buttons_down + } else { + state + .xi_devices + .device(device_id) + .map_or(0, |device| device.buttons_down) + }, + axis_labels: [ + state.atoms.intern("Rel X", false), + state.atoms.intern("Rel Y", false), + state.atoms.intern("Rel Vert Scroll", false), + state.atoms.intern("Rel Horiz Scroll", false), + ], + pointer: ( + i32::from(state.randr.screen_width) / 2, + i32::from(state.randr.screen_height) / 2, + ), + scroll: if device_id == crate::xinput::DEVICEID_MASTER_POINTER { + state.scroll_axis_value + } else { + state + .xi_devices + .device(device_id) + .map_or(state.scroll_axis_value, |device| device.scroll_axis_values) + }, } - - let pointer = ( - i32::from(state.randr.screen_width) / 2, - i32::from(state.randr.screen_height) / 2, - ); - let button_labels = [ - state.atoms.intern("Button Left", false), - state.atoms.intern("Button Middle", false), - state.atoms.intern("Button Right", false), - state.atoms.intern("Button Wheel Up", false), - state.atoms.intern("Button Wheel Down", false), - state.atoms.intern("Button Horiz Wheel Left", false), - state.atoms.intern("Button Horiz Wheel Right", false), - ]; - let axis_labels = [ - state.atoms.intern("Rel X", false), - state.atoms.intern("Rel Y", false), - state.atoms.intern("Rel Vert Scroll", false), - state.atoms.intern("Rel Horiz Scroll", false), - ]; - let scroll = state.scroll_axis_value; - - // `num_classes` is incremented per class written below so the count - // can never drift from the actual byte content. - let mut classes = Vec::new(); - let mut num_classes = 0u16; - write_button_class(&mut classes, DEVICEID, &button_labels); - num_classes += 1; - write_valuator_class( - &mut classes, - DEVICEID, - 0, - axis_labels[0], - -1, - -1, - 0, - pointer.0, - ); - num_classes += 1; - write_valuator_class( - &mut classes, - DEVICEID, - 1, - axis_labels[1], - -1, - -1, - 0, - pointer.1, - ); - num_classes += 1; - write_valuator_class( - &mut classes, - DEVICEID, - 2, - axis_labels[2], - -1, - 0, - 0, - scroll[0], - ); - num_classes += 1; - write_valuator_class( - &mut classes, - DEVICEID, - 3, - axis_labels[3], - -1, - 0, - 0, - scroll[1], - ); - num_classes += 1; - write_scroll_class(&mut classes, DEVICEID, 2, 1); // vertical - num_classes += 1; - write_scroll_class(&mut classes, DEVICEID, 3, 2); // horizontal - num_classes += 1; - (classes, num_classes) } /// State-borrowing replacement for `nested::expose_event_fanout`. @@ -669,34 +575,6 @@ pub fn expose_event_fanout_to_state( dropped } -/// State-borrowing replacement for `nested::emit_expose_subtree`. -/// -/// Walks every mapped descendant of `root` and emits Expose to those -/// that selected `ExposureMask`. Used after a top-level becomes -/// viewable so deeply-nested widgets repaint immediately. -pub fn emit_expose_subtree_to_state(state: &mut ServerState, root: ResourceId) -> Vec { - let mut dropped = Vec::new(); - let children: Vec = state.resources.children(root).to_vec(); - for child in children { - let extents = state - .resources - .window(child) - .filter(|w| w.map_state == MapState::Viewable) - .map(|w| (w.width, w.height)); - if let Some((w, h)) = extents { - let target = child; - let more = - emit_window_event_to_state(state, target, EXPOSURE_MASK_BIT, |buf, seq, order| { - x11::encode_expose_event(buf, seq, order, target, 0, 0, w, h, 0); - }); - merge_dropped(&mut dropped, more); - let recursed = emit_expose_subtree_to_state(state, child); - merge_dropped(&mut dropped, recursed); - } - } - dropped -} - /// Walks every now-Viewable descendant of `root` and emits /// `VisibilityNotify(Unobscured)` to those that selected /// `VisibilityChangeMask`. Used after a top-level is mapped: any @@ -813,9 +691,13 @@ mod tests { server::{ClientState, ServerState}, }; - fn make_client(writer: UnixStream, mask_for_root: u32) -> ClientState { + fn make_client_with_transport( + writer: crate::transport::Transport, + mask_for_root: u32, + ) -> ClientState { ClientState { - writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(writer))), + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(writer)), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), resource_id_base: 0, @@ -827,14 +709,23 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), } } + fn make_client(writer: UnixStream, mask_for_root: u32) -> ClientState { + make_client_with_transport(crate::transport::Transport::Unix(writer), mask_for_root) + } + fn install(state: &mut ServerState, id: u32, mask: u32) -> UnixStream { let (a, b) = UnixStream::pair().unwrap(); let client = make_client(a, mask); @@ -842,6 +733,29 @@ mod tests { b } + fn install_capture(state: &mut ServerState, id: u32) -> crate::transport::CapturedPeer { + let (writer, peer) = crate::transport::Transport::capture_pair(); + state + .clients + .insert(id, make_client_with_transport(writer, 0)); + peer + } + + fn read_all_capture(peer: &mut crate::transport::CapturedPeer) -> Vec { + peer.set_nonblocking(true).expect("set capture nonblocking"); + let mut bytes = Vec::new(); + let mut buffer = [0u8; 128]; + loop { + match peer.read(&mut buffer) { + Ok(0) => break, + Ok(count) => bytes.extend_from_slice(&buffer[..count]), + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) => panic!("capture read failed: {error}"), + } + } + bytes + } + /// Issue #141 — a reparenting WM must not be handed a core press that /// an XI2 client absorbed. Xorg's `DeliverDeviceEvents` /// (`dix/events.c:2895-2916`) tries XI2, then XI1, then core PER @@ -1079,6 +993,87 @@ mod tests { } } + #[test] + fn xi2_focus_event_for_master_does_not_target_xtest_keyboard() { + let mut state = ServerState::new(); + let window = ROOT_WINDOW; + let mut xtest_peer = install_capture(&mut state, 1); + let mut master_peer = install_capture(&mut state, 2); + let mut all_masters_peer = install_capture(&mut state, 3); + let mut all_devices_peer = install_capture(&mut state, 4); + for (client_id, device_id) in [ + (1, crate::xinput::DEVICEID_XTEST_KEYBOARD), + (2, crate::xinput::DEVICEID_MASTER_KEYBOARD), + (3, 1), + (4, 0), + ] { + state + .clients + .get_mut(&client_id) + .expect("registered focus client") + .xi2_masks + .insert((window, device_id), 1 << 9); + } + state + .clients + .get_mut(&2) + .expect("registered master focus client") + .xi2_masks + .insert((window, crate::xinput::DEVICEID_MASTER_KEYBOARD), 1 << 2); + state + .clients + .get_mut(&2) + .expect("registered master focus client") + .xi2_masks + .insert((window, 1), 1 << 9); + + assert!(emit_xi2_focus_event_to_state(&mut state, window, 9, 137, 0, 0, 0, 0).is_empty()); + + assert!( + read_all_capture(&mut xtest_peer).is_empty(), + "the focus transition is for master keyboard 3, not XTEST keyboard 5" + ); + for (peer, label) in [ + (&mut master_peer, "master keyboard"), + (&mut all_masters_peer, "XIAllMasterDevices"), + (&mut all_devices_peer, "XIAllDevices"), + ] { + let event = read_all_capture(peer); + assert_eq!(event.len(), 76, "{label} receives one focus event"); + assert_eq!(u16::from_le_bytes(event[8..10].try_into().unwrap()), 9); + assert_eq!( + u16::from_le_bytes(event[10..12].try_into().unwrap()), + crate::xinput::DEVICEID_MASTER_KEYBOARD, + "focus event deviceid is the master keyboard" + ); + assert_eq!( + u16::from_le_bytes(event[16..18].try_into().unwrap()), + crate::xinput::DEVICEID_MASTER_KEYBOARD, + "focus event sourceid is the master keyboard" + ); + } + assert_eq!(state.clients.len(), 4); + assert_eq!( + state.clients[&1].xi2_masks, + HashMap::from([((window, crate::xinput::DEVICEID_XTEST_KEYBOARD), 1 << 9)]) + ); + assert_eq!( + state.clients[&2].xi2_masks, + HashMap::from([ + ((window, crate::xinput::DEVICEID_MASTER_KEYBOARD), 1 << 2), + ((window, 1), 1 << 9), + ]) + ); + assert_eq!( + state.clients[&3].xi2_masks, + HashMap::from([((window, 1), 1 << 9)]) + ); + assert_eq!( + state.clients[&4].xi2_masks, + HashMap::from([((window, 0), 1 << 9)]) + ); + } + #[test] fn expose_event_fanout_translates_host_xid() { let mut state = ServerState::new(); @@ -1149,4 +1144,36 @@ mod tests { other => panic!("unsubscribed peer2 unexpectedly received: {other:?}"), } } + + /// Property / structure notify family: a subscriber over + /// `OUTBOUND_CAP` is reported and flagged for the core loop to + /// disconnect, gets nothing more, and the other subscriber still gets + /// every event; the raw (SendEvent / server-built) fanout too. + #[test] + fn overflowing_subscriber_is_flagged_and_the_others_still_receive() { + const PROPERTY_CHANGE: u32 = 1 << 22; + let mut state = ServerState::new(); + let _slow = install(&mut state, 1, PROPERTY_CHANGE); + let mut fast = install(&mut state, 2, PROPERTY_CHANGE); + fast.set_nonblocking(true).unwrap(); + client_io::saturate_for_test(state.clients.get_mut(&1).unwrap()); + + let encode = |buf: &mut Vec, _: SequenceNumber, _: ClientByteOrder| { + buf.extend_from_slice(&[28u8; 32]); + }; + let dropped = emit_window_event_to_state(&mut state, ROOT_WINDOW, PROPERTY_CHANGE, encode); + assert_eq!(dropped, [ClientId(1)]); + assert_eq!(client_io::failed_writers(&state.clients), [ClientId(1)]); + let _ = emit_window_event_to_state(&mut state, ROOT_WINDOW, PROPERTY_CHANGE, encode); + let _ = fanout_raw_event_to_clients( + &mut state, + &[ClientId(1), ClientId(2)], + &[28u8; 32], + ClientByteOrder::LittleEndian, + ); + assert_eq!(state.clients[&1].outbound.len(), client_io::outbound_cap()); + let mut got = [0u8; 128]; + assert_eq!(fast.read(&mut got).unwrap(), 96); + assert_eq!(client_io::failed_writers(&state.clients), [ClientId(1)]); + } } diff --git a/crates/yserver-core/src/core_loop/generation.rs b/crates/yserver-core/src/core_loop/generation.rs index d1251d13e..c5810641e 100644 --- a/crates/yserver-core/src/core_loop/generation.rs +++ b/crates/yserver-core/src/core_loop/generation.rs @@ -23,8 +23,9 @@ use super::message::Message; /// A generation ordinal. Cheap to copy/compare; carries no behaviour of /// its own. Numeric identity is deliberately not exposed — nothing /// outside this module needs to construct one except by reading a -/// `GenerationCounter`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +/// `GenerationCounter`. Ordered, so that process-lifetime state can tell a +/// newer session from a quarantined older one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)] pub struct Generation(u64); /// Shared, process-lifetime counter. `CoreSender` holds a clone to tag @@ -70,13 +71,18 @@ pub(crate) fn is_session_scoped(message: &Message) -> bool { Message::HostInput(_) | Message::CrtcConfigReady + | Message::DeviceConfigResult { .. } + | Message::InputPaused | Message::Shutdown | Message::ResetRequested | Message::VtRelease | Message::VtAcquire | Message::SwitchVt(_) | Message::DumpScanout - | Message::DumpDrawables => false, + | Message::DumpDrawables + | Message::PlatformEvent + | Message::Rootless(_) => false, + Message::InternalClient(_) => false, } } @@ -98,9 +104,9 @@ mod tests { use crate::core_loop::message::HostInputEvent; use yserver_protocol::x11::ClientId; - fn device_removed(node: &str) -> Message { + fn device_removed() -> Message { Message::HostInput(HostInputEvent::DeviceRemoved { - device_node: node.into(), + source_id: crate::xinput::InputSourceId(1), }) } @@ -119,6 +125,13 @@ mod tests { assert_ne!(clone.current(), Generation::default()); } + #[test] + fn bump_orders_after_the_previous_generation() { + let counter = GenerationCounter::new(); + let before = counter.current(); + assert!(counter.bump() > before); + } + #[test] fn session_scoped_message_is_dropped_on_generation_mismatch() { let old = Generation::default(); @@ -172,7 +185,7 @@ mod tests { let old = Generation::default(); let current = GenerationCounter::new(); current.bump(); - let msg = device_removed("/dev/input/event3"); + let msg = device_removed(); assert!(should_dispatch(current.current(), old, &msg)); } @@ -187,11 +200,13 @@ mod tests { Message::ResetRequested, Message::CrtcConfigReady, Message::VtRelease, + Message::InputPaused, Message::VtAcquire, Message::SwitchVt(1), Message::DumpScanout, Message::DumpDrawables, - device_removed("/dev/input/event0"), + Message::PlatformEvent, + device_removed(), Message::ClientDisconnected { id: ClientId(1), reason: std::io::Error::other("gone"), diff --git a/crates/yserver-core/src/core_loop/host_access.rs b/crates/yserver-core/src/core_loop/host_access.rs new file mode 100644 index 000000000..d72607c19 --- /dev/null +++ b/crates/yserver-core/src/core_loop/host_access.rs @@ -0,0 +1,720 @@ +//! The host access list (`xhost`): entries, server-interpreted (SI) address +//! validation and matching, and the `ListHosts` entry encoding. +//! +//! Pure: no locking and no I/O except name lookups through [`NameResolver`]. +//! [`AuthState`](super::auth::AuthState) holds the state and decides +//! admission. Faithful to Xorg's `os/access.c` except where +//! docs/superpowers/plans/2026-10-30-xhost-access-control-plan.md, +//! "Decisions (review 2026-10-30)", says otherwise: a `#` id is kept as +//! the full `long` instead of being truncated to `int`, so an oversized or +//! negative id is stored and listed but never matches anyone. + +use std::{ + ffi::{CStr, CString}, + net::Ipv6Addr, +}; + +use yserver_protocol::x11::ClientByteOrder; + +use crate::peer::PeerCred; + +pub const FAMILY_INTERNET: u8 = 0; +pub const FAMILY_DECNET: u8 = 1; +pub const FAMILY_CHAOS: u8 = 2; +pub const FAMILY_SERVER_INTERPRETED: u8 = 5; +pub const FAMILY_INTERNET6: u8 = 6; +pub const FAMILY_LOCAL_HOST: u8 = 252; + +/// `NI_MAXHOST`, Xorg's `SI_HOSTNAME_MAXLEN` (`os/access.c:1809`). +const SI_HOSTNAME_MAXLEN: usize = 1025; +/// `INET6_ADDRSTRLEN`, Xorg's `SI_IPv6_MAXLEN`. +const SI_IPV6_MAXLEN: usize = 46; +/// `GetHosts` stops counting once the entry bytes reach this +/// (`os/access.c:1460-1467`). +const LIST_HOSTS_BYTE_CAP: usize = 1 << 20; + +/// One access-list entry, exactly as the client sent it. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct HostEntry { + pub family: u8, + pub addr: Vec, +} + +/// Xorg's `validhosts` plus `AccessEnabled`. Newest entry first. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct HostList { + pub access_enabled: bool, + pub hosts: Vec, +} + +impl Default for HostList { + /// The `ResetHosts` state without `-ac`: enabled, empty + /// (`os/access.c:956-962`). + fn default() -> Self { + Self { + access_enabled: true, + hosts: Vec::new(), + } + } +} + +impl HostList { + /// `NewHost`: an equal entry already present is a no-op, otherwise the + /// entry is prepended (`os/access.c:1371-1396`). Equality is family, + /// length and bytes (`addrEqual`, `:193-196`). + pub fn insert(&mut self, entry: HostEntry) { + if !self.hosts.contains(&entry) { + self.hosts.insert(0, entry); + } + } + + /// `RemoveHost`: unlink the first equal entry; an absent one is fine + /// (`os/access.c:1439-1446`). + pub fn delete(&mut self, entry: &HostEntry) { + if let Some(index) = self.hosts.iter().position(|host| host == entry) { + self.hosts.remove(index); + } + } +} + +/// Which value a failed `ChangeHosts` reports in its `BadValue`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum BadValue { + /// `CheckAddr` failed for a known family: the value is the length. + Length, + /// An unknown family: the value is the family. + Family, +} + +/// `AddHost`/`RemoveHost` validation for every family except +/// `FamilyLocalHost`, which the caller handles (`os/access.c:1313-1349`, +/// `CheckAddr` at `:1495-1524`). DECnet and Chaos always fail. +pub fn check_addr(family: u8, addr: &[u8], resolver: &dyn NameResolver) -> Result<(), BadValue> { + let valid = match family { + FAMILY_INTERNET => addr.len() == 4, + FAMILY_INTERNET6 => addr.len() == 16, + FAMILY_DECNET | FAMILY_CHAOS => false, + FAMILY_SERVER_INTERPRETED => { + SiEntry::parse(addr).is_some_and(|entry| entry.value_is_valid(resolver)) + } + _ => return Err(BadValue::Family), + }; + if valid { Ok(()) } else { Err(BadValue::Length) } +} + +/// The SI types Xorg registers (`siTypesInitialize`, `os/access.c:2160-2171`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SiType { + Hostname, + Ipv6, + LocalUser, + LocalGroup, +} + +/// Whether a `localuser`/`localgroup` value names a user or a group. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CredKind { + User, + Group, +} + +/// A `FamilyServerInterpreted` address split into its type and value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SiEntry<'a> { + pub kind: SiType, + /// Everything after the first NUL; no trailing NUL on the wire. + pub value: &'a [u8], +} + +impl<'a> SiEntry<'a> { + /// `type\0value`. `None` for a missing NUL or an unregistered type + /// (`siCheckAddr`, `os/access.c:1745-1777`). + #[must_use] + pub fn parse(addr: &'a [u8]) -> Option { + let nul = addr.iter().position(|&b| b == 0)?; + let kind = match &addr[..nul] { + b"hostname" => SiType::Hostname, + b"ipv6" => SiType::Ipv6, + b"localuser" => SiType::LocalUser, + b"localgroup" => SiType::LocalGroup, + _ => return None, + }; + Some(Self { + kind, + value: &addr[nul + 1..], + }) + } + + fn value_is_valid(&self, resolver: &dyn NameResolver) -> bool { + match self.kind { + SiType::Hostname => hostname_is_valid(self.value), + SiType::Ipv6 => ipv6_is_valid(self.value), + SiType::LocalUser => parse_cred_id(self.value, CredKind::User, resolver).is_some(), + SiType::LocalGroup => parse_cred_id(self.value, CredKind::Group, resolver).is_some(), + } + } +} + +/// `siHostnameCheckAddr` (`os/access.c:1901-1966`): RFC 2396 hostname +/// syntax, ASCII only. Xorg writes the digit range as `0x30..=0x3A`, so `:` +/// passes too. +fn hostname_is_valid(value: &[u8]) -> bool { + if value.is_empty() || value.len() >= SI_HOSTNAME_MAXLEN { + return false; + } + let mut dot_allowed = false; + let mut dash_allowed = false; + for &c in value { + match c { + b'.' => { + if !dot_allowed { + return false; + } + dot_allowed = false; + dash_allowed = false; + } + b'-' => { + if !dash_allowed { + return false; + } + dot_allowed = false; + } + 0x30..=0x3A | b'a'..=b'z' | b'A'..=b'Z' => { + dot_allowed = true; + dash_allowed = true; + } + _ => return false, + } + } + true +} + +/// `siIPv6CheckAddr` (`os/access.c:2013-2035`): `3 <= len < +/// INET6_ADDRSTRLEN`, then an IPv6 literal parse of the NUL-terminated copy. +fn ipv6_is_valid(value: &[u8]) -> bool { + if value.len() < 3 || value.len() >= SI_IPV6_MAXLEN { + return false; + } + std::str::from_utf8(before_nul(value)).is_ok_and(|text| text.parse::().is_ok()) +} + +fn before_nul(bytes: &[u8]) -> &[u8] { + bytes + .iter() + .position(|&b| b == 0) + .map_or(bytes, |nul| &bytes[..nul]) +} + +/// `siLocalCredGetId` (`os/access.c:2051-2093`). Xorg copies the value and +/// NUL-terminates it, so everything below sees the bytes before the first +/// NUL. `#` is `strtol` base 0 into the full `long`, with no +/// truncation to `int` (plan decision 1); anything else is a user or group +/// name lookup. +pub fn parse_cred_id(value: &[u8], kind: CredKind, resolver: &dyn NameResolver) -> Option { + let value = before_nul(value); + if let Some(number) = value.strip_prefix(b"#") { + return strtol_base0(number); + } + let name = CString::new(value).ok()?; + let id = match kind { + CredKind::User => resolver.uid(&name), + CredKind::Group => resolver.gid(&name), + }?; + Some(i64::from(id)) +} + +/// C `strtol(s, &end, 0)` on LP64, accepted when `end` moved and `errno` +/// stayed 0: leading whitespace, an optional sign, a `0x` (hex) or `0` +/// (octal) prefix, trailing junk ignored. `None` for no digits or `ERANGE`. +fn strtol_base0(s: &[u8]) -> Option { + let mut i = 0; + while s + .get(i) + .is_some_and(|c| matches!(c, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')) + { + i += 1; + } + let negative = match s.get(i) { + Some(b'-') => { + i += 1; + true + } + Some(b'+') => { + i += 1; + false + } + _ => false, + }; + // `0x` only counts as a prefix when a hex digit follows; otherwise C + // parses the `0` and stops at the `x`. + let radix = if s.get(i) == Some(&b'0') { + if matches!(s.get(i + 1), Some(b'x' | b'X')) + && s.get(i + 2).is_some_and(u8::is_ascii_hexdigit) + { + i += 2; + 16 + } else { + 8 + } + } else { + 10 + }; + let mut magnitude: u64 = 0; + let mut overflow = false; + let mut digits = 0usize; + for &c in &s[i..] { + let Some(digit) = char::from(c).to_digit(radix) else { + break; + }; + digits += 1; + match magnitude + .checked_mul(u64::from(radix)) + .and_then(|m| m.checked_add(u64::from(digit))) + { + Some(m) => magnitude = m, + None => overflow = true, + } + } + if digits == 0 || overflow { + return None; + } + let signed = if negative { + -i128::from(magnitude) + } else { + i128::from(magnitude) + }; + i64::try_from(signed).ok() +} + +/// `siLocalCredAddrMatch` for a local peer (`os/access.c:2096-2140`), plus +/// the `hostname`/`ipv6` matchers, which only accept Internet peers and so +/// never match here (`:1819-1846`, `:1970-1994`). `localuser` compares the +/// peer's effective uid, `localgroup` its primary gid; the full parsed value +/// is compared, so an id outside `0..=u32::MAX` never matches. No +/// credentials never match (`:2104`). +pub fn si_matches_local( + entry: &HostEntry, + cred: Option<&PeerCred>, + resolver: &dyn NameResolver, +) -> bool { + if entry.family != FAMILY_SERVER_INTERPRETED { + return false; + } + let Some(si) = SiEntry::parse(&entry.addr) else { + return false; + }; + let Some(cred) = cred else { + return false; + }; + let (kind, id) = match si.kind { + SiType::LocalUser => (CredKind::User, cred.uid), + SiType::LocalGroup => (CredKind::Group, cred.gid), + SiType::Hostname | SiType::Ipv6 => return false, + }; + parse_cred_id(si.value, kind, resolver) == Some(i64::from(id)) +} + +/// `GetHosts` + `SLHostsExtend` (`os/access.c:1451-1491`, +/// `dix/swaprep.c:648-661`): the `ListHosts` entries, each `family, 0, +/// length:CARD16, addr`, padded to 4 with zeros. Entries are counted until +/// the running byte total reaches 1 MiB; the entry that reaches it is kept. +/// Returns the entry count and the bytes. +/// +/// Deliberately not Xorg: Xorg counts entries in an `int` and stores the +/// count in the reply's CARD16 `nHosts`, so a list of more than 65535 short +/// entries reports a truncated count over the full data. We stop at 65535 +/// entries, so the count and the data agree. +#[must_use] +pub fn encode_entries(hosts: &[HostEntry], byte_order: ClientByteOrder) -> (u16, Vec) { + let mut total = 0usize; + let mut count = 0u16; + for host in hosts { + if count == u16::MAX { + break; + } + count += 1; + total += 4 + host.addr.len().next_multiple_of(4); + if total >= LIST_HOSTS_BYTE_CAP { + break; + } + } + let mut bytes = Vec::with_capacity(total); + for host in &hosts[..usize::from(count)] { + // ChangeHosts carries the length as a CARD16, so a stored address + // always fits. + let len = u16::try_from(host.addr.len()).unwrap_or(u16::MAX); + bytes.push(host.family); + bytes.push(0); + bytes.extend_from_slice(&match byte_order { + ClientByteOrder::LittleEndian => len.to_le_bytes(), + ClientByteOrder::BigEndian => len.to_be_bytes(), + }); + bytes.extend_from_slice(&host.addr); + bytes.resize( + bytes.len() + host.addr.len().next_multiple_of(4) - host.addr.len(), + 0, + ); + } + (count, bytes) +} + +/// User and group name lookup for `localuser:`/`localgroup:`. +/// A trait so tests do not depend on the host's NSS. +pub trait NameResolver { + fn uid(&self, name: &CStr) -> Option; + fn gid(&self, name: &CStr) -> Option; +} + +/// NSS through `getpwnam_r`/`getgrnam_r`: setup threads resolve +/// concurrently, so never the non-reentrant calls. +pub struct SystemResolver; + +/// Upper bound for the `*_r` scratch buffer; a lookup that still reports +/// `ERANGE` at this size is treated as unresolved. +#[cfg(unix)] +const NSS_BUF_MAX: usize = 1 << 20; + +#[cfg(unix)] +impl NameResolver for SystemResolver { + fn uid(&self, name: &CStr) -> Option { + let mut buf = vec![0 as libc::c_char; 1024]; + loop { + // SAFETY: `passwd` is plain old data; `getpwnam_r` overwrites it. + let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; + let mut result: *mut libc::passwd = std::ptr::null_mut(); + // SAFETY: `name` is NUL-terminated, `buf` is writable for its + // length, and `pwd`/`result` are valid out-params. + let rc = unsafe { + libc::getpwnam_r( + name.as_ptr(), + &raw mut pwd, + buf.as_mut_ptr(), + buf.len(), + &raw mut result, + ) + }; + if rc == libc::ERANGE && buf.len() < NSS_BUF_MAX { + buf.resize(buf.len() * 2, 0); + continue; + } + return (rc == 0 && !result.is_null()).then_some(pwd.pw_uid); + } + } + + fn gid(&self, name: &CStr) -> Option { + let mut buf = vec![0 as libc::c_char; 1024]; + loop { + // SAFETY: `group` is plain old data; `getgrnam_r` overwrites it. + let mut grp: libc::group = unsafe { std::mem::zeroed() }; + let mut result: *mut libc::group = std::ptr::null_mut(); + // SAFETY: as in `uid`. + let rc = unsafe { + libc::getgrnam_r( + name.as_ptr(), + &raw mut grp, + buf.as_mut_ptr(), + buf.len(), + &raw mut result, + ) + }; + if rc == libc::ERANGE && buf.len() < NSS_BUF_MAX { + buf.resize(buf.len() * 2, 0); + continue; + } + return (rc == 0 && !result.is_null()).then_some(grp.gr_gid); + } + } +} + +/// Windows has no uids or gids, so no `localuser`/`localgroup` name +/// resolves. +#[cfg(windows)] +impl NameResolver for SystemResolver { + fn uid(&self, _name: &CStr) -> Option { + None + } + + fn gid(&self, _name: &CStr) -> Option { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Fixed NSS: users `root` 0 and `bob` 1000, groups `wheel` 10 and + /// `staff` 50. + struct FakeResolver; + + impl NameResolver for FakeResolver { + fn uid(&self, name: &CStr) -> Option { + match name.to_bytes() { + b"root" => Some(0), + b"bob" => Some(1000), + _ => None, + } + } + + fn gid(&self, name: &CStr) -> Option { + match name.to_bytes() { + b"wheel" => Some(10), + b"staff" => Some(50), + _ => None, + } + } + } + + fn entry(family: u8, addr: &[u8]) -> HostEntry { + HostEntry { + family, + addr: addr.to_vec(), + } + } + + fn si(kind: &str, value: &[u8]) -> Vec { + let mut addr = kind.as_bytes().to_vec(); + addr.push(0); + addr.extend_from_slice(value); + addr + } + + fn cred(uid: u32, gid: u32) -> PeerCred { + PeerCred { + uid, + gid, + pid: None, + } + } + + #[test] + fn insert_dedups_and_prepends() { + let a = entry(FAMILY_INTERNET, &[10, 0, 0, 1]); + let b = entry(FAMILY_INTERNET, &[10, 0, 0, 2]); + let mut list = HostList::default(); + list.insert(a.clone()); + list.insert(b.clone()); + list.insert(a.clone()); + assert_eq!(list.hosts, vec![b, a]); + } + + #[test] + fn delete_of_an_absent_entry_changes_nothing() { + let a = entry(FAMILY_INTERNET, &[10, 0, 0, 1]); + let mut list = HostList::default(); + list.insert(a.clone()); + list.delete(&entry(FAMILY_INTERNET, &[10, 0, 0, 9])); + assert_eq!(list.hosts, vec![a.clone()]); + list.delete(&a); + assert!(list.hosts.is_empty()); + } + + #[test] + fn equality_includes_family_and_length() { + let mut list = HostList::default(); + list.insert(entry(FAMILY_LOCAL_HOST, &[])); + list.insert(entry(FAMILY_LOCAL_HOST, &[1])); + list.insert(entry(FAMILY_INTERNET, &[])); + assert_eq!(list.hosts.len(), 3); + } + + #[test] + fn default_list_is_enabled_and_empty() { + let list = HostList::default(); + assert!(list.access_enabled); + assert!(list.hosts.is_empty()); + } + + #[test] + fn check_addr_lengths_and_families() { + let r = &FakeResolver; + assert_eq!(check_addr(FAMILY_INTERNET, &[0; 4], r), Ok(())); + assert_eq!( + check_addr(FAMILY_INTERNET, &[0; 3], r), + Err(BadValue::Length) + ); + assert_eq!(check_addr(FAMILY_INTERNET6, &[0; 16], r), Ok(())); + assert_eq!( + check_addr(FAMILY_INTERNET6, &[0; 15], r), + Err(BadValue::Length) + ); + for len in [0, 4, 16] { + assert_eq!( + check_addr(FAMILY_DECNET, &vec![0; len], r), + Err(BadValue::Length) + ); + assert_eq!( + check_addr(FAMILY_CHAOS, &vec![0; len], r), + Err(BadValue::Length) + ); + } + assert_eq!(check_addr(7, &[0; 4], r), Err(BadValue::Family)); + } + + #[test] + fn check_addr_server_interpreted() { + let r = &FakeResolver; + assert_eq!( + check_addr(FAMILY_SERVER_INTERPRETED, &si("localuser", b"bob"), r), + Ok(()) + ); + assert_eq!( + check_addr(FAMILY_SERVER_INTERPRETED, &si("foo", b"bar"), r), + Err(BadValue::Length) + ); + assert_eq!( + check_addr(FAMILY_SERVER_INTERPRETED, b"localuserbob", r), + Err(BadValue::Length) + ); + assert_eq!( + check_addr( + FAMILY_SERVER_INTERPRETED, + &si("localuser", b"nosuchuser"), + r + ), + Err(BadValue::Length) + ); + assert_eq!( + check_addr(FAMILY_SERVER_INTERPRETED, &si("localgroup", b"staff"), r), + Ok(()) + ); + assert_eq!( + check_addr(FAMILY_SERVER_INTERPRETED, &si("localgroup", b"bob"), r), + Err(BadValue::Length) + ); + } + + #[test] + fn parse_cred_id_follows_strtol_base_0() { + let r = &FakeResolver; + let id = |v: &[u8]| parse_cred_id(v, CredKind::User, r); + assert_eq!(id(b"#1000"), Some(1000)); + assert_eq!(id(b"#0x3e8"), Some(1000)); + assert_eq!(id(b"#0X3E8"), Some(1000)); + assert_eq!(id(b"#01750"), Some(1000)); + assert_eq!(id(b"#1000x"), Some(1000)); + assert_eq!(id(b"# 1000"), Some(1000)); + assert_eq!(id(b"#+1000"), Some(1000)); + assert_eq!(id(b"#0"), Some(0)); + assert_eq!(id(b"#0x"), Some(0)); + assert_eq!(id(b"#"), None); + assert_eq!(id(b"#x"), None); + assert_eq!(id(b"#-"), None); + assert_eq!(id(b"#99999999999999999999"), None); + assert_eq!(id(b"#9223372036854775807"), Some(i64::MAX)); + assert_eq!(id(b"#9223372036854775808"), None); + assert_eq!(id(b"#-9223372036854775808"), Some(i64::MIN)); + assert_eq!(id(b"#4294967296"), Some(4_294_967_296)); + assert_eq!(id(b"#-1"), Some(-1)); + assert_eq!(id(b"#10\x0099"), Some(10)); + } + + #[test] + fn parse_cred_id_resolves_names_before_the_first_nul() { + let r = &FakeResolver; + assert_eq!(parse_cred_id(b"bob", CredKind::User, r), Some(1000)); + assert_eq!(parse_cred_id(b"alice", CredKind::User, r), None); + assert_eq!(parse_cred_id(b"bob\0junk", CredKind::User, r), Some(1000)); + assert_eq!(parse_cred_id(b"staff", CredKind::Group, r), Some(50)); + assert_eq!(parse_cred_id(b"bob", CredKind::Group, r), None); + assert_eq!(parse_cred_id(b"", CredKind::User, r), None); + } + + #[test] + fn oversized_and_negative_ids_validate_but_never_match() { + let r = &FakeResolver; + for kind in ["localuser", "localgroup"] { + for value in [&b"#4294967296"[..], b"#-1"] { + let addr = si(kind, value); + assert_eq!(check_addr(FAMILY_SERVER_INTERPRETED, &addr, r), Ok(())); + let e = entry(FAMILY_SERVER_INTERPRETED, &addr); + for id in [0, u32::MAX] { + assert!(!si_matches_local(&e, Some(&cred(id, id)), r)); + } + } + } + } + + #[test] + fn hostname_validator() { + assert!(hostname_is_valid(b"a.b-c")); + assert!(hostname_is_valid(b"a:b")); + assert!(hostname_is_valid(&[b'a'; 1024])); + assert!(!hostname_is_valid(b".a")); + assert!(!hostname_is_valid(b"-a")); + assert!(!hostname_is_valid(b"a..b")); + assert!(!hostname_is_valid(b"a_b")); + assert!(!hostname_is_valid(b"")); + assert!(!hostname_is_valid(&[b'a'; 1025])); + } + + #[test] + fn ipv6_validator() { + assert!(ipv6_is_valid(b"::1")); + assert!(ipv6_is_valid(b"::1\0zz")); + assert!(!ipv6_is_valid(b"::")); + assert!(!ipv6_is_valid(b"fe80::1%lo")); + assert!(!ipv6_is_valid(&[b'1'; 46])); + } + + #[test] + fn si_matches_local_compares_euid_and_primary_gid() { + let r = &FakeResolver; + let user = entry(FAMILY_SERVER_INTERPRETED, &si("localuser", b"#1000")); + let named = entry(FAMILY_SERVER_INTERPRETED, &si("localuser", b"bob")); + let group = entry(FAMILY_SERVER_INTERPRETED, &si("localgroup", b"staff")); + assert!(si_matches_local(&user, Some(&cred(1000, 1)), r)); + assert!(si_matches_local(&named, Some(&cred(1000, 1)), r)); + assert!(!si_matches_local(&user, Some(&cred(1001, 1)), r)); + assert!(si_matches_local(&group, Some(&cred(1, 50)), r)); + // A supplementary group is never seen: `PeerCred` carries none. + assert!(!si_matches_local(&group, Some(&cred(1, 10)), r)); + assert!(!si_matches_local(&user, None, r)); + assert!(!si_matches_local(&group, None, r)); + let host = entry(FAMILY_SERVER_INTERPRETED, &si("hostname", b"localhost")); + let v6 = entry(FAMILY_SERVER_INTERPRETED, &si("ipv6", b"::1")); + assert!(!si_matches_local(&host, Some(&cred(0, 0)), r)); + assert!(!si_matches_local(&v6, Some(&cred(0, 0)), r)); + } + + #[test] + fn encode_one_si_entry_matches_measured_xorg() { + let hosts = [entry(FAMILY_SERVER_INTERPRETED, b"localuser\0jos")]; + let (n, le) = encode_entries(&hosts, ClientByteOrder::LittleEndian); + assert_eq!(n, 1); + assert_eq!( + le, + [ + 0x05, 0x00, 0x0d, 0x00, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x75, 0x73, 0x65, 0x72, 0x00, + 0x6a, 0x6f, 0x73, 0x00, 0x00, 0x00 + ] + ); + assert_eq!(le.len() / 4, 5); + let (_, be) = encode_entries(&hosts, ClientByteOrder::BigEndian); + assert_eq!(&be[..4], [0x05, 0x00, 0x00, 0x0d]); + assert_eq!(be[4..], le[4..]); + } + + #[test] + fn encode_keeps_the_entry_that_reaches_one_mib() { + let hosts: Vec = (0..17u8) + .map(|i| entry(FAMILY_SERVER_INTERPRETED, &vec![i; 65532])) + .collect(); + let (n, bytes) = encode_entries(&hosts[..16], ClientByteOrder::LittleEndian); + assert_eq!((n, bytes.len()), (16, 1 << 20)); + let (n, bytes) = encode_entries(&hosts, ClientByteOrder::LittleEndian); + assert_eq!((n, bytes.len()), (16, 1 << 20)); + // Newest first: the 17th (oldest) entry is the one dropped. + assert_eq!(bytes[(1 << 20) - 1], 15); + } + + #[test] + fn encode_stops_at_65535_entries_so_the_count_fits_card16() { + // 65536 empty entries are 256 KiB, far below the byte cap. + let hosts = vec![entry(FAMILY_LOCAL_HOST, &[]); 65536]; + let (n, bytes) = encode_entries(&hosts, ClientByteOrder::LittleEndian); + assert_eq!((n, bytes.len()), (u16::MAX, 4 * 65535)); + let (n, bytes) = encode_entries(&hosts[..65535], ClientByteOrder::LittleEndian); + assert_eq!((n, bytes.len()), (u16::MAX, 4 * 65535)); + } +} diff --git a/crates/yserver-core/src/core_loop/input_inventory.rs b/crates/yserver-core/src/core_loop/input_inventory.rs index c949ec0f7..7010b2494 100644 --- a/crates/yserver-core/src/core_loop/input_inventory.rs +++ b/crates/yserver-core/src/core_loop/input_inventory.rs @@ -8,10 +8,7 @@ //! `docs/superpowers/specs/2026-09-09-server-reset-design.md`, //! "`InputInventory` — the seed source for input, and who owns it". //! -//! Populated purely from `Message::HostInput`'s `DeviceAdded`/ -//! `DeviceRemoved` (see `crates/yserver/src/input/context.rs:314,331` for -//! the event shapes). Nothing consumes it yet — this step is additive -//! only, and does not change any existing behaviour. +//! Populated from process-lifetime `Message::HostInput` lifecycle events. //! //! Deliberately atom-free: `DeviceInfo` carries device facts only — no //! interned property atoms, no XI device ids. That is what will let a @@ -22,41 +19,13 @@ use std::collections::HashMap; use super::message::DeviceInfo; - -/// Evdev device-node key (e.g. `/dev/input/event4`), as reported at -/// `DeviceAdded` time and used again verbatim at `DeviceRemoved`. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct DeviceNode(String); - -impl DeviceNode { - #[must_use] - pub fn new(device_node: impl Into) -> Self { - Self(device_node.into()) - } - - #[must_use] - pub fn as_str(&self) -> &str { - &self.0 - } -} - -impl From<&str> for DeviceNode { - fn from(value: &str) -> Self { - Self::new(value) - } -} - -impl From for DeviceNode { - fn from(value: String) -> Self { - Self::new(value) - } -} +use crate::xinput::{InputSourceId, libinput_props::DeviceConfigChange}; /// Process-lifetime input device inventory, owned beside the core loop /// (a local binding in `run_core`, never a field of `ServerState`). #[derive(Debug, Default)] pub struct InputInventory { - devices: HashMap, + devices: HashMap, } impl InputInventory { @@ -65,40 +34,62 @@ impl InputInventory { Self::default() } - /// Record (or re-record) a device. A duplicate `DeviceAdded` for a - /// node already present replaces the entry rather than duplicating - /// it — plain `HashMap::insert` semantics, called out because it is - /// this step's stated proof obligation. + /// Record or refresh the facts for one runtime source. pub fn add(&mut self, info: DeviceInfo) { - let node = DeviceNode::new(info.device_node.clone()); - self.devices.insert(node, info); + self.devices.insert(info.source_id, info); + } + + /// Mark a source disabled while preserving its facts for server reset. + pub fn suspend(&mut self, source_id: InputSourceId) { + if let Some(info) = self.devices.get_mut(&source_id) { + info.enabled = false; + } + } + + /// Mark every known source unavailable in the same core-loop dispatch as + /// VT release. The backend performs synchronous held-state cleanup before + /// the VT handoff; later per-device suspend messages remain idempotent. + pub fn suspend_all(&mut self) { + for info in self.devices.values_mut() { + info.enabled = false; + } } - /// Drop a device by node. No-op if the node isn't present. - pub fn remove(&mut self, device_node: &str) { - self.devices.remove(&DeviceNode::new(device_node)); + /// Refresh a continued source after libinput has restored its settings. + pub fn resume(&mut self, mut info: DeviceInfo) { + info.enabled = true; + self.add(info); + } + + /// Record a configuration value only after the source's live libinput + /// handle confirms it. Returns false when that source has already been + /// removed from the process-lifetime inventory. + pub fn update_config(&mut self, source: InputSourceId, change: DeviceConfigChange) -> bool { + let Some(info) = self.devices.get_mut(&source) else { + return false; + }; + info.config.apply_confirmed(change); + true + } + + /// Drop one source. No-op if it is already absent. + pub fn remove(&mut self, source_id: InputSourceId) { + self.devices.remove(&source_id); } #[must_use] - pub fn get(&self, device_node: &str) -> Option<&DeviceInfo> { - self.devices.get(&DeviceNode::new(device_node)) - } - - /// Every recorded device, ordered by device node. - /// - /// Sorted rather than in `HashMap` order because the consumer — - /// the server-reset boundary — replays these into - /// `ServerState::xi_seed_touchpad`, which writes a single - /// latest-wins slave-pointer slot. Iteration order therefore - /// decides which device wins, and a reset must not produce a - /// different XI model each time it runs. + pub fn get(&self, source_id: InputSourceId) -> Option<&DeviceInfo> { + self.devices.get(&source_id) + } + + /// Every recorded source, ordered by runtime identity. #[must_use] - pub fn devices_by_node(&self) -> Vec<&DeviceInfo> { - let mut nodes: Vec<&DeviceNode> = self.devices.keys().collect(); - nodes.sort_by(|a, b| a.as_str().cmp(b.as_str())); - nodes + pub fn devices_by_source(&self) -> Vec<&DeviceInfo> { + let mut sources: Vec = self.devices.keys().copied().collect(); + sources.sort_unstable_by_key(|source_id| source_id.0); + sources .into_iter() - .filter_map(|node| self.devices.get(node)) + .filter_map(|source_id| self.devices.get(&source_id)) .collect() } @@ -118,8 +109,16 @@ mod tests { use super::*; use crate::core_loop::message::LibinputConfigSnapshot; - fn device(node: &str, name: &str) -> DeviceInfo { + fn device(source: u64, node: &str, name: &str) -> DeviceInfo { DeviceInfo { + source_id: crate::xinput::InputSourceId(source), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, name: name.into(), device_node: node.into(), sysname: node.trim_start_matches("/dev/input/").into(), @@ -140,39 +139,54 @@ mod tests { #[test] fn add_then_remove_leaves_the_expected_set() { let mut inventory = InputInventory::new(); - inventory.add(device("/dev/input/event3", "Mouse")); - inventory.add(device("/dev/input/event4", "Touchpad")); + inventory.add(device(3, "/dev/input/event3", "Mouse")); + inventory.add(device(4, "/dev/input/event4", "Touchpad")); assert_eq!(inventory.len(), 2); - assert!(inventory.get("/dev/input/event3").is_some()); - assert!(inventory.get("/dev/input/event4").is_some()); + assert!(inventory.get(InputSourceId(3)).is_some()); + assert!(inventory.get(InputSourceId(4)).is_some()); - inventory.remove("/dev/input/event3"); + inventory.remove(InputSourceId(3)); assert_eq!(inventory.len(), 1); - assert!(inventory.get("/dev/input/event3").is_none()); - assert!(inventory.get("/dev/input/event4").is_some()); + assert!(inventory.get(InputSourceId(3)).is_none()); + assert!(inventory.get(InputSourceId(4)).is_some()); } #[test] fn removing_an_absent_node_is_a_no_op() { let mut inventory = InputInventory::new(); - inventory.add(device("/dev/input/event3", "Mouse")); - inventory.remove("/dev/input/event9"); + inventory.add(device(3, "/dev/input/event3", "Mouse")); + inventory.remove(InputSourceId(9)); assert_eq!(inventory.len(), 1); } #[test] - fn duplicate_device_added_for_one_node_replaces_rather_than_duplicates() { + fn suspend_all_marks_every_inventory_source_unavailable() { + let mut inventory = InputInventory::new(); + inventory.add(device(3, "/dev/input/event3", "Mouse")); + inventory.add(device(4, "/dev/input/event4", "Keyboard")); + + inventory.suspend_all(); + + assert_eq!(inventory.len(), 2); + assert_eq!(inventory.devices_by_source().len(), 2); + assert!( + inventory + .devices_by_source() + .iter() + .all(|info| !info.enabled) + ); + } + + #[test] + fn duplicate_device_added_for_one_source_replaces_rather_than_duplicates() { let mut inventory = InputInventory::new(); - inventory.add(device("/dev/input/event4", "Touchpad v1")); - inventory.add(device("/dev/input/event4", "Touchpad v2")); + inventory.add(device(4, "/dev/input/event4", "Touchpad v1")); + inventory.add(device(4, "/dev/input/event9", "Touchpad v2")); assert_eq!( inventory.len(), 1, - "a second DeviceAdded for the same node must replace, not duplicate" - ); - assert_eq!( - inventory.get("/dev/input/event4").unwrap().name, - "Touchpad v2" + "a second DeviceAdded for the same source must replace, not duplicate" ); + assert_eq!(inventory.get(InputSourceId(4)).unwrap().name, "Touchpad v2"); } } diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index b5d09f408..637ea4752 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -27,13 +27,297 @@ const XI2_MAJOR_OPCODE: u8 = 137; const XI2_KEYPRESS_EVTYPE: u16 = 2; const XI2_KEYRELEASE_EVTYPE: u16 = 3; const XI2_MASTER_KEYBOARD_DEVICE_ID: u16 = 3; -const XI2_SLAVE_KEYBOARD_DEVICE_ID: u16 = 5; const XI2_RAW_KEY_PRESS_EVTYPE: u16 = 13; const XI2_RAW_KEY_RELEASE_EVTYPE: u16 = 14; /// XISelectEvents wildcard deviceids. const XI2_ALL_DEVICES: u16 = 0; const XI2_ALL_MASTER_DEVICES: u16 = 1; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct KeyXiSource { + slave_deviceid: Option, + sourceid: u16, + attached_master: Option, +} + +/// Resolve the keyboard XI forms represented by an input origin. Unknown, +/// removed, suspended, disabled, and non-keyboard XTEST targets have no +/// source. A known physical source without an allocated keyboard facet and +/// nested host input use master identity 3 for both deviceid and sourceid. +fn resolve_key_xi_source( + state: &ServerState, + origin: crate::core_loop::InputOrigin, +) -> Option { + use crate::{core_loop::InputOrigin, xinput::XiFacetKind}; + match origin { + InputOrigin::Physical(source) => { + state + .xi_devices + .source(source) + .filter(|info| info.enabled)?; + if let Some(device_id) = state.xi_devices.facet(source, XiFacetKind::Keyboard) { + let device = state.xi_devices.device(device_id)?; + if !device.enabled + || device + .attached_master + .is_some_and(|master| master != XI2_MASTER_KEYBOARD_DEVICE_ID) + { + return None; + } + return Some(KeyXiSource { + slave_deviceid: Some(device_id), + sourceid: device_id, + attached_master: device.attached_master, + }); + } + Some(KeyXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_KEYBOARD_DEVICE_ID, + attached_master: Some(XI2_MASTER_KEYBOARD_DEVICE_ID), + }) + } + InputOrigin::XTest(device_id) => { + let device = state.xi_devices.device(device_id)?; + if !device.enabled { + return None; + } + match state.xi_devices.role(device_id)? { + crate::xinput::XiDeviceRole::MasterKeyboard => Some(KeyXiSource { + slave_deviceid: None, + sourceid: device_id, + attached_master: Some(device_id), + }), + crate::xinput::XiDeviceRole::SlaveKeyboard => Some(KeyXiSource { + slave_deviceid: Some(device_id), + sourceid: device_id, + attached_master: device.attached_master, + }), + crate::xinput::XiDeviceRole::MasterPointer + | crate::xinput::XiDeviceRole::SlavePointer => None, + } + } + InputOrigin::NestedHost => Some(KeyXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_KEYBOARD_DEVICE_ID, + attached_master: Some(XI2_MASTER_KEYBOARD_DEVICE_ID), + }), + } +} + +/// KMS checks physical identity before cooking keys or mutating backend +/// XKB/held state. The fanout repeats this validation for queued input. +pub fn keyboard_origin_is_live(state: &ServerState, origin: crate::core_loop::InputOrigin) -> bool { + resolve_key_xi_source(state, origin).is_some() +} + +/// The independently guarded state transition represented by one host key. +/// A slave may accept its transition while the attached master suppresses a +/// duplicate press or release. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct KeyTransition { + pub device_accepted: bool, + pub master_accepted: bool, +} + +/// Whether this origin currently holds `keycode` in its own XI keyboard view. +/// For unpublished physical sources the equivalent internal source map is +/// used; master-only origins use the core/master QueryKeymap bitmap. +pub fn keyboard_key_is_down( + state: &ServerState, + origin: crate::core_loop::InputOrigin, + keycode: u8, +) -> bool { + use crate::core_loop::InputOrigin; + let Some(source) = resolve_key_xi_source(state, origin) else { + return false; + }; + match origin { + InputOrigin::Physical(source_id) if source.slave_deviceid.is_none() => state + .unpublished_keyboard_keys_down + .get(&source_id) + .is_some_and(|keys| keys.contains_key(&keycode)), + InputOrigin::Physical(_) | InputOrigin::XTest(_) if source.slave_deviceid.is_some() => { + state + .key_down_by_device + .get(&source.slave_deviceid.unwrap_or_default()) + .is_some_and(|keys| keys.contains_key(&keycode)) + } + InputOrigin::XTest(_) | InputOrigin::NestedHost => master_key_is_down(state, keycode), + InputOrigin::Physical(_) => false, + } +} + +/// Check the generating keyboard guard independently from the attached +/// master's down guard. The master release deliberately accepts the first +/// valid release from any attached slave (Xi/exevents.c:922-943). +pub fn key_transition_status( + state: &ServerState, + origin: crate::core_loop::InputOrigin, + keycode: u8, + pressed: bool, +) -> Option { + use crate::core_loop::InputOrigin; + let source = resolve_key_xi_source(state, origin)?; + let device_was_down = match origin { + InputOrigin::Physical(source_id) if source.slave_deviceid.is_none() => state + .unpublished_keyboard_keys_down + .get(&source_id) + .is_some_and(|keys| keys.contains_key(&keycode)), + InputOrigin::Physical(_) | InputOrigin::XTest(_) if source.slave_deviceid.is_some() => { + state + .key_down_by_device + .get(&source.slave_deviceid.unwrap_or_default()) + .is_some_and(|keys| keys.contains_key(&keycode)) + } + InputOrigin::XTest(_) | InputOrigin::NestedHost => master_key_is_down(state, keycode), + InputOrigin::Physical(_) => false, + }; + let device_accepted = pressed != device_was_down; + let master_accepted = match origin { + InputOrigin::Physical(_) if source.attached_master.is_some() => { + if pressed { + !master_key_is_down(state, keycode) + } else { + master_key_is_down(state, keycode) + } + } + // Xorg's master-copy path returns no master event for a floating + // slave (mi/mieq.c:385-398); XTEST addressed to an attached slave + // follows its paired master as usual. + InputOrigin::XTest(_) + if source.slave_deviceid.is_some() && source.attached_master.is_some() => + { + if pressed { + !master_key_is_down(state, keycode) + } else { + master_key_is_down(state, keycode) + } + } + InputOrigin::XTest(_) | InputOrigin::NestedHost if source.attached_master.is_some() => { + // Master-targeted XTEST and nested input have a single guard. + device_accepted + } + _ => false, + }; + Some(KeyTransition { + device_accepted, + master_accepted, + }) +} + +/// Commit one accepted generating-device transition and, independently, an +/// accepted master transition. Call only after `key_transition_status` has +/// accepted the slave/device edge. +pub fn commit_key_transition( + state: &mut ServerState, + origin: crate::core_loop::InputOrigin, + keycode: u8, + pressed: bool, + transition: KeyTransition, +) { + use crate::core_loop::InputOrigin; + if !transition.device_accepted { + return; + } + let Some(source) = resolve_key_xi_source(state, origin) else { + return; + }; + match origin { + InputOrigin::Physical(source_id) if source.slave_deviceid.is_none() => { + let keys = state + .unpublished_keyboard_keys_down + .entry(source_id) + .or_default(); + if pressed { + keys.insert(keycode, origin); + } else { + keys.remove(&keycode); + if keys.is_empty() { + state.unpublished_keyboard_keys_down.remove(&source_id); + } + } + } + InputOrigin::Physical(_) | InputOrigin::XTest(_) if source.slave_deviceid.is_some() => { + let device_id = source.slave_deviceid.unwrap_or_default(); + let keys = state.key_down_by_device.entry(device_id).or_default(); + if pressed { + keys.insert(keycode, origin); + } else { + keys.remove(&keycode); + if keys.is_empty() { + state.key_down_by_device.remove(&device_id); + } + } + } + InputOrigin::XTest(_) | InputOrigin::NestedHost | InputOrigin::Physical(_) => {} + } + + if transition.master_accepted { + set_master_key_down(state, keycode, pressed); + } +} + +fn master_key_is_down(state: &ServerState, keycode: u8) -> bool { + let byte = usize::from(keycode / 8); + let bit = 1u8 << (keycode % 8); + state.keys_down[byte] & bit != 0 +} + +fn set_master_key_down(state: &mut ServerState, keycode: u8, pressed: bool) { + let byte = usize::from(keycode / 8); + let bit = 1u8 << (keycode % 8); + if pressed { + state.keys_down[byte] |= bit; + } else { + state.keys_down[byte] &= !bit; + } +} + +/// Resolve the device-indexed grab/freeze key for an input origin. +fn key_origin_device( + state: &ServerState, + origin: crate::core_loop::InputOrigin, +) -> (u16, Option) { + resolve_key_xi_source(state, origin).map_or((XI2_MASTER_KEYBOARD_DEVICE_ID, None), |source| { + ( + source.slave_deviceid.unwrap_or(source.sourceid), + source.attached_master, + ) + }) +} + +/// Whether `origin` names a keyboard facet that is currently floating under +/// an explicit XI2 grab. KMS uses this before touching master XKB state. +pub fn keyboard_origin_is_floating( + state: &ServerState, + origin: crate::core_loop::InputOrigin, +) -> bool { + let (device_id, master_id) = key_origin_device(state, origin); + matches!( + state.xi_devices.role(device_id), + Some(crate::xinput::XiDeviceRole::SlaveKeyboard) + ) && master_id.is_none() +} + +fn active_keyboard_grab_for_origin( + state: &ServerState, + device_id: u16, + master_id: Option, +) -> Option<(ActiveKeyboardGrab, bool)> { + state + .xi2_keyboard_grabs + .get(&device_id) + .copied() + .map(|grab| (grab, false)) + .or_else(|| { + (device_id == XI2_MASTER_KEYBOARD_DEVICE_ID + || master_id == Some(XI2_MASTER_KEYBOARD_DEVICE_ID)) + .then_some(state.active_keyboard_grab) + .flatten() + .map(|grab| (grab, true)) + }) +} + /// Fan a host key event out to nested clients. /// /// Returns the deduped list of clients whose outbound buffer overflowed @@ -44,27 +328,41 @@ pub fn key_event_fanout_to_state( backend: &mut dyn crate::backend::Backend, event: HostKeyEvent, ) -> Vec { - // QueryKeymap bitmap — device key state tracks the physical - // event regardless of where (or whether) it gets delivered. - // - // NOTE: we deliberately do NOT reconstruct modifier state here and - // stamp it onto the event. The backend already cooks the - // authoritative xkb modifier state into `event.state` - // (`cook_host_key` → `serialize_modifiers`, and XTest fakes are - // cooked the same way via `on_host_input`). A second server-side - // tracker (keys_down × modifier-map) is a redundant source of - // truth that drifts from xkb — `synthesize_held_releases` on a - // VT-switch clears keys_down without touching xkb — and any - // `state == 0` override then clobbers every unmodified keypress - // with the stale modifier ("stuck Ctrl, can't type in wezterm"). - { - let byte = usize::from(event.keycode / 8); - let bit = 1u8 << (event.keycode % 8); - if event.pressed { - state.keys_down[byte] |= bit; - } else { - state.keys_down[byte] &= !bit; - } + let Some(transition) = key_transition_status(state, event.origin, event.keycode, event.pressed) + else { + return Vec::new(); + }; + if !transition.device_accepted { + return Vec::new(); + } + commit_key_transition( + state, + event.origin, + event.keycode, + event.pressed, + transition, + ); + key_event_fanout_after_transition(state, backend, event, transition.master_accepted) +} + +/// Fan an already guarded host key transition out to clients. KMS calls this +/// after it has updated its XKB state only when the master transition was +/// accepted; queued replay paths retain the original transition decision. +pub fn key_event_fanout_after_transition( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + event: HostKeyEvent, + master_transition_accepted: bool, +) -> Vec { + let Some(xi_source) = resolve_key_xi_source(state, event.origin) else { + return Vec::new(); + }; + let device_id = xi_source.slave_deviceid.unwrap_or(xi_source.sourceid); + let master_id = xi_source.attached_master; + let mut switch_dropped = Vec::new(); + if let (Some(sourceid), Some(master_id)) = (xi_source.slave_deviceid, master_id) { + switch_dropped = + crate::xinput::hotplug::announce_xi2_slave_switch(state, master_id, sourceid); } // DPMS: any key resets the idle timer; from any non-On level // we wake the screen *before* fanning out, so the first event @@ -133,72 +431,118 @@ pub fn key_event_fanout_to_state( // regenerates both the core and the XI1 form — queueing the XI1 // form separately here would double-deliver it on thaw (XTS // XUngrabDevice-1: "expecting two events, got 4"). - if state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .is_some_and(crate::server::Xi1Freeze::frozen) - { + let frozen_device = [Some(device_id), master_id] + .into_iter() + .flatten() + .find(|id| { + state + .xi1_frozen + .get(id) + .is_some_and(crate::server::Xi1Freeze::frozen) + }); + if let Some(frozen_device) = frozen_device { state .sync_pending .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_KEYBOARD, - event: crate::server::QueuedInputEvent::HostKey(event), + device: frozen_device, + event: crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + ), }); return Vec::new(); } - let dropped = deliver_routed_key(state, event); - - // XkbStateNotify (GH #59): libxkbcommon-x11 clients (kitty/GLFW, all - // of Wayland's X11 path) keep their xkb_state synchronized ONLY from - // these events via `xkb_state_update_mask()` — NOT from the key - // events. So if the effective modifiers OR the group changed across - // this key event (cook_host_key already advanced the backend's - // xkb_state), fan out a full XkbStateNotify to StateNotify selectors. - // Without this a client that seeded a held modifier from XkbGetState - // (e.g. kitty launched from a `super + Return` chord, with Mod4 held - // at query time) never learns the modifier cleared on release, and - // every key resolves to NoSymbol. The `last_xkb_*` anchors dedup - // against the XkbLatchLockState handler so neither re-emits the other. - let g = backend.current_group(); - let (eff_mods, base_mods, latched_mods, locked_mods) = backend.current_xkb_mods(); - if eff_mods != state.last_xkb_mods || g != state.last_xkb_group { - let base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - let subs = crate::core_loop::xkb_layout::subscribers(state, 0x0004); - // changed: all modifier components + the compat/grab/lookup mirrors - // Xorg fills (0x1F0F); add the group bits on a group switch. - let mut changed: u16 = 0x1F0F; - if g != state.last_xkb_group { - changed |= 0x0090; // XkbGroupStateMask | XkbGroupLockMask - } - let notify = x11::XkbStateNotify { - device_id: 1, - mods: eff_mods, - base_mods, - latched_mods, - locked_mods, - group: g, - locked_group: g, - changed, + let mut dropped = switch_dropped; + merge_dropped( + &mut dropped, + deliver_routed_key_with_master_status(state, event, master_transition_accepted), + ); + + // Xorg `_XkbApplyState` after the key event: libxkbcommon-x11 clients + // track modifiers from XkbStateNotify alone (GH #59). + crate::core_loop::xkb_layout::announce_xkb_state( + state, + backend, + crate::core_loop::xkb_layout::XkbStateCause { keycode: event.keycode, event_type: if event.pressed { 2 } else { 3 }, - request_major: 0, - request_minor: 0, - }; - let _redundant = fanout_event_to_clients(state, &subs, |buf, seq, order| { - let _ = x11::write_xkb_state_notify(buf, order, seq, base, notify); - }); - state.last_xkb_group = g; - state.last_xkb_mods = eff_mods; - } + request: (0, 0), + }, + ); + backend.sync_floating_keyboard_states(state); dropped } +/// Publish a master source switch before KMS emits the raw-key form. Xorg +/// queues `UpdateFromMaster`'s DeviceChanged before the raw and device events. +pub fn announce_key_source_switch( + state: &mut ServerState, + origin: crate::core_loop::InputOrigin, +) -> Vec { + let Some(source) = resolve_key_xi_source(state, origin) else { + return Vec::new(); + }; + let (Some(sourceid), Some(master_id)) = (source.slave_deviceid, source.attached_master) else { + return Vec::new(); + }; + crate::xinput::hotplug::announce_xi2_slave_switch(state, master_id, sourceid) +} + /// The routing+delivery tail of [`key_event_fanout_to_state`] — /// callable without a backend so `xi1_compute_freezes` can replay /// withheld core keys on thaw. pub(crate) fn deliver_routed_key(state: &mut ServerState, event: HostKeyEvent) -> Vec { + deliver_routed_key_with_master_status(state, event, true) +} + +pub(crate) fn deliver_routed_key_after_transition( + state: &mut ServerState, + event: HostKeyEvent, + master_transition_accepted: bool, +) -> Vec { + deliver_routed_key_with_master_status(state, event, master_transition_accepted) +} + +fn deliver_routed_key_with_master_status( + state: &mut ServerState, + event: HostKeyEvent, + master_transition_accepted: bool, +) -> Vec { + if !keyboard_origin_is_live(state, event.origin) { + return Vec::new(); + } + let (device_id, master_id) = key_origin_device(state, event.origin); + if !master_transition_accepted + && master_id == Some(XI2_MASTER_KEYBOARD_DEVICE_ID) + && device_id != XI2_MASTER_KEYBOARD_DEVICE_ID + { + // The slave pass remains independently deliverable even when the + // master guard rejected its copy. An exact slave grab owns this form; + // otherwise route the slave selection on the natural focus path. + if let Some(grab) = state.xi2_keyboard_grabs.get(&device_id).copied() { + let mut dropped = deliver_key_to_grab_owner( + state, + &event, + grab.owner, + grab.grab_window, + grab.via_xi2, + device_id, + ); + merge_dropped(&mut dropped, deliver_xi1_focused_key(state, &event)); + return dropped; + } + let focus = current_focus(state); + let mut dropped = if focus == ResourceId(0) { + Vec::new() + } else { + let target = focused_walk_target(state, focus, &event); + deliver_key_to_window(state, &event, target, false, false) + }; + merge_dropped(&mut dropped, deliver_xi1_focused_key(state, &event)); + return dropped; + } match key_route(state, &event) { // Core delivery has nowhere to go (focus on root, no grab) — // but the XI1 fanout routes by the extension keyboard's own @@ -211,31 +555,42 @@ pub(crate) fn deliver_routed_key(state: &mut ServerState, event: HostKeyEvent) - grab_window, freeze, owner_events, + activating, via_xi2, + device_id: grab_device_id, } => { // Synchronous passive key grab: hold the activating press // so AllowEvents(ReplayKeyboard) can replay it to the // focus window if the grab owner declines it. Mirrors the // sync passive-button-grab freeze in `pointer_fanout`. if freeze && event.pressed { - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .or_default() - .stored = Some(crate::server::QueuedInputEvent::HostKey(event)); + state.xi1_frozen.entry(device_id).or_default().stored = + Some(crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + )); } // Xorg DeliverGrabbedEvent: with owner_events, key events // that would naturally land on one of the grab client's // windows are reported there instead of the grab window. - let natural = if owner_events { + // The activating press skips the walk: ActivatePassiveGrab + // sends it to the grab window (GH #277). + let natural = if owner_events && !activating { key_grabbed_natural_target(state, &event, owner) } else { None }; let mut dropped = if let Some(target) = natural { - deliver_key_to_grab_owner(state, &event, owner, target, via_xi2) + deliver_key_to_grab_owner(state, &event, owner, target, via_xi2, grab_device_id) } else { - deliver_key_to_grab_owner(state, &event, owner, grab_window, via_xi2) + deliver_key_to_grab_owner( + state, + &event, + owner, + grab_window, + via_xi2, + grab_device_id, + ) }; // XI1 leg runs under grabs too — the router handles its // own grab/freeze semantics, including the armed @@ -252,7 +607,13 @@ pub(crate) fn deliver_routed_key(state: &mut ServerState, event: HostKeyEvent) - // focus) where a client selected the event — Xorg // DeliverFocusedEvent's pointer-walk leg. let target = focused_walk_target(state, window, &event); - let mut dropped = deliver_key_to_window(state, &event, target); + let mut dropped = deliver_key_to_window( + state, + &event, + target, + master_transition_accepted, + master_transition_accepted, + ); merge_dropped(&mut dropped, deliver_xi1_focused_key(state, &event)); dropped } @@ -265,11 +626,28 @@ pub(crate) fn deliver_routed_key(state: &mut ServerState, event: HostKeyEvent) - /// after the grab owner declines the key. Mirrors Xorg /// `ComputeFreezes` → `DeliverFocusedEvent` (dix/events.c:1360). pub fn replay_frozen_key_to_focus(state: &mut ServerState, event: HostKeyEvent) -> Vec { + replay_frozen_key_to_focus_after_transition(state, event, true) +} + +pub(crate) fn replay_frozen_key_to_focus_after_transition( + state: &mut ServerState, + event: HostKeyEvent, + master_transition_accepted: bool, +) -> Vec { + if !keyboard_origin_is_live(state, event.origin) { + return Vec::new(); + } let focus = current_focus(state); if focus == ResourceId(0) { return Vec::new(); } - let mut dropped = deliver_key_to_window(state, &event, focus); + let mut dropped = deliver_key_to_window( + state, + &event, + focus, + master_transition_accepted, + master_transition_accepted, + ); merge_dropped(&mut dropped, deliver_xi1_focused_key(state, &event)); dropped } @@ -282,12 +660,15 @@ fn deliver_key_to_window( state: &mut ServerState, event: &HostKeyEvent, target_window: ResourceId, + include_master_form: bool, + include_core_form: bool, ) -> Vec { let mask_bit = if event.pressed { KEY_PRESS_MASK } else { KEY_RELEASE_MASK }; + let fields = key_window_fields(state, event, target_window); // Clients that selected XI2 for this key event on the window. Computed // first because XI2 *shadows* core per client: a client receiving the @@ -296,46 +677,53 @@ fn deliver_key_to_window( // core (XSelectInput KeyPressMask) and XI2 (XISelectEvents) — e.g. // Chromium's Ozone X11 layer — gets every keystroke twice. let xi2_evtype = xi2_evtype_for(event); - let xi2_targets: Vec = state - .clients - .iter() - .filter_map(|(id, client)| { - let mask = xi2_mask_for_client( - client, - target_window, - target_window, - &[ - XI2_SLAVE_KEYBOARD_DEVICE_ID, - XI2_MASTER_KEYBOARD_DEVICE_ID, - 1, - 0, - ], - ); - if mask & (1 << xi2_evtype) != 0 { - Some(ClientId(*id)) - } else { - None + let forms = key_xi2_forms(state, event.origin) + .into_iter() + .filter(|(device_id, _)| include_master_form || *device_id != XI2_MASTER_KEYBOARD_DEVICE_ID) + .collect::>(); + let mut xi2_targets = Vec::new(); + for (device_id, _) in &forms { + for (id, client) in &state.clients { + if key_xi2_form_selected(client, target_window, *device_id, xi2_evtype) + && !xi2_targets.contains(&ClientId(*id)) + { + xi2_targets.push(ClientId(*id)); } - }) - .collect(); + } + } // Core KeyPress/KeyRelease to KeyPressMask/KeyReleaseMask subscribers, // excluding any client already getting the XI2 form above. - let core_targets: Vec = subscribers_by_id(state, target_window, mask_bit) - .into_iter() - .filter(|c| !xi2_targets.contains(c)) - .collect(); + let core_targets: Vec = if include_core_form { + subscribers_by_id(state, target_window, mask_bit) + .into_iter() + .filter(|c| !xi2_targets.contains(c)) + .collect() + } else { + Vec::new() + }; let mut dropped = if core_targets.is_empty() { Vec::new() } else { fanout_event_to_clients(state, &core_targets, |buf, seq, order| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, target_window)); + x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); }) }; - if !xi2_targets.is_empty() { - let xi2_dropped = fanout_event_to_clients(state, &xi2_targets, |buf, seq, order| { - encode_key_xi2(buf, order, seq, event, target_window); + for (device_id, source_id) in forms { + let targets: Vec = state + .clients + .iter() + .filter_map(|(id, client)| { + key_xi2_form_selected(client, target_window, device_id, xi2_evtype) + .then_some(ClientId(*id)) + }) + .collect(); + if targets.is_empty() { + continue; + } + let xi2_dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { + encode_key_xi2_for_device(buf, order, seq, event, fields, device_id, source_id); }); merge_dropped(&mut dropped, xi2_dropped); } @@ -371,14 +759,18 @@ fn deliver_key_to_grab_owner( owner: ClientId, grab_window: ResourceId, via_xi2: bool, + device_id: u16, ) -> Vec { + let fields = key_window_fields(state, event, grab_window); if via_xi2 { + let source_id = + resolve_key_xi_source(state, event.origin).map_or(device_id, |source| source.sourceid); fanout_event_to_clients(state, &[owner], |buf, seq, order| { - encode_key_xi2(buf, order, seq, event, grab_window); + encode_key_xi2_for_device(buf, order, seq, event, fields, device_id, source_id); }) } else { fanout_event_to_clients(state, &[owner], |buf, seq, order| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, grab_window)); + x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); }) } } @@ -391,10 +783,84 @@ fn xi2_evtype_for(event: &HostKeyEvent) -> u16 { } } +/// Device event copies follow Xorg's slave-first mieq pass. A detached +/// keyboard has only its slave form; attached sources also get a master copy. +fn key_xi2_forms(state: &ServerState, origin: crate::core_loop::InputOrigin) -> Vec<(u16, u16)> { + let Some(source) = resolve_key_xi_source(state, origin) else { + return Vec::new(); + }; + let mut forms = Vec::with_capacity(2); + if let Some(slave_id) = source.slave_deviceid { + forms.push((slave_id, slave_id)); + } + if let Some(master_id) = source.attached_master { + forms.push((master_id, source.sourceid)); + } + forms +} + +fn key_xi2_form_selected( + client: &crate::server::ClientState, + window: ResourceId, + device_id: u16, + evtype: u16, +) -> bool { + let devices = if device_id == XI2_MASTER_KEYBOARD_DEVICE_ID { + [device_id, XI2_ALL_MASTER_DEVICES, XI2_ALL_DEVICES] + } else { + [device_id, XI2_ALL_DEVICES, u16::MAX] + }; + let device_count = if device_id == XI2_MASTER_KEYBOARD_DEVICE_ID { + 3 + } else { + 2 + }; + xi2_mask_for_client(client, window, window, &devices[..device_count]) & (1 << evtype) != 0 +} + +/// The window-dependent fields of a key event reported on one window — +/// Xorg `FixUpEventFromWindow` (dix/events.c). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct KeyWindowFields { + window: ResourceId, + event_x: i16, + event_y: i16, + child: ResourceId, +} + +/// Event coordinates are the root coordinates minus the window's inside +/// origin (`pWin->drawable.x/y`). `child` is Xorg `FindChildForEvent`: +/// the child of `window` on the path to the deepest window under the +/// pointer, `None` when that window is `window` itself or is not inside +/// it. During the focus walk that is the previous window on the path, +/// which is what `DeliverDeviceEvents` passes. +fn key_window_fields( + state: &ServerState, + event: &HostKeyEvent, + window: ResourceId, +) -> KeyWindowFields { + let (ox, oy) = state.resources.window_absolute_position(window); + let relative = |root: i16, origin: i32| { + i16::try_from( + i32::from(root) + .saturating_sub(origin) + .clamp(i32::from(i16::MIN), i32::from(i16::MAX)), + ) + .unwrap_or_default() + }; + let sprite = deepest_window_at_pointer(state); + KeyWindowFields { + window, + event_x: relative(event.root_x, ox), + event_y: relative(event.root_y, oy), + child: crate::core_loop::pointer_fanout::xi2_child_toward(state, window, sprite), + } +} + fn key_event_wire( event: &HostKeyEvent, sequence: x11::SequenceNumber, - target_window: ResourceId, + fields: KeyWindowFields, ) -> x11::KeyEvent { x11::KeyEvent { pressed: event.pressed, @@ -402,21 +868,24 @@ fn key_event_wire( sequence, time: event.time, root: ROOT_WINDOW, - event: target_window, + event: fields.window, + child: fields.child, root_x: event.root_x, root_y: event.root_y, - event_x: event.event_x, - event_y: event.event_y, + event_x: fields.event_x, + event_y: fields.event_y, state: event.state, } } -fn encode_key_xi2( +fn encode_key_xi2_for_device( buf: &mut Vec, order: x11::ClientByteOrder, seq: x11::SequenceNumber, event: &HostKeyEvent, - target_window: ResourceId, + fields: KeyWindowFields, + device_id: u16, + source_id: u16, ) { x11::encode_xi2_device_event( buf, @@ -424,18 +893,18 @@ fn encode_key_xi2( seq, XI2_MAJOR_OPCODE, xi2_evtype_for(event), - XI2_MASTER_KEYBOARD_DEVICE_ID, + device_id, event.time, ROOT_WINDOW, - target_window, - ResourceId(0), // child=None; key events target the window directly + fields.window, + fields.child, event.root_x, event.root_y, - event.event_x, - event.event_y, + fields.event_x, + fields.event_y, event.state, u32::from(event.keycode), - XI2_SLAVE_KEYBOARD_DEVICE_ID, + source_id, 0, // flags: no XIPointerEmulated on key events ); } @@ -445,6 +914,10 @@ fn encode_key_xi2( /// valuators, so the keycode, direction and timestamp are all of it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RawKeyEvent { + /// Keep the producer identity with a raw event while it is queued behind + /// a device freeze, even when the backend's current delivery pass is + /// master-only. + pub origin: crate::core_loop::InputOrigin, pub keycode: u8, pub pressed: bool, /// Shared with the device event generated from the same input @@ -477,21 +950,21 @@ impl RawKeyEvent { /// auto-repeat is off globally or for the key, or the key is a modifier. /// /// Delivery mirrors Xorg's two passes through `DeliverRawEvent` -/// (dix/events.c), slave first then master (mi/mieq.c): the slave form -/// (deviceid = sourceid = slave keyboard) goes to root selectors of the -/// slave keyboard / `XIAllDevices`; the master form (deviceid = master -/// keyboard) to root selectors of the master keyboard / `XIAllMasterDevices` -/// / `XIAllDevices`, subject to the keyboard grab. The master form is queued -/// behind a frozen keyboard like any other master event (Xorg -/// `EnqueueEvent`) and delivered on thaw; the slave is never frozen. -/// Keys arrive only on the master keyboard's attached slave, so an -/// `XIAllDevices` selector receives both forms. +/// (dix/events.c), slave first then master (mi/mieq.c). A slave form uses +/// that keyboard's ID for both deviceid and sourceid; its master copy uses +/// deviceid 3 and retains the generating sourceid. Master copies go to root +/// selectors of the master / `XIAllMasterDevices` / `XIAllDevices`, subject +/// to the keyboard grab. The master form queues behind a frozen keyboard and +/// revalidates the origin on thaw; floating keyboards produce no master form. pub fn raw_key_event_to_state( state: &mut ServerState, event: RawKeyEvent, key_was_down: bool, is_modifier: bool, ) -> Vec { + let Some(source) = resolve_key_xi_source(state, event.origin) else { + return Vec::new(); + }; if event.pressed && key_was_down && (is_modifier || !state.keyboard_control.key_auto_repeats(event.keycode)) @@ -503,21 +976,30 @@ pub fn raw_key_event_to_state( return Vec::new(); } let evtype = event.evtype(); - let slave_targets = raw_key_root_selectors( - state, - &[XI2_SLAVE_KEYBOARD_DEVICE_ID, XI2_ALL_DEVICES], - evtype, - ); - let mut dropped = send_raw_key(state, &slave_targets, event, XI2_SLAVE_KEYBOARD_DEVICE_ID); - if state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .is_some_and(crate::server::Xi1Freeze::frozen) - { + let mut dropped = Vec::new(); + if let Some(slave_id) = source.slave_deviceid { + let slave_targets = raw_key_root_selectors(state, &[slave_id, XI2_ALL_DEVICES], evtype); + dropped = send_raw_key(state, &slave_targets, event, slave_id, slave_id); + } + + let Some(master_id) = source.attached_master else { + return dropped; + }; + let freeze_device = source.slave_deviceid.unwrap_or(master_id); + let frozen_device = [Some(freeze_device), Some(master_id)] + .into_iter() + .flatten() + .find(|device_id| { + state + .xi1_frozen + .get(device_id) + .is_some_and(crate::server::Xi1Freeze::frozen) + }); + if let Some(device) = frozen_device { state .sync_pending .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_KEYBOARD, + device, event: crate::server::QueuedInputEvent::RawKey(event), }); } else { @@ -533,13 +1015,15 @@ pub fn raw_key_event_to_state( /// behind a frozen keyboard — the grab consulted is the one in effect when /// the event is finally processed, as on Xorg. pub(crate) fn deliver_raw_key_master(state: &mut ServerState, event: RawKeyEvent) -> Vec { + let Some(source) = resolve_key_xi_source(state, event.origin) else { + return Vec::new(); + }; + let Some(master_id) = source.attached_master else { + return Vec::new(); + }; let evtype = event.evtype(); let bit = 1u64 << evtype; - let master_devices = [ - XI2_MASTER_KEYBOARD_DEVICE_ID, - XI2_ALL_MASTER_DEVICES, - XI2_ALL_DEVICES, - ]; + let master_devices = [master_id, XI2_ALL_MASTER_DEVICES, XI2_ALL_DEVICES]; let grab = state.active_keyboard_grab; let mut dropped = Vec::new(); @@ -565,7 +1049,7 @@ pub(crate) fn deliver_raw_key_master(state: &mut ServerState, event: RawKeyEvent if natural || u64::from(g.xi2_mask) & bit != 0 { merge_dropped( &mut dropped, - send_raw_key(state, &[g.owner], event, XI2_MASTER_KEYBOARD_DEVICE_ID), + send_raw_key(state, &[g.owner], event, master_id, source.sourceid), ); } } @@ -588,7 +1072,7 @@ pub(crate) fn deliver_raw_key_master(state: &mut ServerState, event: RawKeyEvent .collect(); merge_dropped( &mut dropped, - send_raw_key(state, &targets, event, XI2_MASTER_KEYBOARD_DEVICE_ID), + send_raw_key(state, &targets, event, master_id, source.sourceid), ); dropped } @@ -606,14 +1090,15 @@ fn raw_key_root_selectors(state: &ServerState, devices: &[u16], evtype: u16) -> .collect() } -/// Write one raw key event with the given `deviceid` to each target. The -/// source is always the slave keyboard, and keys carry no valuators — the -/// valuator mask is two zero words (Xorg `eventToRawEvent`). +/// Write one raw key event with the given `deviceid` and `sourceid` to each +/// target. Keys carry no valuators; the valuator mask is two zero words +/// (Xorg `eventToRawEvent`). fn send_raw_key( state: &mut ServerState, targets: &[ClientId], event: RawKeyEvent, deviceid: u16, + sourceid: u16, ) -> Vec { if targets.is_empty() { return Vec::new(); @@ -628,7 +1113,7 @@ fn send_raw_key( deviceid, event.time, u32::from(event.keycode), - XI2_SLAVE_KEYBOARD_DEVICE_ID, + sourceid, 0, 0, ); @@ -660,7 +1145,12 @@ enum KeyRoute { /// X11 `owner_events` — when true, try natural delivery to /// the grab owner first (Xorg DeliverGrabbedEvent). owner_events: bool, + /// The press that just activated a passive grab. Xorg + /// `ActivatePassiveGrab` reports it on the grab window with no + /// `owner_events` walk; only later events take the walk. + activating: bool, via_xi2: bool, + device_id: u16, }, /// Normal delivery to a window's subscribers (focus window, or an /// explicit-grab window). @@ -670,8 +1160,10 @@ enum KeyRoute { /// Apply X11 keyboard routing rules. May activate a passive grab or /// auto-release one on the matching key release. fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { + let (device_id, master_id) = key_origin_device(state, event.origin); // Active grab in effect. - if let Some(g) = state.active_keyboard_grab { + if let Some((g, is_master_grab)) = active_keyboard_grab_for_origin(state, device_id, master_id) + { let passive = matches!(g.source, ActiveKeyboardGrabSource::PassiveKey { .. }); // Auto-release a passive-key grab on the matching key-release // (the release still goes to the grab owner below). @@ -679,18 +1171,18 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { && let ActiveKeyboardGrabSource::PassiveKey { keycode: kc } = g.source && kc == event.keycode { - state.active_keyboard_grab = None; - if let Some(freeze) = state - .xi1_frozen - .get_mut(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - { + if is_master_grab { + state.active_keyboard_grab = None; + } else { + state.xi2_keyboard_grabs.remove(&device_id); + state.reattach_xi2_slave(device_id); + } + if let Some(freeze) = state.xi1_frozen.get_mut(&device_id) { freeze.stored = None; } // Release the XI1-side holds the activation placed. crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( - state, - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - g.owner, + state, device_id, g.owner, ); // Xorg DeactivateKeyboardGrab: DoFocusEvents(grab_window // → focus, NotifyUngrab). @@ -707,7 +1199,13 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { grab_window: g.grab_window, freeze: false, owner_events: g.owner_events, + activating: false, via_xi2: g.via_xi2, + device_id: if is_master_grab { + XI2_MASTER_KEYBOARD_DEVICE_ID + } else { + device_id + }, }; } // Explicit grab (GrabKeyboard): key events go to the grabbing @@ -722,7 +1220,13 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { grab_window: g.grab_window, freeze: false, owner_events: g.owner_events, + activating: false, via_xi2: g.via_xi2, + device_id: if is_master_grab { + XI2_MASTER_KEYBOARD_DEVICE_ID + } else { + device_id + }, }; } @@ -738,7 +1242,13 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { }; if event.pressed && let Some(grab) = state - .find_key_grab(grab_walk_start, event.keycode, event.state) + .find_key_grab( + grab_walk_start, + event.keycode, + event.state, + device_id, + master_id, + ) .cloned() { let crate::server::KeyGrab { @@ -749,9 +1259,10 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { owner_events, via_xi2, xi2_mask, + device_id: grabbed_device_id, .. } = grab; - state.active_keyboard_grab = Some(ActiveKeyboardGrab { + let active = ActiveKeyboardGrab { owner, grab_window, source: ActiveKeyboardGrabSource::PassiveKey { @@ -760,7 +1271,15 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { owner_events, via_xi2, xi2_mask, - }); + }; + let device_grab = + grabbed_device_id != 0 && grabbed_device_id != XI2_MASTER_KEYBOARD_DEVICE_ID; + if device_grab { + state.xi2_keyboard_grabs.insert(grabbed_device_id, active); + let _ = state.detach_xi2_slave(grabbed_device_id); + } else { + state.active_keyboard_grab = Some(active); + } // Xorg ActivateKeyboardGrab: DoFocusEvents(focus → // grab_window, NotifyGrab). crate::core_loop::process_request::emit_core_focus_transition( @@ -777,7 +1296,11 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { // this way). crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( state, - crate::xinput::DEVICEID_SLAVE_KEYBOARD, + if device_grab { + grabbed_device_id + } else { + crate::xinput::DEVICEID_MASTER_KEYBOARD + }, owner, keyboard_mode == 0, pointer_mode == 0, @@ -788,7 +1311,13 @@ fn key_route(state: &mut ServerState, event: &HostKeyEvent) -> KeyRoute { // keyboard_mode 0 == Synchronous → freeze for replay. freeze: keyboard_mode == 0, owner_events, + activating: true, via_xi2, + device_id: if device_grab { + grabbed_device_id + } else { + XI2_MASTER_KEYBOARD_DEVICE_ID + }, }; } @@ -821,27 +1350,29 @@ pub(crate) fn current_focus(state: &ServerState) -> ResourceId { /// `DeliverFocusedEvent`); grab/freeze handling inside /// `xi1_route_device_event` is unaffected by the focus. fn deliver_xi1_focused_key(state: &mut ServerState, event: &HostKeyEvent) -> Vec { + let Some(device_id) = + resolve_key_xi_source(state, event.origin).and_then(|source| source.slave_deviceid) + else { + // Nested and unpublished origins have no XI1 slave form; in + // particular they must not be relabeled as virtual XTEST keyboard 5. + return Vec::new(); + }; let xi1_offset = if event.pressed { crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET } else { crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET }; let evcode = crate::server::XI_FIRST_EVENT + xi1_offset; - let (natural, focus_route) = crate::core_loop::xi1_focus::key_delivery_route( - state, - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - ); + let (natural, focus_route) = crate::core_loop::xi1_focus::key_delivery_route(state, device_id); crate::core_loop::pointer_fanout::xi1_route_device_event( state, crate::server::Xi1QueuedEvent { - deviceid: crate::xinput::DEVICEID_SLAVE_KEYBOARD, + deviceid: device_id, evcode, detail: event.keycode, time: event.time, root_x: event.root_x, root_y: event.root_y, - event_x: event.event_x, - event_y: event.event_y, state_mask: event.state, natural_target: natural, focus_route, @@ -856,12 +1387,18 @@ fn deliver_xi1_focused_key(state: &mut ServerState, event: &HostKeyEvent) -> Vec /// window P is the focus or a descendant of it, the event window is /// the first window from P upward (bounded at the focus, inclusive) /// where any client selected the event; otherwise the focus itself. +/// Under PointerRoot the walk is bounded at the root, not at P. fn focused_walk_target(state: &ServerState, focus: ResourceId, event: &HostKeyEvent) -> ResourceId { let mask_bit = if event.pressed { KEY_PRESS_MASK } else { KEY_RELEASE_MASK }; + let focus = if state.core_focus.raw == 1 { + ROOT_WINDOW + } else { + focus + }; let p = deepest_window_at_pointer(state); let mut chain = vec![p]; let mut cur = p; @@ -879,7 +1416,7 @@ fn focused_walk_target(state: &ServerState, focus: ResourceId, event: &HostKeyEv return focus; } for w in chain { - if !crate::core_loop::fanout::subscribers_by_id(state, w, mask_bit).is_empty() { + if !key_selectors(state, event, w, mask_bit).is_empty() { return w; } if w == focus { @@ -889,6 +1426,32 @@ fn focused_walk_target(state: &ServerState, focus: ResourceId, event: &HostKeyEv focus } +/// Clients that selected this key event on `window` in any form: the core +/// mask or the XI2 mask of one of the event's device forms. Xorg +/// `DeliverDeviceEvents` stops at the first window where +/// `EventIsDeliverable` finds any of them (dix/events.c), so a walk that +/// looks at the core masks alone runs past XI2-only selectors. +fn key_selectors( + state: &ServerState, + event: &HostKeyEvent, + window: ResourceId, + mask_bit: u32, +) -> Vec { + let mut clients = crate::core_loop::fanout::subscribers_by_id(state, window, mask_bit); + let evtype = xi2_evtype_for(event); + let forms = key_xi2_forms(state, event.origin); + for (id, client) in &state.clients { + if !clients.contains(&ClientId(*id)) + && forms + .iter() + .any(|(device_id, _)| key_xi2_form_selected(client, window, *device_id, evtype)) + { + clients.push(ClientId(*id)); + } + } + clients +} + /// Natural-delivery probe for an `owner_events` keyboard grab — the /// keyboard analogue of `pointer_fanout::grabbed_natural_target` /// (Xorg `DeliverDeviceEvents` with the grab as client filter): walk @@ -924,12 +1487,21 @@ fn key_grabbed_natural_target( cur = w.parent; } let start = if chain.contains(&focus) { p } else { focus }; + // DeliverDeviceEvents stops at the focus; PointerRoot walks to the root. + let stop = if state.core_focus.raw == 1 { + ROOT_WINDOW + } else { + focus + }; let mut cur = start; for _ in 0..256 { - let subs = crate::core_loop::fanout::subscribers_by_id(state, cur, mask_bit); + let subs = key_selectors(state, event, cur, mask_bit); if !subs.is_empty() { return subs.contains(&owner).then_some(cur); } + if cur == stop { + return None; + } let w = state.resources.window(cur)?; if w.parent == cur { return None; @@ -953,83 +1525,546 @@ pub(crate) fn deepest_window_at_pointer(state: &ServerState) -> ResourceId { Some(child) if child != window => window = child, _ => return window, } - } -} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::server::{ + ActiveKeyboardGrab, ActiveKeyboardGrabSource, KeyGrab, ScreenSaverActive, ServerState, + }; + use yserver_protocol::x11::ClientId; + + use crate::server::ClientState; + use std::{ + collections::{HashMap, HashSet, VecDeque}, + io::Read, + os::unix::net::UnixStream, + sync::{Arc, Mutex, atomic::AtomicU16}, + }; + use yserver_protocol::x11::ClientByteOrder; + + // Duplicated from process_request.rs::tests. If you change one, + // change both. A shared test_fixtures module is the right home + // long-term; tracked as a follow-up. + fn install_client(state: &mut ServerState, id: u32) -> UnixStream { + use crate::resources::ROOT_WINDOW; + let (a, b) = UnixStream::pair().unwrap(); + state.clients.insert( + id, + ClientState { + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), + byte_order: ClientByteOrder::LittleEndian, + last_sequence: Arc::new(AtomicU16::new(0)), + resource_id_base: 0, + resource_id_mask: u32::MAX, + event_masks: HashMap::new(), + save_set: HashSet::new(), + big_requests_enabled: false, + xi2_masks: HashMap::new(), + xi1_event_classes: HashSet::new(), + xi1_window_event_classes: HashMap::new(), + outbound: VecDeque::new(), + outbound_fds: Default::default(), + watching_writable: false, + write_failed: false, + gone: false, + focused_window: ROOT_WINDOW, + reader_control: None, + is_local: true, + fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), + }, + ); + b + } + + fn read_all_available(peer: &mut UnixStream) -> Vec { + peer.set_nonblocking(true).expect("set_nonblocking"); + let mut out = Vec::new(); + let mut buf = [0u8; 512]; + loop { + match peer.read(&mut buf) { + Ok(0) => break, + Ok(n) => out.extend_from_slice(&buf[..n]), + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => break, + Err(err) => panic!("read failed: {err}"), + } + } + peer.set_nonblocking(false).expect("unset_nonblocking"); + out + } + + fn key_event(pressed: bool, keycode: u8) -> HostKeyEvent { + HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed, + keycode, + time: 1, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + } + } + + mod key_source_routing { + use super::*; + use crate::{ + core_loop::{DeviceInfo, InputOrigin, message::LibinputConfigSnapshot}, + xinput::{InputCapabilities, InputSourceId, XiFacetKind}, + }; + + const KEY_PRESS: u32 = 1 << 2; + const KEY_RELEASE: u32 = 1 << 3; + const RAW_KEY_PRESS: u32 = 1 << 13; + const RAW_KEY_RELEASE: u32 = 1 << 14; + const ROUTED_MASK: u32 = KEY_PRESS | KEY_RELEASE | RAW_KEY_PRESS | RAW_KEY_RELEASE; + + pub(super) fn keyboard_info(source_id: InputSourceId) -> DeviceInfo { + DeviceInfo { + source_id, + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: true, + pointer: false, + touch: false, + }, + name: format!("keyboard {}", source_id.0), + device_node: format!("/dev/input/event{}", source_id.0), + sysname: format!("event{}", source_id.0), + vendor_id: 0, + product_id: 0, + is_touchpad: false, + config: LibinputConfigSnapshot::default(), + } + } + + fn capture_client(state: &mut ServerState, id: u32) -> crate::transport::CapturedPeer { + let (writer, peer) = crate::transport::Transport::capture_pair(); + state.clients.insert( + id, + ClientState { + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(writer)), + byte_order: ClientByteOrder::LittleEndian, + last_sequence: Arc::new(AtomicU16::new(0)), + resource_id_base: 0, + resource_id_mask: u32::MAX, + event_masks: HashMap::new(), + save_set: HashSet::new(), + big_requests_enabled: false, + xi2_masks: HashMap::new(), + xi1_event_classes: HashSet::new(), + xi1_window_event_classes: HashMap::new(), + outbound: VecDeque::new(), + outbound_fds: Default::default(), + watching_writable: false, + write_failed: false, + gone: false, + focused_window: ROOT_WINDOW, + reader_control: None, + is_local: true, + fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), + }, + ); + peer + } + + fn root_selector( + state: &mut ServerState, + id: u32, + device: u16, + ) -> crate::transport::CapturedPeer { + let peer = capture_client(state, id); + let client = state.clients.get_mut(&id).unwrap(); + client + .xi2_masks + .insert((ROOT_WINDOW, device), u64::from(ROUTED_MASK)); + state.xi2_client_versions.insert(ClientId(id), (2, 2)); + peer + } + + fn capture_read_all(peer: &mut crate::transport::CapturedPeer) -> Vec { + use std::io::Read; + let mut out = Vec::new(); + let mut buf = [0u8; 512]; + while let Ok(n) = peer.read(&mut buf) { + if n == 0 { + break; + } + out.extend_from_slice(&buf[..n]); + } + out + } + + fn xge_events(peer: &mut crate::transport::CapturedPeer) -> Vec<(u16, u16, u16, u32)> { + let bytes = capture_read_all(peer); + let read_u16 = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]); + let read_u32 = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); + let mut events = Vec::new(); + let mut at = 0; + while at + 32 <= bytes.len() { + if bytes[at] & 0x7f != 35 { + at += 32; + continue; + } + let evtype = read_u16(at + 8); + let source_offset = if (13..=17).contains(&evtype) { 20 } else { 52 }; + events.push(( + evtype, + read_u16(at + 10), + read_u16(at + source_offset), + read_u32(at + 16), + )); + at += 32 + 4 * read_u32(at + 4) as usize; + } + events + } + + fn raw_event(origin: InputOrigin, pressed: bool) -> RawKeyEvent { + RawKeyEvent { + origin, + keycode: 38, + pressed, + time: if pressed { 17 } else { 18 }, + } + } + + fn key_event_from(origin: InputOrigin, pressed: bool) -> HostKeyEvent { + HostKeyEvent { + origin, + pressed, + keycode: 38, + time: if pressed { 17 } else { 18 }, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + } + } + + #[test] + fn physical_keyboard_facets_keep_raw_and_device_source_ids() { + let mut state = ServerState::new(); + let source_a = InputSourceId(0xA11); + let source_b = InputSourceId(0xA12); + let a_id = state.xi_register_source(&keyboard_info(source_a))[0]; + let b_id = state.xi_register_source(&keyboard_info(source_b))[0]; + assert_eq!((a_id, b_id), (6, 7)); + + let mut a_peer = root_selector(&mut state, 1, a_id); + let mut b_peer = root_selector(&mut state, 2, b_id); + let mut master_peer = root_selector(&mut state, 3, 3); + let mut all_peer = root_selector(&mut state, 4, 0); + state.core_focus.raw = ROOT_WINDOW.0; + + let origin = InputOrigin::Physical(source_a); + let _ = raw_key_event_to_state(&mut state, raw_event(origin, true), false, false); + let mut backend = crate::backend::recording::RecordingBackend::default(); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(origin, true)); + + assert_eq!( + xge_events(&mut a_peer), + vec![(13, a_id, a_id, 38), (2, a_id, a_id, 38)], + "the source facet receives its slave raw and device forms" + ); + assert!( + xge_events(&mut b_peer).is_empty(), + "another keyboard is untouched" + ); + assert_eq!( + xge_events(&mut master_peer), + vec![(13, 3, a_id, 38), (2, 3, a_id, 38)], + "master copies name the generating keyboard facet" + ); + assert_eq!( + xge_events(&mut all_peer), + vec![ + (13, a_id, a_id, 38), + (13, 3, a_id, 38), + (2, a_id, a_id, 38), + (2, 3, a_id, 38), + ], + "XIAllDevices sees slave form before the master copy" + ); + + let _ = raw_key_event_to_state(&mut state, raw_event(origin, false), true, false); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(origin, false)); + assert_eq!( + xge_events(&mut a_peer), + vec![(14, a_id, a_id, 38), (3, a_id, a_id, 38)] + ); + assert_eq!( + xge_events(&mut b_peer), + Vec::<(u16, u16, u16, u32)>::new(), + "unrelated keyboard remains untouched" + ); + assert_eq!( + xge_events(&mut master_peer), + vec![(14, 3, a_id, 38), (3, 3, a_id, 38)] + ); + assert_eq!( + xge_events(&mut all_peer), + vec![ + (14, a_id, a_id, 38), + (14, 3, a_id, 38), + (3, a_id, a_id, 38), + (3, 3, a_id, 38), + ] + ); + assert!(state.keys_down.iter().all(|byte| *byte == 0)); + assert!(state.sync_pending.is_empty()); + assert_eq!( + state.xi_devices.facet(source_a, XiFacetKind::Keyboard), + Some(a_id) + ); + assert_eq!( + state.xi_devices.facet(source_b, XiFacetKind::Keyboard), + Some(b_id) + ); + } + + #[test] + fn virtual_nested_unpublished_and_removed_keyboard_sources_route_separately() { + let mut state = ServerState::new(); + // Exhaust physical XI IDs while retaining one known source with + // no published keyboard facet for master-only delivery. + for n in 1..=122 { + let _ = state.xi_register_source(&keyboard_info(InputSourceId(n))); + } + let unpublished = InputSourceId(123); + assert!( + state + .xi_register_source(&keyboard_info(unpublished)) + .is_empty() + ); + let removed_source = InputSourceId(124); + assert!( + state + .xi_register_source(&keyboard_info(removed_source)) + .is_empty() + ); + assert!(state.xi_unregister_source(removed_source).is_empty()); + + let mut all_peer = root_selector(&mut state, 1, 0); + state.core_focus.raw = ROOT_WINDOW.0; + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let xtest = InputOrigin::XTest(5); + let _ = raw_key_event_to_state(&mut state, raw_event(xtest, true), false, false); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(xtest, true)); + assert_eq!( + xge_events(&mut all_peer), + vec![(13, 5, 5, 38), (13, 3, 5, 38), (2, 5, 5, 38), (2, 3, 5, 38),], + "XTEST keeps its explicit virtual keyboard identity" + ); + let _ = raw_key_event_to_state(&mut state, raw_event(xtest, false), true, false); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(xtest, false)); + assert_eq!( + xge_events(&mut all_peer), + vec![(14, 5, 5, 38), (14, 3, 5, 38), (3, 5, 5, 38), (3, 3, 5, 38)] + ); + + let nested = InputOrigin::NestedHost; + let _ = raw_key_event_to_state(&mut state, raw_event(nested, true), false, false); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(nested, true)); + assert_eq!( + xge_events(&mut all_peer), + vec![(13, 3, 3, 38), (2, 3, 3, 38)], + "nested input is master-only and is not attributed to XTEST" + ); + let _ = raw_key_event_to_state(&mut state, raw_event(nested, false), true, false); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(nested, false)); + assert_eq!( + xge_events(&mut all_peer), + vec![(14, 3, 3, 38), (3, 3, 3, 38)] + ); + + let unpublished_origin = InputOrigin::Physical(unpublished); + let _ = raw_key_event_to_state( + &mut state, + raw_event(unpublished_origin, true), + false, + false, + ); + let _ = key_event_fanout_to_state( + &mut state, + &mut backend, + key_event_from(unpublished_origin, true), + ); + assert_eq!( + xge_events(&mut all_peer), + vec![(13, 3, 3, 38), (2, 3, 3, 38)], + "unpublished known sources retain only master forms" + ); + let _ = raw_key_event_to_state( + &mut state, + raw_event(unpublished_origin, false), + true, + false, + ); + let _ = key_event_fanout_to_state( + &mut state, + &mut backend, + key_event_from(unpublished_origin, false), + ); + assert_eq!( + xge_events(&mut all_peer), + vec![(14, 3, 3, 38), (3, 3, 3, 38)] + ); + assert!(state.xi_unregister_source(unpublished).is_empty()); + + let removed = InputOrigin::Physical(removed_source); + let _ = raw_key_event_to_state(&mut state, raw_event(removed, true), false, false); + let _ = + key_event_fanout_to_state(&mut state, &mut backend, key_event_from(removed, true)); + assert!( + xge_events(&mut all_peer).is_empty(), + "removed source events are dropped rather than relabeled" + ); + assert!(state.keys_down.iter().all(|byte| *byte == 0)); + assert!(state.sync_pending.is_empty()); + assert!(state.xi_devices.source(unpublished).is_none()); + assert!( + state + .xi_devices + .facet(unpublished, XiFacetKind::Keyboard) + .is_none() + ); + assert!(state.xi_devices.source(removed_source).is_none()); + assert_eq!(state.xi_devices.devices().len(), 126); + } -#[cfg(test)] -mod tests { - use super::*; - use crate::server::{ - ActiveKeyboardGrab, ActiveKeyboardGrabSource, KeyGrab, ScreenSaverActive, ServerState, - }; - use yserver_protocol::x11::ClientId; + #[test] + fn xi_slave_switch_keyboards_alternate_before_master_key_and_keep_same_source_quiet() { + const DEVICE_CHANGED: u64 = 1 << 1; + let mut state = ServerState::new(); + let razer = InputSourceId(0xA61); + let hyperx = InputSourceId(0xA62); + let razer_id = state.xi_register_source(&keyboard_info(razer))[0]; + let hyperx_id = state.xi_register_source(&keyboard_info(hyperx))[0]; + state.xi_devices.device_mut(razer_id).unwrap().name = "Razer keyboard".to_owned(); + state.xi_devices.device_mut(hyperx_id).unwrap().name = "HyperX keyboard".to_owned(); + assert_eq!((razer_id, hyperx_id), (6, 7)); + + let mut peer = root_selector(&mut state, 61, 3); + state + .clients + .get_mut(&61) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 3), u64::from(ROUTED_MASK) | DEVICE_CHANGED); + let mut backend = crate::backend::recording::RecordingBackend::new(); + + let parse = |bytes: &[u8]| { + let mut events = Vec::new(); + let mut offset = 0; + while offset + 32 <= bytes.len() { + let event_type = u16::from_le_bytes([bytes[offset + 8], bytes[offset + 9]]); + let device_id = u16::from_le_bytes([bytes[offset + 10], bytes[offset + 11]]); + let source_offset = if event_type == 1 { 18 } else { 52 }; + let source_id = u16::from_le_bytes([ + bytes[offset + source_offset], + bytes[offset + source_offset + 1], + ]); + if event_type == 1 { + let num_classes = + u16::from_le_bytes([bytes[offset + 16], bytes[offset + 17]]); + assert_eq!(num_classes, 1, "keyboard switch carries KeyClass"); + assert_eq!( + u16::from_le_bytes([bytes[offset + 32], bytes[offset + 33]]), + 0, + "class is KeyClass" + ); + assert_eq!( + u16::from_le_bytes([bytes[offset + 36], bytes[offset + 37]]), + source_id, + "KeyClass belongs to the new keyboard source" + ); + assert_eq!(bytes[offset + 20], 1, "XI2.h XISlaveSwitch"); + } + events.push((event_type, device_id, source_id)); + let units = + u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()); + offset += 32 + units as usize * 4; + } + assert_eq!(offset, bytes.len(), "complete XI2 event stream"); + events + }; - use crate::server::ClientState; - use std::{ - collections::{HashMap, HashSet, VecDeque}, - io::Read, - os::unix::net::UnixStream, - sync::{Arc, Mutex, atomic::AtomicU16}, - }; - use yserver_protocol::x11::ClientByteOrder; + let input = |source, keycode, pressed| { + let mut event = key_event_from(InputOrigin::Physical(source), pressed); + event.keycode = keycode; + event + }; + let send = |state: &mut ServerState, + backend: &mut crate::backend::recording::RecordingBackend, + peer: &mut crate::transport::CapturedPeer, + source, + keycode, + pressed| { + let _dropped = + key_event_fanout_to_state(state, backend, input(source, keycode, pressed)); + parse(&capture_read_all(peer)) + }; - // Duplicated from process_request.rs::tests. If you change one, - // change both. A shared test_fixtures module is the right home - // long-term; tracked as a follow-up. - fn install_client(state: &mut ServerState, id: u32) -> UnixStream { - use crate::resources::ROOT_WINDOW; - let (a, b) = UnixStream::pair().unwrap(); - state.clients.insert( - id, - ClientState { - writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), - byte_order: ClientByteOrder::LittleEndian, - last_sequence: Arc::new(AtomicU16::new(0)), - resource_id_base: 0, - resource_id_mask: u32::MAX, - event_masks: HashMap::new(), - save_set: HashSet::new(), - big_requests_enabled: false, - xi2_masks: HashMap::new(), - xi1_event_classes: HashSet::new(), - xi1_window_event_classes: HashMap::new(), - outbound: VecDeque::new(), - watching_writable: false, - focused_window: ROOT_WINDOW, - reader_control: None, - is_local: true, - fd_passing: true, - }, - ); - b - } + assert_eq!( + send(&mut state, &mut backend, &mut peer, razer, 38, true), + vec![(1, 3, razer_id), (2, 3, razer_id)] + ); + assert_eq!( + send(&mut state, &mut backend, &mut peer, razer, 39, true), + vec![(2, 3, razer_id)], + "continuing on the same keyboard emits no switch" + ); + assert_eq!( + send(&mut state, &mut backend, &mut peer, hyperx, 40, true), + vec![(1, 3, hyperx_id), (2, 3, hyperx_id)] + ); + assert_eq!( + send(&mut state, &mut backend, &mut peer, hyperx, 41, true), + vec![(2, 3, hyperx_id)], + "continuing on HyperX emits no switch" + ); - fn read_all_available(peer: &mut UnixStream) -> Vec { - peer.set_nonblocking(true).expect("set_nonblocking"); - let mut out = Vec::new(); - let mut buf = [0u8; 512]; - loop { - match peer.read(&mut buf) { - Ok(0) => break, - Ok(n) => out.extend_from_slice(&buf[..n]), - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => break, - Err(err) => panic!("read failed: {err}"), + for (source, keycode) in [(razer, 38), (razer, 39), (hyperx, 40), (hyperx, 41)] { + let _ = send(&mut state, &mut backend, &mut peer, source, keycode, false); } - } - peer.set_nonblocking(false).expect("unset_nonblocking"); - out - } - - fn key_event(pressed: bool, keycode: u8) -> HostKeyEvent { - HostKeyEvent { - pressed, - keycode, - time: 1, - root_x: 10, - root_y: 20, - event_x: 10, - event_y: 20, - state: 0, + assert_eq!(state.xi_last_slave(3), Some(hyperx_id)); + assert!(state.keys_down.iter().all(|byte| *byte == 0)); + assert!( + state + .key_down_by_device + .values() + .all(std::collections::HashMap::is_empty) + ); + assert!(state.sync_pending.is_empty()); + assert_eq!(state.xi_devices.devices().len(), 6); + assert!(state.xi_devices.device(razer_id).unwrap().enabled); + assert!(state.xi_devices.device(hyperx_id).unwrap().enabled); + assert_eq!( + state.xi_devices.source(razer).unwrap().name, + "keyboard 2657" + ); + assert_eq!( + state.xi_devices.source(hyperx).unwrap().name, + "keyboard 2658" + ); } } @@ -1045,6 +2080,7 @@ mod tests { ) -> UnixStream { let (server_side, peer) = UnixStream::pair().unwrap(); let client = ClientState { + admission: crate::access::Admission::Internal, writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(server_side))), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -1057,11 +2093,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), }; state.clients.insert(id, client); peer @@ -1078,6 +2119,29 @@ mod tests { /// selection, only the grab), and freezes the event for replay. /// This is the dead-`p`-in-wezterm fix: previously the press was /// delivered via window selection on the grab window, so a grab + /// Key family: a focus-window key subscriber over `OUTBOUND_CAP` is + /// flagged for the core loop to disconnect, and the reading subscriber + /// still gets the press. + #[test] + fn overflowing_key_subscriber_is_flagged_for_disconnect() { + const WIN: u32 = 0x0020_0001; + let mut state = ServerState::new(); + let _slow = install_kf(&mut state, 8, ResourceId(WIN), KEY_PRESS_MASK, 0); + let mut fast = install_kf(&mut state, 9, ResourceId(WIN), KEY_PRESS_MASK, 0); + let mut backend = crate::backend::recording::RecordingBackend::default(); + state.core_focus.raw = WIN; + crate::core_loop::client_io::saturate_for_test(state.clients.get_mut(&8).unwrap()); + let _ = key_event_fanout_to_state(&mut state, &mut backend, key_event(true, 38)); + assert_eq!( + crate::core_loop::client_io::failed_writers(&state.clients), + [ClientId(8)] + ); + fast.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 64]; + assert!(fast.read(&mut buf).unwrap_or(0) >= 32); + assert_eq!(buf[0] & 0x7f, 2, "KeyPress"); + } + /// Regression: an unmodified keypress (cooked `state == 0`) must /// be delivered with `state == 0` — the fanout must NOT OR in any /// server-tracked modifier state. Pre-fix, a stale modifier @@ -1123,6 +2187,7 @@ mod tests { let mut owner = install_kf(&mut state, 7, ROOT_WINDOW, 0, 0); let mut backend = crate::backend::recording::RecordingBackend::default(); state.key_grabs.push(KeyGrab { + device_id: 0, owner: ClientId(7), grab_window: ROOT_WINDOW, keycode: 33, @@ -1150,7 +2215,7 @@ mod tests { assert!( state .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) .and_then(|f| f.stored.as_ref()) .is_some(), "synchronous grab must freeze the press for replay" @@ -1189,6 +2254,7 @@ mod tests { let _owner = install_kf(&mut state, 7, ROOT_WINDOW, 0, 0); let mut backend = crate::backend::recording::RecordingBackend::default(); state.key_grabs.push(KeyGrab { + device_id: 0, owner: ClientId(7), grab_window: ROOT_WINDOW, keycode: 33, @@ -1204,7 +2270,7 @@ mod tests { assert!( state .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) + .get(&crate::xinput::DEVICEID_XTEST_KEYBOARD) .and_then(|f| f.stored.as_ref()) .is_none(), "async grab must not freeze" @@ -1236,7 +2302,7 @@ mod tests { ); assert_eq!(bytes[1], 2, "xkbType = XkbStateNotify"); assert_eq!(bytes[9], 0x40, "mods @9 = effective Mod4"); - assert_eq!(state.last_xkb_mods, 0x40); + assert_eq!(state.xkb_announced.1.0, 0x40); // Modifier released → effective mods 0. The CLEAR must be announced // (this is what unsticks a seeded modifier in kitty). @@ -1250,7 +2316,7 @@ mod tests { ); assert_eq!(bytes2[1], 2, "xkbType = XkbStateNotify"); assert_eq!(bytes2[9], 0x00, "mods @9 cleared to 0 on modifier release"); - assert_eq!(state.last_xkb_mods, 0); + assert_eq!(state.xkb_announced.1.0, 0); } #[test] @@ -1271,6 +2337,7 @@ mod tests { let grab_owner = ClientId(7); let mut backend = crate::backend::recording::RecordingBackend::default(); state.key_grabs.push(KeyGrab { + device_id: 0, owner: grab_owner, grab_window: ROOT_WINDOW, keycode: 38, @@ -1653,6 +2720,9 @@ mod tests { fn raw(keycode: u8, pressed: bool, time: u32) -> RawKeyEvent { RawKeyEvent { + // These Xvfb captures are driven through XTEST; keep the + // virtual keyboard's explicit source identity in the fixture. + origin: crate::core_loop::InputOrigin::XTest(5), keycode, pressed, time, @@ -1894,7 +2964,7 @@ mod tests { state.active_keyboard_grab = Some(keyboard_grab(1, ROOT_WINDOW, false, false, 0)); state .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) + .entry(crate::xinput::DEVICEID_XTEST_KEYBOARD) .or_default() .state = crate::server::Xi1SyncState::FrozenNoEvent; @@ -1918,7 +2988,7 @@ mod tests { &mut state, &mut backend, &HostXidMap::new(), - crate::xinput::DEVICEID_SLAVE_KEYBOARD, + crate::xinput::DEVICEID_XTEST_KEYBOARD, ); let master = vec![ @@ -1948,7 +3018,7 @@ mod tests { }); state .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) + .entry(crate::xinput::DEVICEID_XTEST_KEYBOARD) .or_default() .state = crate::server::Xi1SyncState::FrozenWithEvent; let _ = raw_key_event_to_state(&mut state, raw(38, false, 101), true, false); @@ -1959,7 +3029,7 @@ mod tests { &mut state, &mut backend, &HostXidMap::new(), - crate::xinput::DEVICEID_SLAVE_KEYBOARD, + crate::xinput::DEVICEID_XTEST_KEYBOARD, ); assert_eq!( @@ -1983,4 +3053,568 @@ mod tests { assert!(raw_events(&mut m22).is_empty()); } } + + /// Event-window fields of key events — Xorg `FixUpEventFromWindow`, + /// `DeliverFocusedEvent`, `DeliverDeviceEvents`, `FindChildForEvent` + /// (dix/events.c). Tree (root coordinates of each INSIDE origin = + /// parent inside origin + x + border_width): + /// + /// - `FRAME` child of root at (100, 50), border 2 → inside (102, 52) + /// - `XEV` child of `FRAME` at (5, 20), border 1 → inside (108, 73) + /// - `INNER` child of `XEV` at (10, 10), border 4 → inside (122, 87); + /// outer box in root coordinates x 118..176, y 83..141 + /// + /// The pointer at root (130, 100) is inside `INNER`, so the sprite + /// window is `INNER`. + mod event_window_fields { + use super::*; + use yserver_protocol::x11::CreateWindowRequest; + + const FRAME: ResourceId = ResourceId(0x0040_0001); + const XEV: ResourceId = ResourceId(0x0020_0001); + const INNER: ResourceId = ResourceId(0x0020_0002); + const IN_INNER: (i16, i16) = (130, 100); + /// Outside `FRAME` (outer x 100..404, y 50..354). + const OUTSIDE: (i16, i16) = (450, 380); + const XI2_KEY_PRESS_BIT: u64 = 1 << 2; + + pub(super) fn window( + state: &mut ServerState, + id: ResourceId, + parent: ResourceId, + geom: (i16, i16, u16, u16, u16), + ) { + let (x, y, width, height, border_width) = geom; + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: id, + parent, + x, + y, + width, + height, + border_width, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(id); + } + + fn tree(pointer: (i16, i16)) -> ServerState { + let mut state = ServerState::new(); + window(&mut state, FRAME, ROOT_WINDOW, (100, 50, 300, 300, 2)); + window(&mut state, XEV, FRAME, (5, 20, 250, 250, 1)); + window(&mut state, INNER, XEV, (10, 10, 50, 50, 4)); + state.pointer_root = pointer; + state + } + + fn press_at(pointer: (i16, i16)) -> HostKeyEvent { + HostKeyEvent { + root_x: pointer.0, + root_y: pointer.1, + // Producers fill these with garbage-in-practice; the + // fanout must not copy them. + event_x: pointer.0, + event_y: pointer.1, + ..key_event(true, 38) + } + } + + fn deliver(state: &mut ServerState, pointer: (i16, i16)) { + let mut backend = crate::backend::recording::RecordingBackend::default(); + let _ = key_event_fanout_to_state(state, &mut backend, press_at(pointer)); + } + + fn read_all(peer: &mut UnixStream) -> Vec { + read_all_available(peer) + } + + /// (event, child, root_x, root_y, event_x, event_y) of the one core + /// KeyPress the peer received. + fn core_fields(peer: &mut UnixStream) -> (u32, u32, i16, i16, i16, i16) { + let b = read_all(peer); + assert_eq!(b.len(), 32, "exactly one core event: {b:?}"); + assert_eq!(b[0], 2, "KeyPress"); + let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + let i16_at = |at: usize| i16::from_le_bytes([b[at], b[at + 1]]); + ( + u32_at(12), + u32_at(16), + i16_at(20), + i16_at(22), + i16_at(24), + i16_at(26), + ) + } + + /// Focus PointerRoot, sprite in the non-selecting `INNER`: the walk + /// propagates to `XEV` (`DeliverDeviceEvents` with no stopAt), and + /// the child is the previous window on the path. + /// event = (130 - 108, 100 - 73) = (22, 27), child = `INNER`. + #[test] + fn pointer_root_focus_propagates_to_selecting_ancestor() { + let mut state = tree(IN_INNER); + let mut xev = install_kf(&mut state, 9, XEV, KEY_PRESS_MASK, 0); + state.core_focus.raw = 1; + deliver(&mut state, IN_INNER); + assert_eq!(core_fields(&mut xev), (XEV.0, INNER.0, 130, 100, 22, 27)); + } + + /// Focus explicitly `XEV`, sprite in `INNER`: `XEV` is an ancestor of + /// the sprite, so the walk runs from `INNER` up to the focus. + /// event = (130 - 108, 100 - 73) = (22, 27), child = `INNER`. + #[test] + fn window_focus_propagates_from_sprite_in_child() { + let mut state = tree(IN_INNER); + let mut xev = install_kf(&mut state, 9, XEV, KEY_PRESS_MASK, 0); + state.core_focus.raw = XEV.0; + deliver(&mut state, IN_INNER); + assert_eq!(core_fields(&mut xev), (XEV.0, INNER.0, 130, 100, 22, 27)); + } + + /// The walk under PointerRoot reaches two levels up: only `FRAME` + /// selects. event = (130 - 102, 100 - 52) = (28, 48), child = `XEV`. + #[test] + fn pointer_root_focus_propagates_two_levels() { + let mut state = tree(IN_INNER); + let mut frame = install_kf(&mut state, 9, FRAME, KEY_PRESS_MASK, 0); + state.core_focus.raw = 1; + deliver(&mut state, IN_INNER); + assert_eq!(core_fields(&mut frame), (FRAME.0, XEV.0, 130, 100, 28, 48)); + } + + /// Sprite outside the focus subtree: delivered to the focus itself, + /// `FixUpEventFromWindow(focus, None)`. + /// event = (450 - 108, 380 - 73) = (342, 307), child = None. + #[test] + fn sprite_outside_focus_reports_relative_to_focus_without_child() { + let mut state = tree(OUTSIDE); + let mut xev = install_kf(&mut state, 9, XEV, KEY_PRESS_MASK, 0); + state.core_focus.raw = XEV.0; + deliver(&mut state, OUTSIDE); + assert_eq!(core_fields(&mut xev), (XEV.0, 0, 450, 380, 342, 307)); + } + + /// Sprite window is the event window: child None, coordinates + /// relative to `INNER`'s inside origin: (130 - 122, 100 - 87) = (8, 13). + #[test] + fn sprite_window_itself_has_no_child() { + let mut state = tree(IN_INNER); + let mut inner = install_kf(&mut state, 9, INNER, KEY_PRESS_MASK, 0); + state.core_focus.raw = 1; + deliver(&mut state, IN_INNER); + assert_eq!(core_fields(&mut inner), (INNER.0, 0, 130, 100, 8, 13)); + } + + fn explicit_grab( + state: &mut ServerState, + owner: u32, + window: ResourceId, + owner_events: bool, + ) { + state.active_keyboard_grab = Some(ActiveKeyboardGrab { + owner: ClientId(owner), + grab_window: window, + source: ActiveKeyboardGrabSource::Explicit, + owner_events, + via_xi2: false, + xi2_mask: 0, + }); + } + + /// Grabbed delivery: `FixUpEventFromWindow(grab->window, None, TRUE)` + /// → child = `FindChildForEvent`: from `INNER` up, the window whose + /// parent is `FRAME` is `XEV`. event = (28, 48). + #[test] + fn grab_reports_relative_to_grab_window_with_found_child() { + let mut state = tree(IN_INNER); + let mut owner = install_kf(&mut state, 7, ROOT_WINDOW, 0, 0); + state.core_focus.raw = XEV.0; + explicit_grab(&mut state, 7, FRAME, false); + deliver(&mut state, IN_INNER); + assert_eq!(core_fields(&mut owner), (FRAME.0, XEV.0, 130, 100, 28, 48)); + } + + /// Grab on the root: event = root coordinates, child = `FRAME`. + #[test] + fn root_grab_child_is_top_level_on_sprite_path() { + let mut state = tree(IN_INNER); + let mut owner = install_kf(&mut state, 7, ROOT_WINDOW, 0, 0); + state.core_focus.raw = XEV.0; + explicit_grab(&mut state, 7, ROOT_WINDOW, false); + deliver(&mut state, IN_INNER); + assert_eq!( + core_fields(&mut owner), + (ROOT_WINDOW.0, FRAME.0, 130, 100, 130, 100) + ); + } + + /// Grab window not on the sprite path: `FindChildForEvent` walks to + /// the root without meeting it → child None. + /// event = (450 - 102, 380 - 52) = (348, 328). + #[test] + fn grab_window_off_sprite_path_has_no_child() { + let mut state = tree(OUTSIDE); + let mut owner = install_kf(&mut state, 7, ROOT_WINDOW, 0, 0); + state.core_focus.raw = XEV.0; + explicit_grab(&mut state, 7, FRAME, false); + deliver(&mut state, OUTSIDE); + assert_eq!(core_fields(&mut owner), (FRAME.0, 0, 450, 380, 348, 328)); + } + + /// owner_events grab: `DeliverGrabbedEvent` runs + /// `DeliverDeviceEvents(sprite, stopAt = focus)`. Nobody selects on + /// `INNER` or the focus `XEV`, so the walk stops at `XEV` without + /// reaching the owner's selection on `FRAME`, and the event goes to + /// the grab window (root): event = (130, 100), child = `FRAME`. + #[test] + fn owner_events_grab_walk_stops_at_focus() { + let mut state = tree(IN_INNER); + let mut owner = install_kf(&mut state, 7, FRAME, KEY_PRESS_MASK, 0); + state.core_focus.raw = XEV.0; + explicit_grab(&mut state, 7, ROOT_WINDOW, true); + deliver(&mut state, IN_INNER); + assert_eq!( + core_fields(&mut owner), + (ROOT_WINDOW.0, FRAME.0, 130, 100, 130, 100) + ); + } + + /// owner_events grab whose owner selects on the focus: natural + /// delivery on `XEV` from the walk, child `INNER`, event (22, 27). + #[test] + fn owner_events_grab_natural_delivery_carries_walk_child() { + let mut state = tree(IN_INNER); + let mut owner = install_kf(&mut state, 7, XEV, KEY_PRESS_MASK, 0); + state.core_focus.raw = XEV.0; + explicit_grab(&mut state, 7, ROOT_WINDOW, true); + deliver(&mut state, IN_INNER); + assert_eq!(core_fields(&mut owner), (XEV.0, INNER.0, 130, 100, 22, 27)); + } + + /// XI2 `XI_KeyPress` on the focus `XEV`, sprite in `INNER`: + /// `FixUpXI2DeviceEventFromWindow` in FP16.16 — root (130, 100), + /// event (22, 27), child `INNER`. + #[test] + fn xi2_key_event_fields_are_window_relative() { + let mut state = tree(IN_INNER); + let mut xev = install_kf(&mut state, 9, XEV, KEY_PRESS_MASK, XI2_KEY_PRESS_BIT); + state.core_focus.raw = XEV.0; + deliver(&mut state, IN_INNER); + let b = read_all(&mut xev); + assert_eq!(b[0], 35, "GenericEvent (XI2 shadows core): {b:?}"); + let u16_at = |at: usize| u16::from_le_bytes([b[at], b[at + 1]]); + let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + let i32_at = |at: usize| i32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + assert_eq!(u16_at(8), XI2_KEYPRESS_EVTYPE); + assert_eq!( + (u32_at(20), u32_at(24), u32_at(28)), + (ROOT_WINDOW.0, XEV.0, INNER.0) + ); + assert_eq!( + (i32_at(32), i32_at(36), i32_at(40), i32_at(44)), + (130 << 16, 100 << 16, 22 << 16, 27 << 16) + ); + } + + /// XI1 `DeviceKeyPress` from a physical keyboard slave, device focus + /// PointerRoot (the default), selected on `XEV`: the XI1 walk from + /// the sprite reaches `XEV`; `FixUpEventFromWindow` fills the same + /// fields as the core form — child `INNER`, event (22, 27). + #[test] + fn xi1_device_key_event_fields_are_window_relative() { + use crate::{core_loop::InputOrigin, xinput::InputSourceId}; + let mut state = tree(IN_INNER); + let source = InputSourceId(0xA11); + let device = + state.xi_register_source(&super::key_source_routing::keyboard_info(source))[0]; + let evcode = crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; + let mut xev = install_kf(&mut state, 9, XEV, 0, 0); + state + .clients + .get_mut(&9) + .unwrap() + .xi1_window_event_classes + .insert( + XEV, + HashSet::from([(u32::from(device) << 8) | u32::from(evcode)]), + ); + state.core_focus.raw = 1; + let mut backend = crate::backend::recording::RecordingBackend::default(); + let event = HostKeyEvent { + origin: InputOrigin::Physical(source), + ..press_at(IN_INNER) + }; + let _ = key_event_fanout_to_state(&mut state, &mut backend, event); + let b = read_all(&mut xev); + let ev = b + .chunks(32) + .find(|e| e[0] == evcode) + .unwrap_or_else(|| panic!("no DeviceKeyPress in {b:?}")); + let u32_at = |at: usize| u32::from_le_bytes(ev[at..at + 4].try_into().unwrap()); + let i16_at = |at: usize| i16::from_le_bytes([ev[at], ev[at + 1]]); + assert_eq!( + ( + u32_at(12), + u32_at(16), + i16_at(20), + i16_at(22), + i16_at(24), + i16_at(26) + ), + (XEV.0, INNER.0, 130, 100, 22, 27) + ); + assert_eq!(ev[31], u8::try_from(device).unwrap()); + } + } + + /// GH #277: where a passive key grab's ACTIVATING event is reported. + /// Xorg `ActivatePassiveGrab` (dix/events.c) delivers it straight to + /// the grab owner with `FixUpEventFromWindow(grab->window, …)` — no + /// `owner_events` walk; only later events go through + /// `DeliverGrabbedEvent`'s walk. Expected values are the Xorg run of + /// `tools/vng-scenarios/key-grab-activation` (probe variants V1–V6). + /// + /// Tree: `T` (100,100 400x300) on the root, its child `B` (0,250 + /// 400x50), `W2` (600,100 100x100). The pointer at root (300,375) is + /// over `B`. Client 7 grabs Mod4+`KEY_2` on the root, owner_events=1. + mod passive_grab_activation { + use super::{event_window_fields::window, *}; + + const T: ResourceId = ResourceId(0x0020_0001); + const B: ResourceId = ResourceId(0x0020_0002); + const W2: ResourceId = ResourceId(0x0020_0003); + const OVER_B: (i16, i16) = (300, 375); + const MOD4: u16 = 0x40; + const KEY_2: u8 = 11; + const KEY_3: u8 = 12; + const OWNER: u32 = 7; + const OTHER: u32 = 8; + + /// Build the probe tree with the grab installed; `B` is selected by + /// `OTHER` when `other_owns_b`, else by the grab owner. + fn setup(focus: u32, other_owns_b: bool) -> (ServerState, UnixStream, UnixStream) { + let mut state = ServerState::new(); + window(&mut state, T, ROOT_WINDOW, (100, 100, 400, 300, 0)); + window(&mut state, B, T, (0, 250, 400, 50, 0)); + window(&mut state, W2, ROOT_WINDOW, (600, 100, 100, 100, 0)); + state.pointer_root = OVER_B; + let keys = KEY_PRESS_MASK | KEY_RELEASE_MASK; + let owner = install_kf(&mut state, OWNER, ROOT_WINDOW, keys, 0); + let other = install_kf(&mut state, OTHER, B, if other_owns_b { keys } else { 0 }, 0); + let masks = &mut state.clients.get_mut(&OWNER).unwrap().event_masks; + masks.insert(T, keys); + masks.insert(W2, keys); + if !other_owns_b { + masks.insert(B, keys); + } + state.core_focus.raw = focus; + state.key_grabs.push(KeyGrab { + device_id: 0, + owner: ClientId(OWNER), + grab_window: ROOT_WINDOW, + keycode: KEY_2, + modifiers: MOD4, + owner_events: true, + pointer_mode: 1, + keyboard_mode: 1, + via_xi2: false, + xi2_mask: 0, + }); + (state, owner, other) + } + + fn press(state: &mut ServerState, keycode: u8) { + let mut backend = crate::backend::recording::RecordingBackend::default(); + let event = HostKeyEvent { + root_x: OVER_B.0, + root_y: OVER_B.1, + state: MOD4, + ..key_event(true, keycode) + }; + let _ = key_event_fanout_to_state(state, &mut backend, event); + } + + /// (event, child, event_x, event_y) of every core KeyPress received. + fn presses(peer: &mut UnixStream) -> Vec<(u32, u32, i16, i16)> { + read_all_available(peer) + .chunks(32) + .filter(|e| e[0] & 0x7f == 2) + .map(|e| { + let u32_at = |at: usize| u32::from_le_bytes(e[at..at + 4].try_into().unwrap()); + let i16_at = |at: usize| i16::from_le_bytes([e[at], e[at + 1]]); + (u32_at(12), u32_at(16), i16_at(24), i16_at(26)) + }) + .collect() + } + + /// The activating press as Xorg reports it: event = root, + /// child = `T`, root coordinates. + const ACTIVATING: (u32, u32, i16, i16) = (ROOT_WINDOW.0, T.0, 300, 375); + + /// Run activate (`KEY_2`) then a second press (`KEY_3`) under the + /// active grab; return what the owner got for each. + fn run(state: &mut ServerState, owner: &mut UnixStream) -> Vec<(u32, u32, i16, i16)> { + press(state, KEY_2); + let mut got = presses(owner); + assert!( + state.active_keyboard_grab.is_some(), + "the press must activate the grab" + ); + press(state, KEY_3); + got.extend(presses(owner)); + got + } + + /// V1: PointerRoot. Activation on the grab window; the next press + /// takes the owner_events walk to `B`. + #[test] + fn v1_pointer_root_activation_reports_on_grab_window() { + let (mut state, mut owner, _) = setup(1, false); + assert_eq!(run(&mut state, &mut owner), [ACTIVATING, (B.0, 0, 200, 25)]); + } + + /// V3: focus `T`, same deliveries as V1. + #[test] + fn v3_focus_t_activation_reports_on_grab_window() { + let (mut state, mut owner, _) = setup(T.0, false); + assert_eq!(run(&mut state, &mut owner), [ACTIVATING, (B.0, 0, 200, 25)]); + } + + /// V4: focus `W2` (sprite outside it). Activation on the root; the + /// next press walks from the focus and lands on `W2`. + #[test] + fn v4_focus_w2_activation_reports_on_grab_window() { + let (mut state, mut owner, _) = setup(W2.0, false); + assert_eq!( + run(&mut state, &mut owner), + [ACTIVATING, (W2.0, 0, -300, 275)] + ); + } + + /// V6: `B` selected only by another client. The walk's first + /// selecting window is not the owner's, so the next press also + /// falls back to the grab window; the other client gets nothing. + #[test] + fn v6_other_client_on_b_gets_nothing() { + let (mut state, mut owner, mut other) = setup(1, true); + assert_eq!(run(&mut state, &mut owner), [ACTIVATING, ACTIVATING]); + assert_eq!(presses(&mut other), []); + } + + /// XI2 variants V7/V8: the owner selects `XI_KeyPress` / + /// `XI_KeyRelease` (XIAllMasterDevices) on root, `T`, `B` and `W2`, + /// no core masks, and holds an XI2 passive grab. Xorg + /// `DeliverDeviceEvents` stops at the first window where any form + /// is deliverable (`EventIsDeliverable` checks the XI2 masks), so + /// the XI2 selection on `B` counts for both the focus walk and the + /// owner_events walk. + fn setup_xi2(owner_events: bool) -> (ServerState, UnixStream) { + let mut state = ServerState::new(); + window(&mut state, T, ROOT_WINDOW, (100, 100, 400, 300, 0)); + window(&mut state, B, T, (0, 250, 400, 50, 0)); + window(&mut state, W2, ROOT_WINDOW, (600, 100, 100, 100, 0)); + state.pointer_root = OVER_B; + let xi2_keys = (1u64 << XI2_KEYPRESS_EVTYPE) | (1u64 << XI2_KEYRELEASE_EVTYPE); + let owner = install_kf(&mut state, OWNER, ROOT_WINDOW, 0, 0); + let masks = &mut state.clients.get_mut(&OWNER).unwrap().xi2_masks; + masks.clear(); + for w in [ROOT_WINDOW, T, B, W2] { + masks.insert((w, XI2_ALL_MASTER_DEVICES), xi2_keys); + } + state.core_focus.raw = 1; + state.key_grabs.push(KeyGrab { + device_id: XI2_MASTER_KEYBOARD_DEVICE_ID, + owner: ClientId(OWNER), + grab_window: ROOT_WINDOW, + keycode: KEY_2, + modifiers: MOD4, + owner_events, + pointer_mode: 1, + keyboard_mode: 1, + via_xi2: true, + xi2_mask: u32::try_from(xi2_keys).unwrap(), + }); + (state, owner) + } + + /// (evtype, event, child, event_x, event_y) of every XI2 key event. + fn xi2_keys(peer: &mut UnixStream) -> Vec<(u16, u32, u32, i32, i32)> { + let b = read_all_available(peer); + let mut out = Vec::new(); + let mut off = 0; + while off + 32 <= b.len() { + let e = &b[off..]; + let len = u32::from_le_bytes(e[4..8].try_into().unwrap()) as usize; + if e[0] == 35 { + let u32_at = |at: usize| u32::from_le_bytes(e[at..at + 4].try_into().unwrap()); + let i32_at = |at: usize| i32::from_le_bytes(e[at..at + 4].try_into().unwrap()); + out.push(( + u16::from_le_bytes([e[8], e[9]]), + u32_at(24), + u32_at(28), + i32_at(40) >> 16, + i32_at(44) >> 16, + )); + } + off += 32 + len * 4; + } + out + } + + fn press_plain(state: &mut ServerState, keycode: u8, mods: u16) { + let mut backend = crate::backend::recording::RecordingBackend::default(); + let event = HostKeyEvent { + root_x: OVER_B.0, + root_y: OVER_B.1, + state: mods, + ..key_event(true, keycode) + }; + let _ = key_event_fanout_to_state(state, &mut backend, event); + } + + const SUPER: u8 = 133; + const XI_PRESS: u16 = XI2_KEYPRESS_EVTYPE; + + /// V7 (owner_events=1): Super → `B`; activating `2` → root/`T`; + /// `3` under the grab → `B`. + #[test] + fn v7_xi2_owner_events_walk_uses_xi2_selections() { + let (mut state, mut owner) = setup_xi2(true); + press_plain(&mut state, SUPER, 0); + press_plain(&mut state, KEY_2, MOD4); + press_plain(&mut state, KEY_3, MOD4); + assert_eq!( + xi2_keys(&mut owner), + [ + (XI_PRESS, B.0, 0, 200, 25), + (XI_PRESS, ROOT_WINDOW.0, T.0, 300, 375), + (XI_PRESS, B.0, 0, 200, 25), + ] + ); + } + + /// V8 (owner_events=0): Super → `B`; activating `2` and `3` + /// under the grab → root/`T`. + #[test] + fn v8_xi2_no_owner_events_reports_on_grab_window() { + let (mut state, mut owner) = setup_xi2(false); + press_plain(&mut state, SUPER, 0); + press_plain(&mut state, KEY_2, MOD4); + press_plain(&mut state, KEY_3, MOD4); + assert_eq!( + xi2_keys(&mut owner), + [ + (XI_PRESS, B.0, 0, 200, 25), + (XI_PRESS, ROOT_WINDOW.0, T.0, 300, 375), + (XI_PRESS, ROOT_WINDOW.0, T.0, 300, 375), + ] + ); + } + } } diff --git a/crates/yserver-core/src/core_loop/message.rs b/crates/yserver-core/src/core_loop/message.rs index 75c581030..b5affacd2 100644 --- a/crates/yserver-core/src/core_loop/message.rs +++ b/crates/yserver-core/src/core_loop/message.rs @@ -2,18 +2,31 @@ //! //! See `docs/superpowers/plans/2026-05-06-single-threaded-core.md` Phase B. -use std::{os::fd::OwnedFd, time::Instant}; +use std::{path::PathBuf, time::Instant}; use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; -use crate::{core_loop::generation::Generation, host_x11::HostKeyEvent, transport::Transport}; +use crate::{ + core_loop::generation::Generation, fd::OwnedFd, host_x11::HostKeyEvent, transport::Transport, +}; /// Snapshot of a libinput device's identity and touchpad configuration at /// device-add time. Plain data — no libinput handles, safe to send across /// thread boundaries. Collected by the input layer and forwarded to the core -/// so that Task 2 can seed the XI2 device-property registry. +/// so the process-lifetime inventory and later XI generations can retain +/// source identity, endpoint proof, capabilities, and recognized settings. #[derive(Debug, Clone)] pub struct DeviceInfo { + /// Process-local identity for this physical source attachment. + pub source_id: crate::xinput::InputSourceId, + /// Whether libinput currently has an open handle for this source. + /// Suspended facts stay in the process inventory with this set false. + pub enabled: bool, + /// Canonical kernel input endpoint identity captured at first add. + /// Used only to prove a continuation during one explicit VT cycle. + pub resume_key: Option, + /// Input functions libinput reports for this source. + pub capabilities: crate::xinput::InputCapabilities, /// Human-readable name (e.g. `"SynPS/2 Synaptics TouchPad"`). pub name: String, /// Evdev device node (e.g. `/dev/input/event4`). @@ -25,10 +38,24 @@ pub struct DeviceInfo { /// True when libinput classifies the device as a touchpad /// (tap finger count > 0). pub is_touchpad: bool, - /// Full libinput config snapshot (meaningful only when is_touchpad). + /// Full recognized libinput configuration snapshot for this source. pub config: LibinputConfigSnapshot, } +/// Canonical `/sys/class/input/` target, including its kernel +/// `inputN/eventM` instance. This is continuation proof metadata, not a +/// normal device selector. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct EndpointInstanceKey(pub PathBuf); + +/// Identifies the producer of host input while it crosses the core channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum InputOrigin { + Physical(crate::xinput::InputSourceId), + XTest(u16), + NestedHost, +} + /// One libinput boolean config item: whether it's available on the device, /// its current value, and its default. `Copy`/`Send` — no libinput handles. #[derive(Debug, Clone, Copy, Default)] @@ -109,10 +136,61 @@ pub struct LibinputConfigSnapshot { pub click_method: OneHot2, /// Accel profiles: bit0=adaptive, bit1=flat (custom excluded — feature-gated). pub accel_profile: OneHot2, + /// Actual libinput acceleration profiles: bit0=adaptive, bit1=flat, + /// bit2=custom. This is kept separate from `accel_profile` so + /// availability is not inferred from the current/default profile slots. + pub accel_profile_available_mask: u8, /// Send-events: bitflags bit0=disabled, bit1=disabled-on-external-mouse. pub send_events: BitFlags2, } +impl LibinputConfigSnapshot { + /// Reflect a configuration change that the live libinput handle has + /// confirmed. Availability and default values come from the device + /// snapshot and are deliberately left untouched. + pub fn apply_confirmed(&mut self, change: crate::xinput::libinput_props::DeviceConfigChange) { + use crate::xinput::libinput_props::DeviceConfigChange as C; + + match change { + C::Tap(value) => self.tap.current = value, + C::TapDrag(value) => self.tap_drag.current = value, + C::TapDragLock(value) => self.tap_drag_lock.current = value, + C::TapButtonMap(value) => self.tap_button_map.current = Some(value), + C::NaturalScroll(value) => self.natural_scroll.current = value, + C::Dwt(value) => self.dwt.current = value, + C::LeftHanded(value) => self.left_handed.current = value, + C::MiddleEmulation(value) => self.middle_emulation.current = value, + C::ScrollMethod(value) => self.scroll_method.current = value, + C::ClickMethod(value) => self.click_method.current = value, + C::SendEvents(value) => self.send_events.current_mask = value, + C::AccelSpeed(value) => self.accel.current = value, + C::AccelProfile(value) => self.accel_profile.current = value.filter(|slot| *slot < 2), + C::ScrollButton(value) => self.scroll_button.current = value, + C::ScrollButtonLock(value) => self.scroll_button_lock.current = value, + } + } +} + +/// An owned recognized XI property write, suitable for validation after it +/// crosses from request parsing into the core configuration lane. +#[derive(Debug, Clone)] +pub struct XiConfigRequest { + pub client: ClientId, + pub sequence: SequenceNumber, + pub minor_opcode: u16, + pub deviceid: u16, + /// Source identity captured when the request was received. This prevents + /// an XI ID reused after unplug from redirecting a queued write. + pub expected_source: crate::xinput::InputSourceId, + pub property: yserver_protocol::x11::AtomId, + pub type_atom: yserver_protocol::x11::AtomId, + pub format: u8, + pub mode: u8, + /// Canonical little-endian property value bytes, with format-8 payloads + /// unchanged. + pub data: Vec, +} + /// All inbound messages multiplexed onto the core thread. /// /// Reader threads, the libinput thread, the signalfd watcher, and setup @@ -150,7 +228,21 @@ pub enum Message { byte_order: ClientByteOrder, is_local: bool, fd_passing: bool, + /// Connected through [`Message::InternalClient`]. + internal: bool, + /// Read from the socket once, before the setup request. + peer: crate::peer::PeerIdentity, + /// How authorization admitted this client, without retaining its cookie. + admission: crate::access::Admission, + /// The setup reply bytes the client received, for RECORD's + /// ClientStarted. + setup_reply: Vec, }, + /// The server's own X client (a window shell's clipboard bridge): the + /// core runs the setup on `stream` as for an accepted connection, with + /// no authorization, and marks the client internal. A Unix socket pair + /// where there is one, else a loopback TCP pair (Windows). + InternalClient(Transport), /// One framed X11 request from a client reader thread. Request { id: ClientId, @@ -178,6 +270,18 @@ pub enum Message { /// the core drains opaque tokens through `Backend` and finishes them on /// its own thread. CrtcConfigReady, + /// The input thread finished applying one source-targeted libinput + /// configuration request. Process-lifetime so reset cannot strand the + /// runner's submitted configuration lane. + DeviceConfigResult { + token: crate::xinput::libinput_props::DeviceConfigToken, + source: crate::xinput::InputSourceId, + result: Result<(), crate::xinput::libinput_props::DeviceConfigError>, + }, + /// The input thread has processed every config command ahead of its VT + /// pause command and completed the suspend dispatch. Results for those + /// commands were sent before this process-lifetime barrier. + InputPaused, /// signalfd readable. Shutdown, /// SIGHUP under a policy other than `-noreset` → cross the @@ -221,11 +325,18 @@ pub enum Message { /// dumps the three are indistinguishable from the scanout alone. /// Diagnostic-only; no-op for backends that don't redirect. DumpDrawables, + /// The backend's platform has work for the core thread (a frame + /// retired, a window closed). No payload: the platform keeps its own + /// queue, drained in `Backend::on_platform_event`. + PlatformEvent, + /// A rootless host's WM-side request (spec §4.4). + Rootless(crate::rootless::HostRequest), } #[derive(Debug)] pub enum HostInputEvent { PointerMotion { + origin: InputOrigin, x: i32, y: i32, time: u32, @@ -238,8 +349,12 @@ pub enum HostInputEvent { /// motions SUM these. (#96 follow-up: chromium-bsu) dx: i32, dy: i32, + /// Accelerated fractional libinput delta for physical relative + /// input. Absolute, nested, and XTEST motion leave this absent. + motion_delta: Option<[f64; 2]>, }, PointerButton { + origin: InputOrigin, /// Linux input button code (`BTN_LEFT = 0x110`, `BTN_RIGHT = 0x111`, /// `BTN_MIDDLE = 0x112`, etc.). u16 because libinput codes are /// always < 0x200 and u8 would silently truncate `BTN_LEFT` to @@ -260,7 +375,7 @@ pub enum HostInputEvent { /// delta-0 XI2 scroll motion so GDK sets `scroll.is_stop`, which /// commits a Firefox history-swipe (bug 1539730). XI2 smooth-scroll /// selectors only — no core event, no button. - PointerScrollStop { time: u32 }, + PointerScrollStop { origin: InputOrigin, time: u32 }, /// Key input from a device: libinput, or an XTEST fake (XTEST keys /// come from a device of their own on Xorg). Generates the XI2 raw /// key event (Xorg `GetKeyboardEvents`). @@ -272,13 +387,23 @@ pub enum HostInputEvent { /// passes through `GetKeyboardEvents`, so a repeat generates no XI2 raw /// key event. KeyRepeat(HostKeyEvent), - /// A new input device has been enumerated by libinput. Carries a - /// snapshot of its identity and touchpad configuration so the core can - /// seed per-device state (Task 2: XI2 property registry). + /// A new input device has been enumerated by libinput. Carries a snapshot + /// of its physical source identity, capabilities, and configuration. DeviceAdded(DeviceInfo), - /// An input device has been removed. `device_node` is the evdev path - /// that was reported at add time and can be used to look up the device. - DeviceRemoved { device_node: String }, + /// A physical source was suspended for VT release. Its identity and + /// properties remain live while its facets become disabled. + DeviceSuspended { + source_id: crate::xinput::InputSourceId, + }, + /// A suspended physical source continued on the same kernel endpoint. + DeviceResumed(DeviceInfo), + /// An input device has been removed by runtime source identity. + DeviceRemoved { + source_id: crate::xinput::InputSourceId, + }, + /// Rootless host pointer input in top-level-local coordinates; the + /// core converts it to root space before any backend sees it. + Rootless(crate::rootless::RootlessInput), } /// Synthetic Linux-style input codes for scroll-wheel "buttons" carried @@ -300,6 +425,10 @@ pub struct SetupAllocateResponse { pub resource_id_mask: u32, pub screen_width_px: u16, pub screen_height_px: u16, + /// Physical size as RANDR last set it (`RRSetScreenSize` mm, e.g. + /// `xrandr --dpi`); Xft derives DPI from these. + pub screen_width_mm: u16, + pub screen_height_mm: u16, pub current_input_masks: u32, } @@ -339,6 +468,14 @@ mod tests { #[test] fn device_info_is_clone_and_debug() { let info = DeviceInfo { + source_id: crate::xinput::InputSourceId(u64::from(line!())), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, name: "Test Touchpad".into(), device_node: "/dev/input/event4".into(), sysname: "event4".into(), @@ -368,6 +505,14 @@ mod tests { #[test] fn host_input_event_device_variants() { let info = DeviceInfo { + source_id: crate::xinput::InputSourceId(u64::from(line!())), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, name: "Mouse".into(), device_node: "/dev/input/event1".into(), sysname: "event1".into(), @@ -381,11 +526,11 @@ mod tests { HostInputEvent::DeviceAdded(_) )); let removed = HostInputEvent::DeviceRemoved { - device_node: "/dev/input/event1".into(), + source_id: crate::xinput::InputSourceId(1), }; match removed { - HostInputEvent::DeviceRemoved { device_node } => { - assert_eq!(device_node, "/dev/input/event1"); + HostInputEvent::DeviceRemoved { source_id } => { + assert_eq!(source_id, crate::xinput::InputSourceId(1)); } other => panic!("expected DeviceRemoved, got {other:?}"), } diff --git a/crates/yserver-core/src/core_loop/mod.rs b/crates/yserver-core/src/core_loop/mod.rs index f5f52536f..abee23705 100644 --- a/crates/yserver-core/src/core_loop/mod.rs +++ b/crates/yserver-core/src/core_loop/mod.rs @@ -9,10 +9,12 @@ pub mod auth; pub mod barriers; pub mod client_io; pub mod client_reader; +pub mod clip_list; pub mod composite_overlay; pub mod damage_fanout; pub mod fanout; pub mod generation; +pub mod host_access; pub mod input_inventory; pub mod key_fanout; pub mod message; @@ -20,6 +22,7 @@ pub mod pointer_fanout; pub mod poll_tokens; pub mod process_disconnect; pub mod process_request; +pub mod record; pub mod reset; pub mod run; pub mod sender; @@ -35,17 +38,18 @@ pub mod xdmcp; pub mod xdmcp; pub mod xi1_focus; pub mod xi1_state_notify; +pub mod xkb_controls; pub mod xkb_layout; pub mod xkb_select; pub use generation::{Generation, GenerationCounter}; -pub use input_inventory::{DeviceNode, InputInventory}; +pub use input_inventory::InputInventory; pub use message::{ - DeviceInfo, HostInputEvent, Message, SYNTH_SCROLL_DOWN, SYNTH_SCROLL_LEFT, SYNTH_SCROLL_RIGHT, - SYNTH_SCROLL_UP, SetupAllocateResponse, + DeviceInfo, EndpointInstanceKey, HostInputEvent, InputOrigin, Message, SYNTH_SCROLL_DOWN, + SYNTH_SCROLL_LEFT, SYNTH_SCROLL_RIGHT, SYNTH_SCROLL_UP, SetupAllocateResponse, }; pub use reset::ResetPolicy; -pub use run::{handle_host_input, run_core}; +pub use run::{handle_host_input, host_screen_resized, run_core}; pub use sender::{BoundSender, CoreReceiver, CoreSender, NOTIFY_TOKEN, channel}; pub use xdmcp::XdmcpService; #[cfg(feature = "xdmcp")] diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 6e42bc2af..fa087ba0c 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -14,6 +14,9 @@ //! demotes it to a plain field on `HostX11Backend` and at that point //! the helper takes `&HostXidMap`. +#[cfg(test)] +mod tests; + use yserver_protocol::x11::{self, ClientId, ResourceId, SequenceNumber}; use crate::{ @@ -27,7 +30,311 @@ use crate::{ const XI2_MAJOR_OPCODE: u8 = 137; const XI2_MASTER_POINTER_DEVICE_ID: u16 = 2; -const XI2_SLAVE_POINTER_DEVICE_ID: u16 = 4; +const XI2_XTEST_POINTER_DEVICE_ID: u16 = crate::xinput::DEVICEID_XTEST_POINTER; + +#[derive(Clone, Copy)] +struct PointerXiSource { + slave_deviceid: Option, + sourceid: u16, + attached_master: Option, +} + +#[derive(Clone, Copy)] +struct PointerButtonTransition { + source_accepted: bool, + master_accepted: bool, +} + +/// Whether a pointer origin can still produce input. KMS calls this before +/// integrating relative motion into its cursor; fanout repeats the check so +/// queued and replayed events cannot outlive their source. +pub fn pointer_origin_is_live(state: &ServerState, origin: crate::core_loop::InputOrigin) -> bool { + resolve_pointer_xi_source(state, origin, false).is_some() +} + +pub fn floating_pointer_device_id( + state: &ServerState, + origin: crate::core_loop::InputOrigin, +) -> Option { + let source = resolve_pointer_xi_source(state, origin, false)?; + source + .slave_deviceid + .filter(|_| source.attached_master.is_none()) +} + +fn resolve_pointer_xi_source( + state: &ServerState, + origin: crate::core_loop::InputOrigin, + tree_change: bool, +) -> Option { + use crate::{core_loop::InputOrigin, xinput::XiFacetKind}; + + let source = match origin { + InputOrigin::Physical(source_id) => { + let info = state.xi_devices.source(source_id)?; + if !info.enabled { + return None; + } + match state.xi_devices.facet(source_id, XiFacetKind::PointerTouch) { + Some(device_id) => { + let device = state.xi_devices.device(device_id)?; + if !device.enabled + || device + .attached_master + .is_some_and(|master| master != XI2_MASTER_POINTER_DEVICE_ID) + { + return None; + } + PointerXiSource { + slave_deviceid: Some(device_id), + sourceid: device_id, + attached_master: device.attached_master, + } + } + // Capacity exhaustion and keyboard-only sources still feed + // the core/master pointer stream without claiming XTEST 4. + None => PointerXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_POINTER_DEVICE_ID, + attached_master: Some(XI2_MASTER_POINTER_DEVICE_ID), + }, + } + } + InputOrigin::XTest(device_id) => { + let device = state.xi_devices.device(device_id)?; + if !device.enabled { + return None; + } + if device_id == XI2_MASTER_POINTER_DEVICE_ID { + PointerXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_POINTER_DEVICE_ID, + attached_master: Some(XI2_MASTER_POINTER_DEVICE_ID), + } + } else if (device_id == XI2_XTEST_POINTER_DEVICE_ID + || device.facet == Some(XiFacetKind::PointerTouch)) + && device + .attached_master + .is_none_or(|master| master == XI2_MASTER_POINTER_DEVICE_ID) + { + PointerXiSource { + slave_deviceid: Some(device_id), + sourceid: device_id, + attached_master: device.attached_master, + } + } else { + return None; + } + } + InputOrigin::NestedHost => PointerXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_POINTER_DEVICE_ID, + attached_master: Some(XI2_MASTER_POINTER_DEVICE_ID), + }, + }; + + Some(if tree_change { + // Xorg CheckMotion(NULL) is a master-generated event, even when the + // pointer happened to be over a physical slave before the tree edit. + PointerXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_POINTER_DEVICE_ID, + attached_master: Some(XI2_MASTER_POINTER_DEVICE_ID), + } + } else { + source + }) +} + +/// Apply Xorg's `UpdateFromMaster` bookkeeping for an accepted pointer +/// event: a source change announces `SlaveSwitch`, and the master inherits +/// the current source valuators. Scroll Motion and scroll-stop call this same +/// helper so both event paths leave the same master baseline. +fn update_from_pointer_master( + state: &mut ServerState, + source: PointerXiSource, + announce_switch: bool, + copy_valuators: bool, +) -> Vec { + let mut dropped = Vec::new(); + let (Some(source_id), Some(master_id)) = (source.slave_deviceid, source.attached_master) else { + return dropped; + }; + if announce_switch { + merge_dropped( + &mut dropped, + crate::xinput::hotplug::announce_xi2_slave_switch(state, master_id, source_id), + ); + } + if copy_valuators + && master_id == XI2_MASTER_POINTER_DEVICE_ID + && let Some(device) = state.xi_devices.device(source_id) + { + state.scroll_axis_value = device.scroll_axis_values; + } + dropped +} + +/// Whether a wheel button's direction has a ScrollClass on its generating +/// slave. Xorg maps buttons 4/5 to the vertical axis and 6/7 to the horizontal +/// axis (`dix/getevents.c:1661-1677`), then emulates only when that axis is +/// present (`:1652-1657,1684-1692`). XTEST is initialized by `CorePointerProc` +/// with two relative axes and no ScrollClass (`dix/devices.c:660-690`). +/// Physical libinput pointers install horizontal and vertical ScrollClasses +/// (`xf86-input-libinput/src/xf86libinput.c:1109-1117`). For a master copy, +/// `slave_deviceid` remains the generating slave, so its class shape controls +/// the conversion. +fn pointer_source_has_scroll_class( + state: &ServerState, + source: PointerXiSource, + button: u8, +) -> bool { + let axis = match button { + 4 | 5 => 2, + 6 | 7 => 3, + _ => return false, + }; + let Some(device_id) = source.slave_deviceid else { + return false; + }; + state.xi_devices.device(device_id).is_some_and(|device| { + matches!( + (device.class_shape, axis), + (crate::xinput::XiClassShape::PhysicalPointer, 2 | 3) + ) + }) +} + +fn pointer_button_transition( + state: &mut ServerState, + origin: crate::core_loop::InputOrigin, + xi_source: PointerXiSource, + button: u8, + pressed: bool, +) -> PointerButtonTransition { + if !(1..=16).contains(&button) { + return PointerButtonTransition { + source_accepted: true, + master_accepted: true, + }; + } + + let bit = 1u16 << (button - 1); + let unpublished_source = match (origin, xi_source.slave_deviceid) { + (crate::core_loop::InputOrigin::Physical(source_id), None) => Some(source_id), + _ => None, + }; + let had_source_state = if let Some(device_id) = xi_source.slave_deviceid { + state + .xi_devices + .device(device_id) + .is_some_and(|device| device.buttons_down & bit != 0) + } else if let Some(source_id) = unpublished_source { + state + .unpublished_pointer_buttons_down + .get(&source_id) + .is_some_and(|buttons| buttons & bit != 0) + } else { + state.buttons_down & bit != 0 + }; + + if pressed == had_source_state { + return PointerButtonTransition { + source_accepted: false, + master_accepted: false, + }; + } + + if let Some(device_id) = xi_source.slave_deviceid { + if let Some(device) = state.xi_devices.device_mut(device_id) { + if pressed { + device.buttons_down |= bit; + } else { + device.buttons_down &= !bit; + } + } + } else if let Some(source_id) = unpublished_source { + let buttons = state + .unpublished_pointer_buttons_down + .entry(source_id) + .or_default(); + if pressed { + *buttons |= bit; + } else { + *buttons &= !bit; + if *buttons == 0 { + state.unpublished_pointer_buttons_down.remove(&source_id); + } + } + } + + let attached_to_master = xi_source.slave_deviceid.is_none_or(|device_id| { + state + .xi_devices + .device(device_id) + .is_some_and(|device| device.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) + }); + if !attached_to_master { + return PointerButtonTransition { + source_accepted: true, + master_accepted: false, + }; + } + + if pressed { + if state.buttons_down & bit != 0 { + return PointerButtonTransition { + source_accepted: true, + master_accepted: false, + }; + } + state.buttons_down |= bit; + return PointerButtonTransition { + source_accepted: true, + master_accepted: true, + }; + } + + // Xorg's master button release is aggregated: a slave release reaches + // that slave, but cannot release the master while any attached slave + // still holds the mapped button. + if attached_pointer_holds_button(state, bit) { + PointerButtonTransition { + source_accepted: true, + master_accepted: false, + } + } else if state.buttons_down & bit != 0 { + state.buttons_down &= !bit; + PointerButtonTransition { + source_accepted: true, + master_accepted: true, + } + } else { + PointerButtonTransition { + source_accepted: true, + master_accepted: false, + } + } +} + +fn attached_pointer_holds_button(state: &ServerState, bit: u16) -> bool { + state.xi_devices.devices().iter().any(|device| { + device.enabled + && device.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID) + && (device.id == XI2_XTEST_POINTER_DEVICE_ID + || device.facet == Some(crate::xinput::XiFacetKind::PointerTouch)) + && device.buttons_down & bit != 0 + }) || state + .unpublished_pointer_buttons_down + .iter() + .any(|(source_id, buttons)| { + buttons & bit != 0 + && state + .xi_devices + .source(*source_id) + .is_some_and(|info| info.enabled && info.capabilities.pointer) + }) +} /// Fan a host pointer event out to nested clients. /// @@ -58,11 +365,39 @@ pub fn pointer_event_fanout_to_state( handle_grabs, is_replay, is_replay, + false, &mut info, ); implicit_pointer_grab_lifecycle(state, &event, &info); if !info.queued { - release_passive_grab_on_button_release(state, event.kind); + release_passive_grab_on_button_release(state, event.kind, event.origin); + } + dropped +} + +/// Fan out the events of a warp: `WarpPointer`, a confine grab pulling the +/// pointer in, or the pointer moved onto a CRTC after a layout change. +/// +/// As [`pointer_event_fanout_to_state`], except that no XI2 raw event is +/// generated. A raw event describes the device, and a warp did not come +/// from one: Xorg's `ProcWarpPointer` (and `CheckPhysLimits`) call +/// `SetCursorPosition(..., TRUE)`, which `miPointerWarpCursor` turns into +/// `miPointerMove`, whose `GetPointerEvents` passes `POINTER_NORAW`; and +/// `fill_pointer_events` (dix/getevents.c) makes no raw event under that +/// flag. RECORD still sees the motion, as before. +pub fn warp_pointer_event_fanout_to_state( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + xid_map: &HostXidMap, + event: HostPointerEvent, +) -> Vec { + let mut info = ImplicitGrabFanoutInfo::default(); + let dropped = pointer_event_fanout_to_state_inner( + state, backend, xid_map, event, true, false, false, true, &mut info, + ); + implicit_pointer_grab_lifecycle(state, &event, &info); + if !info.queued { + release_passive_grab_on_button_release(state, event.kind, event.origin); } dropped } @@ -81,11 +416,11 @@ pub fn replay_frozen_pointer_event_to_state( ) -> Vec { let mut info = ImplicitGrabFanoutInfo::default(); let dropped = pointer_event_fanout_to_state_inner( - state, backend, xid_map, event, false, false, true, &mut info, + state, backend, xid_map, event, false, false, true, false, &mut info, ); implicit_pointer_grab_lifecycle(state, &event, &info); if !info.queued { - release_passive_grab_on_button_release(state, event.kind); + release_passive_grab_on_button_release(state, event.kind, event.origin); } dropped } @@ -117,6 +452,7 @@ struct ImplicitGrabFanoutInfo { /// must not drive grab lifecycle. The lifecycle for this event runs /// when `xi1_compute_freezes` replays it. queued: bool, + master_button_transition: bool, core_press: Option, xi2_press: Option, } @@ -204,8 +540,16 @@ fn pointer_event_fanout_to_state_inner( handle_grabs: bool, is_replay: bool, suppress_raw: bool, + warp: bool, info: &mut ImplicitGrabFanoutInfo, ) -> Vec { + // Reject stale/suspended physical events and invalid XTEST targets before + // pointer mappings, held buttons, barriers, cursor bookkeeping or fanout + // can observe them. This check also runs for queued/replayed events. + let Some(xi_source) = resolve_pointer_xi_source(state, event.origin, event.tree_change) else { + return Vec::new(); + }; + // SetPointerMapping: physical button → logical button before any // routing (Xorg UpdateDeviceState applies b->map at event // generation). A 0 entry disables the button — the event vanishes. @@ -228,23 +572,45 @@ fn pointer_event_fanout_to_state_inner( // onto delivered events: the backend cooks the authoritative // modifier/button state into `event.state` (see the modifier // source-of-truth note in `key_fanout`). - if matches!( + let button_transition = if matches!( event.kind, PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease - ) && (1..=16).contains(&event.detail) - { - let bit = 1u16 << (event.detail - 1); - if event.kind == PointerEventKind::ButtonPress { - state.buttons_down |= bit; + ) { + let replaying = state.playing_sync_events || is_replay || suppress_raw; + let transition = pointer_button_transition( + state, + event.origin, + xi_source, + event.detail, + event.kind == PointerEventKind::ButtonPress, + ); + if replaying { + // A frozen input may have updated its held state before it was + // queued, or it may first become owned when the activating press + // is replayed. The transition helper is idempotent in both cases; + // preserve delivery of the queued/replayed event even when that + // state transition was already applied. + PointerButtonTransition { + source_accepted: true, + master_accepted: true, + } } else { - state.buttons_down &= !bit; + transition } - } + } else { + PointerButtonTransition { + source_accepted: true, + master_accepted: true, + } + }; + info.master_button_transition = button_transition.master_accepted; // Pointer confinement (Xorg CheckPhysLimits): while a confined // grab is active, motion outside the confine rectangle is // replaced by a warp to the nearest inside point; press/release - // coordinates clamp in place. + // coordinates clamp in place. A tree-change crossing is no motion: + // the request that moved the confine window re-clamps after it. if !is_replay + && !event.tree_change && state.pointer_confine_to.0 != 0 && let Some(w) = state.resources.window(state.pointer_confine_to) && w.map_state == crate::resources::MapState::Viewable @@ -488,61 +854,65 @@ fn pointer_event_fanout_to_state_inner( } } } - let now = std::time::Instant::now(); - // Capture priors BEFORE mutating; needed by the IDLETIME wake handler. - #[allow(clippy::cast_possible_truncation)] - let prior_global = now - .duration_since(state.dpms.last_activity) - .as_millis() - .min(u128::from(u32::MAX)) as i64; - // XI2 master device IDs are always small (2 here); cast u16 → u8 is safe. - // Per-device prior: fall back to global if no per-device entry yet. - // Matches `idletime_baseline`'s fallback (server.rs Task 1) — without - // this, the very first input event for a device whose baseline isn't - // recorded would compute prior_device=0 and a per-device Negative - // alarm (whose wait_value > 0) would not see the `old > wait` half of - // its trigger. - let prior_device = state - .per_device_last_activity - .get(&(XI2_MASTER_POINTER_DEVICE_ID as u8)) - .copied() - .map(|t| { - #[allow(clippy::cast_possible_truncation)] - let v = now.duration_since(t).as_millis().min(u128::from(u32::MAX)) as i64; - v - }) - .unwrap_or(prior_global); - - state.dpms.last_activity = now; - state - .per_device_last_activity - .insert(XI2_MASTER_POINTER_DEVICE_ID as u8, now); + // A tree-change crossing is not user input: it neither resets the idle + // clocks nor wakes DPMS or the screen saver. + if !event.tree_change { + let now = std::time::Instant::now(); + // Capture priors BEFORE mutating; needed by the IDLETIME wake handler. + #[allow(clippy::cast_possible_truncation)] + let prior_global = now + .duration_since(state.dpms.last_activity) + .as_millis() + .min(u128::from(u32::MAX)) as i64; + // XI2 master device IDs are always small (2 here); cast u16 → u8 is safe. + // Per-device prior: fall back to global if no per-device entry yet. + // Matches `idletime_baseline`'s fallback (server.rs Task 1) — without + // this, the very first input event for a device whose baseline isn't + // recorded would compute prior_device=0 and a per-device Negative + // alarm (whose wait_value > 0) would not see the `old > wait` half of + // its trigger. + let prior_device = state + .per_device_last_activity + .get(&(XI2_MASTER_POINTER_DEVICE_ID as u8)) + .copied() + .map(|t| { + #[allow(clippy::cast_possible_truncation)] + let v = now.duration_since(t).as_millis().min(u128::from(u32::MAX)) as i64; + v + }) + .unwrap_or(prior_global); - // IDLETIME wake: fires Negative-* alarms before the input event itself - // reaches clients (predictable ordering). - crate::core_loop::process_request::evaluate_idletime_negative_alarms_on_input_wake( - state, - XI2_MASTER_POINTER_DEVICE_ID as u8, - prior_global, - prior_device, - ); + state.dpms.last_activity = now; + state + .per_device_last_activity + .insert(XI2_MASTER_POINTER_DEVICE_ID as u8, now); - if state.dpms.enabled && state.dpms.power_level != 0 { - crate::core_loop::process_request::apply_dpms_transition(state, backend, 0); - // DPMS coupling tail already flipped SS Off if it was On. - } - if matches!( - state.screensaver.active, - crate::server::ScreenSaverActive::On - ) { - // Standalone SS activation (DPMS was On already; SS came up - // via idle timer or ForceScreenSaver) — input wakes it. - crate::core_loop::process_request::apply_screen_saver_transition( + // IDLETIME wake: fires Negative-* alarms before the input event itself + // reaches clients (predictable ordering). + crate::core_loop::process_request::evaluate_idletime_negative_alarms_on_input_wake( state, - backend, - crate::server::ScreenSaverActive::Off, - /*forced=*/ false, + XI2_MASTER_POINTER_DEVICE_ID as u8, + prior_global, + prior_device, ); + + if state.dpms.enabled && state.dpms.power_level != 0 { + crate::core_loop::process_request::apply_dpms_transition(state, backend, 0); + // DPMS coupling tail already flipped SS Off if it was On. + } + if matches!( + state.screensaver.active, + crate::server::ScreenSaverActive::On + ) { + // Standalone SS activation (DPMS was On already; SS came up + // via idle timer or ForceScreenSaver) — input wakes it. + crate::core_loop::process_request::apply_screen_saver_transition( + state, + backend, + crate::server::ScreenSaverActive::Off, + /*forced=*/ false, + ); + } } let mut dropped = Vec::new(); @@ -550,6 +920,80 @@ fn pointer_event_fanout_to_state_inner( // Step 1 — translate host-screen coords to ynest-root coords. let event = translate_host_event(state, xid_map, event); + // Xorg `GetPointerEvents` calls UpdateFromMaster before the raw and + // device forms. A replay has already passed that generation point and + // must not announce a source switch a second time. + if button_transition.source_accepted { + merge_dropped( + &mut dropped, + update_from_pointer_master(state, xi_source, !is_replay && !suppress_raw, true), + ); + } + + // Resolve the same unified freeze predicate here that the enqueue path + // below uses. Xorg calls DeviceEventCallback while enqueueing a frozen + // input event (dix/events.c:1166), before later duplicate suppression; + // this lets RECORD observe XTEST edges that do not change the master + // button bitmap while a physical button is already held. + let source_device_id = xi_source.slave_deviceid.unwrap_or(xi_source.sourceid); + let freeze_device = [Some(source_device_id), xi_source.attached_master] + .into_iter() + .flatten() + .find(|id| { + state + .xi1_frozen + .get(id) + .is_some_and(crate::server::Xi1Freeze::frozen) + }); + let pointer_frozen_unified = freeze_device.is_some(); + let queued_while_frozen = !is_replay + && handle_grabs + && pointer_frozen_unified + && !matches!( + event.kind, + PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify, + ); + + // RECORD sees each physical pointer event once, before grabs and + // delivery, and not again when a frozen queue replays it (Xorg + // `ProcessDeviceEvent` skips the callback while playingEvents). + let master_record_accepted = match event.kind { + PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease => { + button_transition.master_accepted + } + // A floating slave has no master copy in Xorg's mieq path + // (mi/mieq.c:397-425), so it cannot produce a core MotionNotify for + // RECORD either. + PointerEventKind::MotionNotify => xi_source.attached_master.is_some(), + PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify => false, + }; + if !suppress_raw + && !state.playing_sync_events + && xi_source.attached_master.is_some() + && (master_record_accepted || queued_while_frozen) + { + let event_type = match event.kind { + PointerEventKind::ButtonPress => Some(4), + PointerEventKind::ButtonRelease => Some(5), + PointerEventKind::MotionNotify => Some(6), + PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify => None, + }; + if let Some(event_type) = event_type { + crate::core_loop::record::record_device_event( + state, + crate::core_loop::record::RecordedDeviceEvent { + event_type, + detail: if event_type == 6 { 0 } else { event.detail }, + repeat: false, + time: event.time, + root_x: event.root_x, + root_y: event.root_y, + state: event.state, + }, + ); + } + } + if matches!(event.kind, PointerEventKind::MotionNotify) { const MOTION_HISTORY_CAPACITY: usize = 256; if state.pointer_motion_history.len() == MOTION_HISTORY_CAPACITY { @@ -567,7 +1011,17 @@ fn pointer_event_fanout_to_state_inner( // Cache the pointer position so server-generated events that must // carry it (XI2 focus events) don't ship (0,0). Mirrors Xorg keeping // the sprite position in device state. - state.pointer_root = (event.root_x, event.root_y); + let floating_device = xi_source + .slave_deviceid + .filter(|_| xi_source.attached_master.is_none()); + if let Some(device_id) = floating_device { + state.floating_pointer_positions.insert( + device_id, + (f32::from(event.root_x), f32::from(event.root_y)), + ); + } else { + state.pointer_root = (event.root_x, event.root_y); + } // Sync-passive-grab freeze queue (Xorg `dix/events.c:1320` // ComputeFreezes + PlayReleasedEvents). While a sync passive @@ -597,18 +1051,7 @@ fn pointer_event_fanout_to_state_inner( // the Steam menu/Library input-wedge, HW 2026-07-15, #94 follow-up. // The dual representation has since been removed; `xi1_frozen` is the // single source of truth.) - let pointer_frozen_unified = state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .is_some_and(crate::server::Xi1Freeze::frozen); - if !is_replay - && handle_grabs - && pointer_frozen_unified - && !matches!( - event.kind, - PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify, - ) - { + if queued_while_frozen { log::trace!( "pointer_fanout: QUEUE-WHILE-FROZEN kind={:?} button={} root=({},{}) queue_len={}", event.kind, @@ -624,7 +1067,7 @@ fn pointer_event_fanout_to_state_inner( state .sync_pending .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, + device: freeze_device.expect("frozen flag has its controlling device"), event: crate::server::QueuedInputEvent::HostPointer(canonical), }); info.queued = true; @@ -707,7 +1150,13 @@ fn pointer_event_fanout_to_state_inner( .map(|(_, _, _, c, _)| c) .unwrap_or_default(); let xi2_evt = xi2_evtype(event.kind); - let (xi2_clients, _) = compute_xi2_targets(state, target, top_level_id, xi2_evt, None); + let xi2_clients = compute_xi2_targets_for_source( + state, + target, + top_level_id, + xi2_evt, + xi_source.slave_deviceid, + ); let label_clients = |cs: &[ClientId]| -> String { if cs.is_empty() { "".to_string() @@ -743,8 +1192,9 @@ fn pointer_event_fanout_to_state_inner( // QUEUE stay handle_grabs-gated (those are the re-entry hazards). // With no grab in effect, active_grab_target is None and this is the // exact pre-fix behavior for the replayed press. - if let Some((grab_window, grab_client, gx, gy, owner_events, via_xi2, grab_event_mask)) = - active_grab_target(state) + if button_transition.master_accepted + && let Some((grab_window, grab_client, gx, gy, owner_events, via_xi2, grab_event_mask)) = + active_grab_target_for_source(state, xi_source) { // Xorg DeliverGrabbedEvent's owner_events=true rule is NOT // "the immediate hit window is owned by the grab client". @@ -768,6 +1218,7 @@ fn pointer_event_fanout_to_state_inner( let redirect_to_grab = !owner_events || natural_for_grab_client.is_none(); if let Some((natural_window, natural_x, natural_y, child)) = natural_for_grab_client { if !via_xi2 { + let focus = state.crossing_has_focus(natural_window); let extras = fanout_event_to_clients(state, &[grab_client], |buf, seq, order| { encode_pointer_event( buf, @@ -781,6 +1232,7 @@ fn pointer_event_fanout_to_state_inner( event, natural_x, natural_y, + focus, ); }); merge_dropped(&mut dropped, extras); @@ -830,6 +1282,11 @@ fn pointer_event_fanout_to_state_inner( // (handled_core_via_grab below) — never leaked to the natural // target. if !via_xi2 && grab_event_mask & mask_bit != 0 { + let focus = state.crossing_has_focus(grab_window); + // Xorg DeliverGrabbedEvent -> FixUpEventFromWindow: the grab + // window's child toward the pointer's window, which + // xwininfo, xprop and xkill pick a window by. + let grab_child = xi2_child_toward(state, grab_window, target); let extras = fanout_event_to_clients(state, &[grab_client], |buf, seq, order| { encode_pointer_event( buf, @@ -839,10 +1296,11 @@ fn pointer_event_fanout_to_state_inner( event.detail, event.time, grab_window, - ResourceId(0), // active-grab redirect: no propagation child + grab_child, event, event_x, event_y, + focus, ); }); merge_dropped(&mut dropped, extras); @@ -863,25 +1321,18 @@ fn pointer_event_fanout_to_state_inner( // Step 3 — passive button-grab matching for ButtonPress. // - // Delivery mirrors Xorg `DeliverGrabbedEvent` (dix/events.c:4361): + // Delivery mirrors Xorg `ActivatePassiveGrab` (dix/events.c:3833): // - // 1. With `owner_events=true`, run the natural propagation walk - // FILTERED TO THE GRAB CLIENT — `TryClientEvents` - // (dix/events.c:2069) returns -1 for any other client ("not - // delivered due to grab"), which ABORTS the walk at that - // window. Crucially the walk STARTS AT THE GRAB WINDOW, not the - // deepest hit: `ActivatePointerGrab` (dix/events.c:1633) moves - // the sprite up to the grab window (`DoEnterLeaveEvents` with - // `NotifyGrab`) before the activating event is delivered, so the - // press is reported on the grab window or an ANCESTOR of it — - // never a descendant, even one the grab client selected. See - // `grabbed_natural_target_from_grab_window`. - // 2. No natural delivery → report to the grab client on the - // grab window, filtered by the grab's event_mask. - // 3. `GrabModeSync` freezes the pointer queue only when a - // delivery happened (`FreezeThisEventIfNeededForSyncGrab` - // runs under `if (deliveries)`), so the AllowEvents that - // thaws it always has a recipient. + // 1. The activating press goes to the grab client on the GRAB + // WINDOW — `FixUpEventFromWindow(grab->window)` then + // `TryClientEvents(rClient(grab), …)` with the event's own + // filter. No `owner_events` walk and no mask check: that walk + // lives in `DeliverGrabbedEvent` and only applies to the events + // that follow (GH #277, probe V9: event = grab window, child = + // its child toward the sprite, even when the grab client + // selects the press on that child or on an ancestor). + // 2. `GrabModeSync` freezes the pointer queue and stores the press + // for a ReplayPointer. // // Pre-fix the qualification accepted any descendant of the grab // window — wmaker's click-to-focus sync grab on a CLIENT's @@ -904,11 +1355,12 @@ fn pointer_event_fanout_to_state_inner( // every subsequent press/release into a growing queue with no // path to thaw — the XFCE/MATE click-lockup that appeared after // the unified-freeze work landed on master. - let active_grab_present = state.active_pointer_grab.is_some(); + let active_grab_present = active_grab_for_source(state, xi_source).is_some(); if !handled_core_via_grab && !active_grab_present && handle_grabs && event.kind == PointerEventKind::ButtonPress + && button_transition.source_accepted && let Some((grab, _hit_window)) = try_match_passive_grab(state, xid_map, event) { log::debug!( @@ -920,7 +1372,7 @@ fn pointer_event_fanout_to_state_inner( grab.owner_events, ); // Activate the passive grab atomically with the dispatch. - state.set_pointer_grab(crate::server::ActivePointerGrab { + let active_grab = crate::server::ActivePointerGrab { owner: grab.owner, grab_window: grab.grab_window, event_mask: (grab.event_mask & u32::from(u16::MAX)) as u16, @@ -935,7 +1387,23 @@ fn pointer_event_fanout_to_state_inner( } else { 0 }, - }); + }; + let dynamic_device = grab.device_id != 0 + && matches!( + state.xi_devices.role(grab.device_id), + Some(crate::xinput::XiDeviceRole::SlavePointer) + ); + let sync_device = if grab.device_id == 0 { + crate::xinput::DEVICEID_MASTER_POINTER + } else { + grab.device_id + }; + if dynamic_device { + state.xi2_pointer_grabs.insert(grab.device_id, active_grab); + let _ = state.detach_xi2_slave(grab.device_id); + } else { + state.set_pointer_grab(active_grab); + } // Xorg `ActivatePointerGrab` → `DoEnterLeaveEvents(sprite → // grab window, NotifyGrab)` (dix/events.c:1635): the sprite @@ -948,49 +1416,23 @@ fn pointer_event_fanout_to_state_inner( // away (traced: tooltip windows mapped, never destroyed; air HW // 2026-07-01). The symmetric NotifyUngrab chain is emitted when // the grab tears down (AllowEvents ReplayPointer / release). - crate::core_loop::process_request::emit_core_pointer_grab_chain( - state, - target, - grab.grab_window, - 1, // NotifyGrab - ); - - let mask_bit = pointer_mask_bit(event.kind, event.state); - let natural = if grab.owner_events { - grabbed_natural_target_from_grab_window( + if !dynamic_device { + crate::core_loop::process_request::emit_core_pointer_grab_chain( state, - grab.grab_window, target, - target_x, - target_y, - mask_bit, - grab.owner, - ) - } else { - None - }; + grab.grab_window, + 1, // NotifyGrab + ); + } + let mut delivered = false; - if let Some((natural_window, event_x, event_y, child)) = natural { - let extras = fanout_event_to_clients(state, &[grab.owner], |buf, seq, order| { - encode_pointer_event( - buf, - order, - PointerEventKind::ButtonPress, - seq, - event.detail, - event.time, - natural_window, - child, - event, - event_x, - event_y, - ); - }); - merge_dropped(&mut dropped, extras); - delivered = true; - } else if grab.event_mask & mask_bit != 0 - && let Some(grab_target) = client_target_id(state, grab.owner) - { + if let Some(grab_target) = client_target_id(state, grab.owner) { + // Xorg ActivatePassiveGrab hands the activating event to the + // grabbing client with the event's own filter as the mask + // (dix/events.c TryClientEvents(..., GetEventFilter(device, xE), + // ...)), so it arrives even when the grab's event mask lacks + // ButtonPress — dtwm's front panel grabs ButtonRelease only in + // sync mode and thaws on the press it is handed. // Xorg DeliverOneGrabbedEvent -> FixUpEventFromWindow always // rewrites eventX/Y from the root coordinates and the grab // window's screen-absolute origin. The producer's event_x/y @@ -1002,6 +1444,9 @@ fn pointer_event_fanout_to_state_inner( let (gx, gy) = state.resources.window_absolute_position(grab.grab_window); let event_x = clamp_grab_coord(event.root_x, gx); let event_y = clamp_grab_coord(event.root_y, gy); + let focus = state.crossing_has_focus(grab.grab_window); + // As an active grab's (FixUpEventFromWindow). + let grab_child = xi2_child_toward(state, grab.grab_window, target); let extras = fanout_event_to_clients(state, &[grab_target], |buf, seq, order| { encode_pointer_event( buf, @@ -1011,21 +1456,19 @@ fn pointer_event_fanout_to_state_inner( event.detail, event.time, grab.grab_window, - ResourceId(0), // passive grab activation: no propagation child + grab_child, event, event_x, event_y, + focus, ); }); merge_dropped(&mut dropped, extras); delivered = true; } if delivered && grab.pointer_mode == 0 { - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default() - .stored = Some(crate::server::QueuedInputEvent::HostPointer(event)); + state.xi1_frozen.entry(sync_device).or_default().stored = + Some(crate::server::QueuedInputEvent::HostPointer(event)); } // Xorg ActivatePointerGrab → CheckGrabForSyncs: a sync // pointer_mode freezes the pointer's device stream; a sync @@ -1034,7 +1477,7 @@ fn pointer_event_fanout_to_state_inner( // grab and thaw it with AllowEvents). xi1_check_grab_for_syncs( state, - crate::xinput::DEVICEID_SLAVE_POINTER, + sync_device, grab.owner, grab.pointer_mode == 0, grab.keyboard_mode == 0, @@ -1060,7 +1503,10 @@ fn pointer_event_fanout_to_state_inner( event.kind, PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify ); - if !handled_core_via_grab && (top_level_id_opt.is_some() || is_crossing) { + if !handled_core_via_grab + && button_transition.master_accepted + && (top_level_id_opt.is_some() || is_crossing) + { let mask_bit = pointer_mask_bit(event.kind, event.state); // Crossings carry a *per-window* endpoint (the producer stamps each // Leave/Enter chain event with that window's host_xid). The live @@ -1092,7 +1538,15 @@ fn pointer_event_fanout_to_state_inner( } else { (target, target_x, target_y) }; - let (nested_id, event_x, event_y, mut core_targets, propagation_child) = + let (nested_id, event_x, event_y, mut core_targets, propagation_child) = if is_crossing { + ( + cross_start, + cross_x, + cross_y, + core_crossing_targets(state, cross_start, mask_bit), + ResourceId(0), + ) + } else { pointer_propagation_target_by_id( state, cross_start, @@ -1101,7 +1555,8 @@ fn pointer_event_fanout_to_state_inner( mask_bit, xi2_absorbing_evtype(event.kind), ) - .unwrap_or((cross_start, cross_x, cross_y, Vec::new(), ResourceId(0))); + .unwrap_or((cross_start, cross_x, cross_y, Vec::new(), ResourceId(0))) + }; // XI2 shadows core per client (Xorg behaviour, mirrors // `deliver_key_to_window`): a client that receives the XI2 @@ -1127,8 +1582,13 @@ fn pointer_event_fanout_to_state_inner( } else { (target, top_level_id) }; - let (xi2_dedup, _) = - compute_xi2_targets(state, dedup_target, dedup_top_level, xi2_evt, None); + let xi2_dedup = compute_xi2_targets_for_source( + state, + dedup_target, + dedup_top_level, + xi2_evt, + xi_source.slave_deviceid, + ); // Only the MASTER-pointer XI2 form duplicates the core // event, so shadow core only for those clients (Chromium's // Ozone X11 selects core + XI2 on the master → it must NOT @@ -1142,8 +1602,16 @@ fn pointer_event_fanout_to_state_inner( // registered on the e desktop. core_targets.retain(|c| { !xi2_dedup.contains(c) - || xi2_stamp_deviceid(state, *c, dedup_target, dedup_top_level, xi2_evt) - == XI2_SLAVE_POINTER_DEVICE_ID + || xi_source.slave_deviceid.is_some_and(|slave_deviceid| { + xi2_stamp_deviceid_for_source( + state, + *c, + dedup_target, + dedup_top_level, + xi2_evt, + Some(slave_deviceid), + ) == slave_deviceid + }) }); } } @@ -1170,6 +1638,8 @@ fn pointer_event_fanout_to_state_inner( ); } + let focus = state.crossing_has_focus(nested_id); + let extras = fanout_event_to_clients(state, &core_targets, |buf, seq, order| { encode_pointer_event( buf, @@ -1183,6 +1653,7 @@ fn pointer_event_fanout_to_state_inner( event, event_x, event_y, + focus, ); }); // Capture the core candidate. The final resolver compares it with @@ -1231,8 +1702,8 @@ fn pointer_event_fanout_to_state_inner( // DeviceMotionNotify) for clients that selected the matching // `XEventClass` via SelectExtensionEvent. XI1 events propagate up // the ancestor chain like core events (Xorg dix - // DeliverDeviceEvents) and report the slave/extension pointer (4), - // matching the device XTS opens (masters are not XI1-openable). + // DeliverDeviceEvents) and report the resolved source facet (masters + // are not XI1-openable). // // Deliberately BEFORE the `top_level_id_opt` gate below: XI1 // routing resolves its own target from `natural_target` and its @@ -1247,7 +1718,10 @@ fn pointer_event_fanout_to_state_inner( PointerEventKind::MotionNotify => Some(crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET), _ => None, }; - if let Some(offset) = xi1_offset { + if let Some(offset) = xi1_offset + && button_transition.source_accepted + && let Some(deviceid) = xi_source.slave_deviceid + { let evcode = crate::server::XI_FIRST_EVENT + offset; let detail = if event.kind == PointerEventKind::MotionNotify { 0 @@ -1257,14 +1731,12 @@ fn pointer_event_fanout_to_state_inner( let extras = xi1_route_device_event( state, crate::server::Xi1QueuedEvent { - deviceid: crate::xinput::DEVICEID_SLAVE_POINTER, + deviceid, evcode, detail, time: event.time, root_x: event.root_x, root_y: event.root_y, - event_x: target_x, - event_y: target_y, state_mask: event.state, natural_target: target, // Pointer devices have no focus class — always the @@ -1311,11 +1783,10 @@ fn pointer_event_fanout_to_state_inner( // (host_xid → resource) — matching Xorg, which delivers a crossing to // every path window that selected it. Coalesce-safe: for the common // case the producer's window IS the deepest hit, so this is a no-op. - let (mut xi2_targets, xi2_raw_targets) = if matches!( + let mut xi2_targets = if matches!( event.kind, PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify - ) && let Some(crossing_win) = - xid_map.get(&event.host_xid).copied() + ) && let Some(crossing_win) = xid_map.get(&event.host_xid).copied() { nested_id = crossing_win; // Compute per-window coordinates from root + core geometry. The KMS @@ -1325,13 +1796,21 @@ fn pointer_event_fanout_to_state_inner( let (ox, oy) = state.resources.window_absolute_position(crossing_win); event_x = clamp_grab_coord(event.root_x, ox); event_y = clamp_grab_coord(event.root_y, oy); - ( - compute_xi2_exact_targets(state, crossing_win, xi2_evtype), - Vec::new(), - ) + xi2_crossing_targets_for_source(state, crossing_win, xi2_evtype, xi_source) } else { - compute_xi2_targets(state, target, top_level_id, xi2_evtype, xi2_raw_evtype) + compute_xi2_targets_for_source( + state, + target, + top_level_id, + xi2_evtype, + xi_source.slave_deviceid, + ) }; + let (xi2_raw_slave_targets, xi2_raw_master_targets) = xi2_raw_evtype + .map(|raw_evtype| compute_xi2_raw_targets(state, raw_evtype, xi_source)) + .unwrap_or_default(); + let mut xi2_raw_targets = xi2_raw_slave_targets.clone(); + merge_dropped(&mut xi2_raw_targets, xi2_raw_master_targets.clone()); // Set when delivery is grab-scoped (passive-freeze or active-grab // redirect): the event window is then the grab window, not the @@ -1345,19 +1824,34 @@ fn pointer_event_fanout_to_state_inner( // their own windows. (#94 follow-up — grabbed ButtonRelease.) let mut xi2_grab_window_target: Option<(ClientId, ResourceId, i16, i16)> = None; + // Physical wheel input arrives as button 4–7 transitions, then this + // fanout adds the XI2 Motion carrying the scroll valuator. Xorg turns a + // scroll ButtonPress into MotionNotify and fills it before separately + // generating legacy wheel buttons (dix/getevents.c:1646-1697, 1703-1718), + // so a Motion-only XI2 grab must accept the emulated wheel press as Motion. + let source_has_scroll_class = pointer_source_has_scroll_class(state, xi_source, event.detail); + let xi2_scroll_button_press = event.kind == PointerEventKind::ButtonPress + && button_transition.source_accepted + && source_has_scroll_class; + let xi2_grab_accepts_event = |mask: u64| { + mask & (1_u64 << xi2_evtype) != 0 || (xi2_scroll_button_press && mask & (1_u64 << 6) != 0) + }; + let mut xi2_scroll_grab_motion_only = false; + // Synchronous passive XI2 button grabs freeze the device event at // the grab owner until XIAllowEvents(ReplayDevice) replays it. // Without this filter GTK sees the press on the unfocused target // before muffin finishes focus activation, then never receives the // replay it expects. + let active_source_grab = active_grab_for_source(state, xi_source); if handle_grabs && event.kind == PointerEventKind::ButtonPress - && state.active_pointer_grab.is_some_and(|grab| grab.passive) + && active_source_grab.is_some_and(|grab| grab.passive) && state .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) + .get(&source_device_id) .is_some_and(|freeze| freeze.stored.is_some()) - && let Some(grab_owner) = state.active_pointer_grab.map(|grab| grab.owner) + && let Some(grab_owner) = active_source_grab.map(|grab| grab.owner) { xi2_targets.retain(|cid| *cid == grab_owner); xi2_grab_delivery = true; @@ -1377,7 +1871,7 @@ fn pointer_event_fanout_to_state_inner( event.kind, PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify ) && let Some((grab_window, grab_client, gx, gy, owner_events, via_xi2, _)) = - active_grab_target(state) + active_grab_target_for_source(state, xi_source) { // A core-form implicit grab must not hijack XI2 delivery. Xorg's // implicit grab carries the event window's MERGED XI2 mask and still @@ -1388,9 +1882,8 @@ fn pointer_event_fanout_to_state_inner( // xtrace 13 XI2 presses, 0 XI2 releases; Xorg 3/3). Scoped to core // IMPLICIT grabs — explicit XIGrabDevice/GrabPointer and via_xi2 // implicit grabs keep the exclusive redirect below. - let core_implicit = state - .active_pointer_grab - .is_some_and(|g| g.implicit && !g.via_xi2); + let source_active_grab = active_grab_for_source(state, xi_source); + let core_implicit = source_active_grab.is_some_and(|g| g.implicit && !g.via_xi2); // Same ownership-aware natural-delivery test as the Step-2 // core path: `owner_events=true` keeps motion on whichever // GTK sub-window the cursor is over when that sub-window is @@ -1421,15 +1914,20 @@ fn pointer_event_fanout_to_state_inner( // motion for the duration of every click. Explicit // XIGrabDevice grabs carry u64::MAX (wire mask not parsed // — pre-existing permissive delivery, unchanged). - let grab_xi2_mask = state.active_pointer_grab.map_or(u64::MAX, |g| g.xi2_mask); - if grab_xi2_mask & (1 << xi2_evtype) != 0 { + let grab_xi2_mask = source_active_grab.map_or(u64::MAX, |g| g.xi2_mask); + if xi2_grab_accepts_event(grab_xi2_mask) { xi2_targets.push(grab_client); + xi2_scroll_grab_motion_only = + xi2_scroll_button_press && grab_xi2_mask & (1_u64 << xi2_evtype) == 0; nested_id = grab_window; event_x = clamp_grab_coord(event.root_x, gx); event_y = clamp_grab_coord(event.root_y, gy); } } - } else if via_xi2 && !xi2_targets.contains(&grab_client) { + } else if via_xi2 + && !xi2_targets.contains(&grab_client) + && source_active_grab.is_some_and(|grab| xi2_grab_accepts_event(grab.xi2_mask)) + { // owner_events natural delivery did NOT reach the grab owner: // it holds the pointer only via the grab (not XISelectEvents), // so `compute_xi2_targets` excluded it. Xorg @@ -1444,6 +1942,13 @@ fn pointer_event_fanout_to_state_inner( // grab owner is redirected to the grab window (see the // per-recipient override in the delivery loop below). xi2_targets.push(grab_client); + // Xorg's DeliverGrabbedEvent fallback (:4400-4405) delivers + // through the active grab even when owner_events natural + // delivery found no selection. Keep this target scoped to the + // owner so other natural recipients retain their own geometry. + xi2_scroll_grab_motion_only = source_active_grab.is_some_and(|grab| { + xi2_scroll_button_press && grab.xi2_mask & (1_u64 << xi2_evtype) == 0 + }); xi2_grab_window_target = Some(( grab_client, grab_window, @@ -1476,24 +1981,45 @@ fn pointer_event_fanout_to_state_inner( } // XI2 raw events. - if !suppress_raw && let Some(raw_evtype) = xi2_raw_evtype { - let extras = fanout_event_to_clients(state, &xi2_raw_targets, |buf, seq, order| { - x11::encode_xi2_raw_event( - buf, - order, - seq, + // None for a warp ([`warp_pointer_event_fanout_to_state`]). + if !suppress_raw + && !warp + && let Some(raw_evtype) = xi2_raw_evtype + { + // mieq processes the attached slave first, then copies ET_Raw* to its + // master by rewriting deviceid and retaining sourceid. Keep that + // order for clients selecting both forms. Master-only origins have + // no slave event to copy. + if let Some(deviceid) = xi_source.slave_deviceid { + let extras = + fanout_event_to_clients(state, &xi2_raw_slave_targets, |buf, seq, order| { + x11::encode_xi2_raw_event( + buf, + order, + seq, + XI2_MAJOR_OPCODE, + raw_evtype, + deviceid, + event.time, + u32::from(event.detail), + xi_source.sourceid, + event.raw_dx, + event.raw_dy, + ); + }); + merge_dropped(&mut dropped, extras); + } + let extras = fanout_event_to_clients(state, &xi2_raw_master_targets, |buf, seq, order| { + x11::encode_xi2_raw_event( + buf, + order, + seq, XI2_MAJOR_OPCODE, raw_evtype, - // Xorg's mieq master-device copy rewrites `deviceid` to - // the attached master pointer while retaining the - // originating slave in `sourceid` (mi/mieq.c). XI2_MASTER_POINTER_DEVICE_ID, event.time, u32::from(event.detail), - XI2_SLAVE_POINTER_DEVICE_ID, - // XI2 RawMotion valuators = relative device delta (Xorg - // set_raw_valuators), NOT the absolute position. SDL2 - // relative-mouse apps accumulate these. 0 for raw buttons. + xi_source.sourceid, event.raw_dx, event.raw_dy, ); @@ -1523,8 +2049,9 @@ fn pointer_event_fanout_to_state_inner( // cumulative-vs-delta bug. // // ButtonRelease doesn't carry an axis update; only ButtonPress does. - let scroll_axis_info: Option<(u8, i32)> = if event.kind == PointerEventKind::ButtonPress - && (event.detail >= 4 && event.detail <= 7) + let scroll_axis_info: Option<(u8, usize)> = if event.kind == PointerEventKind::ButtonPress + && button_transition.source_accepted + && source_has_scroll_class { let (axis_idx, delta): (usize, i32) = match event.detail { 4 => (0, -1), @@ -1533,13 +2060,190 @@ fn pointer_event_fanout_to_state_inner( 7 => (1, 1), _ => unreachable!(), }; - state.scroll_axis_value[axis_idx] = state.scroll_axis_value[axis_idx].wrapping_add(delta); + if let Some(device_id) = xi_source.slave_deviceid + && let Some(device) = state.xi_devices.device_mut(device_id) + { + device.scroll_axis_values[axis_idx] = + device.scroll_axis_values[axis_idx].wrapping_add(delta); + } else if xi_source.attached_master.is_some() { + state.scroll_axis_value[axis_idx] = + state.scroll_axis_value[axis_idx].wrapping_add(delta); + } let scroll_axis_num: u8 = if axis_idx == 0 { 2 } else { 3 }; - Some((scroll_axis_num, state.scroll_axis_value[axis_idx])) + Some((scroll_axis_num, axis_idx)) } else { None }; + // Xorg's GetPointerEvents snapshots the active slave's axisVal into + // DeviceChanged (dix/getevents.c:286), then mieq copies that valuator + // state to the master (mi/mieq.c:423-425). XIQueryDevice reads the + // master's axisVal (Xi/xiquerydevice.c:369), so this is the master's + // current source value, not a sum across independent physical mice. + if scroll_axis_info.is_some() { + merge_dropped( + &mut dropped, + update_from_pointer_master(state, xi_source, false, true), + ); + } + + // Xorg builds the smooth-scroll MotionNotify before it generates the + // separate legacy wheel-button transitions (dix/getevents.c:1646-1697, + // 1703-1718). Route that Motion by XI_Motion selections and grab masks; + // it is independent of the emulated ButtonPress's master aggregation. + if let Some((axis, axis_idx)) = scroll_axis_info { + const XI_MOTION_EVENT: u16 = 6; + let natural_targets = compute_xi2_targets_for_source( + state, + target, + top_level_id, + XI_MOTION_EVENT, + xi_source.slave_deviceid, + ); + let mut motion_targets = natural_targets.clone(); + let active_motion_grab = active_source_grab + .filter(|grab| grab.via_xi2 && grab.xi2_mask & (1_u64 << XI_MOTION_EVENT) != 0); + let mut motion_grab_window_target = None; + if xi2_grab_delivery { + motion_targets.clear(); + if let Some(grab) = active_motion_grab { + motion_targets.push(grab.owner); + } + } else if let Some(grab) = active_motion_grab + && grab.owner_events + && !natural_targets.contains(&grab.owner) + { + // This smooth-scroll Motion is a distinct event from the + // emulated wheel ButtonPress handled above. Xorg's + // DeliverGrabbedEvent performs owner-events delivery per event, + // then falls back to the grab window only when this Motion + // reached no natural owner selection (dix/events.c:4431-4464). + // Do not key it from `xi2_grab_window_target`: that marker is + // derived from the paired ButtonPress and can disagree with the + // Motion selection. + motion_targets.push(grab.owner); + motion_grab_window_target = active_grab_target_for_source(state, xi_source).and_then( + |(window, owner, gx, gy, _, via_xi2, _)| { + (via_xi2 && owner == grab.owner).then_some(( + owner, + window, + clamp_grab_coord(event.root_x, gx), + clamp_grab_coord(event.root_y, gy), + )) + }, + ); + } + + for cid in motion_targets { + let natural_for_client = natural_targets.contains(&cid); + let fallback_grab_target = motion_grab_window_target + .filter(|(owner, ..)| *owner == cid && !natural_for_client); + let grab_scoped = (xi2_grab_delivery + && active_motion_grab.is_some_and(|g| g.owner == cid)) + || fallback_grab_target.is_some(); + let mut forms = Vec::with_capacity(2); + let (mut wants_master, mut wants_slave) = xi2_pointer_forms_for_source( + state, + cid, + target, + top_level_id, + XI_MOTION_EVENT, + xi_source.slave_deviceid, + ); + let exact_slave_grab = grab_scoped + && active_motion_grab.is_some_and(|grab| grab.owner == cid) + && xi_source.slave_deviceid.is_some_and(|device_id| { + state.xi2_pointer_grabs.get(&device_id).is_some_and(|grab| { + grab.owner == cid + && grab.via_xi2 + && grab.xi2_mask & (1_u64 << XI_MOTION_EVENT) != 0 + }) + }); + if exact_slave_grab { + wants_master = false; + wants_slave = true; + } + if let Some(device_id) = xi_source.slave_deviceid + && wants_slave + && button_transition.source_accepted + { + forms.push((device_id, true)); + } + if (wants_master || !wants_slave) + && button_transition.source_accepted + && xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID) + { + forms.push((XI2_MASTER_POINTER_DEVICE_ID, false)); + } + + for (device_id, is_slave) in forms { + let fixed_geometry = + fallback_grab_target.map(|(_, window, x, y)| (window, ResourceId(0), x, y)); + let fixed_geometry = fixed_geometry.or_else(|| { + (xi2_grab_delivery && active_motion_grab.is_some_and(|g| g.owner == cid)) + .then_some((nested_id, ResourceId(0), event_x, event_y)) + }); + let (event_window, _child, x, y) = fixed_geometry.unwrap_or_else(|| { + let window = xi2_route_window_for_source( + state, + target, + if is_slave { + Xi2PointerForm::Slave + } else { + Xi2PointerForm::Master + }, + XI_MOTION_EVENT, + xi_source.slave_deviceid, + ) + .unwrap_or(target); + if window == nested_id { + (nested_id, ResourceId(0), event_x, event_y) + } else { + let child = xi2_child_toward(state, window, target); + let (ox, oy) = state.resources.window_absolute_position(window); + ( + window, + child, + clamp_grab_coord(event.root_x, ox), + clamp_grab_coord(event.root_y, oy), + ) + } + }); + let value = xi_source + .slave_deviceid + .and_then(|source_id| state.xi_devices.device(source_id)) + .map_or(state.scroll_axis_value[axis_idx], |device| { + device.scroll_axis_values[axis_idx] + }); + let extras = fanout_event_to_clients( + state, + std::slice::from_ref(&cid), + |buf, seq, order| { + x11::encode_xi2_motion_with_scroll( + buf, + order, + seq, + XI2_MAJOR_OPCODE, + device_id, + event.time, + ROOT_WINDOW, + event_window, + event.root_x, + event.root_y, + x, + y, + event.state, + xi_source.sourceid, + axis, + value, + ); + }, + ); + merge_dropped(&mut dropped, extras); + } + } + } + // XI2 device events (crossing or non-crossing). // // Per-client `deviceid`: a client that selected XI2 events on the @@ -1594,8 +2298,31 @@ fn pointer_event_fanout_to_state_inner( PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify ); for cid in &xi2_targets { - let (wants_master, wants_slave) = - xi2_pointer_forms(state, *cid, target, top_level_id, xi2_evtype); + let (mut wants_master, mut wants_slave) = xi2_pointer_forms_for_source( + state, + *cid, + target, + top_level_id, + xi2_evtype, + xi_source.slave_deviceid, + ); + // An exact slave grab uses the grab's XI2 mask and device identity + // for grab delivery. There need not be a separate XISelectEvents + // selection on that device, and a detached source has no master + // cooked-event form to fall back to. + let owner_fallback_delivery = + xi2_grab_window_target.is_some_and(|(owner, ..)| owner == *cid); + let exact_slave_grab = (xi2_grab_delivery || owner_fallback_delivery) + && active_source_grab.is_some_and(|grab| grab.owner == *cid && grab.via_xi2) + && xi_source.slave_deviceid.is_some_and(|device_id| { + state.xi2_pointer_grabs.get(&device_id).is_some_and(|grab| { + grab.owner == *cid && grab.via_xi2 && xi2_grab_accepts_event(grab.xi2_mask) + }) + }); + if exact_slave_grab { + wants_master = false; + wants_slave = true; + } // Crossings and grab-redirected delivery have one fixed event // window. Normal slave/master forms route independently and may // stop on different selected ancestors. @@ -1610,28 +2337,47 @@ fn pointer_event_fanout_to_state_inner( } else { None }; - let forms: [(u16, bool, Xi2PointerForm); 2] = [ - ( - XI2_SLAVE_POINTER_DEVICE_ID, - wants_slave, + let mut forms = Vec::with_capacity(2); + if is_crossing_evt { + // A crossing exists in exactly one form (`xi2_crossing_form`): + // an attached slave never gets its own Enter/Leave, so a client + // selecting XIAllDevices sees one crossing, not a second, + // unbalanced per-slave one, like Xorg. + let (form, deviceid) = xi2_crossing_form(xi_source); + forms.push((deviceid, true, form)); + } else if let Some(slave_deviceid) = xi_source.slave_deviceid { + forms.push(( + slave_deviceid, + wants_slave && button_transition.source_accepted, Xi2PointerForm::Slave, - ), - // Master form for master / `XIAllMasterDevices` / `XIAllDevices` - // selectors, AND as the default when the client has no matching - // window selection (grab owners receive via their grab mask, not - // `XISelectEvents`, and that funnel is master-routed). - ( + )); + } + // Master form for master / `XIAllMasterDevices` / `XIAllDevices` + // selectors, AND as the default when the client has no matching + // window selection (grab owners receive via their grab mask, not + // `XISelectEvents`, and that funnel is master-routed). A source with + // no published slave can only deliver its master form. + if !is_crossing_evt { + let wants_master_form = wants_master || !wants_slave; + forms.push(( XI2_MASTER_POINTER_DEVICE_ID, - wants_master || !wants_slave, + wants_master_form && button_transition.master_accepted, Xi2PointerForm::Master, - ), - ]; - for (deviceid, want, form) in forms { - if !want { + )); + } + for (deviceid, button_want, form) in forms { + if !button_want { continue; } let (ev_win, ev_child, ev_x, ev_y) = fixed_geometry.unwrap_or_else(|| { - let win = xi2_route_window(state, target, form, xi2_evtype).unwrap_or(target); + let win = xi2_route_window_for_source( + state, + target, + form, + xi2_evtype, + xi_source.slave_deviceid, + ) + .unwrap_or(target); if win == nested_id { (nested_id, ResourceId(0), event_x, event_y) } else { @@ -1645,6 +2391,11 @@ fn pointer_event_fanout_to_state_inner( ) } }); + let focus = state.crossing_has_focus(ev_win); + // Xorg snapshots the slave's `axisVal` into DeviceChanged + // (dix/getevents.c:265-286), then copies the slave event to its + // master (mi/mieq.c:422-425). Keep both XI forms on that same + // source counter so a source switch cannot create a false delta. let extras = fanout_event_to_clients(state, std::slice::from_ref(cid), |buf, seq, order| { if is_crossing_evt { @@ -1665,68 +2416,54 @@ fn pointer_event_fanout_to_state_inner( event.state, event.crossing_mode, event.detail, - XI2_SLAVE_POINTER_DEVICE_ID, + xi_source.sourceid, + focus, ); } else { - if let Some((axis, value)) = scroll_axis_info { - x11::encode_xi2_motion_with_scroll( + // Mark scroll-emulated XI_ButtonPress/Release(4..7) + // with XIPointerEmulated so XI2-aware clients discard + // the legacy button after consuming the matching + // XI_Motion scroll-axis update (see + // `yserver-protocol::x11::XI_POINTER_EMULATED`). + let xi2_flags: u32 = if matches!( + event.kind, + PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease + ) && source_has_scroll_class + { + x11::XI_POINTER_EMULATED + } else { + 0 + }; + if button_want + && !(xi2_scroll_grab_motion_only + && active_source_grab.is_some_and(|grab| grab.owner == *cid)) + { + x11::encode_xi2_device_event( buf, order, seq, XI2_MAJOR_OPCODE, + xi2_evtype, deviceid, event.time, ROOT_WINDOW, ev_win, + ev_child, event.root_x, event.root_y, ev_x, ev_y, event.state, - XI2_SLAVE_POINTER_DEVICE_ID, - axis, - value, + u32::from(event.detail), + xi_source.sourceid, + xi2_flags, ); } - // Mark scroll-emulated XI_ButtonPress/Release(4..7) - // with XIPointerEmulated so XI2-aware clients discard - // the legacy button after consuming the matching - // XI_Motion scroll-axis update (see - // `yserver-protocol::x11::XI_POINTER_EMULATED`). - let xi2_flags: u32 = if matches!( - event.kind, - PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease - ) && (4..=7).contains(&event.detail) - { - x11::XI_POINTER_EMULATED - } else { - 0 - }; - x11::encode_xi2_device_event( - buf, - order, - seq, - XI2_MAJOR_OPCODE, - xi2_evtype, - deviceid, - event.time, - ROOT_WINDOW, - ev_win, - ev_child, - event.root_x, - event.root_y, - ev_x, - ev_y, - event.state, - u32::from(event.detail), - XI2_SLAVE_POINTER_DEVICE_ID, - xi2_flags, - ); } }); let delivered = !extras.contains(cid); merge_dropped(&mut dropped, extras); - if event.kind == PointerEventKind::ButtonPress && delivered { + if event.kind == PointerEventKind::ButtonPress && button_want && delivered { // Under a grab this records the grab owner, and the // lifecycle's no-grab gate discards it. Natural delivery is // the only path that can install. Merge every client's mask @@ -1737,7 +2474,9 @@ fn pointer_event_fanout_to_state_inner( .values() .map(|c| { [ - XI2_SLAVE_POINTER_DEVICE_ID, + xi_source + .slave_deviceid + .unwrap_or(XI2_MASTER_POINTER_DEVICE_ID), XI2_MASTER_POINTER_DEVICE_ID, 1, 0, @@ -1775,7 +2514,12 @@ fn implicit_pointer_grab_lifecycle( event: &HostPointerEvent, info: &ImplicitGrabFanoutInfo, ) { - if info.queued { + if info.queued + || (matches!( + event.kind, + PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease + ) && !info.master_button_transition) + { return; } match event.kind { @@ -1788,10 +2532,15 @@ fn implicit_pointer_grab_lifecycle( let Some(press) = info.delivered_press(&state.resources) else { return; }; + let source_has_xi2_grab = + resolve_pointer_xi_source(state, event.origin, event.tree_change) + .and_then(|source| source.slave_deviceid) + .is_some_and(|device_id| state.xi2_pointer_grabs.contains_key(&device_id)); if state.active_pointer_grab.is_some() + || source_has_xi2_grab || state .xi1_active_grabs - .contains_key(&crate::xinput::DEVICEID_SLAVE_POINTER) + .contains_key(&crate::xinput::DEVICEID_XTEST_POINTER) { return; } @@ -1842,6 +2591,7 @@ fn implicit_pointer_grab_lifecycle( pub fn emit_scroll_stop_to_state( state: &mut ServerState, xid_map: &HostXidMap, + origin: crate::core_loop::InputOrigin, pointer_host_xid: u32, root_x: i16, root_y: i16, @@ -1849,7 +2599,15 @@ pub fn emit_scroll_stop_to_state( time: u32, ) { const XI_MOTION: u16 = 6; + let Some(xi_source) = resolve_pointer_xi_source(state, origin, false) else { + return; + }; + // The stop is a pointer event for UpdateFromMaster too. This announces + // a source switch and copies the same source valuators used by ordinary + // pointer events before the stop's XI2 motion forms are emitted. + let _dropped = update_from_pointer_master(state, xi_source, true, true); let probe = HostPointerEvent { + origin, kind: PointerEventKind::MotionNotify, host_xid: pointer_host_xid, detail: 0, @@ -1863,6 +2621,7 @@ pub fn emit_scroll_stop_to_state( child: 0, raw_dx: 0, raw_dy: 0, + tree_change: false, }; let root_hit = resolve_pointer_hit(state, xid_map, &probe); let top_level_id = root_hit @@ -1871,59 +2630,70 @@ pub fn emit_scroll_stop_to_state( .unwrap_or(ROOT_WINDOW); let (target, event_x, event_y) = root_hit.unwrap_or((top_level_id, root_x, root_y)); - let (xi2_targets, _) = compute_xi2_targets(state, target, top_level_id, XI_MOTION, None); + let xi2_targets = compute_xi2_targets_for_source( + state, + target, + top_level_id, + XI_MOTION, + xi_source.slave_deviceid, + ); if xi2_targets.is_empty() { return; } - let mut master_dev_targets: Vec = Vec::new(); - let mut slave_dev_targets: Vec = Vec::new(); for cid in &xi2_targets { - let (wants_master, wants_slave) = - xi2_pointer_forms(state, *cid, target, top_level_id, XI_MOTION); - if wants_slave { - slave_dev_targets.push(*cid); + let (wants_master, wants_slave) = xi2_pointer_forms_for_source( + state, + *cid, + target, + top_level_id, + XI_MOTION, + xi_source.slave_deviceid, + ); + let mut forms = Vec::with_capacity(2); + if let Some(device_id) = xi_source.slave_deviceid + && wants_slave + { + forms.push((device_id, true)); } if wants_master || !wants_slave { - master_dev_targets.push(*cid); + forms.push((XI2_MASTER_POINTER_DEVICE_ID, false)); } - } - // Current cumulative valuator per axis (unchanged → delta 0 → is_stop). - // Index 0 = vertical (scroll axis 2), 1 = horizontal (axis 3); mirrors the - // click path's `scroll_axis_num` mapping. - let axes: [(u8, i32); 2] = [ - (2, state.scroll_axis_value[0]), - (3, state.scroll_axis_value[1]), - ]; - // Slave form before master (see the ordering note in the main fanout). - for (deviceid, group) in [ - (XI2_SLAVE_POINTER_DEVICE_ID, &slave_dev_targets), - (XI2_MASTER_POINTER_DEVICE_ID, &master_dev_targets), - ] { - if group.is_empty() { - continue; + for (deviceid, is_slave) in forms { + let scroll = if is_slave { + state + .xi_devices + .device(deviceid) + .map_or(state.scroll_axis_value, |device| device.scroll_axis_values) + } else { + state.scroll_axis_value + }; + let _ = fanout_event_to_clients(state, std::slice::from_ref(cid), |buf, seq, order| { + // Current cumulative valuator per axis (unchanged → delta + // 0 → is_stop). Index 0 is vertical axis 2; index 1 is + // horizontal axis 3. + let axes = [(2, scroll[0]), (3, scroll[1])]; + for (axis, value) in axes { + x11::encode_xi2_motion_with_scroll( + buf, + order, + seq, + XI2_MAJOR_OPCODE, + deviceid, + time, + ROOT_WINDOW, + target, + root_x, + root_y, + event_x, + event_y, + state_mask, + xi_source.sourceid, + axis, + value, + ); + } + }); } - let _ = fanout_event_to_clients(state, group, |buf, seq, order| { - for (axis, value) in axes { - x11::encode_xi2_motion_with_scroll( - buf, - order, - seq, - XI2_MAJOR_OPCODE, - deviceid, - time, - ROOT_WINDOW, - target, - root_x, - root_y, - event_x, - event_y, - state_mask, - XI2_SLAVE_POINTER_DEVICE_ID, - axis, - value, - ); - } - }); } } @@ -2222,6 +2992,22 @@ fn xi1_fan_device_event( // getValuatorEvents for a 2-axis motion. let is_motion = q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET; + // Xorg FixUpEventFromWindow: coordinates relative to the event + // window's inside origin; child per FindChildForEvent from the + // sprite window (the pointer hit for pointer events, the deepest + // window under the pointer for key events). + let is_key = q.evcode + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET + || q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET; + let sprite = if is_key { + crate::core_loop::key_fanout::deepest_window_at_pointer(state) + } else { + q.natural_target + }; + let child = xi2_child_toward(state, event_window, sprite); + let (ox, oy) = state.resources.window_absolute_position(event_window); + let event_x = clamp_grab_coord(q.root_x, ox); + let event_y = clamp_grab_coord(q.root_y, oy); fanout_event_to_clients(state, targets, |buf, seq, order| { crate::xinput::encode_xi1_device_input_event( buf, @@ -2232,11 +3018,11 @@ fn xi1_fan_device_event( q.time, ROOT_WINDOW.0, event_window.0, - 0, + child.0, q.root_x, q.root_y, - q.event_x, - q.event_y, + event_x, + event_y, q.state_mask, if is_motion { q.deviceid | u16::from(crate::xinput::XI1_MORE_EVENTS) @@ -2267,14 +3053,15 @@ fn xi1_fan_device_event( }) } -/// The paired input device: pointer (4) <-> keyboard (5). Used for -/// other_devices_mode freeze bookkeeping. -pub(crate) fn xi1_other_input_device(deviceid: u16) -> u16 { - if deviceid == crate::xinput::DEVICEID_SLAVE_POINTER { - crate::xinput::DEVICEID_SLAVE_KEYBOARD - } else { - crate::xinput::DEVICEID_SLAVE_POINTER - } +/// Resolve the Xorg paired master from the requested device's current +/// attachment. Floating slaves have no paired device. +pub(crate) fn xi1_other_input_device(state: &ServerState, deviceid: u16) -> Option { + state.xi_devices.paired_master(deviceid).or_else(|| { + state + .xi2_detached_masters + .get(&deviceid) + .and_then(|master| state.xi_devices.paired_master(*master)) + }) } /// Force-thaw a device: reset its sync state outright and flush. Used @@ -2332,6 +3119,16 @@ pub(crate) fn xi1_compute_freezes( crate::server::QueuedInputEvent::HostKey(event) => { let _ = crate::core_loop::key_fanout::deliver_routed_key(state, event); } + crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + ) => { + let _ = crate::core_loop::key_fanout::deliver_routed_key_after_transition( + state, + event, + master_transition_accepted, + ); + } crate::server::QueuedInputEvent::Xi1Routed(event) => { let _ = xi1_route_device_event(state, event, true); } @@ -2342,6 +3139,57 @@ pub(crate) fn xi1_compute_freezes( } } +/// End active grabs on a physical source, restore its saved attachments, +/// and replay input released by a dynamic XI2 grab's paired-device hold. +/// The caller keeps the source registered until held-state releases have +/// passed through the normal fanout path, then disables and unregisters it. +pub fn xi_cleanup_source( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + source: crate::xinput::InputSourceId, +) { + let device_ids: Vec = [ + state + .xi_devices + .facet(source, crate::xinput::XiFacetKind::Keyboard), + state + .xi_devices + .facet(source, crate::xinput::XiFacetKind::PointerTouch), + ] + .into_iter() + .flatten() + .collect(); + + for device_id in device_ids { + xi1_deactivate_device_grab(state, device_id); + + let pointer_owner = state + .xi2_pointer_grabs + .remove(&device_id) + .map(|grab| grab.owner); + let keyboard_owner = state + .xi2_keyboard_grabs + .remove(&device_id) + .map(|grab| grab.owner); + for owner in [pointer_owner, keyboard_owner].into_iter().flatten() { + if let Some(freeze) = state.xi1_frozen.get_mut(&device_id) { + freeze.state = crate::server::Xi1SyncState::Thawed; + freeze.stored = None; + } + xi1_core_grab_bridge_release(state, device_id, owner); + } + if pointer_owner.is_some() + || keyboard_owner.is_some() + || state.xi2_detached_masters.contains_key(&device_id) + { + state.reattach_xi2_slave(device_id); + } + } + + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); +} + /// Port of Xorg `CheckGrabForSyncs` (dix/events.c:1424-1450): set the /// sync state at grab activation. A sync `this_mode` freezes the /// grabbed device ONCE (FrozenNoEvent); a sync `other_mode` holds the @@ -2365,12 +3213,23 @@ pub(crate) fn xi1_check_grab_for_syncs( } } } - let other_dev = xi1_other_input_device(deviceid); - let other = state.xi1_frozen.entry(other_dev).or_default(); - if other_sync { - other.other = Some(owner); - } else if other.other == Some(owner) { - other.other = None; + // Xorg CheckGrabForSyncs only synchronizes the paired device for a + // master grab (dix/events.c:1439). Slave grabs force paired_device_mode + // to Async and never freeze their paired master. + if matches!( + state.xi_devices.role(deviceid), + Some( + crate::xinput::XiDeviceRole::MasterPointer + | crate::xinput::XiDeviceRole::MasterKeyboard + ) + ) && let Some(other_dev) = xi1_other_input_device(state, deviceid) + { + let other = state.xi1_frozen.entry(other_dev).or_default(); + if other_sync { + other.other = Some(owner); + } else if other.other == Some(owner) { + other.other = None; + } } } @@ -2393,7 +3252,13 @@ pub(crate) fn xi1_freeze_this_event_if_needed( .map_or(Xi1SyncState::Thawed, |f| f.state); match st { Xi1SyncState::FreezeBothNextEvent => { - let other_dev = xi1_other_input_device(deviceid); + let other_dev = xi1_other_input_device(state, deviceid); + let Some(other_dev) = other_dev else { + let sync = state.xi1_frozen.entry(deviceid).or_default(); + sync.state = Xi1SyncState::FrozenWithEvent; + sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); + return; + }; let other_owner = xi1_device_grab_owner(state, other_dev); let other = state.xi1_frozen.entry(other_dev).or_default(); if other.state == Xi1SyncState::FreezeBothNextEvent && other_owner == Some(owner) { @@ -2426,8 +3291,8 @@ pub(crate) fn xi1_deactivate_device_grab(state: &mut ServerState, deviceid: u16) sync.state = crate::server::Xi1SyncState::Thawed; sync.stored = None; } - let other_dev = xi1_other_input_device(deviceid); - if let Some(other) = state.xi1_frozen.get_mut(&other_dev) + let other_dev = xi1_other_input_device(state, deviceid); + if let Some(other) = other_dev.and_then(|id| state.xi1_frozen.get_mut(&id)) && other.other == Some(grab.owner) { other.other = None; @@ -2451,8 +3316,8 @@ pub(crate) fn xi1_core_grab_bridge_release( sync.state = crate::server::Xi1SyncState::Thawed; sync.stored = None; } - let other_dev = xi1_other_input_device(deviceid); - if let Some(other) = state.xi1_frozen.get_mut(&other_dev) + let other_dev = xi1_other_input_device(state, deviceid); + if let Some(other) = other_dev.and_then(|id| state.xi1_frozen.get_mut(&id)) && other.other == Some(owner) { other.other = None; @@ -2467,10 +3332,31 @@ pub(crate) fn xi1_device_grab_owner(state: &ServerState, deviceid: u16) -> Optio if let Some(g) = state.xi1_active_grabs.get(&deviceid) { return Some(g.owner); } - if deviceid == crate::xinput::DEVICEID_SLAVE_POINTER { - state.active_pointer_grab.as_ref().map(|g| g.owner) - } else { - state.active_keyboard_grab.as_ref().map(|g| g.owner) + if let Some(g) = state.xi2_pointer_grabs.get(&deviceid) { + return Some(g.owner); + } + if let Some(g) = state.xi2_keyboard_grabs.get(&deviceid) { + return Some(g.owner); + } + match state.xi_devices.role(deviceid)? { + crate::xinput::XiDeviceRole::MasterPointer => { + state.active_pointer_grab.as_ref().map(|grab| grab.owner) + } + crate::xinput::XiDeviceRole::SlavePointer => { + let master = state.xi_devices.attachment(deviceid)?; + (master == crate::xinput::DEVICEID_MASTER_POINTER) + .then(|| state.active_pointer_grab.as_ref().map(|grab| grab.owner)) + .flatten() + } + crate::xinput::XiDeviceRole::MasterKeyboard => { + state.active_keyboard_grab.as_ref().map(|grab| grab.owner) + } + crate::xinput::XiDeviceRole::SlaveKeyboard => { + let master = state.xi_devices.attachment(deviceid)?; + (master == crate::xinput::DEVICEID_MASTER_KEYBOARD) + .then(|| state.active_keyboard_grab.as_ref().map(|grab| grab.owner)) + .flatten() + } } } @@ -2534,12 +3420,42 @@ fn translate_host_event( return event; }; HostPointerEvent { + origin: event.origin, root_x: rx, root_y: ry, ..event } } +/// Recipients of a core Enter/Leave on `window` — Xorg `CoreEnterLeaveEvent` +/// (`dix/events.c:4748`). A crossing never propagates. Under a pointer grab +/// only the grab client gets it: on the grab window through the grab's mask, +/// and with `owner_events` through its own selection on `window`. +fn core_crossing_targets(state: &ServerState, window: ResourceId, mask_bit: u32) -> Vec { + let Some((grab_window, grab_client, _, _, owner_events, via_xi2, grab_mask)) = + active_grab_target(state) + else { + return crate::core_loop::fanout::subscribers_by_id(state, window, mask_bit); + }; + let mut mask = if window == grab_window && !via_xi2 { + grab_mask + } else { + 0 + }; + if owner_events { + mask |= state + .clients + .get(&grab_client.0) + .and_then(|c| c.event_masks.get(&window).copied()) + .unwrap_or(0); + } + if mask & mask_bit == 0 { + Vec::new() + } else { + vec![grab_client] + } +} + fn active_grab_target( state: &ServerState, ) -> Option<( @@ -2552,6 +3468,53 @@ fn active_grab_target( u32, )> { let grab = state.active_pointer_grab?; + active_pointer_grab_target(state, grab) +} + +fn active_grab_for_source( + state: &ServerState, + source: PointerXiSource, +) -> Option { + if let Some(device_id) = source.slave_deviceid { + if let Some(grab) = state.xi2_pointer_grabs.get(&device_id) { + return Some(*grab); + } + return (source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) + .then_some(state.active_pointer_grab) + .flatten(); + } + (source.sourceid == XI2_MASTER_POINTER_DEVICE_ID) + .then_some(state.active_pointer_grab) + .flatten() +} + +fn active_grab_target_for_source( + state: &ServerState, + source: PointerXiSource, +) -> Option<( + yserver_protocol::x11::ResourceId, + ClientId, + i32, + i32, + bool, + bool, + u32, +)> { + active_pointer_grab_target(state, active_grab_for_source(state, source)?) +} + +fn active_pointer_grab_target( + state: &ServerState, + grab: crate::server::ActivePointerGrab, +) -> Option<( + yserver_protocol::x11::ResourceId, + ClientId, + i32, + i32, + bool, + bool, + u32, +)> { let target = client_target_id(state, grab.owner)?; let (gx, gy) = state.resources.window_absolute_position(grab.grab_window); Some(( @@ -2611,110 +3574,56 @@ fn grabbed_natural_target( None } -/// `owner_events=true` natural-delivery walk for a passive grab's -/// ACTIVATING event. Unlike [`grabbed_natural_target`], the walk starts -/// at the GRAB WINDOW, not the deepest hit. -/// -/// Xorg `ActivatePointerGrab` (dix/events.c:1633) fires -/// `DoEnterLeaveEvents(oldWin, grab->window, NotifyGrab)` on activation, -/// which moves the sprite UP to the grab window before the activating -/// event is delivered. `DeliverGrabbedEvent` then runs the owner_events -/// walk from `pSprite->win` (= the grab window), so the press is -/// reported on the grab window (or an ancestor) — NEVER a descendant of -/// it — with `child` = the grab window's child on the path toward the -/// pointer (Xorg `FindChildForEvent`). -/// -/// Starting the walk at the deepest hit instead (the pre-fix behaviour) -/// leaks the activating press to a descendant whenever the grab client -/// also selected the event there. icewm frames its own taskbar and puts -/// a sync AnyModifier button grab on the client container; its taskbar -/// widgets are children of that container and DO select ButtonPress, so -/// the press landed on the widget instead of the container. icewm's -/// `YClientContainer::handleButton` (the only path that calls -/// `XAllowEvents(ReplayPointer)`) never ran, so the frozen pointer never -/// thawed and every panel click died (icewm HW 2026-07-01). -/// -/// `hit`/`hit_x`/`hit_y` are the deepest window under the pointer and -/// its window-relative coords. Returns the delivery window, coords -/// translated to it, and the `child`. Returns `None` (→ caller falls -/// back to grab-window delivery via the grab's own event_mask) when the -/// grab client selected nothing on the chain from the grab window up, or -/// when the grab window is not an ancestor of the hit. -fn grabbed_natural_target_from_grab_window( - state: &ServerState, - grab_window: ResourceId, - hit: ResourceId, - hit_x: i16, - hit_y: i16, - mask_bits: u32, - grab_client: ClientId, -) -> Option<(ResourceId, i16, i16, ResourceId)> { - // Translate the pointer position from the deepest hit up to the - // grab window, recording the grab window's immediate child on the - // path toward the hit (Xorg `FindChildForEvent`). `child` is 0 when - // the pointer is directly on the grab window. - let mut current = hit; - let mut x = hit_x; - let mut y = hit_y; - let mut child = ResourceId(0); - // `0..256` mirrors `grabbed_natural_target`: a defensive cap so a - // malformed (cyclic) window tree can never hang the core loop. - for _ in 0..256 { - if current == grab_window { - break; - } - let window = state.resources.window(current)?; - // Reached the root without meeting the grab window: it is not an - // ancestor of the hit, so there is no natural chain to walk. - if window.parent == current { - return None; - } - // #133 step 8: the inverse of the hit-test walk's - // `to_content_coords`, border term included. - (x, y) = window.to_parent_coords(x, y); - child = current; - current = window.parent; - } - if current != grab_window { - return None; - } - - // Now `current == grab_window` and (x, y) is the pointer relative to - // it. Run the same first-subscriber-or-abort walk as - // `grabbed_natural_target`, but rooted at the grab window (the moved - // sprite position) rather than the deepest hit. - for _ in 0..256 { - let subs = crate::core_loop::fanout::subscribers_by_id(state, current, mask_bits); - if !subs.is_empty() { - return subs - .contains(&grab_client) - .then_some((current, x, y, child)); - } - let window = state.resources.window(current)?; - if window.parent == current { - return None; - } - // #133 step 8: the inverse of the hit-test walk's - // `to_content_coords`, border term included. - (x, y) = window.to_parent_coords(x, y); - child = current; - current = window.parent; +fn release_passive_grab_on_button_release( + state: &mut ServerState, + kind: PointerEventKind, + origin: crate::core_loop::InputOrigin, +) { + if kind != PointerEventKind::ButtonRelease { + return; } - None -} - -fn release_passive_grab_on_button_release(state: &mut ServerState, kind: PointerEventKind) { - if kind == PointerEventKind::ButtonRelease - && state.buttons_down == 0 - && state.active_pointer_grab.is_some_and(|grab| grab.passive) + let Some(source) = resolve_pointer_xi_source(state, origin, false) else { + return; + }; + let device_id = source.slave_deviceid.unwrap_or(source.sourceid); + let source_buttons_down = source + .slave_deviceid + .and_then(|id| { + state + .xi_devices + .device(id) + .map(|device| device.buttons_down) + }) + .unwrap_or(state.buttons_down); + if source_buttons_down == 0 + && state + .xi2_pointer_grabs + .get(&device_id) + .is_some_and(|grab| grab.passive) { + let grab = state + .xi2_pointer_grabs + .remove(&device_id) + .expect("matched per-device passive grab exists"); + if let Some(freeze) = state.xi1_frozen.get_mut(&device_id) { + freeze.stored = None; + } + xi1_core_grab_bridge_release(state, device_id, grab.owner); + state.reattach_xi2_slave(device_id); + return; + } + // The core pointer grab belongs to the master device, whose aggregate + // held-button state is `state.buttons_down`. A release generated by + // another source (for example XTEST4) must not end that grab while an + // attached physical slave still holds the same master button. + if state.buttons_down == 0 && state.active_pointer_grab.is_some_and(|grab| grab.passive) { let grab = state .active_pointer_grab .map(|active| (active.owner, active.grab_window)); state.clear_pointer_grab(); if let Some(freeze) = state .xi1_frozen - .get_mut(&crate::xinput::DEVICEID_SLAVE_POINTER) + .get_mut(&crate::xinput::DEVICEID_MASTER_POINTER) { freeze.stored = None; } @@ -2736,7 +3645,7 @@ fn release_passive_grab_on_button_release(state: &mut ServerState, kind: Pointer // Xorg DeactivatePointerGrab: releasing the grab also // releases the sync holds it placed (a sync keyboard_mode // froze the keyboard on this grab's behalf — XGrabButton-19). - xi1_core_grab_bridge_release(state, crate::xinput::DEVICEID_SLAVE_POINTER, owner); + xi1_core_grab_bridge_release(state, crate::xinput::DEVICEID_MASTER_POINTER, owner); } } } @@ -2814,7 +3723,15 @@ fn try_match_passive_grab( // hit when the press was generated, not a window restacked on top // since. Keeps grab matching and delivery consistent. let (hit_window, _, _) = resolve_pointer_hit(state, xid_map, &event)?; - let grab = state.find_passive_grab(hit_window, event.detail, event.state)?; + let source = resolve_pointer_xi_source(state, event.origin, false)?; + let device_id = source.slave_deviceid.unwrap_or(source.sourceid); + let grab = state.find_passive_grab( + hit_window, + event.detail, + event.state, + device_id, + source.attached_master, + )?; Some((grab, hit_window)) } @@ -2879,7 +3796,7 @@ fn xi2_raw_evtype(kind: PointerEventKind) -> Option { /// (`ResourceId(0)` when `ancestor == descendant` or they are unrelated). /// Fills the XI2 `child` field when an event is reported on an ancestor of /// the hit window, matching Xorg's `DeliverDeviceEvents`. -fn xi2_child_toward( +pub(crate) fn xi2_child_toward( state: &ServerState, ancestor: ResourceId, descendant: ResourceId, @@ -2904,42 +3821,44 @@ enum Xi2PointerForm { Master, } -fn xi2_form_selected_on( +fn xi2_form_selected_on_for_source( client: &crate::server::ClientState, window: ResourceId, form: Xi2PointerForm, evtype: u16, + slave_deviceid: Option, ) -> bool { - let devices: &[u16] = match form { - Xi2PointerForm::Slave => &[XI2_SLAVE_POINTER_DEVICE_ID, 0], - Xi2PointerForm::Master => &[XI2_MASTER_POINTER_DEVICE_ID, 1, 0], - }; let bit = 1u64 << evtype; - devices.iter().any(|device| { + let selected = |device: u16| { client .xi2_masks - .get(&(window, *device)) + .get(&(window, device)) .is_some_and(|mask| mask & bit != 0) - }) + }; + match form { + Xi2PointerForm::Slave => slave_deviceid.is_some_and(selected) || selected(0), + Xi2PointerForm::Master => { + selected(XI2_MASTER_POINTER_DEVICE_ID) || selected(1) || selected(0) + } + } } /// Route one XI2 device form using Xorg's `DeliverDeviceEvents` rule: walk /// leaf-to-root and stop at the first window with a matching selection. /// Every selector on that window receives the form; selectors on higher /// ancestors do not receive duplicate copies. -fn xi2_route_window( +fn xi2_route_window_for_source( state: &ServerState, target: ResourceId, form: Xi2PointerForm, evtype: u16, + slave_deviceid: Option, ) -> Option { let mut window = target; for _ in 0..256 { - if state - .clients - .values() - .any(|client| xi2_form_selected_on(client, window, form, evtype)) - { + if state.clients.values().any(|client| { + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + }) { return Some(window); } if window == ROOT_WINDOW { @@ -2950,78 +3869,132 @@ fn xi2_route_window( None } -fn xi2_form_targets( +fn xi2_form_targets_for_source( state: &ServerState, window: ResourceId, form: Xi2PointerForm, evtype: u16, + slave_deviceid: Option, ) -> Vec { state .clients .iter() .filter_map(|(id, client)| { - xi2_form_selected_on(client, window, form, evtype).then_some(ClientId(*id)) + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + .then_some(ClientId(*id)) }) .collect() } -fn compute_xi2_exact_targets( +/// The one XI2 form a crossing is delivered in. Xorg computes Enter/Leave +/// only for a device that owns a sprite: `ProcessDeviceEvent` calls +/// `CheckMotion` only `if (IsMaster(device) || IsFloating(device))` +/// (`Xi/exevents.c:1854`), and `CheckMotion` passes the slave as `sourceid` +/// to `DoEnterLeaveEvents` (`dix/events.c:3244-3252`). So a crossing caused by +/// an attached slave carries deviceid = master, sourceid = slave; only a +/// floating slave gets crossings stamped with its own id. +fn xi2_crossing_form(xi_source: PointerXiSource) -> (Xi2PointerForm, u16) { + match xi_source.slave_deviceid { + Some(slave) if xi_source.attached_master.is_none() => (Xi2PointerForm::Slave, slave), + _ => (Xi2PointerForm::Master, XI2_MASTER_POINTER_DEVICE_ID), + } +} + +/// Recipients of an XI2 Enter/Leave on `window` — Xorg +/// `DeviceEnterLeaveEvent` (`dix/events.c:4866`): under an XI2 grab only the +/// grab client, through the grab's mask; otherwise the selections on +/// `window` for the crossing's one device form (`xi2_crossing_form`), never +/// propagated. +fn xi2_crossing_targets_for_source( state: &ServerState, window: ResourceId, evtype: u16, + xi_source: PointerXiSource, ) -> Vec { - let mut targets = Vec::new(); - for form in [Xi2PointerForm::Slave, Xi2PointerForm::Master] { - for cid in xi2_form_targets(state, window, form, evtype) { - if !targets.contains(&cid) { - targets.push(cid); - } + match state.active_pointer_grab { + Some(grab) if grab.via_xi2 => client_target_id(state, grab.owner) + .filter(|_| grab.xi2_mask & (1 << evtype) != 0) + .into_iter() + .collect(), + _ => { + let (form, _) = xi2_crossing_form(xi_source); + xi2_form_targets_for_source(state, window, form, evtype, xi_source.slave_deviceid) } } - targets } -fn compute_xi2_targets( +/// The clients that selected the master pointer's XI2 `evtype` on `window`. +pub(crate) fn xi2_master_selectors( + state: &ServerState, + window: ResourceId, + evtype: u16, +) -> Vec { + xi2_form_targets_for_source(state, window, Xi2PointerForm::Master, evtype, None) +} + +fn compute_xi2_targets_for_source( state: &ServerState, target: yserver_protocol::x11::ResourceId, _top_level_id: yserver_protocol::x11::ResourceId, xi2_evtype: u16, - xi2_raw_evtype: Option, -) -> (Vec, Vec) { + slave_deviceid: Option, +) -> Vec { let mut xi2_targets: Vec = Vec::new(); - let mut xi2_raw_targets: Vec = Vec::new(); if xi2_evtype == 0 { - return (xi2_targets, xi2_raw_targets); + return xi2_targets; } - for form in [Xi2PointerForm::Slave, Xi2PointerForm::Master] { - if let Some(window) = xi2_route_window(state, target, form, xi2_evtype) { - for cid in xi2_form_targets(state, window, form, xi2_evtype) { + let forms = if slave_deviceid.is_some() { + [Some(Xi2PointerForm::Slave), Some(Xi2PointerForm::Master)] + } else { + [None, Some(Xi2PointerForm::Master)] + }; + for form in forms.into_iter().flatten() { + if let Some(window) = + xi2_route_window_for_source(state, target, form, xi2_evtype, slave_deviceid) + { + for cid in xi2_form_targets_for_source(state, window, form, xi2_evtype, slave_deviceid) + { if !xi2_targets.contains(&cid) { xi2_targets.push(cid); } } } } + xi2_targets +} + +fn compute_xi2_raw_targets( + state: &ServerState, + raw_evtype: u16, + xi_source: PointerXiSource, +) -> (Vec, Vec) { + let mut slave_targets = Vec::new(); + let mut master_targets = Vec::new(); for (cid_u32, c) in state.clients.iter() { - let cid = ClientId(*cid_u32); - if let Some(raw_evtype) = xi2_raw_evtype { + let raw_bit = 1 << raw_evtype; + if let Some(sourceid) = xi_source.slave_deviceid { + let root_mask = xi2_mask_for_client(c, ROOT_WINDOW, ROOT_WINDOW, &[sourceid, 0]); + if root_mask & raw_bit != 0 { + slave_targets.push(ClientId(*cid_u32)); + } + } + // mieq.c::mieqCopyDeviceEvent returns without producing a master + // copy for IsFloating(sdev) (xserver/mi/mieq.c:397-398). Keep raw + // slave events for the floating device, but do not advertise them + // through the former paired master. + if xi_source.slave_deviceid.is_none() || xi_source.attached_master.is_some() { let root_mask = xi2_mask_for_client( c, ROOT_WINDOW, ROOT_WINDOW, - &[ - 1, - 0, - XI2_SLAVE_POINTER_DEVICE_ID, - XI2_MASTER_POINTER_DEVICE_ID, - ], + &[XI2_MASTER_POINTER_DEVICE_ID, 1, 0], ); - if root_mask & (1 << raw_evtype) != 0 && !xi2_raw_targets.contains(&cid) { - xi2_raw_targets.push(cid); + if root_mask & raw_bit != 0 { + master_targets.push(ClientId(*cid_u32)); } } } - (xi2_targets, xi2_raw_targets) + (slave_targets, master_targets) } /// The XI2 `deviceid` an event delivered to `cid` carries, given the @@ -3033,25 +4006,54 @@ fn compute_xi2_targets( /// Two uses: it picks the deviceid stamped on the delivered XI2 event, /// and it decides whether that XI2 event *duplicates* the core event /// (only the master form does) and must therefore shadow core delivery. -fn xi2_stamp_deviceid( +fn xi2_stamp_deviceid_for_source( state: &ServerState, cid: ClientId, target: ResourceId, _top_level: ResourceId, evtype: u16, + slave_deviceid: Option, ) -> u16 { let Some(client) = state.clients.get(&cid.0) else { return XI2_MASTER_POINTER_DEVICE_ID; }; - if xi2_route_window(state, target, Xi2PointerForm::Master, evtype) - .is_some_and(|window| xi2_form_selected_on(client, window, Xi2PointerForm::Master, evtype)) - { + if xi2_route_window_for_source( + state, + target, + Xi2PointerForm::Master, + evtype, + slave_deviceid, + ) + .is_some_and(|window| { + xi2_form_selected_on_for_source( + client, + window, + Xi2PointerForm::Master, + evtype, + slave_deviceid, + ) + }) { return XI2_MASTER_POINTER_DEVICE_ID; } - if xi2_route_window(state, target, Xi2PointerForm::Slave, evtype) - .is_some_and(|window| xi2_form_selected_on(client, window, Xi2PointerForm::Slave, evtype)) + if let Some(slave_deviceid) = slave_deviceid + && xi2_route_window_for_source( + state, + target, + Xi2PointerForm::Slave, + evtype, + Some(slave_deviceid), + ) + .is_some_and(|window| { + xi2_form_selected_on_for_source( + client, + window, + Xi2PointerForm::Slave, + evtype, + Some(slave_deviceid), + ) + }) { - return XI2_SLAVE_POINTER_DEVICE_ID; + return slave_deviceid; } XI2_MASTER_POINTER_DEVICE_ID } @@ -3067,20 +4069,51 @@ fn xi2_stamp_deviceid( /// handler gates on `deviceid == sourceid`), so a master-only delivery /// leaves it unable to scroll (issue #72), while pointer position + the /// GDK-style clients read the master form. -fn xi2_pointer_forms( +fn xi2_pointer_forms_for_source( state: &ServerState, cid: ClientId, target: ResourceId, _top_level: ResourceId, evtype: u16, + slave_deviceid: Option, ) -> (bool, bool) { let Some(client) = state.clients.get(&cid.0) else { return (false, false); }; - let master = xi2_route_window(state, target, Xi2PointerForm::Master, evtype) - .is_some_and(|window| xi2_form_selected_on(client, window, Xi2PointerForm::Master, evtype)); - let slave = xi2_route_window(state, target, Xi2PointerForm::Slave, evtype) - .is_some_and(|window| xi2_form_selected_on(client, window, Xi2PointerForm::Slave, evtype)); + let master = xi2_route_window_for_source( + state, + target, + Xi2PointerForm::Master, + evtype, + slave_deviceid, + ) + .is_some_and(|window| { + xi2_form_selected_on_for_source( + client, + window, + Xi2PointerForm::Master, + evtype, + slave_deviceid, + ) + }); + let slave = slave_deviceid.is_some_and(|device_id| { + xi2_route_window_for_source( + state, + target, + Xi2PointerForm::Slave, + evtype, + Some(device_id), + ) + .is_some_and(|window| { + xi2_form_selected_on_for_source( + client, + window, + Xi2PointerForm::Slave, + evtype, + Some(device_id), + ) + }) + }); (master, slave) } @@ -3100,12 +4133,7 @@ fn barrier_xi2_targets(state: &ServerState, window: ResourceId, evtype: u16) -> client, window, window, - &[ - XI2_SLAVE_POINTER_DEVICE_ID, - XI2_MASTER_POINTER_DEVICE_ID, - 1, - 0, - ], + &[XI2_MASTER_POINTER_DEVICE_ID, 1, 0], ); ((mask & (1 << evtype)) != 0).then_some(ClientId(*id)) }) @@ -3183,6 +4211,7 @@ fn encode_pointer_event( event: HostPointerEvent, event_x: i16, event_y: i16, + focus: bool, ) { let pointer = x11::PointerEvent { sequence: seq, @@ -3235,6 +4264,7 @@ fn encode_pointer_event( state: event.state, detail: event.detail, mode: event.crossing_mode, + focus, }, ), PointerEventKind::LeaveNotify => x11::encode_leave_notify_event( @@ -3253,6 +4283,7 @@ fn encode_pointer_event( state: event.state, detail: event.detail, mode: event.crossing_mode, + focus, }, ), } @@ -3265,3574 +4296,3 @@ fn merge_dropped(into: &mut Vec, more: Vec) { } } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - backend::recording::RecordingBackend, - host_x11::HostXidMap, - resources::ROOT_WINDOW, - server::{ScreenSaverActive, ServerState}, - }; - use yserver_protocol::x11::ClientId; - - /// AllowSome state machine pins (Xorg dix/events.c semantics): - /// grab activation freezes ONCE; FreezeNextEvent re-arms; trips to - /// FrozenWithEvent on a delivered key/button; deactivation clears - /// the paired device's on-behalf hold. - #[test] - fn xi1_sync_state_machine_pins() { - use crate::{ - server::{Xi1ActiveGrab, Xi1SyncState}, - xinput::{DEVICEID_SLAVE_KEYBOARD as KBD, DEVICEID_SLAVE_POINTER as PTR}, - }; - let mut state = ServerState::new(); - let owner = ClientId(7); - state.xi1_active_grabs.insert( - PTR, - Xi1ActiveGrab { - owner, - deviceid: PTR, - grab_window: crate::resources::ROOT_WINDOW, - owner_events: false, - this_mode: 0, - other_mode: 0, - passive_detail: None, - }, - ); - // Sync grab activation: this device FrozenNoEvent, paired - // device held on the grab's behalf. - xi1_check_grab_for_syncs(&mut state, PTR, owner, true, true); - assert_eq!( - state.xi1_frozen[&PTR].state, - Xi1SyncState::FrozenNoEvent, - "sync this_mode freezes once at activation" - ); - assert_eq!(state.xi1_frozen[&KBD].other, Some(owner)); - assert!(state.xi1_frozen[&PTR].frozen()); - assert!(state.xi1_frozen[&KBD].frozen(), "held via sync.other"); - - // FreezeNextEvent arming + trip on a delivered button event. - state.xi1_frozen.get_mut(&PTR).unwrap().state = Xi1SyncState::FreezeNextEvent; - assert!(!state.xi1_frozen[&PTR].frozen(), "armed ≠ frozen"); - let q = crate::server::Xi1QueuedEvent { - deviceid: PTR, - evcode: crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, - detail: 1, - time: 1, - root_x: 0, - root_y: 0, - event_x: 0, - event_y: 0, - state_mask: 0, - natural_target: crate::resources::ROOT_WINDOW, - focus_route: crate::server::Xi1FocusRoute::Walk, - axes: None, - replay_floor: None, - }; - xi1_freeze_this_event_if_needed(&mut state, PTR, owner, &q); - assert_eq!(state.xi1_frozen[&PTR].state, Xi1SyncState::FrozenWithEvent); - assert!(state.xi1_frozen[&PTR].stored.is_some(), "Replay material"); - - // Deactivation thaws this device AND releases the paired hold. - xi1_deactivate_device_grab(&mut state, PTR); - assert!(!state.xi1_frozen[&PTR].frozen()); - assert_eq!(state.xi1_frozen[&KBD].other, None); - assert!(!state.xi1_frozen[&KBD].frozen()); - } - - use crate::server::ClientState; - use std::{ - collections::{HashMap, HashSet, VecDeque}, - io::Read, - os::unix::net::UnixStream, - sync::{Arc, Mutex, atomic::AtomicU16}, - }; - - // Duplicated from process_request.rs::tests. If you change one, - // change both. A shared test_fixtures module is the right home - // long-term; tracked as a follow-up. - fn install_client(state: &mut ServerState, id: u32) -> UnixStream { - use crate::resources::ROOT_WINDOW; - use yserver_protocol::x11::ClientByteOrder; - let (a, b) = UnixStream::pair().unwrap(); - state.clients.insert( - id, - ClientState { - writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), - byte_order: ClientByteOrder::LittleEndian, - last_sequence: Arc::new(AtomicU16::new(0)), - resource_id_base: 0, - resource_id_mask: u32::MAX, - event_masks: HashMap::new(), - save_set: HashSet::new(), - big_requests_enabled: false, - xi2_masks: HashMap::new(), - xi1_event_classes: HashSet::new(), - xi1_window_event_classes: HashMap::new(), - outbound: VecDeque::new(), - watching_writable: false, - focused_window: ROOT_WINDOW, - reader_control: None, - is_local: true, - fd_passing: true, - }, - ); - b - } - - fn read_all_available(peer: &mut UnixStream) -> Vec { - peer.set_nonblocking(true).expect("set_nonblocking"); - let mut out = Vec::new(); - let mut buf = [0u8; 512]; - loop { - match peer.read(&mut buf) { - Ok(0) => break, - Ok(n) => out.extend_from_slice(&buf[..n]), - Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => break, - Err(err) => panic!("read failed: {err}"), - } - } - peer.set_nonblocking(false).expect("unset_nonblocking"); - out - } - - fn motion_event() -> HostPointerEvent { - HostPointerEvent { - kind: PointerEventKind::MotionNotify, - host_xid: 0, - detail: 0, - time: 1, - root_x: 10, - root_y: 20, - event_x: 10, - event_y: 20, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - } - } - - #[test] - fn translated_motion_is_recorded_once_in_bounded_history() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let event = motion_event(); - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - event, - true, - false, - ); - assert_eq!(state.pointer_motion_history.len(), 1); - assert_eq!(state.pointer_motion_history[0].time, event.time); - assert_eq!(state.pointer_motion_history[0].root_x, event.root_x); - assert_eq!(state.pointer_motion_history[0].root_y, event.root_y); - } - - /// Regression (HW-confirmed 2026-07-10, Telegram/Qt on silence): - /// a client selecting `XIAllDevices(0)` receives every pointer event - /// in BOTH slave- and master-stamped forms, and the SLAVE form MUST be - /// emitted first — matching Xorg's `mieqProcessDeviceEvent` - /// ("process slave first, then master", mi/mieq.c). Qt compresses - /// consecutive XI_Motion keeping only the last (qxcbconnection.cpp) and - /// drops the slave-deviceid copy (qxcbconnection_xi2.cpp:689). With the - /// old master-first order every master copy was trailed by its slave - /// copy → compressed away → and the surviving slave copy dropped, so - /// ZERO motion (and thus zero smooth-scroll, which rides XI_Motion) - /// reached the widget: hover-scrollbars + wheel dead while clicks - /// (not motion-compressed) worked. Slave-first leaves the master copy - /// — the one Qt keeps — trailing, so it survives compression. - /// Issue #94 follow-up: an XI2 client holding an active `XIGrabDevice` - /// (`owner_events=true`) must receive the grabbed `ButtonRelease` even - /// when the pointer is over a window it never `XISelectEvents`'d on — - /// Xorg `DeliverGrabbedEvent` falls back to grab-window delivery using - /// the grab mask. CEF grabs the pointer on mousedown and holds it to - /// mouseup; the release fires over a window it holds only via the grab, - /// so without the fallback the mouse-up reaches nobody and clicks never - /// complete (Steam nav/menus/close all dead post-crash-fix). - #[test] - fn xi2_grabbed_button_release_reaches_grab_owner_via_grab_window() { - use crate::server::ActivePointerGrab; - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const GC: u32 = 2; // grab owner (CEF-like) - let grab_win = ResourceId(0x0020_0001); // GC's window == grab window - let hit_win = ResourceId(0x0020_0002); // child GC owns but did NOT select on - - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - let mut gc_peer = install_client(&mut state, GC); - - state.resources.create_window( - ClientId(GC), - CreateWindowRequest { - depth: 24, - window: grab_win, - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(GC), - CreateWindowRequest { - depth: 24, - window: hit_win, - parent: grab_win, - x: 10, - y: 10, - width: 40, - height: 40, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(grab_win); - let _ = state.resources.map_window(hit_win); - - // Active XI2 grab held by GC (matching CEF's XIGrabDevice device=2, - // async, owner_events=true). GC has NO XISelectEvents mask anywhere - // — it holds the pointer purely via the grab. - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(GC), - grab_window: grab_win, - event_mask: 0xFFFF, - cursor: ResourceId(0), - time: 0, - owner_events: true, - via_xi2: true, - implicit: false, - passive: false, - xi2_mask: u64::MAX, - }); - - let mut xid_map = HostXidMap::new(); - xid_map.insert(0xCAFE_u32, grab_win); - - let mut rel = motion_event(); - rel.kind = PointerEventKind::ButtonRelease; - rel.host_xid = 0xCAFE; - rel.detail = 1; - rel.root_x = 20; - rel.root_y = 20; - rel.event_x = 20; - rel.event_y = 20; - - let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, rel, true, false); - - let bytes = read_all_available(&mut gc_peer); - let mut found = None; - let mut off = 0usize; - while off + 32 <= bytes.len() { - if bytes[off] == 35 && u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]) == 5 { - found = Some(u32::from_le_bytes( - bytes[off + 24..off + 28].try_into().unwrap(), - )); - break; - } - let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; - off += 32 + length * 4; - } - assert!( - found.is_some(), - "grab owner must receive the grabbed XI2 ButtonRelease (Xorg grab-window fallback); got none" - ); - assert_eq!( - found.unwrap(), - grab_win.0, - "grabbed release must be reported on the grab window" - ); - } - - /// Core grabs use the same grab-window fallback as XI2 grabs: when - /// owner-events delivery finds no selected natural target, the grab - /// owner still receives the event on the grab window. - #[test] - fn core_grabbed_button_release_reaches_grab_owner_via_grab_window() { - use crate::server::ActivePointerGrab; - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - - const OWNER: u32 = 2; - let grab_win = ResourceId(0x0020_0001); - let hit_win = ResourceId(0x0020_0002); - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut owner_peer = install_client(&mut state, OWNER); - - for (window, parent, x, y, width, height) in [ - (grab_win, ROOT_WINDOW, 0, 0, 100, 100), - (hit_win, grab_win, 10, 10, 40, 40), - ] { - state.resources.create_window( - ClientId(OWNER), - CreateWindowRequest { - depth: 24, - window, - parent, - x, - y, - width, - height, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - let _ = state.resources.map_window(grab_win); - let _ = state.resources.map_window(hit_win); - - // No core event mask is selected on either window. Delivery must - // therefore fall back to the grab's event mask and grab window. - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(OWNER), - grab_window: grab_win, - event_mask: 0xFFFF, - cursor: ResourceId(0), - time: 0, - owner_events: true, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }); - - let mut xid_map = HostXidMap::new(); - xid_map.insert(0xCAFE, hit_win); - - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = 0xCAFE; - release.detail = 1; - release.root_x = 20; - release.root_y = 20; - release.event_x = 10; - release.event_y = 10; - - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - // Core ButtonRelease is event code 5 and its event window occupies - // bytes 12..16 of the fixed 32-byte event. - let bytes = read_all_available(&mut owner_peer); - let event_window = bytes.chunks_exact(32).find_map(|event| { - (event[0] & 0x7F == 5) - .then(|| u32::from_le_bytes(event[12..16].try_into().expect("event window bytes"))) - }); - assert_eq!( - event_window, - Some(grab_win.0), - "grabbed core release must be reported on the grab window", - ); - } - - /// Issue #94 follow-up (Steam menu/Library input-wedge, HW-confirmed - /// 2026-07-15): the QUEUE-WHILE-FROZEN gate must key on the UNIFIED - /// device freeze state alone — `xi1_frozen[PTR].frozen()`, i.e. Xorg's - /// `sync.frozen = sync.other || state >= FROZEN` (dix/events.c:1327) — - /// and NOT additionally on the legacy core passive-grab fields - /// (the former passive-grab flag plus a stored frozen event). Both were set - /// together when a sync passive grab activates, but several paths thaw - /// the unified state independently of the core fields (traced: marco's - /// click-to-focus sync grab thawed by a later UngrabKeyboard, and by a - /// SetInputFocus-driven async grab). With the old OR-gate the pointer - /// then queued every event forever with no path to thaw — total input - /// wedge, zap-only (q climbed to 134 while xi1_frozen[PTR]=Thawed, - /// core_passive_grab=Some, frozen_ptr_event still set). Once the unified - /// state is thawed, events MUST flow, never enqueue. - #[test] - fn thawed_unified_state_does_not_queue_despite_lingering_passive_grab() { - use crate::xinput::DEVICEID_SLAVE_POINTER as PTR; - const OWNER: u32 = 3; - let grab_win = yserver_protocol::x11::ResourceId(0x0020_0001); - - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - let _peer = install_client(&mut state, OWNER); - - // A sync passive grab is still active from the core's POV, but the - // unified per-device freeze has already been thawed out-of-band. The - // gate must key on the unified freeze state alone: an active passive - // grab must not resurrect the freeze. (Pre-unification this was a - // second source of truth; the legacy core slots are now gone, so the - // only way to express "frozen" is the unified `xi1_frozen` state — left - // Thawed here, the authoritative signal saying "not frozen".) - state.set_pointer_grab(crate::server::ActivePointerGrab { - owner: ClientId(OWNER), - grab_window: grab_win, - event_mask: 0xffff, - cursor: yserver_protocol::x11::ResourceId(0), - time: 0, - owner_events: false, - via_xi2: false, - implicit: false, - passive: true, - xi2_mask: 0, - }); - assert!( - !state - .xi1_frozen - .get(&PTR) - .is_some_and(crate::server::Xi1Freeze::frozen), - "precondition: unified pointer state is thawed" - ); - - let xid_map = HostXidMap::new(); - let ev = motion_event(); - let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, ev, true, false); - - assert!( - !state - .sync_pending - .iter() - .any(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER), - "a pointer event must NOT be swallowed into the freeze queue when the \ - unified device state is thawed (Xorg gates enqueue on sync.frozen only); \ - got {} queued — the Steam input-wedge", - state - .sync_pending - .iter() - .filter(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER) - .count(), - ); - } - - /// XI2 device propagation stops at the first selected window, across all - /// clients. The leaf selector receives the event and an unrelated - /// selector on an ancestor does not receive a duplicate. Xorg does this - /// for Steam's GTK child / CEF top-level pair; delivering both copies made - /// CEF interpret an ordinary menu click as a client-side-decoration drag. - #[test] - fn xi2_device_event_stops_at_deepest_selected_window() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - let toplevel = ResourceId(0x0020_0001); // owned by client A - let leaf = ResourceId(0x0020_0002); // child of toplevel, owned by A - - let mut state = ServerState::new(); - let mut a_peer = install_client(&mut state, 1); // owns both windows - let mut b_peer = install_client(&mut state, 2); // selects on the toplevel only - - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: toplevel, - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: leaf, - parent: toplevel, - x: 10, - y: 10, - width: 40, - height: 40, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(toplevel); - let _ = state.resources.map_window(leaf); - - // A selects XI_ButtonPress(4) under XIAllDevices(0) on the LEAF. - state - .clients - .get_mut(&1) - .unwrap() - .xi2_masks - .insert((leaf, 0u16), 1 << 4); - // B selects the same event on the TOPLEVEL only. - state - .clients - .get_mut(&2) - .unwrap() - .xi2_masks - .insert((toplevel, 0u16), 1 << 4); - - let mut xid_map = HostXidMap::new(); - xid_map.insert(0xCAFE_u32, toplevel); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: 0xCAFE, - detail: 1, - time: 1, - root_x: 20, - root_y: 20, - event_x: 20, - event_y: 20, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - true, - false, - ); - - // event window is bytes[24..28] of an XI2 device event (GenericEvent - // type 35, evtype at [8..10]). - let button_event_window = |bytes: &[u8]| -> Option { - let mut off = 0usize; - while off + 32 <= bytes.len() { - if bytes[off] == 35 && u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]) == 4 { - return Some(u32::from_le_bytes( - bytes[off + 24..off + 28].try_into().unwrap(), - )); - } - let length = - u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; - off += 32 + length * 4; - } - None - }; - - let a_bytes = read_all_available(&mut a_peer); - let b_bytes = read_all_available(&mut b_peer); - assert_eq!( - button_event_window(&a_bytes), - Some(leaf.0), - "owner/leaf-selector must be reported on the hit leaf" - ); - assert_eq!( - button_event_window(&b_bytes), - None, - "Xorg stops XI2 propagation at the selected leaf; an ancestor \ - selector must not receive a duplicate device event" - ); - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(1), leaf)), - "the implicit grab belongs to the deepest XI2 press recipient" - ); - } - - #[test] - fn xi2_motion_emits_slave_form_before_master_form() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - let mut peer = install_client(&mut state, 1); - // XIAllDevices(0), XI_Motion (evtype 6), on the root — where a - // windowless motion lands. device 0 yields BOTH forms (issue #72). - state - .clients - .get_mut(&1) - .expect("client") - .xi2_masks - .insert((ROOT_WINDOW, 0), 1 << 6); - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - motion_event(), - true, - false, - ); - assert!(dropped.is_empty()); - let bytes = read_all_available(&mut peer); - // Walk the GenericEvent stream, collecting each XI_Motion(6)'s - // deviceid. Layout: [0]=35 GenericEvent, [4..8]=length (extra - // 4-byte units past the 32-byte base), [8..10]=evtype, - // [10..12]=deviceid. - let mut motion_deviceids: Vec = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - assert_eq!(bytes[off], 35, "GenericEvent"); - let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; - let evtype = u16::from_le_bytes(bytes[off + 8..off + 10].try_into().unwrap()); - let deviceid = u16::from_le_bytes(bytes[off + 10..off + 12].try_into().unwrap()); - if evtype == 6 { - motion_deviceids.push(deviceid); - } - off += 32 + length * 4; - } - assert_eq!(off, bytes.len(), "event stream fully consumed"); - assert_eq!( - motion_deviceids, - vec![XI2_SLAVE_POINTER_DEVICE_ID, XI2_MASTER_POINTER_DEVICE_ID], - "XIAllDevices(0) motion selector must receive the slave-stamped \ - form BEFORE the master-stamped form (Xorg mi/mieq.c order); \ - master-first silently breaks Qt smooth-scroll + hover" - ); - } - - #[test] - fn xi2_raw_motion_uses_master_device_and_slave_source_ids() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - let mut peer = install_client(&mut state, 1); - state - .clients - .get_mut(&1) - .expect("client") - .xi2_masks - .insert((ROOT_WINDOW, 0), 1 << 17); - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - motion_event(), - true, - false, - ); - assert!(dropped.is_empty()); - let bytes = read_all_available(&mut peer); - let off = (0..bytes.len().saturating_sub(32)) - .find(|&i| bytes[i] == 35 && u16::from_le_bytes([bytes[i + 8], bytes[i + 9]]) == 17) - .expect("XI_RawMotion event present"); - assert_eq!( - u16::from_le_bytes([bytes[off + 10], bytes[off + 11]]), - XI2_MASTER_POINTER_DEVICE_ID, - "Xorg delivers the mieq master-device copy of raw pointer events" - ); - assert_eq!( - u16::from_le_bytes([bytes[off + 20], bytes[off + 21]]), - XI2_SLAVE_POINTER_DEVICE_ID, - "sourceid must match the originating slave pointer" - ); - } - - #[test] - fn replayed_pointer_press_does_not_repeat_raw_event() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - let mut peer = install_client(&mut state, 1); - state - .clients - .get_mut(&1) - .expect("client") - .xi2_masks - .insert((ROOT_WINDOW, 0), (1 << 4) | (1 << 15)); - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.detail = 1; - - let dropped = replay_frozen_pointer_event_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - press, - ); - assert!(dropped.is_empty()); - - let bytes = read_all_available(&mut peer); - let mut evtypes = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - assert_eq!(bytes[off], 35, "GenericEvent"); - let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; - evtypes.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); - off += 32 + length * 4; - } - assert_eq!(off, bytes.len(), "event stream fully consumed"); - assert!( - evtypes.contains(&4), - "natural XI_ButtonPress must be replayed" - ); - assert!( - !evtypes.contains(&15), - "XI_RawButtonPress describes physical input and must not be replayed" - ); - } - - #[test] - fn button_target_locked_at_generation_survives_restack() { - // Click-below regression. A button generated over the top-level A - // must deliver to A even if a WM raises B above A between the - // press and its fanout. yserver used to re-resolve the target at - // delivery (`root_pointer_target_at` on the current tree), so a - // restack landing in between retargeted the in-flight click to - // the window raised on top — "click lands on the window below". - use crate::resources::{ROOT_VISUAL, ROOT_WINDOW}; - use yserver_protocol::x11::{ConfigureWindowRequest, CreateWindowRequest}; - - let mut state = ServerState::new(); - // Two overlapping full-size top-levels. Create B first, then A, so - // A is on top (create inserts at the top of the stack). - let b = ResourceId(0x0020_0000); - let a = ResourceId(0x0010_0000); - for win in [b, a] { - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: win, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 400, - height: 400, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - } - - // The producer stamped host_xid HA at generation, when A was on top. - let host_a: u32 = 0x0040_0aaa; - let mut xid_map = HostXidMap::new(); - xid_map.insert(host_a, a); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: host_a, - detail: 1, - time: 1, - root_x: 100, - root_y: 100, - event_x: 100, - event_y: 100, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - - // Precondition: A is on top; the press resolves to A. - assert_eq!( - resolve_pointer_hit(&state, &xid_map, &press) - .map(|(t, _, _)| state.top_level_for_target(t)), - Some(a), - "precondition: click resolves to the top window A", - ); - - // A WM raises B above A AFTER the press was generated. - let restacked = state.resources.configure_window(ConfigureWindowRequest { - window: b, - value_mask: 0, - x: None, - y: None, - width: None, - height: None, - border_width: None, - sibling: Some(a), - stack_mode: Some(0), // Above - }); - assert!(restacked.is_some(), "restack applied"); - - // The LIVE hit-test now resolves B (B is topmost). This proves the - // scenario diverges — so a delivery-time re-resolve would pick B. - assert_eq!( - state - .root_pointer_target_at(100, 100) - .map(|(t, _, _)| state.top_level_for_target(t)), - Some(b), - "after the restack, the live hit-test resolves the now-top window B", - ); - - // Regression: the in-flight button must STILL deliver to A — its - // generation-time target — not the restacked-on-top B. - assert_eq!( - resolve_pointer_hit(&state, &xid_map, &press) - .map(|(t, _, _)| state.top_level_for_target(t)), - Some(a), - "button target is locked at event generation; a restack between \ - press and delivery must not retarget it to the window below", - ); - - // A motion event, by contrast, tracks the live pointer (resolves B). - let motion = HostPointerEvent { - kind: PointerEventKind::MotionNotify, - ..press - }; - assert_eq!( - resolve_pointer_hit(&state, &xid_map, &motion) - .map(|(t, _, _)| state.top_level_for_target(t)), - Some(b), - "motion tracks the live pointer (resolves the now-top B)", - ); - } - - #[test] - fn motion_clamps_against_solid_barrier() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - state.pointer_barriers.insert( - 0x0050_0001, - crate::server::PointerBarrier { - owner: ClientId(1), - window: ROOT_WINDOW, - x1: 100, - y1: 0, - x2: 100, - y2: 200, - directions: 0, - devices: Vec::new(), - hit: false, - seen: false, - event_id: 1, - release_event_id: 0, - last_timestamp: 0, - }, - ); - state.pointer_root = (90, 50); - let mut ev = motion_event(); - ev.root_x = 110; - ev.root_y = 50; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - ev, - true, - false, - ); - assert!(dropped.is_empty()); - assert_eq!(state.pointer_root, (99, 50)); - assert_eq!(backend.warped_to, Some((99, 50))); - } - - /// Regression (HW-observed 2026-06-18): the clamp moved only - /// `root_x`, but `translate_host_event` later re-derives - /// `root = window.x + event_x`. With the host window in `xid_map` - /// (the real path — the empty-map case above can't exercise it) - /// that overwrote the clamped root with the un-clamped value, so - /// `pointer_root` ended up *past* the wall and the next motion never - /// re-crossed it — a porous barrier. The clamp must shift `event_x` - /// by the same delta so the wall holds across translate. - #[test] - fn clamp_shifts_event_x_so_pointer_root_holds_across_translate() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - state.pointer_barriers.insert( - 0x0050_0001, - crate::server::PointerBarrier { - owner: ClientId(1), - window: ROOT_WINDOW, - x1: 100, - y1: 0, - x2: 100, - y2: 200, - directions: 0, - devices: Vec::new(), - hit: false, - seen: false, - event_id: 1, - release_event_id: 0, - last_timestamp: 0, - }, - ); - state.pointer_root = (90, 50); - // Map the host window so `translate_host_event` re-derives root - // from `event_x` — ROOT_WINDOW is at (0,0), so root == event_x. - let host_xid = 0x1234_u32; - let mut xid_map = HostXidMap::new(); - xid_map.insert(host_xid, ROOT_WINDOW); - let mut ev = motion_event(); - ev.host_xid = host_xid; - ev.root_x = 110; - ev.root_y = 50; - ev.event_x = 110; - ev.event_y = 50; - let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, ev, true, false); - // Pre-fix this was (110, 50): translate clobbered the clamp. - assert_eq!( - state.pointer_root, - (99, 50), - "pointer_root must hold at the wall (x1-1), not snap back past it" - ); - assert_eq!(backend.warped_to, Some((99, 50))); - } - - #[test] - fn barrier_bypass_skips_clamp() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - state.pointer_barriers.insert( - 0x0050_0001, - crate::server::PointerBarrier { - owner: ClientId(1), - window: ROOT_WINDOW, - x1: 100, - y1: 0, - x2: 100, - y2: 200, - directions: 0, - devices: Vec::new(), - hit: false, - seen: false, - event_id: 1, - release_event_id: 0, - last_timestamp: 0, - }, - ); - state.pointer_root = (90, 50); - state.barrier_bypass = true; - let mut ev = motion_event(); - ev.root_x = 110; - ev.root_y = 50; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - ev, - true, - false, - ); - assert!(dropped.is_empty()); - assert_eq!(state.pointer_root, (110, 50)); - assert_eq!(backend.warped_to, None); - } - - #[test] - fn barrier_hit_event_delivered_to_selecting_client() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - let mut peer = install_client(&mut state, 1); - state - .clients - .get_mut(&1) - .expect("client") - .xi2_masks - .insert((ROOT_WINDOW, 2), 1 << 25); - let bid = 0x0050_0002; - state.pointer_barriers.insert( - bid, - crate::server::PointerBarrier { - owner: ClientId(1), - window: ROOT_WINDOW, - x1: 100, - y1: 0, - x2: 100, - y2: 200, - directions: 0, - devices: Vec::new(), - hit: false, - seen: false, - event_id: 1, - release_event_id: 0, - last_timestamp: 0, - }, - ); - state.pointer_root = (90, 50); - let mut ev = motion_event(); - ev.root_x = 110; - ev.root_y = 50; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - ev, - true, - false, - ); - assert!(dropped.is_empty()); - assert_eq!(state.pointer_root, (99, 50)); - assert!(state.pointer_barriers.get(&bid).expect("barrier").hit); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 68); - assert_eq!(bytes[0], 35, "GenericEvent"); - assert_eq!(bytes[1], 137, "XI2 major opcode"); - assert_eq!(&bytes[4..8], &9u32.to_le_bytes(), "length"); - assert_eq!(&bytes[8..10], &25u16.to_le_bytes(), "BarrierHit"); - assert_eq!(&bytes[28..32], &bid.to_le_bytes(), "barrier xid"); - assert_eq!( - &bytes[44..48], - &(99i32 << 16).to_le_bytes(), - "root_x FP1616" - ); - } - - /// Regression (HW-observed 2026-06-18): a client that selected - /// BarrierHit under the `XIAllMasterDevices` wildcard (deviceid 1) — - /// what libXi's `XISelectEvents(XIAllMasterDevices, …)` stores — - /// received NO barrier events, because `barrier_xi2_targets` only - /// queried the concrete master-pointer id (2). With no HIT events the - /// client could never call `XIBarrierReleasePointer`, so the pointer - /// was pinned at the wall forever. Selection under the wildcard must - /// deliver. - #[test] - fn barrier_hit_delivered_for_xiallmasterdevices_selection() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - let mut peer = install_client(&mut state, 1); - // Wildcard device 1 (XIAllMasterDevices), NOT the concrete id 2. - state - .clients - .get_mut(&1) - .expect("client") - .xi2_masks - .insert((ROOT_WINDOW, 1), 1 << 25); - let bid = 0x0050_0004; - state.pointer_barriers.insert( - bid, - crate::server::PointerBarrier { - owner: ClientId(1), - window: ROOT_WINDOW, - x1: 100, - y1: 0, - x2: 100, - y2: 200, - directions: 0, - devices: Vec::new(), - hit: false, - seen: false, - event_id: 1, - release_event_id: 0, - last_timestamp: 0, - }, - ); - state.pointer_root = (90, 50); - let mut ev = motion_event(); - ev.root_x = 110; - ev.root_y = 50; - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - ev, - true, - false, - ); - let bytes = read_all_available(&mut peer); - assert_eq!( - bytes.len(), - 68, - "BarrierHit must be delivered to the wildcard selector" - ); - assert_eq!(&bytes[8..10], &25u16.to_le_bytes(), "BarrierHit"); - assert_eq!(&bytes[28..32], &bid.to_le_bytes(), "barrier xid"); - } - - #[test] - fn release_lets_pointer_cross_then_rearms() { - let mut state = ServerState::new(); - let mut backend = crate::backend::recording::RecordingBackend::new(); - let bid = 0x0050_0003; - state.pointer_barriers.insert( - bid, - crate::server::PointerBarrier { - owner: ClientId(1), - window: ROOT_WINDOW, - x1: 100, - y1: 0, - x2: 100, - y2: 200, - directions: 0, - devices: Vec::new(), - hit: true, - seen: false, - event_id: 1, - release_event_id: 1, - last_timestamp: 10, - }, - ); - state.pointer_root = (90, 50); - let mut ev = motion_event(); - ev.root_x = 110; - ev.root_y = 50; - ev.time = 20; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - ev, - true, - false, - ); - assert!(dropped.is_empty()); - assert_eq!(state.pointer_root, (110, 50)); - let barrier = state.pointer_barriers.get(&bid).expect("barrier"); - assert!(!barrier.hit, "leave sweep should clear hit"); - assert_eq!(barrier.event_id, 2, "leave sweep re-arms the barrier"); - - let mut ev2 = motion_event(); - ev2.root_x = 90; - ev2.root_y = 50; - ev2.time = 21; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &HostXidMap::new(), - ev2, - true, - false, - ); - assert!(dropped.is_empty()); - assert_eq!( - state.pointer_root, - (100, 50), - "re-armed barrier clamps again" - ); - } - - /// wmaker wedge regression (2026-06-04, silence HW): a WM places a - /// SYNCHRONOUS `owner_events=true` button grab on a CLIENT's window - /// (click-to-focus). A press on that window's subtree must be - /// reported to the GRAB CLIENT on the grab window — per Xorg - /// `DeliverGrabbedEvent` (dix/events.c:4361), the `owner_events` - /// natural walk is filtered to the grab client: `TryClientEvents` - /// (dix/events.c:2069) returns -1 for any other client ("not - /// delivered due to grab"), aborting propagation, and the event - /// falls back to the grab window. Pre-fix, the descendant arm of - /// `target_qualifies_for_natural` leaked the press to the app - /// client while the sync grab froze the queue — the WM never saw - /// the press, never called AllowEvents, and the pointer stream - /// stayed frozen forever (cursor moves, clicks dead). - #[test] - fn passive_sync_grab_on_foreign_window_delivers_to_grab_client_and_freezes() { - use yserver_protocol::x11::ResourceId; - - let mut state = ServerState::new(); - let grab_window = ResourceId(0x0020_0001); // app client's top-level - let child_window = ResourceId(0x0020_0002); // GL child producing the click - - let mut wm_peer = install_client(&mut state, 1); - let mut app_peer = install_client(&mut state, 2); - - state.resources.create_window( - ClientId(2), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: grab_window, - parent: crate::resources::ROOT_WINDOW, - x: 610, - y: 250, - width: 1280, - height: 800, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(2), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: child_window, - parent: grab_window, - x: 0, - y: 0, - width: 1280, - height: 800, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(grab_window); - let _ = state.resources.map_window(child_window); - - // The WM has NO event mask anywhere on the chain — its - // interest is expressed solely via the grab. The app client - // selects ButtonPress on its child (the leak target pre-fix). - state - .clients - .get_mut(&2) - .unwrap() - .event_masks - .insert(child_window, 0x0000_0004); - - // wmaker idiom: XGrabButton(AnyButton, AnyModifier, client_win, - // owner_events=True, ButtonPressMask, GrabModeSync, - // GrabModeAsync). - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(1), - grab_window, - button: 0, // AnyButton - modifiers: 0x8000, // AnyModifier - owner_events: true, - event_mask: 0x0000_0004, // ButtonPressMask - pointer_mode: 0, // GrabModeSync - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: false, - }); - - let mut xid_map = HostXidMap::new(); - // KMS stamps the actual GL child as the producer but event_x/y are - // root-relative. The Steam trace had root/event=(909,299) while - // the grabbed toplevel was at (610,250). - xid_map.insert(0xCAFE_u32, child_window); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: 0xCAFE, - detail: 1, - time: 0, - root_x: 909, - root_y: 299, - event_x: 909, - event_y: 299, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - true, - false, - ); - - let wm_bytes = read_all_available(&mut wm_peer); - assert!( - wm_bytes.len() >= 32, - "sync passive grab must deliver the activating press to the \ - grab client (the WM) — otherwise nobody ever AllowEvents and \ - the frozen pointer queue wedges; got {} bytes", - wm_bytes.len(), - ); - assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); - assert_eq!( - &wm_bytes[12..16], - &grab_window.0.to_le_bytes(), - "press must be reported on the grab window (Xorg grab-window \ - fallback — the grab client has no mask on the natural chain)", - ); - assert_eq!( - i16::from_le_bytes([wm_bytes[24], wm_bytes[25]]), - 299, - "event-x must be relative to the passive grab window", - ); - assert_eq!( - i16::from_le_bytes([wm_bytes[26], wm_bytes[27]]), - 49, - "event-y must be relative to the passive grab window", - ); - - let app_bytes = read_all_available(&mut app_peer); - let app_core: Vec<&[u8]> = app_bytes.chunks(32).filter(|c| c[0] == 4).collect(); - assert!( - app_core.is_empty(), - "the app client must NOT see the core press while the grab \ - holds (Xorg TryClientEvents: 'not delivered due to grab'); \ - got {} core ButtonPress event(s)", - app_core.len(), - ); - - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_some(), - "GrabModeSync activation must freeze the pointer queue", - ); - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(1), grab_window)), - "passive grab must be active for client 1", - ); - } - - /// icewm framed-taskbar regression (2026-07-01, air HW): icewm - /// frames its OWN taskbar as a managed client and puts a sync - /// AnyModifier `owner_events=true` button grab on the client - /// container (`YClientContainer::grabButtons`). The taskbar widgets - /// are descendants of that container and — being icewm's own - /// windows — ALSO select ButtonPress. The activating press must - /// still be reported on the GRAB WINDOW (the container), because - /// Xorg moves the sprite up to the grab window on activation - /// (`ActivatePointerGrab` → `DoEnterLeaveEvents` NotifyGrab). Only - /// then does icewm's `YClientContainer::handleButton` run and call - /// `XAllowEvents(ReplayPointer)`. Pre-fix the press leaked to the - /// deepest widget (whose handler never thaws), wedging every panel - /// click. The reported `child` is the container's child on the path - /// toward the pointer (Xorg `FindChildForEvent`). - #[test] - fn passive_sync_grab_reports_activating_press_on_grab_window_not_owned_descendant() { - use yserver_protocol::x11::ResourceId; - - let mut state = ServerState::new(); - let container = ResourceId(0x0020_0001); // grab window (client container) - let client_win = ResourceId(0x0020_0002); // framed taskbar client - let widget = ResourceId(0x0020_0003); // a taskbar button - - let mut wm_peer = install_client(&mut state, 1); - - for (win, parent, x, y, w, h) in [ - (container, crate::resources::ROOT_WINDOW, 0, 0, 400, 24), - (client_win, container, 0, 0, 400, 24), - (widget, client_win, 10, 5, 40, 15), - ] { - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: win, - parent, - x, - y, - width: w, - height: h, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - // icewm selects ButtonPress on the container AND every widget. - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(win, 0x0000_0004); - } - - // icewm idiom: XGrabButton(button, AnyModifier, container, - // owner_events=True, ButtonPressMask, GrabModeSync, GrabModeAsync). - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(1), - grab_window: container, - button: 1, - modifiers: 0x8000, // AnyModifier - owner_events: true, - event_mask: 0x0000_0004, // ButtonPressMask - pointer_mode: 0, // GrabModeSync - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: false, - }); - - let mut xid_map = HostXidMap::new(); - xid_map.insert(0xCAFE_u32, container); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - // Press over the widget at (20, 8) relative to the container - // (inside the widget, which spans x∈[10,50) y∈[5,20)). - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: 0xCAFE, - detail: 1, - time: 0, - root_x: 20, - root_y: 8, - event_x: 20, - event_y: 8, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - true, - false, - ); - - let wm_bytes = read_all_available(&mut wm_peer); - assert!(wm_bytes.len() >= 32, "grab client must receive the press"); - assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); - assert_eq!( - &wm_bytes[12..16], - &container.0.to_le_bytes(), - "activating press must be reported on the GRAB WINDOW (the \ - container), not the owned descendant widget — Xorg moves the \ - sprite up to the grab window on activation", - ); - assert_eq!( - &wm_bytes[16..20], - &client_win.0.to_le_bytes(), - "child must be the grab window's child on the path toward the \ - pointer (Xorg FindChildForEvent)", - ); - // event-x/y are relative to the grab window (container at 0,0). - assert_eq!( - i16::from_le_bytes([wm_bytes[24], wm_bytes[25]]), - 20, - "event-x is relative to the grab window", - ); - assert_eq!( - i16::from_le_bytes([wm_bytes[26], wm_bytes[27]]), - 8, - "event-y is relative to the grab window", - ); - - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_some(), - "GrabModeSync activation must freeze the pointer queue", - ); - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(1), container)), - "passive grab must be active for client 1", - ); - } - - /// icewm stuck-tooltip regression (2026-07-01, air HW): activating a - /// passive grab must emit the `NotifyGrab` Leave/Enter crossing chain - /// (Xorg `ActivatePointerGrab` → `DoEnterLeaveEvents(sprite → grab - /// window)`). icewm's `YWindow::handleCrossing` hides a panel tooltip - /// on ANY LeaveNotify; without the widget's grab-Leave the tooltip - /// showing on the clicked panel item never disappears (traced: - /// tooltip windows Created+Mapped, never Destroyed). - #[test] - fn passive_grab_activation_emits_notify_grab_leave_on_the_sprite_widget() { - use yserver_protocol::x11::ResourceId; - - let mut state = ServerState::new(); - let container = ResourceId(0x0020_0001); // grab window - let client_win = ResourceId(0x0020_0002); - let widget = ResourceId(0x0020_0003); // the hovered panel item - - let mut wm_peer = install_client(&mut state, 1); - - for (win, parent, x, y, w, h) in [ - (container, crate::resources::ROOT_WINDOW, 0, 0, 400, 24), - (client_win, container, 0, 0, 400, 24), - (widget, client_win, 10, 5, 40, 15), - ] { - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: win, - parent, - x, - y, - width: w, - height: h, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - // icewm selects ButtonPress | EnterWindow | LeaveWindow. - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(win, 0x0000_0004 | 0x0000_0010 | 0x0000_0020); - } - - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(1), - grab_window: container, - button: 1, - modifiers: 0x8000, - owner_events: true, - event_mask: 0x0000_0004, - pointer_mode: 0, - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: false, - }); - - let mut xid_map = HostXidMap::new(); - xid_map.insert(0xCAFE_u32, container); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: 0xCAFE, - detail: 1, - time: 0, - root_x: 20, - root_y: 8, - event_x: 20, - event_y: 8, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - true, - false, - ); - - // LeaveNotify = type 8; mode byte is at offset 30; NotifyGrab = 1. - let leave_grab_on_widget = read_all_available(&mut wm_peer) - .chunks(32) - .filter(|c| c.len() == 32) - .any(|c| c[0] == 8 && c[30] == 1 && c[12..16] == widget.0.to_le_bytes()); - assert!( - leave_grab_on_widget, - "grab activation must deliver LeaveNotify(mode=Grab) on the \ - sprite widget so icewm dismisses its panel tooltip", - ); - } - - /// icewm never-disappearing-tooltip regression (2026-07-02, air HW). - /// A NORMAL-mode crossing chain (no grab, pure hover) between two - /// sibling widgets A→B must deliver A's `LeaveNotify` on window A — - /// even though the cursor now physically sits over sibling B, so the - /// live deepest hit is B. The producer (`update_pointer_window` → - /// `normal_mode_crossings`) stamps each chain event with its own - /// window's `host_xid`; core delivery must honour that per-window - /// endpoint, not collapse every chain event onto the live deepest - /// hit. Pre-fix, `resolve_pointer_hit` re-resolved crossings to the - /// live hit (B) for BOTH the Leave and the Enter, so widget A never - /// saw a LeaveNotify with `event=A` and icewm's per-widget tooltip - /// (hidden on any LeaveNotify) orphaned. The XI2 path already - /// resolved crossings per-window; this pins the core path to match. - #[test] - fn normal_crossing_leave_delivers_on_left_sibling_not_live_hit() { - use yserver_protocol::x11::ResourceId; - - let mut state = ServerState::new(); - let client_win = ResourceId(0x0020_0001); - let widget_a = ResourceId(0x0020_0002); // pointer leaving this - let widget_b = ResourceId(0x0020_0003); // pointer now over this - - let mut peer = install_client(&mut state, 1); - let mut xi_peer = install_client(&mut state, 2); - - for (win, parent, x, y, w, h) in [ - (client_win, crate::resources::ROOT_WINDOW, 0, 0, 400, 24), - (widget_a, client_win, 10, 5, 40, 15), // abs (10,5)-(50,20) - (widget_b, client_win, 60, 5, 40, 15), // abs (60,5)-(100,20) - ] { - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: win, - parent, - x, - y, - width: w, - height: h, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - // icewm selects EnterWindow | LeaveWindow on each widget. - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(win, 0x0000_0010 | 0x0000_0020); - // A second client selects the XI2 crossing form so the same - // per-window coordinates and crossing detail are pinned there. - state - .clients - .get_mut(&2) - .unwrap() - .xi2_masks - .insert((win, 0), (1 << 7) | (1 << 8)); - } - - let mut xid_map = HostXidMap::new(); - xid_map.insert(0xA001_u32, widget_a); - xid_map.insert(0xB001_u32, widget_b); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - // Cursor now sits over widget B (root (70,10)); the producer emits - // the Leave for A and the Enter for B at that same position. - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - HostPointerEvent { - kind: PointerEventKind::LeaveNotify, - host_xid: 0xA001, // the window being LEFT - detail: 3, // Nonlinear - time: 1, - root_x: 70, - root_y: 10, - event_x: 60, // relative to widget_a origin (10,5) - event_y: 5, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - true, - false, - ); - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - HostPointerEvent { - kind: PointerEventKind::EnterNotify, - host_xid: 0xB001, // the window being ENTERED - detail: 3, // Nonlinear - time: 1, - root_x: 70, - root_y: 10, - event_x: 10, // relative to widget_b origin (60,5) - event_y: 5, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - true, - false, - ); - - // LeaveNotify = type 8; event window at bytes 12..16. - let events: Vec<[u8; 32]> = read_all_available(&mut peer) - .chunks(32) - .filter(|c| c.len() == 32) - .map(|c| c.try_into().unwrap()) - .collect(); - let leave_on_a = events - .iter() - .any(|c| c[0] == 8 && c[12..16] == widget_a.0.to_le_bytes()); - let enter_on_b = events - .iter() - .any(|c| c[0] == 7 && c[12..16] == widget_b.0.to_le_bytes()); - assert!( - leave_on_a, - "LeaveNotify must be delivered on the window being LEFT (widget A), \ - not collapsed onto the live deepest hit (widget B); icewm hides its \ - per-widget tooltip on this Leave", - ); - assert!( - enter_on_b, - "EnterNotify must be delivered on the window being ENTERED (widget B)", - ); - let leave_on_a = events - .iter() - .find(|c| c[0] == 8 && c[12..16] == widget_a.0.to_le_bytes()) - .unwrap(); - assert_eq!( - i16::from_le_bytes(leave_on_a[24..26].try_into().unwrap()), - 60 - ); - assert_eq!( - i16::from_le_bytes(leave_on_a[26..28].try_into().unwrap()), - 5 - ); - let enter_on_b = events - .iter() - .find(|c| c[0] == 7 && c[12..16] == widget_b.0.to_le_bytes()) - .unwrap(); - assert_eq!( - i16::from_le_bytes(enter_on_b[24..26].try_into().unwrap()), - 10 - ); - assert_eq!( - i16::from_le_bytes(enter_on_b[26..28].try_into().unwrap()), - 5 - ); - - let xi_bytes = read_all_available(&mut xi_peer); - let xi_events: Vec<&[u8]> = xi_bytes.chunks(76).collect(); - assert_eq!( - xi_events.len(), - 4, - "XIAllDevices receives slave + master forms of Leave + Enter" - ); - let xi_leave = xi_events - .iter() - .find(|e| u16::from_le_bytes(e[8..10].try_into().unwrap()) == 8) - .unwrap(); - assert_eq!(xi_leave[19], 3, "XI2 Leave preserves NotifyNonlinear"); - assert_eq!( - i32::from_le_bytes(xi_leave[40..44].try_into().unwrap()) >> 16, - 60 - ); - assert_eq!( - i32::from_le_bytes(xi_leave[44..48].try_into().unwrap()) >> 16, - 5 - ); - let xi_enter = xi_events - .iter() - .find(|e| u16::from_le_bytes(e[8..10].try_into().unwrap()) == 7) - .unwrap(); - assert_eq!(xi_enter[19], 3, "XI2 Enter preserves NotifyNonlinear"); - assert_eq!( - i32::from_le_bytes(xi_enter[40..44].try_into().unwrap()) >> 16, - 10 - ); - assert_eq!( - i32::from_le_bytes(xi_enter[44..48].try_into().unwrap()) >> 16, - 5 - ); - } - - /// openbox resize regression: an active core grab can live on a - /// tiny hidden helper window while the WM selects motion on a - /// visible frame window containing a foreign app child. With - /// `owner_events=true`, motion over that foreign child must still - /// propagate naturally to the WM's frame window, not redirect to - /// the helper grab window. - #[test] - fn active_grab_owner_events_uses_grab_client_filtered_propagation() { - use crate::{backend::Backend, resources::ROOT_VISUAL, server::ActivePointerGrab}; - - const WM_CLIENT_ID: u32 = 1; - const APP_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0080; - const FRAME_WIN: u32 = 0x0010_0081; - const APP_CHILD_WIN: u32 = 0x0020_0082; - const HOST_FRAME_XID: u32 = 0xCAFE_0081; - - let mut state = ServerState::new(); - let mut wm_peer = install_client(&mut state, WM_CLIENT_ID); - let mut backend = RecordingBackend::new(); - wm_peer.set_nonblocking(true).expect("nonblocking"); - - state.resources.create_window( - ClientId(WM_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: -100, - y: -100, - width: 1, - height: 1, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(WM_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(FRAME_WIN), - parent: ROOT_WINDOW, - x: 500, - y: 300, - width: 200, - height: 150, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(APP_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(APP_CHILD_WIN), - parent: ResourceId(FRAME_WIN), - x: 20, - y: 20, - width: 100, - height: 80, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - let _ = state.resources.map_window(ResourceId(FRAME_WIN)); - let _ = state.resources.map_window(ResourceId(APP_CHILD_WIN)); - - state - .clients - .get_mut(&WM_CLIENT_ID) - .expect("wm client") - .event_masks - .insert(ResourceId(FRAME_WIN), 0x0000_0040); - - Backend::register_top_level(&mut backend, None, ResourceId(FRAME_WIN), HOST_FRAME_XID) - .expect("register frame host xid"); - - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(WM_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - event_mask: 0x0000_0040, - cursor: ResourceId(0), - time: 0, - owner_events: true, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }); - - let motion = HostPointerEvent { - kind: PointerEventKind::MotionNotify, - host_xid: HOST_FRAME_XID, - detail: 0, - time: 0x2000, - root_x: 545, - root_y: 345, - event_x: 45, - event_y: 45, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); - assert!(dropped.is_empty()); - - let mut buf = [0u8; 32]; - let n = wm_peer.read(&mut buf).expect("wm got motion"); - assert_eq!(n, 32, "expected one core MotionNotify"); - assert_eq!(buf[0], 6, "event type should be MotionNotify"); - assert_eq!( - &buf[12..16], - &FRAME_WIN.to_le_bytes(), - "motion must report against the WM-selected frame window, not the hidden grab helper", - ); - assert_eq!( - i16::from_le_bytes([buf[24], buf[25]]), - 45, - "event_x must stay frame-relative", - ); - assert_eq!( - i16::from_le_bytes([buf[26], buf[27]]), - 45, - "event_y must stay frame-relative", - ); - } - - /// Regression (#90, ImageMagick `import` on real HW): an active core - /// pointer grab that selected `ButtonMotion` but NOT `PointerMotion` - /// must not be fed no-button motion. `import` does - /// `XGrabPointer(owner_events=false, - /// ButtonPress|ButtonRelease|ButtonMotion|OwnerGrabButton)`; pre-fix - /// yserver delivered every MotionNotify (incl. state=0), so `import` - /// drew its selection rectangle from the origin before any button was - /// pressed. Xorg `DeliverGrabbedEvent` only reports events the grab's - /// mask selected — but still CAPTURES the rest (never propagates them - /// to the natural target). - #[test] - fn active_grab_buttonmotion_mask_suppresses_no_button_motion() { - use crate::{backend::Backend, resources::ROOT_VISUAL, server::ActivePointerGrab}; - - const WM_CLIENT_ID: u32 = 1; - const APP_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0090; - const APP_WIN: u32 = 0x0020_0091; - const HOST_APP_XID: u32 = 0xCAFE_0091; - // ButtonPress | ButtonRelease | ButtonMotion (import's mask minus - // OwnerGrabButton, which is not a delivery-selection bit). Note it - // deliberately does NOT include PointerMotion (0x40). - const IMPORT_MASK: u32 = 0x0000_0004 | 0x0000_0008 | 0x0000_2000; - - let mut state = ServerState::new(); - let mut wm_peer = install_client(&mut state, WM_CLIENT_ID); - let mut app_peer = install_client(&mut state, APP_CLIENT_ID); - let mut backend = RecordingBackend::new(); - - // Tiny offscreen helper window owned by the grab client (import's - // grab is on the root, but any grab window exercises the same - // owner_events=false redirect path). - state.resources.create_window( - ClientId(WM_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: -100, - y: -100, - width: 1, - height: 1, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - // A foreign app window the pointer is actually over; it selects - // PointerMotion so we can prove the grab CAPTURES the suppressed - // motion rather than leaking it to the natural target. - state.resources.create_window( - ClientId(APP_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(APP_WIN), - parent: ROOT_WINDOW, - x: 400, - y: 300, - width: 300, - height: 200, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - let _ = state.resources.map_window(ResourceId(APP_WIN)); - - state - .clients - .get_mut(&APP_CLIENT_ID) - .expect("app client") - .event_masks - .insert(ResourceId(APP_WIN), 0x0000_0040); // PointerMotion - - Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP_XID) - .expect("register app host xid"); - - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(WM_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - event_mask: IMPORT_MASK as u16, - cursor: ResourceId(0), - time: 0, - owner_events: false, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }); - - let xid_map = backend.xid_map().clone(); - - // (1) No-button motion (state=0): ButtonMotion mask must suppress - // delivery to the grab client, AND the grab must capture it so - // it never reaches the app's PointerMotion selection. - let no_button_motion = HostPointerEvent { - kind: PointerEventKind::MotionNotify, - host_xid: HOST_APP_XID, - detail: 0, - time: 0x1000, - root_x: 450, - root_y: 350, - event_x: 50, - event_y: 50, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - no_button_motion, - true, - false, - ); - assert!(dropped.is_empty()); - assert!( - read_all_available(&mut wm_peer).is_empty(), - "grab client selected ButtonMotion (not PointerMotion) — no-button motion must NOT be delivered", - ); - assert!( - read_all_available(&mut app_peer).is_empty(), - "active grab must CAPTURE the suppressed motion, not leak it to the app's natural PointerMotion selection", - ); - - // (2) Motion with Button1 held (state=0x100): now the event - // carries the ButtonMotion bit → the grab client receives it, - // reported against the grab window (owner_events=false). - let button_motion = HostPointerEvent { - kind: PointerEventKind::MotionNotify, - host_xid: HOST_APP_XID, - detail: 0, - time: 0x1001, - root_x: 451, - root_y: 351, - event_x: 51, - event_y: 51, - state: 0x0100, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let dropped = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - button_motion, - true, - false, - ); - assert!(dropped.is_empty()); - let wm_bytes = read_all_available(&mut wm_peer); - assert_eq!(wm_bytes.len(), 32, "expected exactly one core MotionNotify"); - assert_eq!(wm_bytes[0], 6, "event type should be MotionNotify"); - assert_eq!( - &wm_bytes[12..16], - &GRAB_WIN.to_le_bytes(), - "owner_events=false: motion reported against the grab window", - ); - assert!( - read_all_available(&mut app_peer).is_empty(), - "button-held motion is still captured by the grab, not sent to the app", - ); - - // (3) ButtonPress (mask includes ButtonPress) is still delivered. - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_APP_XID, - detail: 1, - time: 0x1002, - root_x: 451, - root_y: 351, - event_x: 51, - event_y: 51, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!(dropped.is_empty()); - let wm_bytes = read_all_available(&mut wm_peer); - assert_eq!(wm_bytes.len(), 32, "expected exactly one core ButtonPress"); - assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); - assert_eq!( - &wm_bytes[12..16], - &GRAB_WIN.to_le_bytes(), - "owner_events=false: press reported against the grab window", - ); - } - - #[test] - fn pointer_event_resets_dpms_last_activity() { - use std::time::{Duration, Instant}; - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - state.dpms.last_activity = Instant::now() - Duration::from_secs(10); - let stale = state.dpms.last_activity; - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - let elapsed = state.dpms.last_activity.duration_since(stale); - assert!( - elapsed > Duration::from_secs(9), - "last_activity should be ≈now, not stale" - ); - } - - #[test] - fn pointer_event_during_off_wakes_via_set_dpms_power_on() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - state.dpms.power_level = 3; // Off - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - let calls = backend.calls.lock().unwrap().clone(); - assert!( - calls - .iter() - .any(|c| matches!(c, crate::backend::recording::RecordedCall::SetDpmsPower(0))), - "wake must call set_dpms_power(0); got {calls:?}" - ); - assert_eq!( - state.dpms.power_level, 0, - "in-memory level should be On after wake" - ); - } - - #[test] - fn pointer_event_during_off_with_backend_error_still_advances_state() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - state.dpms.power_level = 3; - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - backend.dpms_set_returns_err = true; - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - assert_eq!( - state.dpms.power_level, 0, - "state must advance on backend error" - ); - } - - #[test] - fn pointer_event_during_screen_saver_on_flips_off_via_independent_path() { - // Standalone SS-On (DPMS still On). Motion event must flip - // SS Off with forced=0. - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - // dpms.power_level already 0 from new() - state.screensaver.active = ScreenSaverActive::On; - state.screensaver.selected_by.insert(ClientId(1), 0x01); - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - assert_eq!(state.screensaver.active, ScreenSaverActive::Off); - assert!(!state.screensaver.forced, "input-driven Off is non-forced"); - } - - #[test] - fn pointer_event_updates_global_and_per_device_vcp_last_activity() { - use std::time::Duration; - let mut state = ServerState::new(); - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(30); - let stale = state.dpms.last_activity; - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - assert!( - state.dpms.last_activity > stale, - "global last_activity advanced" - ); - let vcp = state - .per_device_last_activity - .get(&2) - .copied() - .expect("VCP per-device entry inserted"); - assert!(vcp > stale, "VCP per-device last_activity advanced"); - } - - #[test] - fn pointer_event_fires_neg_transition_alarm_when_prior_idle_crosses_threshold() { - use std::time::Duration; - use yserver_protocol::x11::sync as x11sync; - let mut state = ServerState::new(); - // User idle for 90s, NegativeTransition alarm at 60s. - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(90); - state - .per_device_last_activity - .insert(2, std::time::Instant::now() - Duration::from_secs(90)); - let alarm_id = 0x4000; - state.sync_alarms.insert( - alarm_id, - crate::server::SyncAlarm { - owner: ClientId(1), - counter: x11sync::IDLETIME_DEVICE_VCP, - wait_value: 60_000, - delta: 0, - test_type: x11sync::TEST_NEGATIVE_TRANSITION, - events: false, - state: x11sync::ALARM_STATE_ACTIVE, - event_clients: Vec::new(), - value_type: 0, - raw_wait: 60_000, - check_type: x11sync::TEST_NEGATIVE_TRANSITION, - }, - ); - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - // Alarm stays Active (Transition + delta=0 — Task 2 fix); cache reflects post-wake idle=0. - assert_eq!( - state.sync_alarms[&alarm_id].state, - x11sync::ALARM_STATE_ACTIVE - ); - assert_eq!( - state - .idletime_last_evaluated - .get(&x11sync::IDLETIME_DEVICE_VCP) - .copied(), - Some(0), - "post-wake last_evaluated should be 0" - ); - } - - #[test] - fn pointer_event_fires_neg_transition_alarm_on_per_device_idletime_vcp() { - use std::time::Duration; - use yserver_protocol::x11::sync as x11sync; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(90); - state - .per_device_last_activity - .insert(2, std::time::Instant::now() - Duration::from_secs(90)); - let alarm_id = 0x5000; - state.sync_alarms.insert( - alarm_id, - crate::server::SyncAlarm { - owner: ClientId(1), - counter: x11sync::IDLETIME_DEVICE_VCP, - wait_value: 60_000, - delta: 0, - test_type: x11sync::TEST_NEGATIVE_TRANSITION, - events: true, // load-bearing - state: x11sync::ALARM_STATE_ACTIVE, - event_clients: Vec::new(), - value_type: 0, - raw_wait: 60_000, - check_type: x11sync::TEST_NEGATIVE_TRANSITION, - }, - ); - let xid_map = HostXidMap::new(); - let mut backend = crate::backend::recording::RecordingBackend::default(); - - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - motion_event(), - true, - false, - ); - - // PRIMARY: AlarmNotify event type 84. - let bytes = read_all_available(&mut peer); - // AlarmNotify is a 32-byte sequential event; type byte at offset 0. - assert!( - bytes.len() >= 32, - "expected AlarmNotify event (32B); got {} bytes", - bytes.len() - ); - assert_eq!( - bytes[0], 84, - "AlarmNotify event type (SYNC_FIRST_EVENT + 1)" - ); - assert_eq!(bytes[1], 1, "AlarmNotify kind = AlarmNotify (1)"); - assert_eq!( - state.sync_alarms[&alarm_id].state, - x11sync::ALARM_STATE_ACTIVE - ); - assert_eq!( - state - .idletime_last_evaluated - .get(&x11sync::IDLETIME_DEVICE_VCP) - .copied(), - Some(0) - ); - } - - /// Regression (e27 clicks dead): the device classification that gates - /// both the core/XI2 dedup and the XI2 `deviceid` stamp. A client - /// selecting on the SLAVE pointer must classify as slave (so the dedup - /// leaves its CORE ButtonPress intact — Enlightenment needs the core - /// click); a client selecting the MASTER, `XIAllMasterDevices`, or - /// `XIAllDevices` must classify as master (so it is still deduped, - /// preserving Chromium's no-double-ButtonPress fix). HW-confirmed on - /// both e27 (clicks work) and Chrome (no double-click) 2026-06-25. - #[test] - fn xi2_stamp_deviceid_classifies_slave_vs_master_selectors() { - let mut state = ServerState::new(); - let _p1 = install_client(&mut state, 1); - let _p2 = install_client(&mut state, 2); - let _p3 = install_client(&mut state, 3); - let _p4 = install_client(&mut state, 4); - let win = ResourceId(0x10_0009); - const XI_BUTTON_PRESS_MASK: u32 = 1 << 4; - // client 1: slave-pointer selection (Enlightenment's pattern). - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (win, XI2_SLAVE_POINTER_DEVICE_ID), - u64::from(XI_BUTTON_PRESS_MASK), - ); - // client 2: master-pointer selection (Chromium's pattern). - state.clients.get_mut(&2).unwrap().xi2_masks.insert( - (win, XI2_MASTER_POINTER_DEVICE_ID), - u64::from(XI_BUTTON_PRESS_MASK), - ); - // client 3: XIAllMasterDevices (1) wildcard. - state - .clients - .get_mut(&3) - .unwrap() - .xi2_masks - .insert((win, 1), u64::from(XI_BUTTON_PRESS_MASK)); - // client 4: no XI2 selection at all. - - assert_eq!( - xi2_stamp_deviceid(&state, ClientId(1), win, win, 4), - XI2_SLAVE_POINTER_DEVICE_ID, - "slave-device selector must stay slave (keeps core delivery)" - ); - assert_eq!( - xi2_stamp_deviceid(&state, ClientId(2), win, win, 4), - XI2_MASTER_POINTER_DEVICE_ID, - "master-device selector must be master (stays deduped)" - ); - assert_eq!( - xi2_stamp_deviceid(&state, ClientId(3), win, win, 4), - XI2_MASTER_POINTER_DEVICE_ID, - "XIAllMasterDevices selector classifies as master" - ); - assert_eq!( - xi2_stamp_deviceid(&state, ClientId(4), win, win, 4), - XI2_MASTER_POINTER_DEVICE_ID, - "no XI2 selection defaults to master" - ); - } - - /// Issue #72: lite-xl (SDL2) got NO mouse interactions because it - /// splits its XI2 selection across device-id wildcards on the SAME - /// window — Motion/Touch/Gesture under `XIAllMasterDevices(1)` but - /// ButtonPress/Release under `XIAllDevices(0)`. The old first-match - /// `xi2_mask_for_client` returned only the device-1 mask (no button - /// bits) and never OR'd in device-0, so every XI_ButtonPress/Release - /// was delivered to NOBODY (`xi2_targets=[]`) — no clicks, no scroll, - /// no scrollbar drag. The masks below are the real values from the - /// lite-xl HW log. - #[test] - fn xi2_split_device_wildcards_deliver_button_press_issue_72() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 11); - let window = ResourceId(0x0080_0037); - // XIAllMasterDevices(1): Motion(6)+Enter(7)+Touch(18/19/20)+ - // Gesture(27/28/29) — NO button bits. - state - .clients - .get_mut(&11) - .unwrap() - .xi2_masks - .insert((window, 1u16), 0x381c_00c0u64); - // XIAllDevices(0): DeviceChanged(1)+ButtonPress(4)+ButtonRelease(5)+ - // Motion(6)+Enter(7)+Leave(8)+Hierarchy(11)+Property(12). - state - .clients - .get_mut(&11) - .unwrap() - .xi2_masks - .insert((window, 0u16), 0x19f2u64); - - // XI_ButtonPress (4) is selected ONLY under XIAllDevices(0). Under - // the old first-match semantics device 1 matched first and had no - // button bit -> empty targets -> the click reached no client. - let (press_targets, _raw) = compute_xi2_targets(&state, window, window, 4, Some(15)); - assert!( - press_targets.contains(&ClientId(11)), - "issue #72: XI_ButtonPress selected under XIAllDevices(0) must be \ - delivered even when motion is selected under XIAllMasterDevices(1)" - ); - - // XI_ButtonRelease (5) is likewise only under XIAllDevices(0). - let (release_targets, _raw) = compute_xi2_targets(&state, window, window, 5, Some(16)); - assert!( - release_targets.contains(&ClientId(11)), - "issue #72: XI_ButtonRelease under XIAllDevices(0) must be delivered" - ); - - // Sanity: XI_Motion (6) — selected under BOTH wildcards — still - // reaches the client (this arm passed even under first-match). - let (motion_targets, _raw) = compute_xi2_targets(&state, window, window, 6, Some(17)); - assert!( - motion_targets.contains(&ClientId(11)), - "XI_Motion must continue to be delivered" - ); - } - - /// Regression for issue #72 at the decision point: the per-form - /// membership `xi2_pointer_forms` computes. A client selecting under - /// `XIAllDevices(0)` (the SDL3/lite-xl idiom) MUST land in BOTH the - /// master- and slave-stamped delivery buckets. SDL3 parses smooth - /// scroll ONLY off the slave-stamped motion (its handler gates on - /// `deviceid == sourceid`); the pre-fix single-form (master-only / - /// first-match) bucketing returned `wants_slave == false`, leaving - /// lite-xl unable to scroll. - #[test] - fn xi2_pointer_forms_all_devices_selector_gets_both_forms_issue_72() { - const MOTION: u16 = 6; - const BUTTON_PRESS: u16 = 4; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 11); - let win = ResourceId(0x0080_0037); - - let set_masks = |state: &mut ServerState, masks: &[(u16, u32)]| { - let client = state.clients.get_mut(&11).unwrap(); - client.xi2_masks.clear(); - for &(dev, mask) in masks { - client.xi2_masks.insert((win, dev), u64::from(mask)); - } - }; - - // Case 1 — real lite-xl/SDL3 masks: XIAllMasterDevices(1) carries - // Motion (no button bits); XIAllDevices(0) carries ButtonPress+ - // Motion. Both evtypes MUST yield BOTH forms so SDL3 sees the - // slave-stamped scroll motion. `wants_slave == true` here is the - // core issue-#72 fix: it was false under master-only bucketing. - set_masks(&mut state, &[(1u16, 0x381c_00c0u32), (0u16, 0x19f2u32)]); - assert_eq!( - xi2_pointer_forms(&state, ClientId(11), win, win, MOTION), - (true, true), - "issue #72: an XIAllDevices(0) selector must get BOTH forms for \ - Motion so SDL3 can parse smooth scroll off the slave-stamped motion" - ); - assert_eq!( - xi2_pointer_forms(&state, ClientId(11), win, win, BUTTON_PRESS), - (true, true), - "ButtonPress selected under XIAllDevices(0) must also yield BOTH forms" - ); - - // Case 2 — XIAllMasterDevices(1) only, Motion bit set: device 1 - // covers master devices only, so master form yes, slave form no. - set_masks(&mut state, &[(1u16, 0x0000_0040u32)]); - assert_eq!( - xi2_pointer_forms(&state, ClientId(11), win, win, MOTION), - (true, false), - "XIAllMasterDevices(1) covers master devices only: master form, NO slave form" - ); - - // Case 3 — concrete slave pointer only (Enlightenment's pattern): - // slave form yes, master form no; preserves core delivery. - set_masks(&mut state, &[(XI2_SLAVE_POINTER_DEVICE_ID, 0x0000_0040u32)]); - assert_eq!( - xi2_pointer_forms(&state, ClientId(11), win, win, MOTION), - (false, true), - "a concrete slave-pointer selector gets the slave form only" - ); - - // Case 4 — XIAllDevices(0) only: device 0 matches both master and - // slave, so both forms. - set_masks(&mut state, &[(0u16, 0x0000_0040u32)]); - assert_eq!( - xi2_pointer_forms(&state, ClientId(11), win, win, MOTION), - (true, true), - "XIAllDevices(0) matches both master and slave: BOTH forms" - ); - } - - /// X11 implicit pointer grab (#94, Xorg dix/events.c:2150-2193 + - /// 2415-2421): a delivered ButtonPress activates an async grab owned - /// by the press recipient on the press's event window; the matching - /// ButtonRelease is delivered under that grab even when the hit-test - /// now resolves to another client's window (muffin mutates the tree - /// between press and release — Steam got presses without releases). - #[test] - fn implicit_grab_core_release_follows_press_recipient() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const APP: u32 = 1; - const OTHER: u32 = 2; - let win_a = ResourceId(0x0010_0001); - let win_b = ResourceId(0x0020_0001); - const HOST_A: u32 = 0xCAFE_0001; - const HOST_B: u32 = 0xCAFE_0002; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut app_peer = install_client(&mut state, APP); - let mut other_peer = install_client(&mut state, OTHER); - - for (client, win, x) in [(APP, win_a, 0i16), (OTHER, win_b, 500i16)] { - state.resources.create_window( - ClientId(client), - CreateWindowRequest { - depth: 24, - window: win, - parent: ROOT_WINDOW, - x, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - } - // ButtonPress|ButtonRelease. - for (client, win) in [(APP, win_a), (OTHER, win_b)] { - state - .clients - .get_mut(&client) - .unwrap() - .event_masks - .insert(win, 0x0000_000c); - } - let mut xid_map = HostXidMap::new(); - xid_map.insert(HOST_A, win_a); - xid_map.insert(HOST_B, win_b); - - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.host_xid = HOST_A; - press.detail = 1; - press.time = 1000; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && g.owner == ClientId(APP) && g.grab_window == win_a), - "delivered press must install the implicit grab (Xorg dix/events.c:2415)" - ); - let _ = read_all_available(&mut app_peer); // drain the press - - // Release resolves over OTHER's window (the WM-mutated-tree shape). - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = HOST_B; - release.detail = 1; - release.time = 1010; - release.root_x = 550; - release.root_y = 10; - release.event_x = 50; - release.event_y = 10; - release.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let bytes = read_all_available(&mut app_peer); - let mut saw_release = false; - let mut off = 0usize; - while off + 32 <= bytes.len() { - if bytes[off] & 0x7F == 5 { - saw_release = true; - assert_eq!( - &bytes[off + 12..off + 16], - &win_a.0.to_le_bytes(), - "grabbed release must be reported on the grab (press) window" - ); - } - off += 32; - } - assert!( - saw_release, - "implicit grab: the release must follow the press recipient, not re-hit-test" - ); - let other_bytes = read_all_available(&mut other_peer); - assert!( - !other_bytes.chunks(32).any(|c| c[0] & 0x7F == 5), - "the grab captures the release — OTHER must not receive it" - ); - assert!( - state.active_pointer_grab.is_none(), - "final release tears the implicit grab down (Xi/exevents.c:1931)" - ); - } - - /// XI2 form of the implicit grab (#94 — the actual Steam/Cinnamon - /// shape: Steam selects cooked XI2 buttons, no core mask). The XI2 - /// ButtonPress installs a via_xi2 implicit grab; the release delivers - /// to the owner on the grab window through the XI2 redirect. - #[test] - fn implicit_grab_xi2_release_follows_press_recipient() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const APP: u32 = 1; - const OTHER: u32 = 2; - let win_a = ResourceId(0x0010_0001); - let win_b = ResourceId(0x0020_0001); - const HOST_A: u32 = 0xCAFE_0001; - const HOST_B: u32 = 0xCAFE_0002; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut app_peer = install_client(&mut state, APP); - let _other_peer = install_client(&mut state, OTHER); - - for (client, win, x) in [(APP, win_a, 0i16), (OTHER, win_b, 500i16)] { - state.resources.create_window( - ClientId(client), - CreateWindowRequest { - depth: 24, - window: win, - parent: ROOT_WINDOW, - x, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - } - // XI_ButtonPress(4) | XI_ButtonRelease(5) on the master pointer. - state - .clients - .get_mut(&APP) - .unwrap() - .xi2_masks - .insert((win_a, XI2_MASTER_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); - state - .clients - .get_mut(&OTHER) - .unwrap() - .xi2_masks - .insert((win_b, XI2_MASTER_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); - let mut xid_map = HostXidMap::new(); - xid_map.insert(HOST_A, win_a); - xid_map.insert(HOST_B, win_b); - - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.host_xid = HOST_A; - press.detail = 1; - press.time = 1000; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && g.via_xi2 && g.owner == ClientId(APP)), - "XI2-delivered press must install a via_xi2 implicit grab" - ); - let _ = read_all_available(&mut app_peer); - - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = HOST_B; - release.detail = 1; - release.time = 1010; - release.root_x = 550; - release.root_y = 10; - release.event_x = 50; - release.event_y = 10; - release.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let bytes = read_all_available(&mut app_peer); - let mut found_win = None; - let mut off = 0usize; - while off + 32 <= bytes.len() { - if bytes[off] == 35 && u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]) == 5 { - found_win = Some(u32::from_le_bytes( - bytes[off + 24..off + 28].try_into().unwrap(), - )); - break; - } - let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; - off += 32 + length * 4; - } - assert_eq!( - found_win, - Some(win_a.0), - "XI2 release must reach the implicit-grab owner on the grab window" - ); - assert!( - state.active_pointer_grab.is_none(), - "grab released after final release" - ); - } - - /// Xorg oracle from the FAILING `xfce.xtrace` vs `xfce-xorg.xtrace`: an - /// XFCE dialog selects XI2 buttons under `device=1` (XIAllMasterDevices, - /// not the master id 2), gets its ButtonPress (delivered as master 0x02), - /// but yserver dropped EVERY XI2 ButtonRelease (xtrace: 13 XI2 presses, 0 - /// XI2 releases; Xorg delivered 3/3). The dialog "reacts to the click but - /// it never takes effect". Every PASSING implicit-grab test selects under - /// device 2, so this pins the device=1 (all-master) selector: press AND - /// release must both reach the selector on its window. - #[test] - fn implicit_grab_xi2_release_reaches_all_master_selector_xfce() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const APP: u32 = 1; - const XI2_ALL_MASTER: u16 = 1; // XIAllMasterDevices - let win_a = ResourceId(0x0050_0003); - const HOST_A: u32 = 0xCAFE_0001; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut app_peer = install_client(&mut state, APP); - - state.resources.create_window( - ClientId(APP), - CreateWindowRequest { - depth: 24, - window: win_a, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win_a); - // XI_ButtonPress(4) | XI_ButtonRelease(5) selected under XIAllMasterDevices. - state - .clients - .get_mut(&APP) - .unwrap() - .xi2_masks - .insert((win_a, XI2_ALL_MASTER), (1 << 4) | (1 << 5)); - let mut xid_map = HostXidMap::new(); - xid_map.insert(HOST_A, win_a); - - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.host_xid = HOST_A; - press.detail = 1; - press.time = 1000; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - - let xge_evtypes = |bytes: &[u8]| -> Vec { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - assert!( - xge_evtypes(&read_all_available(&mut app_peer)).contains(&4), - "precondition: the all-master XI2 selector receives the ButtonPress" - ); - - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = HOST_A; - release.detail = 1; - release.time = 1010; - release.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - assert!( - xge_evtypes(&read_all_available(&mut app_peer)).contains(&5), - "XI2 ButtonRelease must reach the XIAllMasterDevices selector on its \ - window (xfce.xtrace dropped it: 0 XI2 releases vs Xorg 3/3)" - ); - } - - /// #94 XFCE dialog repro (fail `xfce.xtrace` / pass `xfce-xorg.xtrace`). - /// The real shape: a CORE selector on an ANCESTOR window (xtrace conn 005, - /// event=0x00300a58) plus the XI2 dialog on a leaf child (conn 014, - /// event=0x00500003). The deeper XI2 delivery owns the implicit grab, so - /// the release follows that XI2 grab rather than propagating naturally to - /// the core ancestor. - #[test] - fn implicit_grab_release_reaches_xi2_leaf_with_core_ancestor_selector_xfce() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const CORE_ANCESTOR: u32 = 1; // xtrace conn 005 (core selector on ancestor) - const XI2_LEAF: u32 = 2; // xtrace conn 014 (XI2 dialog) - let parent = ResourceId(0x0030_0a58); - let leaf = ResourceId(0x0050_0003); - const HOST_LEAF: u32 = 0xCAFE_0001; - const XI2_ALL_MASTER: u16 = 1; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut core_peer = install_client(&mut state, CORE_ANCESTOR); - let mut leaf_peer = install_client(&mut state, XI2_LEAF); - - // parent (core selector) ← leaf (XI2 selector), leaf covers the hit. - state.resources.create_window( - ClientId(CORE_ANCESTOR), - CreateWindowRequest { - depth: 24, - window: parent, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 200, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(parent); - state.resources.create_window( - ClientId(XI2_LEAF), - CreateWindowRequest { - depth: 24, - window: leaf, - parent, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(leaf); - // Ancestor: CORE ButtonPress|ButtonRelease (0x0c). Leaf: XI2 under - // XIAllMasterDevices. - state - .clients - .get_mut(&CORE_ANCESTOR) - .unwrap() - .event_masks - .insert(parent, 0x0000_000c); - state - .clients - .get_mut(&XI2_LEAF) - .unwrap() - .xi2_masks - .insert((leaf, XI2_ALL_MASTER), (1 << 4) | (1 << 5)); - let mut xid_map = HostXidMap::new(); - xid_map.insert(HOST_LEAF, leaf); - - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.host_xid = HOST_LEAF; - press.detail = 1; - press.time = 1000; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - let _ = read_all_available(&mut core_peer); - let leaf_after_press = read_all_available(&mut leaf_peer); - - let xge_evtypes = |bytes: &[u8]| -> Vec { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - assert!( - xge_evtypes(&leaf_after_press).contains(&4), - "precondition: the XI2 leaf selector receives the ButtonPress" - ); - - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = HOST_LEAF; - release.detail = 1; - release.time = 1010; - release.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let core_after = read_all_available(&mut core_peer); - let leaf_after = read_all_available(&mut leaf_peer); - assert!( - !core_after.chunks(32).any(|c| c.first() == Some(&5)), - "the XI2 implicit grab captures the release before core ancestor propagation" - ); - assert!( - xge_evtypes(&leaf_after).contains(&5), - "XI2 ButtonRelease must reach the XI2 leaf selector even though a \ - core client selects on an ancestor (xfce.xtrace: leaf got the \ - press but the release was dropped)" - ); - } - - /// Enlightenment (E27) dock-click repro, hardware-measured on silence. - /// One client selects BOTH core ButtonPress|ButtonRelease AND XI2 on the - /// SLAVE pointer for the same window; the core dedup keeps the core form - /// for slave stamps, so the press is delivered twice — once per protocol. - /// - /// The implicit grab that press installs must be typed CORE, not XI2: - /// Xorg `DeliverEventsToWindow` delivers core first and activates the - /// grab from that call, so `ActivateImplicitGrab` sees `ButtonPress` and - /// picks `grabtype = CORE` (dix/events.c:2158), which its own comment at - /// dix/events.c:2417 spells out — "since core events are delivered first, - /// an implicit grab may be activated on a core grab, stopping the XI - /// events." - /// - /// Typing it XI2 set `via_xi2`, and the active-grab redirect then - /// suppressed the CORE form of the release while still marking the event - /// handled — captured and dropped, with natural propagation skipped too. - /// E27 lost the mouse-up on every dock click: the button stayed down - /// client-side, so clicks became drags and then input wedged entirely. - /// - /// Oracle is measured, not assumed — silence, same session, same clicks: - /// yserver before core 10/2 XI2 9/8 - /// yserver after core 28/28 XI2 28/28 - /// Xorg baseline core 3/3 XI2 3/3 - /// Core press and release balance 1:1 on Xorg, so the release must land. - #[test] - fn implicit_grab_core_release_survives_dual_core_and_slave_xi2_selection_e27() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const APP: u32 = 1; - let canvas = ResourceId(0x0010_0009); // E27 canvas, from the trace - const HOST_CANVAS: u32 = 0x0040_0dbb; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut app_peer = install_client(&mut state, APP); - - state.resources.create_window( - ClientId(APP), - CreateWindowRequest { - depth: 24, - window: canvas, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 200, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(canvas); - // Core ButtonPress|ButtonRelease (0x0c) AND XI2 press/release on the - // SLAVE pointer — both on the same window, the E27 shape. - state - .clients - .get_mut(&APP) - .unwrap() - .event_masks - .insert(canvas, 0x0000_000c); - state - .clients - .get_mut(&APP) - .unwrap() - .xi2_masks - .insert((canvas, XI2_SLAVE_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); - let mut xid_map = HostXidMap::new(); - xid_map.insert(HOST_CANVAS, canvas); - - // Walk the wire correctly: XGE (type 35) carries a length in words, - // so a flat chunks(32) misaligns once both forms share a stream. - let split_events = |bytes: &[u8]| -> (Vec, Vec) { - let (mut core, mut xge) = (Vec::new(), Vec::new()); - let mut off = 0usize; - while off + 32 <= bytes.len() { - if bytes[off] == 35 { - xge.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); - off += 32 - + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4; - } else { - core.push(bytes[off] & 0x7f); - off += 32; - } - } - (core, xge) - }; - - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.host_xid = HOST_CANVAS; - press.detail = 1; - press.time = 1000; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - - let (core_press, xge_press) = split_events(&read_all_available(&mut app_peer)); - assert!( - core_press.contains(&4), - "precondition: the core selector receives the ButtonPress" - ); - assert!( - xge_press.contains(&4), - "precondition: the slave XI2 selector also receives the press \ - (the slave carve-out in the core dedup keeps both forms)" - ); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && !g.via_xi2), - "the implicit grab must be typed CORE when both forms were \ - delivered to the same window (Xorg ActivateImplicitGrab)" - ); - - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = HOST_CANVAS; - release.detail = 1; - release.time = 1010; - release.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let (core_release, _) = split_events(&read_all_available(&mut app_peer)); - assert!( - core_release.contains(&5), - "core ButtonRelease must reach the client — an XI2-typed implicit \ - grab captured it at the active-grab redirect and dropped it, \ - wedging E27 (measured core 10 press / 2 release; Xorg 3/3)" - ); - } - - /// Under a via_xi2 implicit grab, delivery is filtered by the owner's - /// XI2 selection on the grab window (Xorg merges the window xi2mask - /// into the implicit GrabRec): press+release-only selectors must not - /// receive XI_Motion during the click, and the motion must not leak - /// to the window under the cursor either (the grab captures it). - #[test] - fn implicit_grab_xi2_motion_filtered_by_owner_selection() { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - const APP: u32 = 1; - const OTHER: u32 = 2; - let win_a = ResourceId(0x0010_0001); - let win_b = ResourceId(0x0020_0001); - const HOST_A: u32 = 0xCAFE_0001; - const HOST_B: u32 = 0xCAFE_0002; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut app_peer = install_client(&mut state, APP); - let mut other_peer = install_client(&mut state, OTHER); - - for (client, win, x) in [(APP, win_a, 0i16), (OTHER, win_b, 500i16)] { - state.resources.create_window( - ClientId(client), - CreateWindowRequest { - depth: 24, - window: win, - parent: ROOT_WINDOW, - x, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - } - // APP: XI_ButtonPress(4)|XI_ButtonRelease(5) ONLY — no XI_Motion(6). - state - .clients - .get_mut(&APP) - .unwrap() - .xi2_masks - .insert((win_a, XI2_MASTER_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); - // OTHER selects XI_Motion on its own window — the grab must - // capture the motion away from it anyway. - state - .clients - .get_mut(&OTHER) - .unwrap() - .xi2_masks - .insert((win_b, XI2_MASTER_POINTER_DEVICE_ID), 1 << 6); - let mut xid_map = HostXidMap::new(); - xid_map.insert(HOST_A, win_a); - xid_map.insert(HOST_B, win_b); - - let mut press = motion_event(); - press.kind = PointerEventKind::ButtonPress; - press.host_xid = HOST_A; - press.detail = 1; - press.time = 1000; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && g.via_xi2), - "precondition: XI2 implicit grab installed" - ); - let _ = read_all_available(&mut app_peer); - let _ = read_all_available(&mut other_peer); - - // Motion over OTHER's window while the implicit grab is held. - let mut motion = motion_event(); - motion.host_xid = HOST_B; - motion.time = 1005; - motion.root_x = 550; - motion.root_y = 10; - motion.event_x = 50; - motion.event_y = 10; - motion.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); - - let xge_evtypes = |bytes: &[u8]| -> Vec { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - assert!( - !xge_evtypes(&read_all_available(&mut app_peer)).contains(&6), - "owner did not select XI_Motion on the grab window — the \ - implicit grab must not over-deliver it (Xorg xi2mask filter)" - ); - assert!( - xge_evtypes(&read_all_available(&mut other_peer)).is_empty(), - "the grab captures motion — the window under the cursor gets nothing" - ); - - // The release (selected) still delivers to the owner on the grab window. - let mut release = motion_event(); - release.kind = PointerEventKind::ButtonRelease; - release.host_xid = HOST_B; - release.detail = 1; - release.time = 1010; - release.root_x = 550; - release.root_y = 10; - release.event_x = 50; - release.event_y = 10; - release.state = 0x100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - assert!( - xge_evtypes(&read_all_available(&mut app_peer)).contains(&5), - "selected XI_ButtonRelease still delivers under the implicit grab" - ); - assert!( - state.active_pointer_grab.is_none(), - "grab torn down after final release" - ); - } - - /// One mapped 100x100 window at (x,0) owned by `client`, host xid - /// registered in `map`. Implicit-grab test scaffolding. - fn implicit_test_window( - state: &mut ServerState, - map: &mut HostXidMap, - client: u32, - win: u32, - host: u32, - x: i16, - ) -> yserver_protocol::x11::ResourceId { - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - let id = ResourceId(win); - state.resources.create_window( - ClientId(client), - CreateWindowRequest { - depth: 24, - window: id, - parent: ROOT_WINDOW, - x, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(id); - map.insert(host, id); - id - } - - fn button_event(kind: PointerEventKind, host: u32, button: u8, time: u32) -> HostPointerEvent { - let mut ev = motion_event(); - ev.kind = kind; - ev.host_xid = host; - ev.detail = button; - ev.time = time; - ev - } - - fn install_passive_test_grab( - state: &mut ServerState, - xid_map: &mut HostXidMap, - owner: u32, - event_mask: u32, - via_xi2: bool, - ) -> yserver_protocol::x11::ResourceId { - let win = implicit_test_window(state, xid_map, owner, 0x0010_0001, 0xCAFE_0001, 0); - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(owner), - grab_window: win, - button: 1, - modifiers: 0x8000, - owner_events: false, - event_mask, - pointer_mode: 1, - keyboard_mode: 1, - confine_to: yserver_protocol::x11::ResourceId(0), - via_xi2, - }); - win - } - - #[test] - fn passive_grab_activation_populates_and_final_release_clears_record() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let _peer = install_client(&mut state, 1); - let mut xid_map = HostXidMap::new(); - let win = install_passive_test_grab(&mut state, &mut xid_map, 1, 0x000c, false); - - let fan = |state: &mut ServerState, backend: &mut RecordingBackend, kind, button, time| { - let event = button_event(kind, 0xCAFE_0001, button, time); - let _ = pointer_event_fanout_to_state(state, backend, &xid_map, event, true, false); - }; - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonPress, - 1, - 1000, - ); - assert!(state.active_pointer_grab.is_some_and(|grab| { - grab.owner == ClientId(1) && grab.grab_window == win && grab.passive && !grab.implicit - })); - - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonPress, - 3, - 1001, - ); - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonRelease, - 1, - 1002, - ); - assert!( - state.active_pointer_grab.is_some_and(|grab| grab.passive), - "a non-final release must not deactivate the passive grab" - ); - - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonRelease, - 3, - 1003, - ); - assert!( - state.active_pointer_grab.is_none(), - "the final release must clear the passive grab" - ); - } - - #[test] - fn active_grab_target_uses_matched_passive_grab_not_last_registered() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let _peer = install_client(&mut state, 1); - let mut xid_map = HostXidMap::new(); - let win = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); - for (modifiers, event_mask) in [(0, 0x000c), (1, 0x0040)] { - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(1), - grab_window: win, - button: 1, - modifiers, - owner_events: false, - event_mask, - pointer_mode: 1, - keyboard_mode: 1, - confine_to: yserver_protocol::x11::ResourceId(0), - via_xi2: false, - }); - } - let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - - let (_, _, _, _, _, _, mask) = active_grab_target(&state).expect("passive grab active"); - assert_eq!( - mask, 0x000c, - "the active record must snapshot the grab that matched, not the last registration" - ); - } - - #[test] - fn xi2_passive_grab_delivers_final_release_before_teardown() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let mut peer = install_client(&mut state, 1); - let mut xid_map = HostXidMap::new(); - let win = install_passive_test_grab(&mut state, &mut xid_map, 1, (1 << 4) | (1 << 5), true); - - let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - let _ = read_all_available(&mut peer); - let mut release = button_event(PointerEventKind::ButtonRelease, 0xCAFE_0001, 1, 1001); - release.state = 0x0100; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let bytes = read_all_available(&mut peer); - assert!(bytes.windows(28).any(|event| { - event[0] == 35 - && u16::from_le_bytes([event[8], event[9]]) == 5 - && u32::from_le_bytes(event[24..28].try_into().unwrap()) == win.0 - })); - assert!(state.active_pointer_grab.is_none()); - } - - /// Xorg gate is `if (deliveries)` (dix/events.c:2415): a press nobody - /// selected installs nothing. - #[test] - fn implicit_grab_not_installed_when_press_undelivered() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let _peer = install_client(&mut state, 1); - let mut xid_map = HostXidMap::new(); - // Window exists but no client selects button events anywhere. - let _w = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); - let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!(state.active_pointer_grab.is_none()); - } - - /// A press while an explicit grab is active never installs (Xorg - /// `if (!grab ...)`) — and must not clobber the explicit record. - #[test] - fn implicit_grab_not_installed_under_explicit_grab() { - use crate::server::ActivePointerGrab; - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let _peer = install_client(&mut state, 1); - let mut xid_map = HostXidMap::new(); - let w = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(w, 0x0000_000c); - let explicit = ActivePointerGrab { - owner: ClientId(1), - grab_window: w, - event_mask: 0x000c, - cursor: yserver_protocol::x11::ResourceId(0), - time: 500, - owner_events: false, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }; - state.active_pointer_grab = Some(explicit); - let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!( - state - .active_pointer_grab - .is_some_and(|g| !g.implicit && g.time == 500), - "explicit grab record must be untouched by the press" - ); - // And the explicit grab does NOT auto-release on the final release. - let release = button_event(PointerEventKind::ButtonRelease, 0xCAFE_0001, 1, 1010); - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - assert!( - state.active_pointer_grab.is_some(), - "explicit grabs persist until UngrabPointer (only implicit auto-releases)" - ); - } - - /// Multi-button click: the grab holds until ALL buttons release - /// (Xi/exevents.c:1935 `!b->buttonsDown`), a second press neither - /// reinstalls nor activates passive grabs (dix `if (!grab && - /// CheckDeviceGrabs...)`, yserver's active_grab_present gate), and - /// pressing again after a partial release still doesn't reinstall - /// (pins the no-transition-gate model). - #[test] - fn implicit_grab_multi_button_lifecycle() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::default(); - let _peer = install_client(&mut state, 1); - let _wm = install_client(&mut state, 2); - let mut xid_map = HostXidMap::new(); - let w = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(w, 0x0000_000c); - // A passive grab that WOULD match button 3 — it must not activate - // while the implicit grab holds the device. - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(2), - grab_window: w, - button: 3, - modifiers: 0x8000, // AnyModifier - owner_events: false, - event_mask: 0x0000_000c, - pointer_mode: 1, - keyboard_mode: 1, - confine_to: yserver_protocol::x11::ResourceId(0), - via_xi2: false, - }); - - let fan = |state: &mut ServerState, backend: &mut RecordingBackend, kind, button, time| { - let ev = button_event(kind, 0xCAFE_0001, button, time); - let _ = pointer_event_fanout_to_state(state, backend, &xid_map, ev, true, false); - }; - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonPress, - 1, - 1000, - ); - assert!(state.active_pointer_grab.is_some_and(|g| g.implicit)); - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonPress, - 3, - 1005, - ); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && !g.passive), - "second press: no passive activation, implicit grab unchanged" - ); - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonRelease, - 1, - 1010, - ); - assert!( - state.active_pointer_grab.is_some(), - "grab persists while button 3 is still down" - ); - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonPress, - 1, - 1015, - ); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && g.time == 1000), - "re-press during the grab must not reinstall (time unchanged)" - ); - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonRelease, - 1, - 1020, - ); - fan( - &mut state, - &mut backend, - PointerEventKind::ButtonRelease, - 3, - 1025, - ); - assert!( - state.active_pointer_grab.is_none(), - "final release tears down" - ); - } -} diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs b/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs new file mode 100644 index 000000000..e8cda2e31 --- /dev/null +++ b/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs @@ -0,0 +1,5950 @@ +use super::*; +use crate::{ + backend::recording::RecordingBackend, + host_x11::HostXidMap, + resources::ROOT_WINDOW, + server::{ScreenSaverActive, ServerState}, +}; +use yserver_protocol::x11::ClientId; + +/// AllowSome state machine pins (Xorg dix/events.c semantics): a +/// master grab freezes ONCE and holds its paired master; FreezeNextEvent +/// re-arms, trips to FrozenWithEvent on a delivered key/button, and +/// deactivation clears the paired device's on-behalf hold. +#[test] +fn xi1_sync_state_machine_pins() { + use crate::{ + server::{Xi1ActiveGrab, Xi1SyncState}, + xinput::{DEVICEID_MASTER_KEYBOARD as KBD, DEVICEID_MASTER_POINTER as PTR}, + }; + let mut state = ServerState::new(); + let owner = ClientId(7); + state.xi1_active_grabs.insert( + PTR, + Xi1ActiveGrab { + owner, + deviceid: PTR, + grab_window: crate::resources::ROOT_WINDOW, + owner_events: false, + this_mode: 0, + other_mode: 0, + passive_detail: None, + }, + ); + // Sync grab activation: this device FrozenNoEvent, paired + // device held on the grab's behalf. + xi1_check_grab_for_syncs(&mut state, PTR, owner, true, true); + assert_eq!( + state.xi1_frozen[&PTR].state, + Xi1SyncState::FrozenNoEvent, + "sync this_mode freezes once at activation" + ); + assert_eq!(state.xi1_frozen[&KBD].other, Some(owner)); + assert!(state.xi1_frozen[&PTR].frozen()); + assert!(state.xi1_frozen[&KBD].frozen(), "held via sync.other"); + + // FreezeNextEvent arming + trip on a delivered button event. + state.xi1_frozen.get_mut(&PTR).unwrap().state = Xi1SyncState::FreezeNextEvent; + assert!(!state.xi1_frozen[&PTR].frozen(), "armed ≠ frozen"); + let q = crate::server::Xi1QueuedEvent { + deviceid: PTR, + evcode: crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + time: 1, + root_x: 0, + root_y: 0, + state_mask: 0, + natural_target: crate::resources::ROOT_WINDOW, + focus_route: crate::server::Xi1FocusRoute::Walk, + axes: None, + replay_floor: None, + }; + xi1_freeze_this_event_if_needed(&mut state, PTR, owner, &q); + assert_eq!(state.xi1_frozen[&PTR].state, Xi1SyncState::FrozenWithEvent); + assert!(state.xi1_frozen[&PTR].stored.is_some(), "Replay material"); + + // Deactivation thaws this device AND releases the paired hold. + xi1_deactivate_device_grab(&mut state, PTR); + assert!(!state.xi1_frozen[&PTR].frozen()); + assert_eq!(state.xi1_frozen[&KBD].other, None); + assert!(!state.xi1_frozen[&KBD].frozen()); +} + +#[test] +fn xi_source_removal_grab_cleanup_keeps_registry_for_atomic_unregister() { + use crate::{ + backend::recording::RecordingBackend, + core_loop::{DeviceInfo, message::LibinputConfigSnapshot}, + xinput::{InputCapabilities, InputSourceId, XiFacetKind}, + }; + + let source = InputSourceId(0xD14); + let info = DeviceInfo { + source_id: source, + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: true, + pointer: true, + touch: false, + }, + name: "removal cleanup source".to_owned(), + device_node: "/dev/input/removal-cleanup".to_owned(), + sysname: "removal-cleanup".to_owned(), + vendor_id: 0, + product_id: 0, + is_touchpad: false, + config: LibinputConfigSnapshot::default(), + }; + let mut state = ServerState::new(); + let ids = state.xi_register_source(&info); + let mut backend = RecordingBackend::new(); + + xi_cleanup_source(&mut state, &mut backend, source); + + assert_eq!( + state + .xi_devices + .source(source) + .map(|current| current.name.as_str()), + Some("removal cleanup source"), + "grab cleanup must leave the source registered until KMS drains state and unregisters both facets together", + ); + assert_eq!( + state.xi_devices.facet(source, XiFacetKind::Keyboard), + Some(ids[0]), + ); + assert_eq!( + state.xi_devices.facet(source, XiFacetKind::PointerTouch), + Some(ids[1]), + ); +} + +use crate::server::ClientState; +use std::{ + collections::{HashMap, HashSet, VecDeque}, + io::Read, + os::unix::net::UnixStream, + sync::{Arc, Mutex, atomic::AtomicU16}, +}; + +// Duplicated from process_request.rs::tests. If you change one, +// change both. A shared test_fixtures module is the right home +// long-term; tracked as a follow-up. +fn install_client(state: &mut ServerState, id: u32) -> UnixStream { + use crate::resources::ROOT_WINDOW; + use yserver_protocol::x11::ClientByteOrder; + let (a, b) = UnixStream::pair().unwrap(); + state.clients.insert( + id, + ClientState { + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), + byte_order: ClientByteOrder::LittleEndian, + last_sequence: Arc::new(AtomicU16::new(0)), + resource_id_base: 0, + resource_id_mask: u32::MAX, + event_masks: HashMap::new(), + save_set: HashSet::new(), + big_requests_enabled: false, + xi2_masks: HashMap::new(), + xi1_event_classes: HashSet::new(), + xi1_window_event_classes: HashMap::new(), + outbound: VecDeque::new(), + outbound_fds: Default::default(), + watching_writable: false, + write_failed: false, + gone: false, + focused_window: ROOT_WINDOW, + reader_control: None, + is_local: true, + fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), + }, + ); + b +} + +fn install_capture_client(state: &mut ServerState, id: u32) -> crate::transport::CapturedPeer { + use crate::resources::ROOT_WINDOW; + use yserver_protocol::x11::ClientByteOrder; + let (writer, peer) = crate::transport::Transport::capture_pair(); + state.clients.insert( + id, + ClientState { + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(writer)), + byte_order: ClientByteOrder::LittleEndian, + last_sequence: Arc::new(AtomicU16::new(0)), + resource_id_base: 0, + resource_id_mask: u32::MAX, + event_masks: HashMap::new(), + save_set: HashSet::new(), + big_requests_enabled: false, + xi2_masks: HashMap::new(), + xi1_event_classes: HashSet::new(), + xi1_window_event_classes: HashMap::new(), + outbound: VecDeque::new(), + outbound_fds: Default::default(), + watching_writable: false, + write_failed: false, + gone: false, + focused_window: ROOT_WINDOW, + reader_control: None, + is_local: true, + fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), + }, + ); + peer +} + +fn read_all_available(peer: &mut UnixStream) -> Vec { + peer.set_nonblocking(true).expect("set_nonblocking"); + let mut out = Vec::new(); + let mut buf = [0u8; 512]; + loop { + match peer.read(&mut buf) { + Ok(0) => break, + Ok(n) => out.extend_from_slice(&buf[..n]), + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => break, + Err(err) => panic!("read failed: {err}"), + } + } + peer.set_nonblocking(false).expect("unset_nonblocking"); + out +} + +fn read_all_capture_available(peer: &mut crate::transport::CapturedPeer) -> Vec { + peer.set_nonblocking(true).expect("set_nonblocking"); + let mut out = Vec::new(); + let mut buf = [0u8; 512]; + loop { + match peer.read(&mut buf) { + Ok(0) => break, + Ok(n) => out.extend_from_slice(&buf[..n]), + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => break, + Err(err) => panic!("read failed: {err}"), + } + } + peer.set_nonblocking(false).expect("unset_nonblocking"); + out +} + +fn motion_event() -> HostPointerEvent { + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + host_xid: 0, + detail: 0, + time: 1, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + } +} + +fn source_button_event( + kind: PointerEventKind, + origin: crate::core_loop::InputOrigin, + detail: u8, + time: u32, +) -> HostPointerEvent { + HostPointerEvent { + kind, + detail, + time, + origin, + ..motion_event() + } +} + +fn pointer_source(state: &mut ServerState, source: u64, pointer: bool) -> u16 { + let info = crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(source), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer, + touch: false, + }, + name: format!("pointer source {source}"), + device_node: format!("/dev/input/event{source}"), + sysname: format!("event{source}"), + vendor_id: 1, + product_id: source as u32, + is_touchpad: false, + config: crate::core_loop::message::LibinputConfigSnapshot::default(), + }; + let facets = state.xi_register_source(&info); + if pointer { + facets.first().copied().unwrap_or(0) + } else { + 0 + } +} + +fn xi2_event_ids(bytes: &[u8]) -> Vec<(u16, u16, u16)> { + let mut result = Vec::new(); + let mut offset = 0; + while offset + 32 <= bytes.len() { + assert_eq!(bytes[offset], 35, "expected GenericEvent"); + let extra = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()); + let evtype = u16::from_le_bytes(bytes[offset + 8..offset + 10].try_into().unwrap()); + let deviceid = u16::from_le_bytes(bytes[offset + 10..offset + 12].try_into().unwrap()); + let source_offset = if matches!(evtype, 13..=17) { 20 } else { 52 }; + let sourceid = u16::from_le_bytes( + bytes[offset + source_offset..offset + source_offset + 2] + .try_into() + .unwrap(), + ); + result.push((evtype, deviceid, sourceid)); + offset += 32 + extra as usize * 4; + } + assert_eq!(offset, bytes.len(), "event stream fully consumed"); + result +} + +fn xi2_scroll_values(bytes: &[u8]) -> Vec<(u16, u16, i32)> { + let mut result = Vec::new(); + let mut offset = 0; + while offset + 32 <= bytes.len() { + assert_eq!(bytes[offset], 35, "expected GenericEvent"); + let units = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()); + let evtype = u16::from_le_bytes(bytes[offset + 8..offset + 10].try_into().unwrap()); + let deviceid = u16::from_le_bytes(bytes[offset + 10..offset + 12].try_into().unwrap()); + if evtype == 6 && units == 28 { + let sourceid = u16::from_le_bytes(bytes[offset + 52..offset + 54].try_into().unwrap()); + let value = i32::from_le_bytes(bytes[offset + 136..offset + 140].try_into().unwrap()); + result.push((deviceid, sourceid, value)); + } + offset += 32 + units as usize * 4; + } + assert_eq!(offset, bytes.len(), "event stream fully consumed"); + result +} + +fn xi1_device_event_ids(bytes: &[u8]) -> Vec<(u8, u8)> { + let mut result = Vec::new(); + let mut offset = 0; + while offset + 32 <= bytes.len() { + if bytes[offset] == 35 { + let units = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()); + offset += 32 + units as usize * 4; + } else { + let event_type = bytes[offset]; + if (crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET + ..=crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET) + .contains(&event_type) + { + result.push((event_type, bytes[offset + 31] & 0x7f)); + } + offset += 32; + } + } + assert_eq!(offset, bytes.len(), "event stream fully consumed"); + result +} + +fn select_xi2(state: &mut ServerState, client: u32, device: u16, mask: u64) { + state + .clients + .get_mut(&client) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, device), mask); +} + +fn select_xi1_button(state: &mut ServerState, client: u32, device: u16, offset: u8) { + state + .clients + .get_mut(&client) + .unwrap() + .xi1_window_event_classes + .entry(ROOT_WINDOW) + .or_default() + .insert((u32::from(device) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset)); +} + +#[test] +fn pointer_source_selection_uses_resolved_xi1_and_xi2_facets() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut xi2_peer = install_capture_client(&mut state, 1); + let mut xi1_peer = install_capture_client(&mut state, 2); + let razer = pointer_source(&mut state, 301, true); + let hyperx = pointer_source(&mut state, 302, true); + assert_eq!((razer, hyperx), (6, 7)); + select_xi2(&mut state, 1, razer, 1 << 4); + select_xi1_button( + &mut state, + 2, + hyperx, + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + ); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(301)), + 1, + 1, + ), + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!( + xi2_event_ids(&read_all_capture_available(&mut xi2_peer)), + vec![(4, razer, razer)] + ); + assert!(read_all_capture_available(&mut xi1_peer).is_empty()); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(302)), + 1, + 2, + ), + true, + false, + ); + assert!(dropped.is_empty()); + assert!(read_all_capture_available(&mut xi2_peer).is_empty()); + assert_eq!( + xi1_device_event_ids(&read_all_capture_available(&mut xi1_peer)), + vec![( + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + hyperx as u8, + )] + ); + + assert_eq!(state.buttons_down, 1); + assert_eq!(state.xi_devices.device(razer).unwrap().buttons_down, 1); + assert_eq!(state.xi_devices.device(hyperx).unwrap().buttons_down, 1); + assert_eq!(state.sync_pending.len(), 0); + assert_eq!(state.xi_devices.devices().len(), 6); + assert_eq!(state.unpublished_pointer_buttons_down.len(), 0); + assert_eq!(state.scroll_axis_value, [0, 0]); + assert_eq!( + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down, device.scroll_axis_values)) + .collect::>(), + vec![ + (2, 0, [0, 0]), + (3, 0, [0, 0]), + (4, 0, [0, 0]), + (5, 0, [0, 0]), + (razer, 1, [0, 0]), + (hyperx, 1, [0, 0]), + ], + "unrelated devices and facets keep their own state" + ); +} + +#[test] +fn pointer_source_selection_aggregates_holds_and_preserves_slave_release_cookies() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + let razer = pointer_source(&mut state, 311, true); + let hyperx = pointer_source(&mut state, 312, true); + let device_mask = (1 << 4) | (1 << 5); + for device in [2, 4, razer, hyperx] { + select_xi2(&mut state, 1, device, device_mask); + } + + macro_rules! send { + ($event:expr) => {{ + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + $event, + true, + false, + ); + assert!(dropped.is_empty()); + xi2_event_ids(&read_all_capture_available(&mut peer)) + }}; + } + + assert_eq!( + send!(source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(311)), + 1, + 1, + )), + vec![(4, razer, razer), (4, 2, razer)] + ); + assert!( + send!(source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(311)), + 1, + 11, + )) + .is_empty(), + "a duplicate press from one slave is ignored" + ); + assert_eq!( + send!(source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(312)), + 1, + 2, + )), + vec![(4, hyperx, hyperx)], + "a second attached slave keeps its event, but the master press is duplicate" + ); + assert_eq!(state.buttons_down, 1); + assert_eq!(state.xi_devices.device(razer).unwrap().buttons_down, 1); + assert_eq!(state.xi_devices.device(hyperx).unwrap().buttons_down, 1); + + // A virtual XTEST click takes its own slave hold during the physical + // drag. It cannot create another master press, and it keeps the + // master down when the first physical source releases. + assert_eq!( + send!(source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::XTest(4), + 1, + 3, + )), + vec![(4, 4, 4)] + ); + assert_eq!( + send!(source_button_event( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(311)), + 1, + 4, + )), + vec![(5, razer, razer)], + "the per-slave release cookie survives while master release is suppressed" + ); + assert!( + send!(source_button_event( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(311)), + 1, + 41, + )) + .is_empty(), + "a duplicate release from one slave is ignored" + ); + assert_eq!(state.buttons_down, 1); + assert_eq!(state.xi_devices.device(razer).unwrap().buttons_down, 0); + assert_eq!(state.xi_devices.device(hyperx).unwrap().buttons_down, 1); + assert_eq!(state.xi_devices.device(4).unwrap().buttons_down, 1); + + // Removing Razer drops only its source state; HyperX and XTEST remain + // attached holders, so unplugging one mouse cannot release the drag. + assert_eq!( + state.xi_unregister_source(crate::xinput::InputSourceId(311)), + vec![razer] + ); + assert!(state.xi_devices.device(razer).is_none()); + assert_eq!(state.xi_devices.device(hyperx).unwrap().buttons_down, 1); + assert_eq!(state.xi_devices.device(4).unwrap().buttons_down, 1); + assert_eq!(state.buttons_down, 1); + + assert_eq!( + send!(source_button_event( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(312)), + 1, + 5, + )), + vec![(5, hyperx, hyperx)] + ); + assert_eq!(state.buttons_down, 1); + assert_eq!( + send!(source_button_event( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::XTest(4), + 1, + 6, + )), + vec![(5, 4, 4), (5, 2, 4)], + "the final attached holder releases the master button" + ); + assert_eq!(state.buttons_down, 0); + assert_eq!(state.xi_devices.device(hyperx).unwrap().buttons_down, 0); + assert_eq!(state.xi_devices.device(4).unwrap().buttons_down, 0); + assert_eq!(state.sync_pending.len(), 0); + assert_eq!(state.xi_devices.devices().len(), 5); + assert!( + state + .xi_devices + .source(crate::xinput::InputSourceId(311)) + .is_none() + ); + assert!( + state + .xi_devices + .facet( + crate::xinput::InputSourceId(311), + crate::xinput::XiFacetKind::PointerTouch + ) + .is_none() + ); + assert!( + state + .xi_devices + .source(crate::xinput::InputSourceId(312)) + .is_some() + ); + assert!(state.unpublished_pointer_buttons_down.is_empty()); + assert_eq!(state.scroll_axis_value, [0, 0]); + assert_eq!( + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down, device.scroll_axis_values)) + .collect::>(), + vec![ + (2, 0, [0, 0]), + (3, 0, [0, 0]), + (4, 0, [0, 0]), + (5, 0, [0, 0]), + (hyperx, 0, [0, 0]), + ], + "the removed source leaves no state and unrelated devices stay clear" + ); +} + +#[test] +fn pointer_source_selection_keeps_scroll_values_and_stops_per_source() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + let razer = pointer_source(&mut state, 321, true); + let hyperx = pointer_source(&mut state, 322, true); + select_xi2(&mut state, 1, razer, 1 << 6); + select_xi2(&mut state, 1, hyperx, 1 << 6); + + for (source, count) in [(321, 2), (322, 1)] { + for n in 0..count { + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(source)), + 5, + source as u32 + n as u32, + ), + true, + false, + ); + assert!(dropped.is_empty()); + let _ = read_all_capture_available(&mut peer); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(source)), + 5, + source as u32 + n as u32, + ), + true, + false, + ); + assert!(dropped.is_empty()); + let _ = read_all_capture_available(&mut peer); + } + } + assert_eq!( + state.xi_devices.device(razer).unwrap().scroll_axis_values, + [2, 0] + ); + assert_eq!( + state.xi_devices.device(hyperx).unwrap().scroll_axis_values, + [1, 0] + ); + assert_eq!(state.scroll_axis_value, [1, 0]); + + for (source, device, expected) in [(321, razer, 2), (322, hyperx, 1)] { + crate::core_loop::pointer_fanout::emit_scroll_stop_to_state( + &mut state, + &HostXidMap::new(), + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(source)), + 0, + 10, + 20, + 0, + source as u32, + ); + assert_eq!( + xi2_scroll_values(&read_all_capture_available(&mut peer)), + vec![(device, device, expected), (device, device, 0)], + "scroll stop uses the selected source's cumulative valuator" + ); + assert_eq!( + state.xi_devices.device(device).unwrap().scroll_axis_values[0], + expected + ); + } + assert_eq!(state.xi_devices.device(razer).unwrap().buttons_down, 0); + assert_eq!(state.xi_devices.device(hyperx).unwrap().buttons_down, 0); + assert_eq!(state.buttons_down, 0); + assert_eq!(state.sync_pending.len(), 0); + assert_eq!(state.xi_devices.devices().len(), 6); + assert_eq!(state.scroll_axis_value, [1, 0]); + assert!(state.unpublished_pointer_buttons_down.is_empty()); + assert_eq!( + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down, device.scroll_axis_values)) + .collect::>(), + vec![ + (2, 0, [0, 0]), + (3, 0, [0, 0]), + (4, 0, [0, 0]), + (5, 0, [0, 0]), + (razer, 0, [2, 0]), + (hyperx, 0, [1, 0]), + ], + "each source retains its own valuator state" + ); +} + +#[test] +fn xi_slave_switch_master_scroll_value_uses_the_current_source_baseline() { + use crate::core_loop::InputOrigin; + + const RAZER: u64 = 0xA61; + const HYPERX: u64 = 0xA62; + const XI_BUTTON_PRESS: u32 = 1 << 4; + const XI_MOTION: u32 = 1 << 6; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 92); + let razer = pointer_source(&mut state, RAZER, true); + let hyperx = pointer_source(&mut state, HYPERX, true); + let mut selection = Vec::new(); + selection.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + selection.extend_from_slice(&1u16.to_le_bytes()); + selection.extend_from_slice(&[0; 2]); + selection.extend_from_slice(&2u16.to_le_bytes()); // master pointer + selection.extend_from_slice(&1u16.to_le_bytes()); // one mask word + selection.extend_from_slice( + &(crate::xinput::XI2_DEVICE_CHANGED_MASK | XI_BUTTON_PRESS | XI_MOTION).to_le_bytes(), + ); + crate::core_loop::process_request::process_request( + &mut state, + &mut backend, + yserver_protocol::x11::ClientId(92), + yserver_protocol::x11::SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 137, + data: 46, // XISelectEvents + length_units: 5, + }, + &selection, + None, + ) + .expect("select master DeviceChanged, ButtonPress, and Motion events"); + + for time in 1..=10 { + for kind in [ + PointerEventKind::ButtonPress, + PointerEventKind::ButtonRelease, + ] { + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + kind, + InputOrigin::Physical(crate::xinput::InputSourceId(RAZER)), + 5, + time, + ), + true, + false, + ); + assert!(dropped.is_empty()); + } + let _ = read_all_capture_available(&mut peer); + } + + assert_eq!(state.scroll_axis_value, [10, 0]); + assert_eq!( + state.xi_devices.device(razer).unwrap().scroll_axis_values, + [10, 0] + ); + assert_eq!( + state.xi_devices.device(hyperx).unwrap().scroll_axis_values, + [0, 0] + ); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + PointerEventKind::ButtonPress, + InputOrigin::Physical(crate::xinput::InputSourceId(HYPERX)), + 5, + 11, + ), + true, + false, + ); + assert!(dropped.is_empty()); + let bytes = read_all_capture_available(&mut peer); + + let mut switch_baseline = None; + let mut offset = 0; + while offset < bytes.len() { + assert_eq!(bytes[offset], 35, "XI2 GenericEvent"); + let units = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()) as usize; + let evtype = u16::from_le_bytes([bytes[offset + 8], bytes[offset + 9]]); + if evtype == 1 { + let num_classes = u16::from_le_bytes([bytes[offset + 16], bytes[offset + 17]]) as usize; + let mut class_offset = offset + 32; + for _ in 0..num_classes { + let class_type = u16::from_le_bytes([bytes[class_offset], bytes[class_offset + 1]]); + let class_units = + u16::from_le_bytes([bytes[class_offset + 2], bytes[class_offset + 3]]) as usize; + let source_id = + u16::from_le_bytes([bytes[class_offset + 4], bytes[class_offset + 5]]); + let axis = u16::from_le_bytes([bytes[class_offset + 6], bytes[class_offset + 7]]); + if class_type == 2 && source_id == hyperx && axis == 2 { + switch_baseline = Some(i32::from_le_bytes( + bytes[class_offset + 28..class_offset + 32] + .try_into() + .unwrap(), + )); + } + class_offset += class_units * 4; + } + assert_eq!(class_offset, offset + 32 + units * 4); + } + offset += 32 + units * 4; + } + assert_eq!(switch_baseline, Some(0)); + assert_eq!( + xi2_scroll_values(&bytes), + vec![(2, hyperx, 1)], + "the master event advances from the switching slave's baseline" + ); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + PointerEventKind::ButtonRelease, + InputOrigin::Physical(crate::xinput::InputSourceId(HYPERX)), + 5, + 12, + ), + true, + false, + ); + assert!(dropped.is_empty()); + let _ = read_all_capture_available(&mut peer); + assert_eq!(state.scroll_axis_value, [1, 0]); + assert_eq!( + state.xi_devices.device(razer).unwrap().scroll_axis_values, + [10, 0] + ); + assert_eq!( + state.xi_devices.device(hyperx).unwrap().scroll_axis_values, + [1, 0] + ); + assert_eq!(state.buttons_down, 0); + assert!(state.sync_pending.is_empty()); + assert!(state.unpublished_pointer_buttons_down.is_empty()); +} + +#[test] +fn xi_scroll_stop_switches_back_from_xtest_and_keeps_master_query_baseline() { + use crate::core_loop::InputOrigin; + use yserver_protocol::x11::{RequestHeader, SequenceNumber}; + + const CLIENT: u32 = 0xA740; + const TOUCHPAD_SOURCE: u64 = 0xA7401; + const XI_DEVICE_CHANGED: u32 = 1 << 1; + const XI_MOTION: u32 = 1 << 6; + + fn request( + state: &mut ServerState, + backend: &mut RecordingBackend, + sequence: u16, + minor: u8, + body: &[u8], + ) { + crate::core_loop::process_request::process_request( + state, + backend, + ClientId(CLIENT), + SequenceNumber(sequence), + RequestHeader { + opcode: 137, + data: minor, + length_units: u32::try_from((body.len() + 4) / 4).unwrap(), + }, + body, + None, + ) + .expect("production XI2 request dispatch"); + } + + fn query_master_scroll(bytes: &[u8]) -> i32 { + assert_eq!(bytes[0], 1, "XIQueryDevice reply"); + let devices = u16::from_le_bytes([bytes[8], bytes[9]]) as usize; + let mut offset = 32; + for _ in 0..devices { + let device = u16::from_le_bytes([bytes[offset], bytes[offset + 1]]); + let classes = u16::from_le_bytes([bytes[offset + 6], bytes[offset + 7]]) as usize; + let name_len = u16::from_le_bytes([bytes[offset + 8], bytes[offset + 9]]) as usize; + let mut class_offset = offset + 12 + name_len; + while !class_offset.is_multiple_of(4) { + class_offset += 1; + } + for _ in 0..classes { + let class = u16::from_le_bytes([bytes[class_offset], bytes[class_offset + 1]]); + let units = + u16::from_le_bytes([bytes[class_offset + 2], bytes[class_offset + 3]]) as usize; + let axis = u16::from_le_bytes([bytes[class_offset + 6], bytes[class_offset + 7]]); + if device == 2 && class == 2 && axis == 2 { + return i32::from_le_bytes( + bytes[class_offset + 28..class_offset + 32] + .try_into() + .unwrap(), + ); + } + class_offset += units * 4; + } + offset = class_offset; + } + panic!("master vertical scroll valuator missing from query reply"); + } + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, CLIENT); + let touchpad = pointer_source(&mut state, TOUCHPAD_SOURCE, true); + + request(&mut state, &mut backend, 1, 47, &[2, 0, 4, 0]); + let _ = read_all_capture_available(&mut peer); + let mut select = Vec::new(); + select.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&[0; 2]); + select.extend_from_slice(&2u16.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&(XI_DEVICE_CHANGED | XI_MOTION).to_le_bytes()); + request(&mut state, &mut backend, 2, 46, &select); + let _ = read_all_capture_available(&mut peer); + + // Five source events establish the touchpad's valuator before a + // virtual XTEST motion switches the master back to device 4. + // Xorg runs UpdateFromMaster on both pointer events and stops at + // dix/getevents.c:687-708, so the following stop must switch back, + // copy this source's valuator, and report the same query baseline. + for time in 10..15 { + for kind in [ + PointerEventKind::ButtonPress, + PointerEventKind::ButtonRelease, + ] { + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + kind, + InputOrigin::Physical(crate::xinput::InputSourceId(TOUCHPAD_SOURCE)), + 5, + time, + ), + true, + false, + ); + assert!(dropped.is_empty()); + } + } + assert_eq!( + state + .xi_devices + .device(touchpad) + .unwrap() + .scroll_axis_values, + [5, 0] + ); + let _ = read_all_capture_available(&mut peer); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + HostPointerEvent { + origin: InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + ..motion_event() + }, + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!(state.xi_last_slave(2), Some(4)); + let _ = read_all_capture_available(&mut peer); + + crate::core_loop::pointer_fanout::emit_scroll_stop_to_state( + &mut state, + &HostXidMap::new(), + InputOrigin::Physical(crate::xinput::InputSourceId(TOUCHPAD_SOURCE)), + 0, + 10, + 20, + 0, + 20, + ); + let stop_bytes = read_all_capture_available(&mut peer); + let events = xi2_scroll_values(&stop_bytes); + let mut switch_source = None; + let mut offset = 0; + while offset < stop_bytes.len() { + assert_eq!(stop_bytes[offset], 35, "XI2 GenericEvent"); + let units = + u32::from_le_bytes(stop_bytes[offset + 4..offset + 8].try_into().unwrap()) as usize; + if u16::from_le_bytes([stop_bytes[offset + 8], stop_bytes[offset + 9]]) == 1 { + switch_source = Some(u16::from_le_bytes([ + stop_bytes[offset + 18], + stop_bytes[offset + 19], + ])); + } + offset += 32 + units * 4; + } + assert_eq!( + switch_source, + Some(touchpad), + "PointerScrollStop emits the SlaveSwitch DeviceChanged before stop motion" + ); + assert_eq!(state.xi_last_slave(2), Some(touchpad)); + assert_eq!(events, vec![(2, touchpad, 5), (2, touchpad, 0)]); + assert_eq!(state.scroll_axis_value, [5, 0]); + + request(&mut state, &mut backend, 3, 48, &[2, 0, 0, 0]); + assert_eq!( + query_master_scroll(&read_all_capture_available(&mut peer)), + 5 + ); + assert_eq!( + state + .xi_devices + .device(touchpad) + .unwrap() + .scroll_axis_values, + [5, 0] + ); + assert_eq!( + state.xi_devices.device(touchpad).unwrap().attached_master, + Some(2) + ); + assert!(state.xi2_pointer_grabs.is_empty()); + assert!(state.active_pointer_grab.is_none()); + assert!(state.sync_pending.is_empty()); + assert_eq!(state.buttons_down, 0); + assert_eq!(state.xi_devices.device(touchpad).unwrap().buttons_down, 0); +} + +#[test] +fn physical_scroll_motion_survives_xtest_hold_of_the_emulated_button() { + use crate::core_loop::InputOrigin; + use yserver_protocol::x11::{RequestHeader, SequenceNumber}; + + const CLIENT: u32 = 0xA741; + const SOURCE: u64 = 0xA7411; + const XI_MOTION: u32 = 1 << 6; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, CLIENT); + let pointer = pointer_source(&mut state, SOURCE, true); + let dispatch = + |state: &mut ServerState, backend: &mut RecordingBackend, sequence, minor, body: &[u8]| { + crate::core_loop::process_request::process_request( + state, + backend, + ClientId(CLIENT), + SequenceNumber(sequence), + RequestHeader { + opcode: 137, + data: minor, + length_units: u32::try_from((body.len() + 4) / 4).unwrap(), + }, + body, + None, + ) + .expect("production XI2 request dispatch") + }; + dispatch(&mut state, &mut backend, 1, 47, &[2, 0, 4, 0]); + let _ = read_all_capture_available(&mut peer); + let mut select = Vec::new(); + select.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&[0; 2]); + select.extend_from_slice(&2u16.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&XI_MOTION.to_le_bytes()); + dispatch(&mut state, &mut backend, 2, 46, &select); + let _ = read_all_capture_available(&mut peer); + + let press = |origin| source_button_event(PointerEventKind::ButtonPress, origin, 5, 30); + let release = |origin| source_button_event(PointerEventKind::ButtonRelease, origin, 5, 31); + { + let event = press(InputOrigin::XTest(4)); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + assert!(dropped.is_empty()); + } + let xtest_events = read_all_capture_available(&mut peer); + assert!( + xi2_event_ids(&xtest_events) + .iter() + .all(|(event_type, ..)| *event_type == 6), + "Motion selection receives smooth scrolling but no emulated ButtonPress" + ); + assert_eq!( + state + .xi_devices + .device(crate::xinput::DEVICEID_XTEST_POINTER) + .unwrap() + .buttons_down, + 1 << 4, + "XTEST button transition holds the master even without XI_ButtonPress selected" + ); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + press(InputOrigin::Physical(crate::xinput::InputSourceId(SOURCE))), + true, + false, + ); + assert!(dropped.is_empty()); + let physical_scroll = read_all_capture_available(&mut peer); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + release(InputOrigin::Physical(crate::xinput::InputSourceId(SOURCE))), + true, + false, + ); + assert!(dropped.is_empty()); + let release_events = xi2_event_ids(&read_all_capture_available(&mut peer)); + + // Xorg makes the scroll valuator Motion before generating legacy + // wheel-button emulation (dix/getevents.c:1646-1697, 1703-1718). The separate + // button transition is rejected by master aggregation while XTEST + // holds button 5, but the physical scroll Motion still reaches the + // attached master. + assert_eq!(xi2_scroll_values(&physical_scroll), vec![(2, pointer, 1)]); + assert!( + !xi2_event_ids(&physical_scroll) + .iter() + .any(|(evtype, device, source)| *evtype == 4 && *device == 2 && *source == pointer), + "suppressed master ButtonPress stays suppressed" + ); + assert!( + release_events.is_empty(), + "the physical wheel release is aggregated away" + ); + assert_eq!( + state.xi_devices.device(pointer).unwrap().scroll_axis_values, + [1, 0] + ); + assert_eq!(state.scroll_axis_value, [1, 0]); + assert_eq!(state.xi_devices.device(pointer).unwrap().buttons_down, 0); + assert_eq!( + state.xi_devices.device(pointer).unwrap().attached_master, + Some(2) + ); + assert_eq!( + state + .xi_devices + .device(crate::xinput::DEVICEID_XTEST_POINTER) + .unwrap() + .buttons_down, + 1 << 4, + "the XTEST source still holds logical button 5", + ); + assert_eq!( + state.buttons_down, + 1 << 4, + "master button remains held by XTEST" + ); + assert!(state.xi2_pointer_grabs.is_empty()); + assert!(state.active_pointer_grab.is_none()); + assert!(state.sync_pending.is_empty()); + assert!(state.unpublished_pointer_buttons_down.is_empty()); +} + +#[test] +fn record_does_not_admit_frozen_input_from_a_floating_pointer() { + use crate::{core_loop::InputOrigin, host_x11::HostPointerEvent, server::QueuedInputEvent}; + use yserver_protocol::x11::{RequestHeader, SequenceNumber}; + + const RECORDER: u32 = 0xA743; + const GRABBER: u32 = 0xA744; + const SOURCE: u64 = 0xA7431; + const CONTEXT: u32 = 1; + + fn request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + opcode: u8, + minor: u8, + body: &[u8], + ) { + crate::core_loop::process_request::process_request( + state, + backend, + ClientId(client), + SequenceNumber(sequence), + RequestHeader { + opcode, + data: minor, + length_units: u32::try_from((body.len() + 4) / 4).unwrap(), + }, + body, + None, + ) + .expect("production request dispatch"); + } + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut recorder = install_capture_client(&mut state, RECORDER); + let mut grabber = install_capture_client(&mut state, GRABBER); + let pointer = pointer_source(&mut state, SOURCE, true); + + // CreateContext/EnableContext select core ButtonPress..ButtonRelease + // through the RECORD dispatcher, like Xorg's Record callback test. + let mut create_context = Vec::new(); + create_context.extend_from_slice(&CONTEXT.to_le_bytes()); + create_context.extend_from_slice(&[0; 4]); // element header + pad + create_context.extend_from_slice(&1u32.to_le_bytes()); // one client spec + create_context.extend_from_slice(&1u32.to_le_bytes()); // one range + create_context.extend_from_slice(&2u32.to_le_bytes()); // FutureClients + let mut range = [0u8; 24]; + range[18] = 2; // KeyPress / ButtonPress + range[19] = 5; // KeyRelease / ButtonRelease + create_context.extend_from_slice(&range); + request( + &mut state, + &mut backend, + RECORDER, + 1, + 154, + 1, + &create_context, + ); + request( + &mut state, + &mut backend, + RECORDER, + 2, + 154, + 5, + &CONTEXT.to_le_bytes(), + ); + let _ = read_all_capture_available(&mut recorder); + + request(&mut state, &mut backend, GRABBER, 1, 137, 47, &[2, 0, 4, 0]); + let _ = read_all_capture_available(&mut grabber); + let mut grab = Vec::new(); + grab.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + grab.extend_from_slice(&0u32.to_le_bytes()); // CurrentTime + grab.extend_from_slice(&0u32.to_le_bytes()); // no cursor + grab.extend_from_slice(&pointer.to_le_bytes()); + grab.extend_from_slice(&[0, 1, 0, 0]); // synchronous device, async paired + grab.extend_from_slice(&0u16.to_le_bytes()); // no event-mask words + grab.extend_from_slice(&[0; 2]); + request(&mut state, &mut backend, GRABBER, 2, 137, 51, &grab); + let _ = read_all_capture_available(&mut grabber); + assert_eq!( + state.xi_devices.device(pointer).unwrap().attached_master, + None + ); + assert!(state.xi2_pointer_grabs.contains_key(&pointer)); + assert!(state.xi1_frozen[&pointer].frozen()); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + HostPointerEvent { + origin: InputOrigin::Physical(crate::xinput::InputSourceId(SOURCE)), + kind: PointerEventKind::ButtonPress, + detail: 1, + time: 40, + ..motion_event() + }, + true, + false, + ); + assert!(dropped.is_empty()); + let record_wire = read_all_capture_available(&mut recorder); + let mut core_events = Vec::new(); + let mut offset = 0; + while offset + 32 <= record_wire.len() { + assert_eq!(record_wire[offset], 1, "RECORD reply stream"); + let words = + u32::from_le_bytes(record_wire[offset + 4..offset + 8].try_into().unwrap()) as usize; + let end = offset + 32 + words * 4; + assert!(end <= record_wire.len(), "complete RECORD reply"); + if record_wire[offset + 1] == 0 && words > 0 { + core_events.push(record_wire[offset + 32]); + } + offset = end; + } + + // Xorg calls DeviceEventCallback on frozen queue admission, but + // record/record.c:784 converts to core only for IsMaster. A floating + // source has no attached master copy (mi/mieq.c:397), so it must not + // record a core ButtonPress while its own sync grab queues it. + assert!( + core_events.is_empty(), + "floating frozen input is not core RECORD data" + ); + assert_eq!(state.sync_pending.len(), 1); + assert_eq!(state.sync_pending[0].device, pointer); + assert!(matches!( + state.sync_pending[0].event, + QueuedInputEvent::HostPointer(HostPointerEvent { + kind: PointerEventKind::ButtonPress, + detail: 1, + .. + }) + )); + assert_eq!(state.xi_devices.device(pointer).unwrap().buttons_down, 1); + assert_eq!( + state.buttons_down, 0, + "floating source has no master button hold" + ); + assert_eq!( + state.xi_devices.device(pointer).unwrap().attached_master, + None + ); + assert!(state.xi1_frozen[&pointer].frozen()); + assert!(state.xi2_pointer_grabs.contains_key(&pointer)); +} + +#[test] +fn xi_owner_events_fallback_preserves_other_recipients_root_geometry() { + use crate::{core_loop::InputOrigin, resources::ROOT_VISUAL}; + use yserver_protocol::x11::{RequestHeader, SequenceNumber}; + + const GRABBER: u32 = 0xA745; + const SELECTOR: u32 = 0xA746; + const SOURCE: u64 = 0xA7451; + const HOST_XID: u32 = 0xCAFE_A745; + const CHILD: u32 = 0x0010_A745; + const XI_MOTION: u32 = 1 << 6; + + fn request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + minor: u8, + body: &[u8], + ) { + crate::core_loop::process_request::process_request( + state, + backend, + ClientId(client), + SequenceNumber(sequence), + RequestHeader { + opcode: 137, + data: minor, + length_units: u32::try_from((body.len() + 4) / 4).unwrap(), + }, + body, + None, + ) + .expect("production XI2 request dispatch"); + } + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut grabber = install_capture_client(&mut state, GRABBER); + let mut selector = install_capture_client(&mut state, SELECTOR); + let pointer = pointer_source(&mut state, SOURCE, true); + + state.resources.create_window( + ClientId(SELECTOR), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD), + parent: ROOT_WINDOW, + x: 20, + y: 30, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(CHILD)); + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_XID, ResourceId(CHILD)); + + for client in [GRABBER, SELECTOR] { + request(&mut state, &mut backend, client, 1, 47, &[2, 0, 4, 0]); + } + let _ = read_all_capture_available(&mut grabber); + let _ = read_all_capture_available(&mut selector); + + let mut select = Vec::new(); + select.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&[0; 2]); + select.extend_from_slice(&2u16.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&XI_MOTION.to_le_bytes()); + request(&mut state, &mut backend, SELECTOR, 2, 46, &select); + let _ = read_all_capture_available(&mut selector); + + let mut grab = Vec::new(); + grab.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + grab.extend_from_slice(&0u32.to_le_bytes()); // CurrentTime + grab.extend_from_slice(&0u32.to_le_bytes()); // no cursor + grab.extend_from_slice(&2u16.to_le_bytes()); // master pointer + grab.extend_from_slice(&[1, 1, 1, 0]); // async, async paired, owner_events=true + grab.extend_from_slice(&1u16.to_le_bytes()); + grab.extend_from_slice(&XI_MOTION.to_le_bytes()); + request(&mut state, &mut backend, GRABBER, 2, 51, &grab); + let _ = read_all_capture_available(&mut grabber); + assert!( + state + .active_pointer_grab + .is_some_and(|active| { active.owner == ClientId(GRABBER) && active.owner_events }) + ); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: InputOrigin::Physical(crate::xinput::InputSourceId(SOURCE)), + kind: PointerEventKind::MotionNotify, + host_xid: HOST_XID, + root_x: 45, + root_y: 65, + event_x: 25, + event_y: 35, + time: 50, + ..motion_event() + }, + true, + false, + ); + assert!(dropped.is_empty()); + + let selector_bytes = read_all_capture_available(&mut selector); + let grabber_bytes = read_all_capture_available(&mut grabber); + assert_eq!(selector_bytes[0], 35, "selector receives XI_Motion"); + assert_eq!( + u16::from_le_bytes([selector_bytes[8], selector_bytes[9]]), + 6 + ); + assert_eq!( + u32::from_le_bytes(selector_bytes[24..28].try_into().unwrap()), + ROOT_WINDOW.0, + "other recipients keep the root event window under owner-events fallback" + ); + assert_eq!( + u32::from_le_bytes(selector_bytes[28..32].try_into().unwrap()), + CHILD, + "the selected root event retains its child path" + ); + assert_eq!( + i16::from_le_bytes(selector_bytes[42..44].try_into().unwrap()), + 45, + "root selection receives root-local event_x" + ); + assert_eq!( + i16::from_le_bytes(selector_bytes[46..48].try_into().unwrap()), + 65, + "root selection receives root-local event_y" + ); + assert_eq!( + grabber_bytes[0], 35, + "fallback grab owner receives XI_Motion" + ); + assert_eq!( + u32::from_le_bytes(grabber_bytes[24..28].try_into().unwrap()), + ROOT_WINDOW.0, + "grab owner gets its grab window" + ); + assert_eq!( + u32::from_le_bytes(grabber_bytes[28..32].try_into().unwrap()), + 0, + "grab-owner fallback has no child" + ); + assert_eq!( + i16::from_le_bytes(grabber_bytes[42..44].try_into().unwrap()), + 45 + ); + assert_eq!( + i16::from_le_bytes(grabber_bytes[46..48].try_into().unwrap()), + 65 + ); + assert_eq!(state.pointer_root, (45, 65)); + assert_eq!( + state.xi_devices.device(pointer).unwrap().attached_master, + Some(2) + ); + assert!(state.sync_pending.is_empty()); + assert_eq!(state.buttons_down, 0); + assert_eq!(state.xi_devices.device(pointer).unwrap().buttons_down, 0); + assert_eq!(state.active_pointer_grab.unwrap().owner, ClientId(GRABBER)); +} + +#[test] +fn xi_slave_switch_pointer_alternates_before_master_motion_and_uses_facet_scroll() { + use crate::core_loop::InputOrigin; + + const RAZER: u64 = 0xA51; + const HYPERX: u64 = 0xA52; + const XI_MOTION: u64 = 1 << 6; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 91); + let razer = pointer_source(&mut state, RAZER, true); + let hyperx = pointer_source(&mut state, HYPERX, true); + state.xi_devices.device_mut(razer).unwrap().name = "Razer".to_owned(); + state.xi_devices.device_mut(hyperx).unwrap().name = "HyperX".to_owned(); + assert_eq!((razer, hyperx), (6, 7)); + select_xi2( + &mut state, + 91, + 2, + u64::from(crate::xinput::XI2_DEVICE_CHANGED_MASK), + ); + + // Generate independent scroll state through the ordinary pointer + // event path before checking the classes carried by later switches. + for (source, device) in [(RAZER, razer), (HYPERX, hyperx)] { + for (kind, time) in [ + (PointerEventKind::ButtonPress, 1), + (PointerEventKind::ButtonRelease, 2), + ] { + let _dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event( + kind, + InputOrigin::Physical(crate::xinput::InputSourceId(source)), + 5, + time, + ), + true, + false, + ); + } + assert_eq!( + state.xi_devices.device(device).unwrap().scroll_axis_values, + [1, 0] + ); + let _ = read_all_capture_available(&mut peer); + } + + select_xi2( + &mut state, + 91, + 2, + u64::from(crate::xinput::XI2_DEVICE_CHANGED_MASK) | XI_MOTION, + ); + let mut headers = Vec::new(); + for (source, device) in [(RAZER, razer), (HYPERX, hyperx), (HYPERX, hyperx)] { + let event = HostPointerEvent { + origin: InputOrigin::Physical(crate::xinput::InputSourceId(source)), + ..motion_event() + }; + let _dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + let bytes = read_all_capture_available(&mut peer); + let mut offset = 0; + while offset + 32 <= bytes.len() { + let event_type = u16::from_le_bytes([bytes[offset + 8], bytes[offset + 9]]); + let event_device = u16::from_le_bytes([bytes[offset + 10], bytes[offset + 11]]); + let source_offset = if event_type == 1 { 18 } else { 52 }; + let event_source = u16::from_le_bytes([ + bytes[offset + source_offset], + bytes[offset + source_offset + 1], + ]); + if event_type == 1 { + let reason = bytes[offset + 20]; + let num_classes = + u16::from_le_bytes([bytes[offset + 16], bytes[offset + 17]]) as usize; + let mut class_offset = offset + 32; + let mut valuators = Vec::new(); + for _ in 0..num_classes { + let class_type = + u16::from_le_bytes([bytes[class_offset], bytes[class_offset + 1]]); + let units = + u16::from_le_bytes([bytes[class_offset + 2], bytes[class_offset + 3]]) + as usize; + let class_source = + u16::from_le_bytes([bytes[class_offset + 4], bytes[class_offset + 5]]); + if class_type == 2 { + let number = + u16::from_le_bytes([bytes[class_offset + 6], bytes[class_offset + 7]]); + let value = i32::from_le_bytes( + bytes[class_offset + 28..class_offset + 32] + .try_into() + .unwrap(), + ); + valuators.push((class_source, number, value)); + } + class_offset += units * 4; + } + assert_eq!( + class_offset, + offset + + 32 + + u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap(),) + as usize + * 4 + ); + assert_eq!(event_device, 2, "DeviceChanged is on the master pointer"); + assert_eq!(event_source, device, "sourceid is the newly active slave"); + assert_eq!(reason, 1, "XI2.h XISlaveSwitch"); + assert_eq!( + valuators, + vec![ + (device, 0, 400), + (device, 1, 300), + (device, 2, 1), + (device, 3, 0), + ], + "class valuators use the switching facet's scroll snapshot" + ); + } + headers.push((event_type, event_device, event_source)); + let units = + u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()) as usize; + offset += 32 + units * 4; + } + assert_eq!(offset, bytes.len(), "complete XI2 event stream"); + } + assert_eq!( + headers, + vec![ + (1, 2, razer), + (6, 2, razer), + (1, 2, hyperx), + (6, 2, hyperx), + (6, 2, hyperx), + ], + "a source switch precedes that source's first master event; same-source motion has none" + ); + + // A floating slave still delivers its own form, but cannot replace + // the attached master's last source. + assert!(state.detach_xi2_slave(razer)); + let floating = HostPointerEvent { + origin: InputOrigin::XTest(razer), + ..motion_event() + }; + let _dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + floating, + true, + false, + ); + let floating_events = read_all_capture_available(&mut peer); + assert!( + !floating_events + .chunks_exact(32) + .any(|event| event[0] == 35 && u16::from_le_bytes([event[8], event[9]]) == 1), + "floating input does not emit a master DeviceChanged" + ); + assert_eq!(state.xi_last_slave(2), Some(hyperx)); + assert_eq!(state.buttons_down, 0); + assert!(state.sync_pending.is_empty()); + assert!(state.unpublished_pointer_buttons_down.is_empty()); + assert_eq!(state.xi_devices.devices().len(), 6); + assert_eq!( + state.xi_devices.device(razer).unwrap().scroll_axis_values, + [1, 0] + ); + assert_eq!( + state.xi_devices.device(hyperx).unwrap().scroll_axis_values, + [1, 0] + ); + assert!(state.xi_devices.device(razer).unwrap().enabled); + assert!(state.xi_devices.device(hyperx).unwrap().enabled); +} + +#[test] +fn pointer_source_selection_unpublished_source_tracks_its_own_hold() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + for source in 2000..2122 { + assert_ne!(pointer_source(&mut state, source, true), 0); + } + let unpublished = crate::xinput::InputSourceId(330); + assert_eq!(pointer_source(&mut state, unpublished.0, true), 0); + select_xi2(&mut state, 1, 2, 1 << 4 | 1 << 5); + select_xi2(&mut state, 1, 4, 1 << 4 | 1 << 5); + + for (kind, origin, expected) in [ + ( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::Physical(unpublished), + vec![(4, 2, 2)], + ), + ( + PointerEventKind::ButtonPress, + crate::core_loop::InputOrigin::XTest(4), + vec![(4, 4, 4)], + ), + ( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::Physical(unpublished), + Vec::new(), + ), + ( + PointerEventKind::ButtonRelease, + crate::core_loop::InputOrigin::XTest(4), + vec![(5, 4, 4), (5, 2, 4)], + ), + ] { + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + source_button_event(kind, origin, 1, 1), + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!( + xi2_event_ids(&read_all_capture_available(&mut peer)), + expected + ); + } + assert_eq!( + state.unpublished_pointer_buttons_down.get(&unpublished), + None + ); + assert_eq!(state.buttons_down, 0); + assert_eq!(state.xi_devices.devices().len(), 126); + assert_eq!(state.xi_devices.device(4).unwrap().buttons_down, 0); + assert_eq!(state.sync_pending.len(), 0); + assert!(state.xi_devices.source(unpublished).is_some()); + assert!( + state + .xi_devices + .facet(unpublished, crate::xinput::XiFacetKind::PointerTouch) + .is_none() + ); + assert_eq!(state.buttons_down, 0); + assert!( + state + .xi_devices + .devices() + .iter() + .all(|device| device.buttons_down == 0) + ); + assert!( + state + .xi_devices + .devices() + .iter() + .all(|device| device.scroll_axis_values == [0, 0]) + ); +} + +#[test] +fn replayed_pointer_press_records_held_state_until_release() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let origin = crate::core_loop::InputOrigin::XTest(4); + let press = source_button_event(PointerEventKind::ButtonPress, origin, 1, 1); + + let _ = + replay_frozen_pointer_event_to_state(&mut state, &mut backend, &HostXidMap::new(), press); + assert_eq!( + state.buttons_down, 1, + "replayed press marks the master button down" + ); + assert_eq!( + state.xi_devices.device(4).unwrap().buttons_down, + 1, + "replayed press marks its generating XI device down" + ); + + let release = source_button_event(PointerEventKind::ButtonRelease, origin, 1, 2); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + release, + true, + false, + ); + assert_eq!(state.buttons_down, 0, "release leaves the master button up"); + assert_eq!( + state.xi_devices.device(4).unwrap().buttons_down, + 0, + "release leaves its generating XI device up" + ); +} + +#[test] +fn pointer_source_routing_attributes_two_physical_facets() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + let first = pointer_source(&mut state, 101, true); + let second = pointer_source(&mut state, 102, true); + assert_eq!((first, second), (6, 7)); + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 0), (1 << 6) | (1 << 17)); + + for source in [101, 102] { + let mut event = motion_event(); + event.origin = + crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(source)); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + assert!(dropped.is_empty()); + } + + let events = xi2_event_ids(&read_all_capture_available(&mut peer)); + let device_forms: Vec<_> = events + .iter() + .copied() + .filter(|(kind, _, _)| *kind == 6) + .collect(); + let raw_forms: Vec<_> = events + .iter() + .copied() + .filter(|(kind, _, _)| *kind == 17) + .collect(); + assert_eq!( + device_forms, + vec![ + (6, first, first), + (6, 2, first), + (6, second, second), + (6, 2, second) + ] + ); + assert_eq!( + raw_forms, + vec![ + (17, first, first), + (17, 2, first), + (17, second, second), + (17, 2, second), + ] + ); + assert_eq!( + state.xi_devices.facet( + crate::xinput::InputSourceId(101), + crate::xinput::XiFacetKind::PointerTouch + ), + Some(first) + ); + assert_eq!( + state.xi_devices.facet( + crate::xinput::InputSourceId(102), + crate::xinput::XiFacetKind::PointerTouch + ), + Some(second) + ); + assert_eq!(state.buttons_down, 0); +} + +#[test] +fn pointer_source_routing_preserves_xtest_targets_and_nested_master_only() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + let physical = pointer_source(&mut state, 103, true); + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 0), (1 << 6) | (1 << 17)); + + for origin in [ + crate::core_loop::InputOrigin::XTest(4), + crate::core_loop::InputOrigin::XTest(physical), + crate::core_loop::InputOrigin::NestedHost, + ] { + let mut event = motion_event(); + event.origin = origin; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + assert!(dropped.is_empty()); + } + + let events = xi2_event_ids(&read_all_capture_available(&mut peer)); + let device_forms: Vec<_> = events + .iter() + .copied() + .filter(|(kind, _, _)| *kind == 6) + .collect(); + let raw_forms: Vec<_> = events + .iter() + .copied() + .filter(|(kind, _, _)| *kind == 17) + .collect(); + assert_eq!( + device_forms, + vec![ + (6, 4, 4), + (6, 2, 4), + (6, physical, physical), + (6, 2, physical), + (6, 2, 2) + ] + ); + assert_eq!( + raw_forms, + vec![ + (17, 4, 4), + (17, 2, 4), + (17, physical, physical), + (17, 2, physical), + (17, 2, 2), + ] + ); + assert_eq!( + state.xi_devices.facet( + crate::xinput::InputSourceId(103), + crate::xinput::XiFacetKind::PointerTouch + ), + Some(physical) + ); + assert_eq!(state.buttons_down, 0); +} + +#[test] +fn pointer_source_routing_unpublished_source_is_master_only_and_unknown_is_dropped() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + for source in 2000..2122 { + assert_ne!(pointer_source(&mut state, source, true), 0); + } + assert_eq!( + pointer_source(&mut state, 104, true), + 0, + "physical XI IDs are exhausted" + ); + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 0), (1 << 6) | (1 << 17)); + + let mut unpublished = motion_event(); + unpublished.origin = crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(104)); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + unpublished, + true, + false, + ); + assert!(dropped.is_empty()); + let events = xi2_event_ids(&read_all_capture_available(&mut peer)); + assert_eq!(events, vec![(17, 2, 2), (6, 2, 2)]); + + let before_history = state.pointer_motion_history.len(); + let before_registry = state.xi_devices.devices().len(); + let mut unknown = motion_event(); + unknown.origin = crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(999)); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + unknown, + true, + false, + ); + assert!(dropped.is_empty()); + assert!(read_all_capture_available(&mut peer).is_empty()); + assert_eq!(state.pointer_motion_history.len(), before_history); + assert_eq!(state.xi_devices.devices().len(), before_registry); + assert!( + state + .xi_devices + .source(crate::xinput::InputSourceId(999)) + .is_none() + ); + assert_eq!(state.buttons_down, 0); + + let disabled_source = crate::xinput::InputSourceId(105); + pointer_source(&mut state, disabled_source.0, true); + let mut disabled_info = state.xi_devices.source(disabled_source).unwrap().clone(); + disabled_info.enabled = false; + state.xi_register_source(&disabled_info); + let mut disabled_press = motion_event(); + disabled_press.kind = PointerEventKind::ButtonPress; + disabled_press.detail = 1; + disabled_press.origin = crate::core_loop::InputOrigin::Physical(disabled_source); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + disabled_press, + true, + false, + ); + assert!(dropped.is_empty()); + assert!(read_all_capture_available(&mut peer).is_empty()); + assert_eq!( + state.buttons_down, 0, + "disabled source cannot mutate held state" + ); + assert_eq!(state.sync_pending.len(), 0); + assert_eq!(state.xi_devices.devices().len(), before_registry); + assert!( + state + .xi_devices + .facet(disabled_source, crate::xinput::XiFacetKind::PointerTouch) + .is_none() + ); + assert!(!state.xi_devices.source(disabled_source).unwrap().enabled); +} + +#[test] +fn translated_motion_is_recorded_once_in_bounded_history() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let event = motion_event(); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + assert_eq!(state.pointer_motion_history.len(), 1); + assert_eq!(state.pointer_motion_history[0].time, event.time); + assert_eq!(state.pointer_motion_history[0].root_x, event.root_x); + assert_eq!(state.pointer_motion_history[0].root_y, event.root_y); +} + +/// Regression (HW-confirmed 2026-07-10, Telegram/Qt on silence): +/// a client selecting `XIAllDevices(0)` receives every pointer event +/// in BOTH slave- and master-stamped forms, and the SLAVE form MUST be +/// emitted first — matching Xorg's `mieqProcessDeviceEvent` +/// ("process slave first, then master", mi/mieq.c). Qt compresses +/// consecutive XI_Motion keeping only the last (qxcbconnection.cpp) and +/// drops the slave-deviceid copy (qxcbconnection_xi2.cpp:689). With the +/// old master-first order every master copy was trailed by its slave +/// copy → compressed away → and the surviving slave copy dropped, so +/// ZERO motion (and thus zero smooth-scroll, which rides XI_Motion) +/// reached the widget: hover-scrollbars + wheel dead while clicks +/// (not motion-compressed) worked. Slave-first leaves the master copy +/// — the one Qt keeps — trailing, so it survives compression. +/// Issue #94 follow-up: an XI2 client holding an active `XIGrabDevice` +/// (`owner_events=true`) must receive the grabbed `ButtonRelease` even +/// when the pointer is over a window it never `XISelectEvents`'d on — +/// Xorg `DeliverGrabbedEvent` falls back to grab-window delivery using +/// the grab mask. CEF grabs the pointer on mousedown and holds it to +/// mouseup; the release fires over a window it holds only via the grab, +/// so without the fallback the mouse-up reaches nobody and clicks never +/// complete (Steam nav/menus/close all dead post-crash-fix). +#[test] +fn xi2_grabbed_button_release_reaches_grab_owner_via_grab_window() { + use crate::server::ActivePointerGrab; + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const GC: u32 = 2; // grab owner (CEF-like) + let grab_win = ResourceId(0x0020_0001); // GC's window == grab window + let hit_win = ResourceId(0x0020_0002); // child GC owns but did NOT select on + + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + let mut gc_peer = install_client(&mut state, GC); + + state.resources.create_window( + ClientId(GC), + CreateWindowRequest { + depth: 24, + window: grab_win, + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(GC), + CreateWindowRequest { + depth: 24, + window: hit_win, + parent: grab_win, + x: 10, + y: 10, + width: 40, + height: 40, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(grab_win); + let _ = state.resources.map_window(hit_win); + + // Active XI2 grab held by GC (matching CEF's XIGrabDevice device=2, + // async, owner_events=true). GC has NO XISelectEvents mask anywhere + // — it holds the pointer purely via the grab. + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(GC), + grab_window: grab_win, + event_mask: 0xFFFF, + cursor: ResourceId(0), + time: 0, + owner_events: true, + via_xi2: true, + implicit: false, + passive: false, + xi2_mask: u64::MAX, + }); + + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE_u32, grab_win); + + let mut rel = motion_event(); + rel.kind = PointerEventKind::ButtonRelease; + rel.host_xid = 0xCAFE; + rel.detail = 1; + rel.root_x = 20; + rel.root_y = 20; + rel.event_x = 20; + rel.event_y = 20; + + let mut press = rel; + press.kind = PointerEventKind::ButtonPress; + press.state = 0; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let _ = read_all_available(&mut gc_peer); + + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, rel, true, false); + + let bytes = read_all_available(&mut gc_peer); + let mut found = None; + let mut off = 0usize; + while off + 32 <= bytes.len() { + if bytes[off] == 35 && u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]) == 5 { + found = Some(u32::from_le_bytes( + bytes[off + 24..off + 28].try_into().unwrap(), + )); + break; + } + let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; + off += 32 + length * 4; + } + assert!( + found.is_some(), + "grab owner must receive the grabbed XI2 ButtonRelease (Xorg grab-window fallback); got none" + ); + assert_eq!( + found.unwrap(), + grab_win.0, + "grabbed release must be reported on the grab window" + ); +} + +/// Core grabs use the same grab-window fallback as XI2 grabs: when +/// owner-events delivery finds no selected natural target, the grab +/// owner still receives the event on the grab window. +#[test] +fn core_grabbed_button_release_reaches_grab_owner_via_grab_window() { + use crate::server::ActivePointerGrab; + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + + const OWNER: u32 = 2; + let grab_win = ResourceId(0x0020_0001); + let hit_win = ResourceId(0x0020_0002); + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut owner_peer = install_client(&mut state, OWNER); + + for (window, parent, x, y, width, height) in [ + (grab_win, ROOT_WINDOW, 0, 0, 100, 100), + (hit_win, grab_win, 10, 10, 40, 40), + ] { + state.resources.create_window( + ClientId(OWNER), + CreateWindowRequest { + depth: 24, + window, + parent, + x, + y, + width, + height, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + let _ = state.resources.map_window(grab_win); + let _ = state.resources.map_window(hit_win); + + // No core event mask is selected on either window. Delivery must + // therefore fall back to the grab's event mask and grab window. + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(OWNER), + grab_window: grab_win, + event_mask: 0xFFFF, + cursor: ResourceId(0), + time: 0, + owner_events: true, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE, hit_win); + + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = 0xCAFE; + release.detail = 1; + release.root_x = 20; + release.root_y = 20; + release.event_x = 10; + release.event_y = 10; + + let mut press = release; + press.kind = PointerEventKind::ButtonPress; + press.state = 0; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let _ = read_all_available(&mut owner_peer); + + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + // Core ButtonRelease is event code 5 and its event window occupies + // bytes 12..16 of the fixed 32-byte event. + let bytes = read_all_available(&mut owner_peer); + let event_window = bytes.chunks_exact(32).find_map(|event| { + (event[0] & 0x7F == 5) + .then(|| u32::from_le_bytes(event[12..16].try_into().expect("event window bytes"))) + }); + assert_eq!( + event_window, + Some(grab_win.0), + "grabbed core release must be reported on the grab window", + ); +} + +/// Issue #94 follow-up (Steam menu/Library input-wedge, HW-confirmed +/// 2026-07-15): the QUEUE-WHILE-FROZEN gate must key on the UNIFIED +/// device freeze state alone — `xi1_frozen[PTR].frozen()`, i.e. Xorg's +/// `sync.frozen = sync.other || state >= FROZEN` (dix/events.c:1327) — +/// and NOT additionally on the legacy core passive-grab fields +/// (the former passive-grab flag plus a stored frozen event). Both were set +/// together when a sync passive grab activates, but several paths thaw +/// the unified state independently of the core fields (traced: marco's +/// click-to-focus sync grab thawed by a later UngrabKeyboard, and by a +/// SetInputFocus-driven async grab). With the old OR-gate the pointer +/// then queued every event forever with no path to thaw — total input +/// wedge, zap-only (q climbed to 134 while xi1_frozen[PTR]=Thawed, +/// core_passive_grab=Some, frozen_ptr_event still set). Once the unified +/// state is thawed, events MUST flow, never enqueue. +#[test] +fn thawed_unified_state_does_not_queue_despite_lingering_passive_grab() { + use crate::xinput::DEVICEID_XTEST_POINTER as PTR; + const OWNER: u32 = 3; + let grab_win = yserver_protocol::x11::ResourceId(0x0020_0001); + + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + let _peer = install_client(&mut state, OWNER); + + // A sync passive grab is still active from the core's POV, but the + // unified per-device freeze has already been thawed out-of-band. The + // gate must key on the unified freeze state alone: an active passive + // grab must not resurrect the freeze. (Pre-unification this was a + // second source of truth; the legacy core slots are now gone, so the + // only way to express "frozen" is the unified `xi1_frozen` state — left + // Thawed here, the authoritative signal saying "not frozen".) + state.set_pointer_grab(crate::server::ActivePointerGrab { + owner: ClientId(OWNER), + grab_window: grab_win, + event_mask: 0xffff, + cursor: yserver_protocol::x11::ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: true, + xi2_mask: 0, + }); + assert!( + !state + .xi1_frozen + .get(&PTR) + .is_some_and(crate::server::Xi1Freeze::frozen), + "precondition: unified pointer state is thawed" + ); + + let xid_map = HostXidMap::new(); + let ev = motion_event(); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, ev, true, false); + + assert!( + !state + .sync_pending + .iter() + .any(|p| p.device == crate::xinput::DEVICEID_XTEST_POINTER), + "a pointer event must NOT be swallowed into the freeze queue when the \ + unified device state is thawed (Xorg gates enqueue on sync.frozen only); \ + got {} queued — the Steam input-wedge", + state + .sync_pending + .iter() + .filter(|p| p.device == crate::xinput::DEVICEID_XTEST_POINTER) + .count(), + ); +} + +/// XI2 device propagation stops at the first selected window, across all +/// clients. The leaf selector receives the event and an unrelated +/// selector on an ancestor does not receive a duplicate. Xorg does this +/// for Steam's GTK child / CEF top-level pair; delivering both copies made +/// CEF interpret an ordinary menu click as a client-side-decoration drag. +#[test] +fn xi2_device_event_stops_at_deepest_selected_window() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + let toplevel = ResourceId(0x0020_0001); // owned by client A + let leaf = ResourceId(0x0020_0002); // child of toplevel, owned by A + + let mut state = ServerState::new(); + let mut a_peer = install_client(&mut state, 1); // owns both windows + let mut b_peer = install_client(&mut state, 2); // selects on the toplevel only + + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: toplevel, + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: leaf, + parent: toplevel, + x: 10, + y: 10, + width: 40, + height: 40, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(toplevel); + let _ = state.resources.map_window(leaf); + + // A selects XI_ButtonPress(4) under XIAllDevices(0) on the LEAF. + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((leaf, 0u16), 1 << 4); + // B selects the same event on the TOPLEVEL only. + state + .clients + .get_mut(&2) + .unwrap() + .xi2_masks + .insert((toplevel, 0u16), 1 << 4); + + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE_u32, toplevel); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: 0xCAFE, + detail: 1, + time: 1, + root_x: 20, + root_y: 20, + event_x: 20, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + + // event window is bytes[24..28] of an XI2 device event (GenericEvent + // type 35, evtype at [8..10]). + let button_event_window = |bytes: &[u8]| -> Option { + let mut off = 0usize; + while off + 32 <= bytes.len() { + if bytes[off] == 35 && u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]) == 4 { + return Some(u32::from_le_bytes( + bytes[off + 24..off + 28].try_into().unwrap(), + )); + } + let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; + off += 32 + length * 4; + } + None + }; + + let a_bytes = read_all_available(&mut a_peer); + let b_bytes = read_all_available(&mut b_peer); + assert_eq!( + button_event_window(&a_bytes), + Some(leaf.0), + "owner/leaf-selector must be reported on the hit leaf" + ); + assert_eq!( + button_event_window(&b_bytes), + None, + "Xorg stops XI2 propagation at the selected leaf; an ancestor \ + selector must not receive a duplicate device event" + ); + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(1), leaf)), + "the implicit grab belongs to the deepest XI2 press recipient" + ); +} + +#[test] +fn xi2_motion_emits_slave_form_before_master_form() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + // XIAllDevices(0), XI_Motion (evtype 6), on the root — where a + // windowless motion lands. device 0 yields BOTH forms (issue #72). + state + .clients + .get_mut(&1) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, 0), 1 << 6); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + motion_event(), + true, + false, + ); + assert!(dropped.is_empty()); + let bytes = read_all_available(&mut peer); + // Walk the GenericEvent stream, collecting each XI_Motion(6)'s + // deviceid. Layout: [0]=35 GenericEvent, [4..8]=length (extra + // 4-byte units past the 32-byte base), [8..10]=evtype, + // [10..12]=deviceid. + let mut motion_deviceids: Vec = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + assert_eq!(bytes[off], 35, "GenericEvent"); + let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; + let evtype = u16::from_le_bytes(bytes[off + 8..off + 10].try_into().unwrap()); + let deviceid = u16::from_le_bytes(bytes[off + 10..off + 12].try_into().unwrap()); + if evtype == 6 { + motion_deviceids.push(deviceid); + } + off += 32 + length * 4; + } + assert_eq!(off, bytes.len(), "event stream fully consumed"); + assert_eq!( + motion_deviceids, + vec![XI2_XTEST_POINTER_DEVICE_ID, XI2_MASTER_POINTER_DEVICE_ID], + "XIAllDevices(0) motion selector must receive the slave-stamped \ + form BEFORE the master-stamped form (Xorg mi/mieq.c order); \ + master-first silently breaks Qt smooth-scroll + hover" + ); +} + +/// Pointer family: a core-motion and an XI2-motion subscriber over +/// `OUTBOUND_CAP` are flagged for the core loop to disconnect, and the +/// reading subscriber still gets the motion. +#[test] +fn overflowing_motion_subscribers_are_flagged_for_disconnect() { + for xi2 in [false, true] { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let _slow = install_client(&mut state, 1); + let mut fast = install_client(&mut state, 2); + for id in [1, 2] { + let client = state.clients.get_mut(&id).expect("client"); + if xi2 { + client.xi2_masks.insert((ROOT_WINDOW, 1), 1 << 6); + } else { + client.event_masks.insert(ROOT_WINDOW, 1 << 6); + } + } + crate::core_loop::client_io::saturate_for_test(state.clients.get_mut(&1).expect("client")); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + motion_event(), + true, + false, + ); + assert_eq!( + crate::core_loop::client_io::failed_writers(&state.clients), + [ClientId(1)], + "xi2={xi2}" + ); + assert!(!read_all_available(&mut fast).is_empty(), "xi2={xi2}"); + } +} + +#[test] +fn xi2_raw_motion_uses_master_device_and_slave_source_ids() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut facet_peer = install_client(&mut state, 1); + let mut master_peer = install_client(&mut state, 2); + let mut all_master_peer = install_client(&mut state, 3); + let mut all_devices_peer = install_client(&mut state, 4); + let facet = pointer_source(&mut state, 101, true); + for (client_id, device_id) in [ + (1, facet), + (2, XI2_MASTER_POINTER_DEVICE_ID), + (3, 1), + (4, 0), + ] { + state + .clients + .get_mut(&client_id) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, device_id), 1 << 17); + } + let mut event = motion_event(); + event.origin = crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(101)); + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + assert!(dropped.is_empty()); + let facet_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut facet_peer)) + .into_iter() + .filter(|(kind, _, _)| *kind == 17) + .collect(); + let master_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut master_peer)) + .into_iter() + .filter(|(kind, _, _)| *kind == 17) + .collect(); + let all_master_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut all_master_peer)) + .into_iter() + .filter(|(kind, _, _)| *kind == 17) + .collect(); + let all_devices_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut all_devices_peer)) + .into_iter() + .filter(|(kind, _, _)| *kind == 17) + .collect(); + assert_eq!( + facet_raw, + vec![(17, facet, facet)], + "a raw selection on the physical facet gets only the slave form" + ); + assert_eq!( + master_raw, + vec![(17, XI2_MASTER_POINTER_DEVICE_ID, facet)], + "a raw selection on the master pointer gets only the master form" + ); + assert_eq!( + all_master_raw, + vec![(17, XI2_MASTER_POINTER_DEVICE_ID, facet)], + "XIAllMasterDevices gets only the master form" + ); + assert_eq!( + all_devices_raw, + vec![ + (17, facet, facet), + (17, XI2_MASTER_POINTER_DEVICE_ID, facet), + ], + "XIAllDevices gets slave raw first, then the master raw copy" + ); +} + +#[test] +fn xi2_raw_buttons_use_both_device_forms_per_selection() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut facet_peer = install_client(&mut state, 1); + let mut master_peer = install_client(&mut state, 2); + let mut all_master_peer = install_client(&mut state, 3); + let mut all_devices_peer = install_client(&mut state, 4); + let facet = pointer_source(&mut state, 101, true); + let raw_button_mask = (1 << 15) | (1 << 16); + for (client_id, device_id) in [ + (1, facet), + (2, XI2_MASTER_POINTER_DEVICE_ID), + (3, 1), + (4, 0), + ] { + state + .clients + .get_mut(&client_id) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, device_id), raw_button_mask); + } + + let mut press = motion_event(); + press.origin = crate::core_loop::InputOrigin::Physical(crate::xinput::InputSourceId(101)); + press.kind = PointerEventKind::ButtonPress; + press.detail = 1; + press.time = 10; + assert!( + pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + press, + true, + false, + ) + .is_empty() + ); + + let mut release = press; + release.kind = PointerEventKind::ButtonRelease; + release.state = 1 << 8; + release.time = 11; + assert!( + pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + release, + true, + false, + ) + .is_empty() + ); + + let facet_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut facet_peer)) + .into_iter() + .filter(|(kind, _, _)| matches!(*kind, 15 | 16)) + .collect(); + let master_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut master_peer)) + .into_iter() + .filter(|(kind, _, _)| matches!(*kind, 15 | 16)) + .collect(); + let all_master_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut all_master_peer)) + .into_iter() + .filter(|(kind, _, _)| matches!(*kind, 15 | 16)) + .collect(); + let all_devices_raw: Vec<_> = xi2_event_ids(&read_all_available(&mut all_devices_peer)) + .into_iter() + .filter(|(kind, _, _)| matches!(*kind, 15 | 16)) + .collect(); + assert_eq!(facet_raw, vec![(15, facet, facet), (16, facet, facet)]); + assert_eq!( + master_raw, + vec![ + (15, XI2_MASTER_POINTER_DEVICE_ID, facet), + (16, XI2_MASTER_POINTER_DEVICE_ID, facet), + ] + ); + assert_eq!( + all_master_raw, + vec![ + (15, XI2_MASTER_POINTER_DEVICE_ID, facet), + (16, XI2_MASTER_POINTER_DEVICE_ID, facet), + ] + ); + assert_eq!( + all_devices_raw, + vec![ + (15, facet, facet), + (15, XI2_MASTER_POINTER_DEVICE_ID, facet), + (16, facet, facet), + (16, XI2_MASTER_POINTER_DEVICE_ID, facet), + ], + "XIAllDevices gets slave raw before master raw for both button edges" + ); +} + +#[test] +fn replayed_pointer_press_does_not_repeat_raw_event() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + state + .clients + .get_mut(&1) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, 0), (1 << 4) | (1 << 15)); + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.detail = 1; + + let dropped = + replay_frozen_pointer_event_to_state(&mut state, &mut backend, &HostXidMap::new(), press); + assert!(dropped.is_empty()); + + let bytes = read_all_available(&mut peer); + let mut evtypes = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + assert_eq!(bytes[off], 35, "GenericEvent"); + let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; + evtypes.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); + off += 32 + length * 4; + } + assert_eq!(off, bytes.len(), "event stream fully consumed"); + assert!( + evtypes.contains(&4), + "natural XI_ButtonPress must be replayed" + ); + assert!( + !evtypes.iter().any(|evtype| matches!(*evtype, 15..=17)), + "raw pointer events describe physical input and must not be replayed" + ); +} + +#[test] +fn button_target_locked_at_generation_survives_restack() { + // Click-below regression. A button generated over the top-level A + // must deliver to A even if a WM raises B above A between the + // press and its fanout. yserver used to re-resolve the target at + // delivery (`root_pointer_target_at` on the current tree), so a + // restack landing in between retargeted the in-flight click to + // the window raised on top — "click lands on the window below". + use crate::resources::{ROOT_VISUAL, ROOT_WINDOW}; + use yserver_protocol::x11::{ConfigureWindowRequest, CreateWindowRequest}; + + let mut state = ServerState::new(); + // Two overlapping full-size top-levels. Create B first, then A, so + // A is on top (create inserts at the top of the stack). + let b = ResourceId(0x0020_0000); + let a = ResourceId(0x0010_0000); + for win in [b, a] { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: win, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 400, + height: 400, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + } + + // The producer stamped host_xid HA at generation, when A was on top. + let host_a: u32 = 0x0040_0aaa; + let mut xid_map = HostXidMap::new(); + xid_map.insert(host_a, a); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: host_a, + detail: 1, + time: 1, + root_x: 100, + root_y: 100, + event_x: 100, + event_y: 100, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + + // Precondition: A is on top; the press resolves to A. + assert_eq!( + resolve_pointer_hit(&state, &xid_map, &press) + .map(|(t, _, _)| state.top_level_for_target(t)), + Some(a), + "precondition: click resolves to the top window A", + ); + + // A WM raises B above A AFTER the press was generated. + let restacked = state.resources.configure_window(ConfigureWindowRequest { + window: b, + value_mask: 0, + x: None, + y: None, + width: None, + height: None, + border_width: None, + sibling: Some(a), + stack_mode: Some(0), // Above + }); + assert!(restacked.is_some(), "restack applied"); + + // The LIVE hit-test now resolves B (B is topmost). This proves the + // scenario diverges — so a delivery-time re-resolve would pick B. + assert_eq!( + state + .root_pointer_target_at(100, 100) + .map(|(t, _, _)| state.top_level_for_target(t)), + Some(b), + "after the restack, the live hit-test resolves the now-top window B", + ); + + // Regression: the in-flight button must STILL deliver to A — its + // generation-time target — not the restacked-on-top B. + assert_eq!( + resolve_pointer_hit(&state, &xid_map, &press) + .map(|(t, _, _)| state.top_level_for_target(t)), + Some(a), + "button target is locked at event generation; a restack between \ + press and delivery must not retarget it to the window below", + ); + + // A motion event, by contrast, tracks the live pointer (resolves B). + let motion = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + ..press + }; + assert_eq!( + resolve_pointer_hit(&state, &xid_map, &motion) + .map(|(t, _, _)| state.top_level_for_target(t)), + Some(b), + "motion tracks the live pointer (resolves the now-top B)", + ); +} + +#[test] +fn motion_clamps_against_solid_barrier() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + state.pointer_barriers.insert( + 0x0050_0001, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + state.pointer_root = (90, 50); + let mut ev = motion_event(); + ev.root_x = 110; + ev.root_y = 50; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + ev, + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!(state.pointer_root, (99, 50)); + assert_eq!(backend.warped_to, Some((99, 50))); +} + +/// Regression (HW-observed 2026-06-18): the clamp moved only +/// `root_x`, but `translate_host_event` later re-derives +/// `root = window.x + event_x`. With the host window in `xid_map` +/// (the real path — the empty-map case above can't exercise it) +/// that overwrote the clamped root with the un-clamped value, so +/// `pointer_root` ended up *past* the wall and the next motion never +/// re-crossed it — a porous barrier. The clamp must shift `event_x` +/// by the same delta so the wall holds across translate. +#[test] +fn clamp_shifts_event_x_so_pointer_root_holds_across_translate() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + state.pointer_barriers.insert( + 0x0050_0001, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + state.pointer_root = (90, 50); + // Map the host window so `translate_host_event` re-derives root + // from `event_x` — ROOT_WINDOW is at (0,0), so root == event_x. + let host_xid = 0x1234_u32; + let mut xid_map = HostXidMap::new(); + xid_map.insert(host_xid, ROOT_WINDOW); + let mut ev = motion_event(); + ev.host_xid = host_xid; + ev.root_x = 110; + ev.root_y = 50; + ev.event_x = 110; + ev.event_y = 50; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, ev, true, false); + // Pre-fix this was (110, 50): translate clobbered the clamp. + assert_eq!( + state.pointer_root, + (99, 50), + "pointer_root must hold at the wall (x1-1), not snap back past it" + ); + assert_eq!(backend.warped_to, Some((99, 50))); +} + +#[test] +fn barrier_bypass_skips_clamp() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + state.pointer_barriers.insert( + 0x0050_0001, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + state.pointer_root = (90, 50); + state.barrier_bypass = true; + let mut ev = motion_event(); + ev.root_x = 110; + ev.root_y = 50; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + ev, + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!(state.pointer_root, (110, 50)); + assert_eq!(backend.warped_to, None); +} + +#[test] +fn barrier_hit_event_delivered_to_selecting_client() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + state + .clients + .get_mut(&1) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, 2), 1 << 25); + let bid = 0x0050_0002; + state.pointer_barriers.insert( + bid, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + state.pointer_root = (90, 50); + let mut ev = motion_event(); + ev.root_x = 110; + ev.root_y = 50; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + ev, + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!(state.pointer_root, (99, 50)); + assert!(state.pointer_barriers.get(&bid).expect("barrier").hit); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 68); + assert_eq!(bytes[0], 35, "GenericEvent"); + assert_eq!(bytes[1], 137, "XI2 major opcode"); + assert_eq!(&bytes[4..8], &9u32.to_le_bytes(), "length"); + assert_eq!(&bytes[8..10], &25u16.to_le_bytes(), "BarrierHit"); + assert_eq!(&bytes[28..32], &bid.to_le_bytes(), "barrier xid"); + assert_eq!( + &bytes[44..48], + &(99i32 << 16).to_le_bytes(), + "root_x FP1616" + ); +} + +fn barrier_hit_bytes_for_selector(device_id: u16) -> Vec { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut peer = install_capture_client(&mut state, 1); + let source_id = crate::xinput::InputSourceId(101); + let pointer_id = pointer_source(&mut state, source_id.0, true); + state + .clients + .get_mut(&1) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, device_id), 1 << 25); + assert_eq!( + barrier_xi2_targets(&state, ROOT_WINDOW, 25), + if matches!(device_id, 0..=2) { + vec![ClientId(1)] + } else { + Vec::new() + }, + "barrier selection candidates for device {device_id}", + ); + let bid = 0x0050_0006; + state.pointer_barriers.insert( + bid, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + state.pointer_root = (90, 50); + let mut event = motion_event(); + event.origin = crate::core_loop::message::InputOrigin::Physical(source_id); + event.root_x = 110; + event.root_y = 50; + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + event, + true, + false, + ); + + assert!(dropped.is_empty()); + assert_eq!(state.pointer_root, (99, 50)); + assert!(state.pointer_barriers.get(&bid).expect("barrier").hit); + assert_eq!( + state + .xi_devices + .facet(source_id, crate::xinput::XiFacetKind::PointerTouch), + Some(pointer_id) + ); + assert_eq!( + state.xi_devices.source(source_id).map(|info| info.enabled), + Some(true) + ); + assert_eq!( + state + .xi_devices + .device(pointer_id) + .map(|device| device.buttons_down), + Some(0), + "barrier handling must not alter the source's held-button state", + ); + read_all_capture_available(&mut peer) +} + +#[test] +fn xi_dynamic_reset_barrier_targets_master_selectors_not_xtest_pointer() { + let xtest = barrier_hit_bytes_for_selector(crate::xinput::DEVICEID_XTEST_POINTER); + assert!( + xtest.is_empty(), + "a master pointer barrier event must not be selected through virtual XTEST pointer 4" + ); + + for selector in [ + XI2_MASTER_POINTER_DEVICE_ID, + 1, // XIAllMasterDevices + 0, // XIAllDevices + ] { + let bytes = barrier_hit_bytes_for_selector(selector); + assert_eq!(bytes.len(), 68, "selector {selector} receives BarrierHit"); + assert_eq!(&bytes[8..10], &25u16.to_le_bytes(), "BarrierHit"); + assert_eq!( + &bytes[10..12], + &XI2_MASTER_POINTER_DEVICE_ID.to_le_bytes(), + "barrier deviceid remains the master pointer", + ); + assert_eq!( + &bytes[40..42], + &XI2_MASTER_POINTER_DEVICE_ID.to_le_bytes(), + "barrier sourceid remains the master pointer", + ); + } +} + +/// Regression (HW-observed 2026-06-18): a client that selected +/// BarrierHit under the `XIAllMasterDevices` wildcard (deviceid 1) — +/// what libXi's `XISelectEvents(XIAllMasterDevices, …)` stores — +/// received NO barrier events, because `barrier_xi2_targets` only +/// queried the concrete master-pointer id (2). With no HIT events the +/// client could never call `XIBarrierReleasePointer`, so the pointer +/// was pinned at the wall forever. Selection under the wildcard must +/// deliver. +#[test] +fn barrier_hit_delivered_for_xiallmasterdevices_selection() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + // Wildcard device 1 (XIAllMasterDevices), NOT the concrete id 2. + state + .clients + .get_mut(&1) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, 1), 1 << 25); + let bid = 0x0050_0004; + state.pointer_barriers.insert( + bid, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + state.pointer_root = (90, 50); + let mut ev = motion_event(); + ev.root_x = 110; + ev.root_y = 50; + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + ev, + true, + false, + ); + let bytes = read_all_available(&mut peer); + assert_eq!( + bytes.len(), + 68, + "BarrierHit must be delivered to the wildcard selector" + ); + assert_eq!(&bytes[8..10], &25u16.to_le_bytes(), "BarrierHit"); + assert_eq!(&bytes[28..32], &bid.to_le_bytes(), "barrier xid"); +} + +#[test] +fn release_lets_pointer_cross_then_rearms() { + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let bid = 0x0050_0003; + state.pointer_barriers.insert( + bid, + crate::server::PointerBarrier { + owner: ClientId(1), + window: ROOT_WINDOW, + x1: 100, + y1: 0, + x2: 100, + y2: 200, + directions: 0, + devices: Vec::new(), + hit: true, + seen: false, + event_id: 1, + release_event_id: 1, + last_timestamp: 10, + }, + ); + state.pointer_root = (90, 50); + let mut ev = motion_event(); + ev.root_x = 110; + ev.root_y = 50; + ev.time = 20; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + ev, + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!(state.pointer_root, (110, 50)); + let barrier = state.pointer_barriers.get(&bid).expect("barrier"); + assert!(!barrier.hit, "leave sweep should clear hit"); + assert_eq!(barrier.event_id, 2, "leave sweep re-arms the barrier"); + + let mut ev2 = motion_event(); + ev2.root_x = 90; + ev2.root_y = 50; + ev2.time = 21; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + ev2, + true, + false, + ); + assert!(dropped.is_empty()); + assert_eq!( + state.pointer_root, + (100, 50), + "re-armed barrier clamps again" + ); +} + +/// wmaker wedge regression (2026-06-04, silence HW): a WM places a +/// SYNCHRONOUS `owner_events=true` button grab on a CLIENT's window +/// (click-to-focus). A press on that window's subtree must be +/// reported to the GRAB CLIENT on the grab window — per Xorg +/// `DeliverGrabbedEvent` (dix/events.c:4361), the `owner_events` +/// natural walk is filtered to the grab client: `TryClientEvents` +/// (dix/events.c:2069) returns -1 for any other client ("not +/// delivered due to grab"), aborting propagation, and the event +/// falls back to the grab window. Pre-fix, the descendant arm of +/// `target_qualifies_for_natural` leaked the press to the app +/// client while the sync grab froze the queue — the WM never saw +/// the press, never called AllowEvents, and the pointer stream +/// stayed frozen forever (cursor moves, clicks dead). +#[test] +fn passive_sync_grab_on_foreign_window_delivers_to_grab_client_and_freezes() { + use yserver_protocol::x11::ResourceId; + + let mut state = ServerState::new(); + let grab_window = ResourceId(0x0020_0001); // app client's top-level + let child_window = ResourceId(0x0020_0002); // GL child producing the click + + let mut wm_peer = install_client(&mut state, 1); + let mut app_peer = install_client(&mut state, 2); + + state.resources.create_window( + ClientId(2), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: grab_window, + parent: crate::resources::ROOT_WINDOW, + x: 610, + y: 250, + width: 1280, + height: 800, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(2), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: child_window, + parent: grab_window, + x: 0, + y: 0, + width: 1280, + height: 800, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(grab_window); + let _ = state.resources.map_window(child_window); + + // The WM has NO event mask anywhere on the chain — its + // interest is expressed solely via the grab. The app client + // selects ButtonPress on its child (the leak target pre-fix). + state + .clients + .get_mut(&2) + .unwrap() + .event_masks + .insert(child_window, 0x0000_0004); + + // wmaker idiom: XGrabButton(AnyButton, AnyModifier, client_win, + // owner_events=True, ButtonPressMask, GrabModeSync, + // GrabModeAsync). + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(1), + grab_window, + button: 0, // AnyButton + modifiers: 0x8000, // AnyModifier + owner_events: true, + event_mask: 0x0000_0004, // ButtonPressMask + pointer_mode: 0, // GrabModeSync + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + + let mut xid_map = HostXidMap::new(); + // KMS stamps the actual GL child as the producer but event_x/y are + // root-relative. The Steam trace had root/event=(909,299) while + // the grabbed toplevel was at (610,250). + xid_map.insert(0xCAFE_u32, child_window); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: 0xCAFE, + detail: 1, + time: 0, + root_x: 909, + root_y: 299, + event_x: 909, + event_y: 299, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + + let wm_bytes = read_all_available(&mut wm_peer); + assert!( + wm_bytes.len() >= 32, + "sync passive grab must deliver the activating press to the \ + grab client (the WM) — otherwise nobody ever AllowEvents and \ + the frozen pointer queue wedges; got {} bytes", + wm_bytes.len(), + ); + assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); + assert_eq!( + &wm_bytes[12..16], + &grab_window.0.to_le_bytes(), + "press must be reported on the grab window (Xorg grab-window \ + fallback — the grab client has no mask on the natural chain)", + ); + assert_eq!( + i16::from_le_bytes([wm_bytes[24], wm_bytes[25]]), + 299, + "event-x must be relative to the passive grab window", + ); + assert_eq!( + i16::from_le_bytes([wm_bytes[26], wm_bytes[27]]), + 49, + "event-y must be relative to the passive grab window", + ); + + let app_bytes = read_all_available(&mut app_peer); + let app_core: Vec<&[u8]> = app_bytes.chunks(32).filter(|c| c[0] == 4).collect(); + assert!( + app_core.is_empty(), + "the app client must NOT see the core press while the grab \ + holds (Xorg TryClientEvents: 'not delivered due to grab'); \ + got {} core ButtonPress event(s)", + app_core.len(), + ); + + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_some(), + "GrabModeSync activation must freeze the pointer queue", + ); + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(1), grab_window)), + "passive grab must be active for client 1", + ); +} + +/// icewm framed-taskbar regression (2026-07-01, air HW): icewm +/// frames its OWN taskbar as a managed client and puts a sync +/// AnyModifier `owner_events=true` button grab on the client +/// container (`YClientContainer::grabButtons`). The taskbar widgets +/// are descendants of that container and — being icewm's own +/// windows — ALSO select ButtonPress. The activating press must +/// still be reported on the GRAB WINDOW (the container): Xorg +/// `ActivatePassiveGrab` delivers it with +/// `FixUpEventFromWindow(grab->window)`, without the owner_events walk +/// (GH #277). Only then does icewm's `YClientContainer::handleButton` run and call +/// `XAllowEvents(ReplayPointer)`. Pre-fix the press leaked to the +/// deepest widget (whose handler never thaws), wedging every panel +/// click. The reported `child` is the container's child on the path +/// toward the pointer (Xorg `FindChildForEvent`). +#[test] +fn passive_sync_grab_reports_activating_press_on_grab_window_not_owned_descendant() { + use yserver_protocol::x11::ResourceId; + + let mut state = ServerState::new(); + let container = ResourceId(0x0020_0001); // grab window (client container) + let client_win = ResourceId(0x0020_0002); // framed taskbar client + let widget = ResourceId(0x0020_0003); // a taskbar button + + let mut wm_peer = install_client(&mut state, 1); + + for (win, parent, x, y, w, h) in [ + (container, crate::resources::ROOT_WINDOW, 0, 0, 400, 24), + (client_win, container, 0, 0, 400, 24), + (widget, client_win, 10, 5, 40, 15), + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: win, + parent, + x, + y, + width: w, + height: h, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + // icewm selects ButtonPress on the container AND every widget. + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(win, 0x0000_0004); + } + + // icewm idiom: XGrabButton(button, AnyModifier, container, + // owner_events=True, ButtonPressMask, GrabModeSync, GrabModeAsync). + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(1), + grab_window: container, + button: 1, + modifiers: 0x8000, // AnyModifier + owner_events: true, + event_mask: 0x0000_0004, // ButtonPressMask + pointer_mode: 0, // GrabModeSync + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE_u32, container); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + // Press over the widget at (20, 8) relative to the container + // (inside the widget, which spans x∈[10,50) y∈[5,20)). + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: 0xCAFE, + detail: 1, + time: 0, + root_x: 20, + root_y: 8, + event_x: 20, + event_y: 8, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + + let wm_bytes = read_all_available(&mut wm_peer); + assert!(wm_bytes.len() >= 32, "grab client must receive the press"); + assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); + assert_eq!( + &wm_bytes[12..16], + &container.0.to_le_bytes(), + "activating press must be reported on the GRAB WINDOW (the \ + container), not the owned descendant widget — Xorg \ + ActivatePassiveGrab skips the owner_events walk", + ); + assert_eq!( + &wm_bytes[16..20], + &client_win.0.to_le_bytes(), + "child must be the grab window's child on the path toward the \ + pointer (Xorg FindChildForEvent)", + ); + // event-x/y are relative to the grab window (container at 0,0). + assert_eq!( + i16::from_le_bytes([wm_bytes[24], wm_bytes[25]]), + 20, + "event-x is relative to the grab window", + ); + assert_eq!( + i16::from_le_bytes([wm_bytes[26], wm_bytes[27]]), + 8, + "event-y is relative to the grab window", + ); + + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_some(), + "GrabModeSync activation must freeze the pointer queue", + ); + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(1), container)), + "passive grab must be active for client 1", + ); +} + +/// CDE dtwm's front panel: a sync passive grab whose event mask holds +/// ButtonRelease only. Xorg ActivatePassiveGrab hands the activating +/// press to the grabbing client regardless of the grab's mask (measured: +/// tools/vng-scenarios/goldens/passive-grab.txt); without it dtwm never +/// AllowEvents and both devices stay frozen. +#[test] +fn passive_sync_grab_delivers_activating_press_outside_grab_mask() { + use yserver_protocol::x11::ResourceId; + + let mut state = ServerState::new(); + let panel = ResourceId(0x0020_0001); + let mut wm_peer = install_client(&mut state, 1); + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: panel, + parent: crate::resources::ROOT_WINDOW, + width: 200, + height: 200, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(panel); + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(1), + grab_window: panel, + button: 0, // AnyButton + modifiers: 0x8000, // AnyModifier + owner_events: false, + event_mask: 0x0000_0008, // ButtonReleaseMask + pointer_mode: 0, // GrabModeSync + keyboard_mode: 0, // GrabModeSync + confine_to: ResourceId(0), + via_xi2: false, + }); + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE_u32, panel); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + kind: PointerEventKind::ButtonPress, + host_xid: 0xCAFE, + detail: 1, + time: 0, + root_x: 50, + root_y: 50, + event_x: 50, + event_y: 50, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + origin: crate::core_loop::message::InputOrigin::XTest(4), + }, + true, + false, + ); + + let wm_bytes = read_all_available(&mut wm_peer); + assert!(wm_bytes.len() >= 32, "grab client must receive the press"); + assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); + assert_eq!(&wm_bytes[12..16], &panel.0.to_le_bytes()); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .is_some_and(|f| f.stored.is_some()), + "the press is stored for a ReplayPointer", + ); +} + +/// icewm stuck-tooltip regression (2026-07-01, air HW): activating a +/// passive grab must emit the `NotifyGrab` Leave/Enter crossing chain +/// (Xorg `ActivatePointerGrab` → `DoEnterLeaveEvents(sprite → grab +/// window)`). icewm's `YWindow::handleCrossing` hides a panel tooltip +/// on ANY LeaveNotify; without the widget's grab-Leave the tooltip +/// showing on the clicked panel item never disappears (traced: +/// tooltip windows Created+Mapped, never Destroyed). +#[test] +fn passive_grab_activation_emits_notify_grab_leave_on_the_sprite_widget() { + use yserver_protocol::x11::ResourceId; + + let mut state = ServerState::new(); + let container = ResourceId(0x0020_0001); // grab window + let client_win = ResourceId(0x0020_0002); + let widget = ResourceId(0x0020_0003); // the hovered panel item + + let mut wm_peer = install_client(&mut state, 1); + + for (win, parent, x, y, w, h) in [ + (container, crate::resources::ROOT_WINDOW, 0, 0, 400, 24), + (client_win, container, 0, 0, 400, 24), + (widget, client_win, 10, 5, 40, 15), + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: win, + parent, + x, + y, + width: w, + height: h, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + // icewm selects ButtonPress | EnterWindow | LeaveWindow. + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(win, 0x0000_0004 | 0x0000_0010 | 0x0000_0020); + } + + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(1), + grab_window: container, + button: 1, + modifiers: 0x8000, + owner_events: true, + event_mask: 0x0000_0004, + pointer_mode: 0, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE_u32, container); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: 0xCAFE, + detail: 1, + time: 0, + root_x: 20, + root_y: 8, + event_x: 20, + event_y: 8, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + + // LeaveNotify = type 8; mode byte is at offset 30; NotifyGrab = 1. + let leave_grab_on_widget = read_all_available(&mut wm_peer) + .chunks(32) + .filter(|c| c.len() == 32) + .any(|c| c[0] == 8 && c[30] == 1 && c[12..16] == widget.0.to_le_bytes()); + assert!( + leave_grab_on_widget, + "grab activation must deliver LeaveNotify(mode=Grab) on the \ + sprite widget so icewm dismisses its panel tooltip", + ); +} + +/// icewm never-disappearing-tooltip regression (2026-07-02, air HW). +/// A NORMAL-mode crossing chain (no grab, pure hover) between two +/// sibling widgets A→B must deliver A's `LeaveNotify` on window A — +/// even though the cursor now physically sits over sibling B, so the +/// live deepest hit is B. The producer (`update_pointer_window` → +/// `normal_mode_crossings`) stamps each chain event with its own +/// window's `host_xid`; core delivery must honour that per-window +/// endpoint, not collapse every chain event onto the live deepest +/// hit. Pre-fix, `resolve_pointer_hit` re-resolved crossings to the +/// live hit (B) for BOTH the Leave and the Enter, so widget A never +/// saw a LeaveNotify with `event=A` and icewm's per-widget tooltip +/// (hidden on any LeaveNotify) orphaned. The XI2 path already +/// resolved crossings per-window; this pins the core path to match. +#[test] +fn normal_crossing_leave_delivers_on_left_sibling_not_live_hit() { + use yserver_protocol::x11::ResourceId; + + let mut state = ServerState::new(); + let client_win = ResourceId(0x0020_0001); + let widget_a = ResourceId(0x0020_0002); // pointer leaving this + let widget_b = ResourceId(0x0020_0003); // pointer now over this + + let mut peer = install_client(&mut state, 1); + let mut xi_peer = install_client(&mut state, 2); + let mut slave_only_peer = install_client(&mut state, 3); + + for (win, parent, x, y, w, h) in [ + (client_win, crate::resources::ROOT_WINDOW, 0, 0, 400, 24), + (widget_a, client_win, 10, 5, 40, 15), // abs (10,5)-(50,20) + (widget_b, client_win, 60, 5, 40, 15), // abs (60,5)-(100,20) + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: win, + parent, + x, + y, + width: w, + height: h, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + // icewm selects EnterWindow | LeaveWindow on each widget. + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(win, 0x0000_0010 | 0x0000_0020); + // A second client selects the XI2 crossing form so the same + // per-window coordinates and crossing detail are pinned there. + state + .clients + .get_mut(&2) + .unwrap() + .xi2_masks + .insert((win, 0), (1 << 7) | (1 << 8)); + // A third selects the crossings for the XTEST slave alone. + state + .clients + .get_mut(&3) + .unwrap() + .xi2_masks + .insert((win, 4), (1 << 7) | (1 << 8)); + } + + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xA001_u32, widget_a); + xid_map.insert(0xB001_u32, widget_b); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + // Cursor now sits over widget B (root (70,10)); the producer emits + // the Leave for A and the Enter for B at that same position. + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::LeaveNotify, + host_xid: 0xA001, // the window being LEFT + detail: 3, // Nonlinear + time: 1, + root_x: 70, + root_y: 10, + event_x: 60, // relative to widget_a origin (10,5) + event_y: 5, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::EnterNotify, + host_xid: 0xB001, // the window being ENTERED + detail: 3, // Nonlinear + time: 1, + root_x: 70, + root_y: 10, + event_x: 10, // relative to widget_b origin (60,5) + event_y: 5, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + + // LeaveNotify = type 8; event window at bytes 12..16. + let events: Vec<[u8; 32]> = read_all_available(&mut peer) + .chunks(32) + .filter(|c| c.len() == 32) + .map(|c| c.try_into().unwrap()) + .collect(); + let leave_on_a = events + .iter() + .any(|c| c[0] == 8 && c[12..16] == widget_a.0.to_le_bytes()); + let enter_on_b = events + .iter() + .any(|c| c[0] == 7 && c[12..16] == widget_b.0.to_le_bytes()); + assert!( + leave_on_a, + "LeaveNotify must be delivered on the window being LEFT (widget A), \ + not collapsed onto the live deepest hit (widget B); icewm hides its \ + per-widget tooltip on this Leave", + ); + assert!( + enter_on_b, + "EnterNotify must be delivered on the window being ENTERED (widget B)", + ); + let leave_on_a = events + .iter() + .find(|c| c[0] == 8 && c[12..16] == widget_a.0.to_le_bytes()) + .unwrap(); + assert_eq!( + i16::from_le_bytes(leave_on_a[24..26].try_into().unwrap()), + 60 + ); + assert_eq!( + i16::from_le_bytes(leave_on_a[26..28].try_into().unwrap()), + 5 + ); + let enter_on_b = events + .iter() + .find(|c| c[0] == 7 && c[12..16] == widget_b.0.to_le_bytes()) + .unwrap(); + assert_eq!( + i16::from_le_bytes(enter_on_b[24..26].try_into().unwrap()), + 10 + ); + assert_eq!( + i16::from_le_bytes(enter_on_b[26..28].try_into().unwrap()), + 5 + ); + + let xi_bytes = read_all_available(&mut xi_peer); + let xi_events: Vec<&[u8]> = xi_bytes.chunks(76).collect(); + // Xorg (goldens/xi2-crossing-devices.txt): an attached slave owns no + // sprite, so XIAllDevices gets ONE Leave and ONE Enter, deviceid = + // master pointer, sourceid = the XTEST slave that moved it. + assert_eq!( + xi_events.len(), + 2, + "XIAllDevices receives only the master form of Leave + Enter" + ); + for e in &xi_events { + assert_eq!( + u16::from_le_bytes(e[10..12].try_into().unwrap()), + 2, + "deviceid" + ); + assert_eq!( + u16::from_le_bytes(e[16..18].try_into().unwrap()), + 4, + "sourceid" + ); + } + assert!( + read_all_available(&mut slave_only_peer).is_empty(), + "a selection on the attached XTEST slave alone gets no crossings" + ); + let xi_leave = xi_events + .iter() + .find(|e| u16::from_le_bytes(e[8..10].try_into().unwrap()) == 8) + .unwrap(); + assert_eq!(xi_leave[19], 3, "XI2 Leave preserves NotifyNonlinear"); + assert_eq!( + i32::from_le_bytes(xi_leave[40..44].try_into().unwrap()) >> 16, + 60 + ); + assert_eq!( + i32::from_le_bytes(xi_leave[44..48].try_into().unwrap()) >> 16, + 5 + ); + let xi_enter = xi_events + .iter() + .find(|e| u16::from_le_bytes(e[8..10].try_into().unwrap()) == 7) + .unwrap(); + assert_eq!(xi_enter[19], 3, "XI2 Enter preserves NotifyNonlinear"); + assert_eq!( + i32::from_le_bytes(xi_enter[40..44].try_into().unwrap()) >> 16, + 10 + ); + assert_eq!( + i32::from_le_bytes(xi_enter[44..48].try_into().unwrap()) >> 16, + 5 + ); +} + +/// Xorg `Xi/exevents.c:1854` runs `CheckMotion` (and so crossings) only +/// for a master or a floating slave; `dix/events.c:3244-3252` stamps the +/// slave as `sourceid`. +#[test] +fn xi2_crossings_belong_to_the_device_that_owns_the_sprite() { + let attached = PointerXiSource { + slave_deviceid: Some(7), + sourceid: 7, + attached_master: Some(XI2_MASTER_POINTER_DEVICE_ID), + }; + let floating = PointerXiSource { + slave_deviceid: Some(7), + sourceid: 7, + attached_master: None, + }; + let master = PointerXiSource { + slave_deviceid: None, + sourceid: XI2_MASTER_POINTER_DEVICE_ID, + attached_master: Some(XI2_MASTER_POINTER_DEVICE_ID), + }; + assert!(matches!( + xi2_crossing_form(attached), + (Xi2PointerForm::Master, XI2_MASTER_POINTER_DEVICE_ID) + )); + assert!(matches!( + xi2_crossing_form(floating), + (Xi2PointerForm::Slave, 7) + )); + assert!(matches!( + xi2_crossing_form(master), + (Xi2PointerForm::Master, XI2_MASTER_POINTER_DEVICE_ID) + )); +} + +/// openbox resize regression: an active core grab can live on a +/// tiny hidden helper window while the WM selects motion on a +/// visible frame window containing a foreign app child. With +/// `owner_events=true`, motion over that foreign child must still +/// propagate naturally to the WM's frame window, not redirect to +/// the helper grab window. +#[test] +fn active_grab_owner_events_uses_grab_client_filtered_propagation() { + use crate::{backend::Backend, resources::ROOT_VISUAL, server::ActivePointerGrab}; + + const WM_CLIENT_ID: u32 = 1; + const APP_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0080; + const FRAME_WIN: u32 = 0x0010_0081; + const APP_CHILD_WIN: u32 = 0x0020_0082; + const HOST_FRAME_XID: u32 = 0xCAFE_0081; + + let mut state = ServerState::new(); + let mut wm_peer = install_client(&mut state, WM_CLIENT_ID); + let mut backend = RecordingBackend::new(); + wm_peer.set_nonblocking(true).expect("nonblocking"); + + state.resources.create_window( + ClientId(WM_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: -100, + y: -100, + width: 1, + height: 1, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(WM_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(FRAME_WIN), + parent: ROOT_WINDOW, + x: 500, + y: 300, + width: 200, + height: 150, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(APP_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(APP_CHILD_WIN), + parent: ResourceId(FRAME_WIN), + x: 20, + y: 20, + width: 100, + height: 80, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + let _ = state.resources.map_window(ResourceId(FRAME_WIN)); + let _ = state.resources.map_window(ResourceId(APP_CHILD_WIN)); + + state + .clients + .get_mut(&WM_CLIENT_ID) + .expect("wm client") + .event_masks + .insert(ResourceId(FRAME_WIN), 0x0000_0040); + + Backend::register_top_level(&mut backend, None, ResourceId(FRAME_WIN), HOST_FRAME_XID) + .expect("register frame host xid"); + + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(WM_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + event_mask: 0x0000_0040, + cursor: ResourceId(0), + time: 0, + owner_events: true, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + + let motion = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + host_xid: HOST_FRAME_XID, + detail: 0, + time: 0x2000, + root_x: 545, + root_y: 345, + event_x: 45, + event_y: 45, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); + assert!(dropped.is_empty()); + + let mut buf = [0u8; 32]; + let n = wm_peer.read(&mut buf).expect("wm got motion"); + assert_eq!(n, 32, "expected one core MotionNotify"); + assert_eq!(buf[0], 6, "event type should be MotionNotify"); + assert_eq!( + &buf[12..16], + &FRAME_WIN.to_le_bytes(), + "motion must report against the WM-selected frame window, not the hidden grab helper", + ); + assert_eq!( + i16::from_le_bytes([buf[24], buf[25]]), + 45, + "event_x must stay frame-relative", + ); + assert_eq!( + i16::from_le_bytes([buf[26], buf[27]]), + 45, + "event_y must stay frame-relative", + ); +} + +/// Regression (#90, ImageMagick `import` on real HW): an active core +/// pointer grab that selected `ButtonMotion` but NOT `PointerMotion` +/// must not be fed no-button motion. `import` does +/// `XGrabPointer(owner_events=false, +/// ButtonPress|ButtonRelease|ButtonMotion|OwnerGrabButton)`; pre-fix +/// yserver delivered every MotionNotify (incl. state=0), so `import` +/// drew its selection rectangle from the origin before any button was +/// pressed. Xorg `DeliverGrabbedEvent` only reports events the grab's +/// mask selected — but still CAPTURES the rest (never propagates them +/// to the natural target). +#[test] +fn active_grab_buttonmotion_mask_suppresses_no_button_motion() { + use crate::{backend::Backend, resources::ROOT_VISUAL, server::ActivePointerGrab}; + + const WM_CLIENT_ID: u32 = 1; + const APP_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0090; + const APP_WIN: u32 = 0x0020_0091; + const HOST_APP_XID: u32 = 0xCAFE_0091; + // ButtonPress | ButtonRelease | ButtonMotion (import's mask minus + // OwnerGrabButton, which is not a delivery-selection bit). Note it + // deliberately does NOT include PointerMotion (0x40). + const IMPORT_MASK: u32 = 0x0000_0004 | 0x0000_0008 | 0x0000_2000; + + let mut state = ServerState::new(); + let mut wm_peer = install_client(&mut state, WM_CLIENT_ID); + let mut app_peer = install_client(&mut state, APP_CLIENT_ID); + let mut backend = RecordingBackend::new(); + + // Tiny offscreen helper window owned by the grab client (import's + // grab is on the root, but any grab window exercises the same + // owner_events=false redirect path). + state.resources.create_window( + ClientId(WM_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: -100, + y: -100, + width: 1, + height: 1, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + // A foreign app window the pointer is actually over; it selects + // PointerMotion so we can prove the grab CAPTURES the suppressed + // motion rather than leaking it to the natural target. + state.resources.create_window( + ClientId(APP_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(APP_WIN), + parent: ROOT_WINDOW, + x: 400, + y: 300, + width: 300, + height: 200, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + let _ = state.resources.map_window(ResourceId(APP_WIN)); + + state + .clients + .get_mut(&APP_CLIENT_ID) + .expect("app client") + .event_masks + .insert(ResourceId(APP_WIN), 0x0000_0040); // PointerMotion + + Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP_XID) + .expect("register app host xid"); + + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(WM_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + event_mask: IMPORT_MASK as u16, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + + let xid_map = backend.xid_map().clone(); + + // (1) No-button motion (state=0): ButtonMotion mask must suppress + // delivery to the grab client, AND the grab must capture it so + // it never reaches the app's PointerMotion selection. + let no_button_motion = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + host_xid: HOST_APP_XID, + detail: 0, + time: 0x1000, + root_x: 450, + root_y: 350, + event_x: 50, + event_y: 50, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + no_button_motion, + true, + false, + ); + assert!(dropped.is_empty()); + assert!( + read_all_available(&mut wm_peer).is_empty(), + "grab client selected ButtonMotion (not PointerMotion) — no-button motion must NOT be delivered", + ); + assert!( + read_all_available(&mut app_peer).is_empty(), + "active grab must CAPTURE the suppressed motion, not leak it to the app's natural PointerMotion selection", + ); + + // (2) Motion with Button1 held (state=0x100): now the event + // carries the ButtonMotion bit → the grab client receives it, + // reported against the grab window (owner_events=false). + let button_motion = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + host_xid: HOST_APP_XID, + detail: 0, + time: 0x1001, + root_x: 451, + root_y: 351, + event_x: 51, + event_y: 51, + state: 0x0100, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + button_motion, + true, + false, + ); + assert!(dropped.is_empty()); + let wm_bytes = read_all_available(&mut wm_peer); + assert_eq!(wm_bytes.len(), 32, "expected exactly one core MotionNotify"); + assert_eq!(wm_bytes[0], 6, "event type should be MotionNotify"); + assert_eq!( + &wm_bytes[12..16], + &GRAB_WIN.to_le_bytes(), + "owner_events=false: motion reported against the grab window", + ); + assert!( + read_all_available(&mut app_peer).is_empty(), + "button-held motion is still captured by the grab, not sent to the app", + ); + + // (3) ButtonPress (mask includes ButtonPress) is still delivered. + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_APP_XID, + detail: 1, + time: 0x1002, + root_x: 451, + root_y: 351, + event_x: 51, + event_y: 51, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!(dropped.is_empty()); + let wm_bytes = read_all_available(&mut wm_peer); + assert_eq!(wm_bytes.len(), 32, "expected exactly one core ButtonPress"); + assert_eq!(wm_bytes[0], 4, "event type should be ButtonPress"); + assert_eq!( + &wm_bytes[12..16], + &GRAB_WIN.to_le_bytes(), + "owner_events=false: press reported against the grab window", + ); +} + +#[test] +fn pointer_event_resets_dpms_last_activity() { + use std::time::{Duration, Instant}; + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + state.dpms.last_activity = Instant::now() - Duration::from_secs(10); + let stale = state.dpms.last_activity; + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + let elapsed = state.dpms.last_activity.duration_since(stale); + assert!( + elapsed > Duration::from_secs(9), + "last_activity should be ≈now, not stale" + ); +} + +#[test] +fn pointer_event_during_off_wakes_via_set_dpms_power_on() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + state.dpms.power_level = 3; // Off + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + let calls = backend.calls.lock().unwrap().clone(); + assert!( + calls + .iter() + .any(|c| matches!(c, crate::backend::recording::RecordedCall::SetDpmsPower(0))), + "wake must call set_dpms_power(0); got {calls:?}" + ); + assert_eq!( + state.dpms.power_level, 0, + "in-memory level should be On after wake" + ); +} + +#[test] +fn pointer_event_during_off_with_backend_error_still_advances_state() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + state.dpms.power_level = 3; + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + backend.dpms_set_returns_err = true; + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + assert_eq!( + state.dpms.power_level, 0, + "state must advance on backend error" + ); +} + +#[test] +fn pointer_event_during_screen_saver_on_flips_off_via_independent_path() { + // Standalone SS-On (DPMS still On). Motion event must flip + // SS Off with forced=0. + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + // dpms.power_level already 0 from new() + state.screensaver.active = ScreenSaverActive::On; + state.screensaver.selected_by.insert(ClientId(1), 0x01); + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + assert_eq!(state.screensaver.active, ScreenSaverActive::Off); + assert!(!state.screensaver.forced, "input-driven Off is non-forced"); +} + +#[test] +fn pointer_event_updates_global_and_per_device_vcp_last_activity() { + use std::time::Duration; + let mut state = ServerState::new(); + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(30); + let stale = state.dpms.last_activity; + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + assert!( + state.dpms.last_activity > stale, + "global last_activity advanced" + ); + let vcp = state + .per_device_last_activity + .get(&2) + .copied() + .expect("VCP per-device entry inserted"); + assert!(vcp > stale, "VCP per-device last_activity advanced"); +} + +#[test] +fn pointer_event_fires_neg_transition_alarm_when_prior_idle_crosses_threshold() { + use std::time::Duration; + use yserver_protocol::x11::sync as x11sync; + let mut state = ServerState::new(); + // User idle for 90s, NegativeTransition alarm at 60s. + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(90); + state + .per_device_last_activity + .insert(2, std::time::Instant::now() - Duration::from_secs(90)); + let alarm_id = 0x4000; + state.sync_alarms.insert( + alarm_id, + crate::server::SyncAlarm { + owner: ClientId(1), + counter: x11sync::IDLETIME_DEVICE_VCP, + wait_value: 60_000, + delta: 0, + test_type: x11sync::TEST_NEGATIVE_TRANSITION, + events: false, + state: x11sync::ALARM_STATE_ACTIVE, + event_clients: Vec::new(), + value_type: 0, + raw_wait: 60_000, + check_type: x11sync::TEST_NEGATIVE_TRANSITION, + }, + ); + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + // Alarm stays Active (Transition + delta=0 — Task 2 fix); cache reflects post-wake idle=0. + assert_eq!( + state.sync_alarms[&alarm_id].state, + x11sync::ALARM_STATE_ACTIVE + ); + assert_eq!( + state + .idletime_last_evaluated + .get(&x11sync::IDLETIME_DEVICE_VCP) + .copied(), + Some(0), + "post-wake last_evaluated should be 0" + ); +} + +#[test] +fn pointer_event_fires_neg_transition_alarm_on_per_device_idletime_vcp() { + use std::time::Duration; + use yserver_protocol::x11::sync as x11sync; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(90); + state + .per_device_last_activity + .insert(2, std::time::Instant::now() - Duration::from_secs(90)); + let alarm_id = 0x5000; + state.sync_alarms.insert( + alarm_id, + crate::server::SyncAlarm { + owner: ClientId(1), + counter: x11sync::IDLETIME_DEVICE_VCP, + wait_value: 60_000, + delta: 0, + test_type: x11sync::TEST_NEGATIVE_TRANSITION, + events: true, // load-bearing + state: x11sync::ALARM_STATE_ACTIVE, + event_clients: Vec::new(), + value_type: 0, + raw_wait: 60_000, + check_type: x11sync::TEST_NEGATIVE_TRANSITION, + }, + ); + let xid_map = HostXidMap::new(); + let mut backend = crate::backend::recording::RecordingBackend::default(); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + motion_event(), + true, + false, + ); + + // PRIMARY: AlarmNotify event type 84. + let bytes = read_all_available(&mut peer); + // AlarmNotify is a 32-byte sequential event; type byte at offset 0. + assert!( + bytes.len() >= 32, + "expected AlarmNotify event (32B); got {} bytes", + bytes.len() + ); + assert_eq!( + bytes[0], 84, + "AlarmNotify event type (SYNC_FIRST_EVENT + 1)" + ); + assert_eq!(bytes[1], 1, "AlarmNotify kind = AlarmNotify (1)"); + assert_eq!( + state.sync_alarms[&alarm_id].state, + x11sync::ALARM_STATE_ACTIVE + ); + assert_eq!( + state + .idletime_last_evaluated + .get(&x11sync::IDLETIME_DEVICE_VCP) + .copied(), + Some(0) + ); +} + +/// Regression (e27 clicks dead): the device classification that gates +/// both the core/XI2 dedup and the XI2 `deviceid` stamp. A client +/// selecting on the SLAVE pointer must classify as slave (so the dedup +/// leaves its CORE ButtonPress intact — Enlightenment needs the core +/// click); a client selecting the MASTER, `XIAllMasterDevices`, or +/// `XIAllDevices` must classify as master (so it is still deduped, +/// preserving Chromium's no-double-ButtonPress fix). HW-confirmed on +/// both e27 (clicks work) and Chrome (no double-click) 2026-06-25. +#[test] +fn xi2_stamp_deviceid_classifies_slave_vs_master_selectors() { + let mut state = ServerState::new(); + let _p1 = install_client(&mut state, 1); + let _p2 = install_client(&mut state, 2); + let _p3 = install_client(&mut state, 3); + let _p4 = install_client(&mut state, 4); + let win = ResourceId(0x10_0009); + const XI_BUTTON_PRESS_MASK: u32 = 1 << 4; + // client 1: slave-pointer selection (Enlightenment's pattern). + state.clients.get_mut(&1).unwrap().xi2_masks.insert( + (win, XI2_XTEST_POINTER_DEVICE_ID), + u64::from(XI_BUTTON_PRESS_MASK), + ); + // client 2: master-pointer selection (Chromium's pattern). + state.clients.get_mut(&2).unwrap().xi2_masks.insert( + (win, XI2_MASTER_POINTER_DEVICE_ID), + u64::from(XI_BUTTON_PRESS_MASK), + ); + // client 3: XIAllMasterDevices (1) wildcard. + state + .clients + .get_mut(&3) + .unwrap() + .xi2_masks + .insert((win, 1), u64::from(XI_BUTTON_PRESS_MASK)); + // client 4: no XI2 selection at all. + + assert_eq!( + xi2_stamp_deviceid_for_source(&state, ClientId(1), win, win, 4, Some(4)), + XI2_XTEST_POINTER_DEVICE_ID, + "slave-device selector must stay slave (keeps core delivery)" + ); + assert_eq!( + xi2_stamp_deviceid_for_source(&state, ClientId(2), win, win, 4, Some(4)), + XI2_MASTER_POINTER_DEVICE_ID, + "master-device selector must be master (stays deduped)" + ); + assert_eq!( + xi2_stamp_deviceid_for_source(&state, ClientId(3), win, win, 4, Some(4)), + XI2_MASTER_POINTER_DEVICE_ID, + "XIAllMasterDevices selector classifies as master" + ); + assert_eq!( + xi2_stamp_deviceid_for_source(&state, ClientId(4), win, win, 4, Some(4)), + XI2_MASTER_POINTER_DEVICE_ID, + "no XI2 selection defaults to master" + ); +} + +/// Issue #72: lite-xl (SDL2) got NO mouse interactions because it +/// splits its XI2 selection across device-id wildcards on the SAME +/// window — Motion/Touch/Gesture under `XIAllMasterDevices(1)` but +/// ButtonPress/Release under `XIAllDevices(0)`. The old first-match +/// `xi2_mask_for_client` returned only the device-1 mask (no button +/// bits) and never OR'd in device-0, so every XI_ButtonPress/Release +/// was delivered to NOBODY (`xi2_targets=[]`) — no clicks, no scroll, +/// no scrollbar drag. The masks below are the real values from the +/// lite-xl HW log. +#[test] +fn xi2_split_device_wildcards_deliver_button_press_issue_72() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 11); + let window = ResourceId(0x0080_0037); + // XIAllMasterDevices(1): Motion(6)+Enter(7)+Touch(18/19/20)+ + // Gesture(27/28/29) — NO button bits. + state + .clients + .get_mut(&11) + .unwrap() + .xi2_masks + .insert((window, 1u16), 0x381c_00c0u64); + // XIAllDevices(0): DeviceChanged(1)+ButtonPress(4)+ButtonRelease(5)+ + // Motion(6)+Enter(7)+Leave(8)+Hierarchy(11)+Property(12). + state + .clients + .get_mut(&11) + .unwrap() + .xi2_masks + .insert((window, 0u16), 0x19f2u64); + + // XI_ButtonPress (4) is selected ONLY under XIAllDevices(0). Under + // the old first-match semantics device 1 matched first and had no + // button bit -> empty targets -> the click reached no client. + let press_targets = compute_xi2_targets_for_source(&state, window, window, 4, Some(4)); + assert!( + press_targets.contains(&ClientId(11)), + "issue #72: XI_ButtonPress selected under XIAllDevices(0) must be \ + delivered even when motion is selected under XIAllMasterDevices(1)" + ); + + // XI_ButtonRelease (5) is likewise only under XIAllDevices(0). + let release_targets = compute_xi2_targets_for_source(&state, window, window, 5, Some(4)); + assert!( + release_targets.contains(&ClientId(11)), + "issue #72: XI_ButtonRelease under XIAllDevices(0) must be delivered" + ); + + // Sanity: XI_Motion (6) — selected under BOTH wildcards — still + // reaches the client (this arm passed even under first-match). + let motion_targets = compute_xi2_targets_for_source(&state, window, window, 6, Some(4)); + assert!( + motion_targets.contains(&ClientId(11)), + "XI_Motion must continue to be delivered" + ); +} + +/// Regression for issue #72 at the decision point: the per-form +/// membership `xi2_pointer_forms` computes. A client selecting under +/// `XIAllDevices(0)` (the SDL3/lite-xl idiom) MUST land in BOTH the +/// master- and slave-stamped delivery buckets. SDL3 parses smooth +/// scroll ONLY off the slave-stamped motion (its handler gates on +/// `deviceid == sourceid`); the pre-fix single-form (master-only / +/// first-match) bucketing returned `wants_slave == false`, leaving +/// lite-xl unable to scroll. +#[test] +fn xi2_pointer_forms_all_devices_selector_gets_both_forms_issue_72() { + const MOTION: u16 = 6; + const BUTTON_PRESS: u16 = 4; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 11); + let win = ResourceId(0x0080_0037); + + let set_masks = |state: &mut ServerState, masks: &[(u16, u32)]| { + let client = state.clients.get_mut(&11).unwrap(); + client.xi2_masks.clear(); + for &(dev, mask) in masks { + client.xi2_masks.insert((win, dev), u64::from(mask)); + } + }; + + // Case 1 — real lite-xl/SDL3 masks: XIAllMasterDevices(1) carries + // Motion (no button bits); XIAllDevices(0) carries ButtonPress+ + // Motion. Both evtypes MUST yield BOTH forms so SDL3 sees the + // slave-stamped scroll motion. `wants_slave == true` here is the + // core issue-#72 fix: it was false under master-only bucketing. + set_masks(&mut state, &[(1u16, 0x381c_00c0u32), (0u16, 0x19f2u32)]); + assert_eq!( + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4)), + (true, true), + "issue #72: an XIAllDevices(0) selector must get BOTH forms for \ + Motion so SDL3 can parse smooth scroll off the slave-stamped motion" + ); + assert_eq!( + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, BUTTON_PRESS, Some(4)), + (true, true), + "ButtonPress selected under XIAllDevices(0) must also yield BOTH forms" + ); + + // Case 2 — XIAllMasterDevices(1) only, Motion bit set: device 1 + // covers master devices only, so master form yes, slave form no. + set_masks(&mut state, &[(1u16, 0x0000_0040u32)]); + assert_eq!( + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4)), + (true, false), + "XIAllMasterDevices(1) covers master devices only: master form, NO slave form" + ); + + // Case 3 — concrete slave pointer only (Enlightenment's pattern): + // slave form yes, master form no; preserves core delivery. + set_masks(&mut state, &[(XI2_XTEST_POINTER_DEVICE_ID, 0x0000_0040u32)]); + assert_eq!( + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4)), + (false, true), + "a concrete slave-pointer selector gets the slave form only" + ); + + // Case 4 — XIAllDevices(0) only: device 0 matches both master and + // slave, so both forms. + set_masks(&mut state, &[(0u16, 0x0000_0040u32)]); + assert_eq!( + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4)), + (true, true), + "XIAllDevices(0) matches both master and slave: BOTH forms" + ); +} + +/// X11 implicit pointer grab (#94, Xorg dix/events.c:2150-2193 + +/// 2415-2421): a delivered ButtonPress activates an async grab owned +/// by the press recipient on the press's event window; the matching +/// ButtonRelease is delivered under that grab even when the hit-test +/// now resolves to another client's window (muffin mutates the tree +/// between press and release — Steam got presses without releases). +#[test] +fn implicit_grab_core_release_follows_press_recipient() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const APP: u32 = 1; + const OTHER: u32 = 2; + let win_a = ResourceId(0x0010_0001); + let win_b = ResourceId(0x0020_0001); + const HOST_A: u32 = 0xCAFE_0001; + const HOST_B: u32 = 0xCAFE_0002; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut app_peer = install_client(&mut state, APP); + let mut other_peer = install_client(&mut state, OTHER); + + for (client, win, x) in [(APP, win_a, 0i16), (OTHER, win_b, 500i16)] { + state.resources.create_window( + ClientId(client), + CreateWindowRequest { + depth: 24, + window: win, + parent: ROOT_WINDOW, + x, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + } + // ButtonPress|ButtonRelease. + for (client, win) in [(APP, win_a), (OTHER, win_b)] { + state + .clients + .get_mut(&client) + .unwrap() + .event_masks + .insert(win, 0x0000_000c); + } + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_A, win_a); + xid_map.insert(HOST_B, win_b); + + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.host_xid = HOST_A; + press.detail = 1; + press.time = 1000; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && g.owner == ClientId(APP) && g.grab_window == win_a), + "delivered press must install the implicit grab (Xorg dix/events.c:2415)" + ); + let _ = read_all_available(&mut app_peer); // drain the press + + // Release resolves over OTHER's window (the WM-mutated-tree shape). + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = HOST_B; + release.detail = 1; + release.time = 1010; + release.root_x = 550; + release.root_y = 10; + release.event_x = 50; + release.event_y = 10; + release.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let bytes = read_all_available(&mut app_peer); + let mut saw_release = false; + let mut off = 0usize; + while off + 32 <= bytes.len() { + if bytes[off] & 0x7F == 5 { + saw_release = true; + assert_eq!( + &bytes[off + 12..off + 16], + &win_a.0.to_le_bytes(), + "grabbed release must be reported on the grab (press) window" + ); + } + off += 32; + } + assert!( + saw_release, + "implicit grab: the release must follow the press recipient, not re-hit-test" + ); + let other_bytes = read_all_available(&mut other_peer); + assert!( + !other_bytes.chunks(32).any(|c| c[0] & 0x7F == 5), + "the grab captures the release — OTHER must not receive it" + ); + assert!( + state.active_pointer_grab.is_none(), + "final release tears the implicit grab down (Xi/exevents.c:1931)" + ); +} + +/// XI2 form of the implicit grab (#94 — the actual Steam/Cinnamon +/// shape: Steam selects cooked XI2 buttons, no core mask). The XI2 +/// ButtonPress installs a via_xi2 implicit grab; the release delivers +/// to the owner on the grab window through the XI2 redirect. +#[test] +fn implicit_grab_xi2_release_follows_press_recipient() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const APP: u32 = 1; + const OTHER: u32 = 2; + let win_a = ResourceId(0x0010_0001); + let win_b = ResourceId(0x0020_0001); + const HOST_A: u32 = 0xCAFE_0001; + const HOST_B: u32 = 0xCAFE_0002; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut app_peer = install_client(&mut state, APP); + let _other_peer = install_client(&mut state, OTHER); + + for (client, win, x) in [(APP, win_a, 0i16), (OTHER, win_b, 500i16)] { + state.resources.create_window( + ClientId(client), + CreateWindowRequest { + depth: 24, + window: win, + parent: ROOT_WINDOW, + x, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + } + // XI_ButtonPress(4) | XI_ButtonRelease(5) on the master pointer. + state + .clients + .get_mut(&APP) + .unwrap() + .xi2_masks + .insert((win_a, XI2_MASTER_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); + state + .clients + .get_mut(&OTHER) + .unwrap() + .xi2_masks + .insert((win_b, XI2_MASTER_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_A, win_a); + xid_map.insert(HOST_B, win_b); + + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.host_xid = HOST_A; + press.detail = 1; + press.time = 1000; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && g.via_xi2 && g.owner == ClientId(APP)), + "XI2-delivered press must install a via_xi2 implicit grab" + ); + let _ = read_all_available(&mut app_peer); + + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = HOST_B; + release.detail = 1; + release.time = 1010; + release.root_x = 550; + release.root_y = 10; + release.event_x = 50; + release.event_y = 10; + release.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let bytes = read_all_available(&mut app_peer); + let mut found_win = None; + let mut off = 0usize; + while off + 32 <= bytes.len() { + if bytes[off] == 35 && u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]) == 5 { + found_win = Some(u32::from_le_bytes( + bytes[off + 24..off + 28].try_into().unwrap(), + )); + break; + } + let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; + off += 32 + length * 4; + } + assert_eq!( + found_win, + Some(win_a.0), + "XI2 release must reach the implicit-grab owner on the grab window" + ); + assert!( + state.active_pointer_grab.is_none(), + "grab released after final release" + ); +} + +/// Xorg oracle from the FAILING `xfce.xtrace` vs `xfce-xorg.xtrace`: an +/// XFCE dialog selects XI2 buttons under `device=1` (XIAllMasterDevices, +/// not the master id 2), gets its ButtonPress (delivered as master 0x02), +/// but yserver dropped EVERY XI2 ButtonRelease (xtrace: 13 XI2 presses, 0 +/// XI2 releases; Xorg delivered 3/3). The dialog "reacts to the click but +/// it never takes effect". Every PASSING implicit-grab test selects under +/// device 2, so this pins the device=1 (all-master) selector: press AND +/// release must both reach the selector on its window. +#[test] +fn implicit_grab_xi2_release_reaches_all_master_selector_xfce() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const APP: u32 = 1; + const XI2_ALL_MASTER: u16 = 1; // XIAllMasterDevices + let win_a = ResourceId(0x0050_0003); + const HOST_A: u32 = 0xCAFE_0001; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut app_peer = install_client(&mut state, APP); + + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: win_a, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win_a); + // XI_ButtonPress(4) | XI_ButtonRelease(5) selected under XIAllMasterDevices. + state + .clients + .get_mut(&APP) + .unwrap() + .xi2_masks + .insert((win_a, XI2_ALL_MASTER), (1 << 4) | (1 << 5)); + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_A, win_a); + + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.host_xid = HOST_A; + press.detail = 1; + press.time = 1000; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + let xge_evtypes = |bytes: &[u8]| -> Vec { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + assert!( + xge_evtypes(&read_all_available(&mut app_peer)).contains(&4), + "precondition: the all-master XI2 selector receives the ButtonPress" + ); + + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = HOST_A; + release.detail = 1; + release.time = 1010; + release.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + assert!( + xge_evtypes(&read_all_available(&mut app_peer)).contains(&5), + "XI2 ButtonRelease must reach the XIAllMasterDevices selector on its \ + window (xfce.xtrace dropped it: 0 XI2 releases vs Xorg 3/3)" + ); +} + +/// #94 XFCE dialog repro (fail `xfce.xtrace` / pass `xfce-xorg.xtrace`). +/// The real shape: a CORE selector on an ANCESTOR window (xtrace conn 005, +/// event=0x00300a58) plus the XI2 dialog on a leaf child (conn 014, +/// event=0x00500003). The deeper XI2 delivery owns the implicit grab, so +/// the release follows that XI2 grab rather than propagating naturally to +/// the core ancestor. +#[test] +fn implicit_grab_release_reaches_xi2_leaf_with_core_ancestor_selector_xfce() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const CORE_ANCESTOR: u32 = 1; // xtrace conn 005 (core selector on ancestor) + const XI2_LEAF: u32 = 2; // xtrace conn 014 (XI2 dialog) + let parent = ResourceId(0x0030_0a58); + let leaf = ResourceId(0x0050_0003); + const HOST_LEAF: u32 = 0xCAFE_0001; + const XI2_ALL_MASTER: u16 = 1; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut core_peer = install_client(&mut state, CORE_ANCESTOR); + let mut leaf_peer = install_client(&mut state, XI2_LEAF); + + // parent (core selector) ← leaf (XI2 selector), leaf covers the hit. + state.resources.create_window( + ClientId(CORE_ANCESTOR), + CreateWindowRequest { + depth: 24, + window: parent, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 200, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(parent); + state.resources.create_window( + ClientId(XI2_LEAF), + CreateWindowRequest { + depth: 24, + window: leaf, + parent, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(leaf); + // Ancestor: CORE ButtonPress|ButtonRelease (0x0c). Leaf: XI2 under + // XIAllMasterDevices. + state + .clients + .get_mut(&CORE_ANCESTOR) + .unwrap() + .event_masks + .insert(parent, 0x0000_000c); + state + .clients + .get_mut(&XI2_LEAF) + .unwrap() + .xi2_masks + .insert((leaf, XI2_ALL_MASTER), (1 << 4) | (1 << 5)); + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_LEAF, leaf); + + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.host_xid = HOST_LEAF; + press.detail = 1; + press.time = 1000; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let _ = read_all_available(&mut core_peer); + let leaf_after_press = read_all_available(&mut leaf_peer); + + let xge_evtypes = |bytes: &[u8]| -> Vec { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + assert!( + xge_evtypes(&leaf_after_press).contains(&4), + "precondition: the XI2 leaf selector receives the ButtonPress" + ); + + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = HOST_LEAF; + release.detail = 1; + release.time = 1010; + release.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let core_after = read_all_available(&mut core_peer); + let leaf_after = read_all_available(&mut leaf_peer); + assert!( + !core_after.chunks(32).any(|c| c.first() == Some(&5)), + "the XI2 implicit grab captures the release before core ancestor propagation" + ); + assert!( + xge_evtypes(&leaf_after).contains(&5), + "XI2 ButtonRelease must reach the XI2 leaf selector even though a \ + core client selects on an ancestor (xfce.xtrace: leaf got the \ + press but the release was dropped)" + ); +} + +/// Enlightenment (E27) dock-click repro, hardware-measured on silence. +/// One client selects BOTH core ButtonPress|ButtonRelease AND XI2 on the +/// SLAVE pointer for the same window; the core dedup keeps the core form +/// for slave stamps, so the press is delivered twice — once per protocol. +/// +/// The implicit grab that press installs must be typed CORE, not XI2: +/// Xorg `DeliverEventsToWindow` delivers core first and activates the +/// grab from that call, so `ActivateImplicitGrab` sees `ButtonPress` and +/// picks `grabtype = CORE` (dix/events.c:2158), which its own comment at +/// dix/events.c:2417 spells out — "since core events are delivered first, +/// an implicit grab may be activated on a core grab, stopping the XI +/// events." +/// +/// Typing it XI2 set `via_xi2`, and the active-grab redirect then +/// suppressed the CORE form of the release while still marking the event +/// handled — captured and dropped, with natural propagation skipped too. +/// E27 lost the mouse-up on every dock click: the button stayed down +/// client-side, so clicks became drags and then input wedged entirely. +/// +/// Oracle is measured, not assumed — silence, same session, same clicks: +/// yserver before core 10/2 XI2 9/8 +/// yserver after core 28/28 XI2 28/28 +/// Xorg baseline core 3/3 XI2 3/3 +/// Core press and release balance 1:1 on Xorg, so the release must land. +#[test] +fn implicit_grab_core_release_survives_dual_core_and_slave_xi2_selection_e27() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const APP: u32 = 1; + let canvas = ResourceId(0x0010_0009); // E27 canvas, from the trace + const HOST_CANVAS: u32 = 0x0040_0dbb; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut app_peer = install_client(&mut state, APP); + + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: canvas, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 200, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(canvas); + // Core ButtonPress|ButtonRelease (0x0c) AND XI2 press/release on the + // SLAVE pointer — both on the same window, the E27 shape. + state + .clients + .get_mut(&APP) + .unwrap() + .event_masks + .insert(canvas, 0x0000_000c); + state + .clients + .get_mut(&APP) + .unwrap() + .xi2_masks + .insert((canvas, XI2_XTEST_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_CANVAS, canvas); + + // Walk the wire correctly: XGE (type 35) carries a length in words, + // so a flat chunks(32) misaligns once both forms share a stream. + let split_events = |bytes: &[u8]| -> (Vec, Vec) { + let (mut core, mut xge) = (Vec::new(), Vec::new()); + let mut off = 0usize; + while off + 32 <= bytes.len() { + if bytes[off] == 35 { + xge.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); + off += 32 + + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4; + } else { + core.push(bytes[off] & 0x7f); + off += 32; + } + } + (core, xge) + }; + + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.host_xid = HOST_CANVAS; + press.detail = 1; + press.time = 1000; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + let (core_press, xge_press) = split_events(&read_all_available(&mut app_peer)); + assert!( + core_press.contains(&4), + "precondition: the core selector receives the ButtonPress" + ); + assert!( + xge_press.contains(&4), + "precondition: the slave XI2 selector also receives the press \ + (the slave carve-out in the core dedup keeps both forms)" + ); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && !g.via_xi2), + "the implicit grab must be typed CORE when both forms were \ + delivered to the same window (Xorg ActivateImplicitGrab)" + ); + + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = HOST_CANVAS; + release.detail = 1; + release.time = 1010; + release.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let (core_release, _) = split_events(&read_all_available(&mut app_peer)); + assert!( + core_release.contains(&5), + "core ButtonRelease must reach the client — an XI2-typed implicit \ + grab captured it at the active-grab redirect and dropped it, \ + wedging E27 (measured core 10 press / 2 release; Xorg 3/3)" + ); +} + +/// Under a via_xi2 implicit grab, delivery is filtered by the owner's +/// XI2 selection on the grab window (Xorg merges the window xi2mask +/// into the implicit GrabRec): press+release-only selectors must not +/// receive XI_Motion during the click, and the motion must not leak +/// to the window under the cursor either (the grab captures it). +#[test] +fn implicit_grab_xi2_motion_filtered_by_owner_selection() { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + const APP: u32 = 1; + const OTHER: u32 = 2; + let win_a = ResourceId(0x0010_0001); + let win_b = ResourceId(0x0020_0001); + const HOST_A: u32 = 0xCAFE_0001; + const HOST_B: u32 = 0xCAFE_0002; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut app_peer = install_client(&mut state, APP); + let mut other_peer = install_client(&mut state, OTHER); + + for (client, win, x) in [(APP, win_a, 0i16), (OTHER, win_b, 500i16)] { + state.resources.create_window( + ClientId(client), + CreateWindowRequest { + depth: 24, + window: win, + parent: ROOT_WINDOW, + x, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + } + // APP: XI_ButtonPress(4)|XI_ButtonRelease(5) ONLY — no XI_Motion(6). + state + .clients + .get_mut(&APP) + .unwrap() + .xi2_masks + .insert((win_a, XI2_MASTER_POINTER_DEVICE_ID), (1 << 4) | (1 << 5)); + // OTHER selects XI_Motion on its own window — the grab must + // capture the motion away from it anyway. + state + .clients + .get_mut(&OTHER) + .unwrap() + .xi2_masks + .insert((win_b, XI2_MASTER_POINTER_DEVICE_ID), 1 << 6); + let mut xid_map = HostXidMap::new(); + xid_map.insert(HOST_A, win_a); + xid_map.insert(HOST_B, win_b); + + let mut press = motion_event(); + press.kind = PointerEventKind::ButtonPress; + press.host_xid = HOST_A; + press.detail = 1; + press.time = 1000; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && g.via_xi2), + "precondition: XI2 implicit grab installed" + ); + let _ = read_all_available(&mut app_peer); + let _ = read_all_available(&mut other_peer); + + // Motion over OTHER's window while the implicit grab is held. + let mut motion = motion_event(); + motion.host_xid = HOST_B; + motion.time = 1005; + motion.root_x = 550; + motion.root_y = 10; + motion.event_x = 50; + motion.event_y = 10; + motion.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); + + let xge_evtypes = |bytes: &[u8]| -> Vec { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + assert!( + !xge_evtypes(&read_all_available(&mut app_peer)).contains(&6), + "owner did not select XI_Motion on the grab window — the \ + implicit grab must not over-deliver it (Xorg xi2mask filter)" + ); + assert!( + xge_evtypes(&read_all_available(&mut other_peer)).is_empty(), + "the grab captures motion — the window under the cursor gets nothing" + ); + + // The release (selected) still delivers to the owner on the grab window. + let mut release = motion_event(); + release.kind = PointerEventKind::ButtonRelease; + release.host_xid = HOST_B; + release.detail = 1; + release.time = 1010; + release.root_x = 550; + release.root_y = 10; + release.event_x = 50; + release.event_y = 10; + release.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + assert!( + xge_evtypes(&read_all_available(&mut app_peer)).contains(&5), + "selected XI_ButtonRelease still delivers under the implicit grab" + ); + assert!( + state.active_pointer_grab.is_none(), + "grab torn down after final release" + ); +} + +/// One mapped 100x100 window at (x,0) owned by `client`, host xid +/// registered in `map`. Implicit-grab test scaffolding. +fn implicit_test_window( + state: &mut ServerState, + map: &mut HostXidMap, + client: u32, + win: u32, + host: u32, + x: i16, +) -> yserver_protocol::x11::ResourceId { + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + let id = ResourceId(win); + state.resources.create_window( + ClientId(client), + CreateWindowRequest { + depth: 24, + window: id, + parent: ROOT_WINDOW, + x, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(id); + map.insert(host, id); + id +} + +fn button_event(kind: PointerEventKind, host: u32, button: u8, time: u32) -> HostPointerEvent { + let mut ev = motion_event(); + ev.kind = kind; + ev.host_xid = host; + ev.detail = button; + ev.time = time; + ev +} + +fn install_passive_test_grab( + state: &mut ServerState, + xid_map: &mut HostXidMap, + owner: u32, + event_mask: u32, + via_xi2: bool, +) -> yserver_protocol::x11::ResourceId { + let win = implicit_test_window(state, xid_map, owner, 0x0010_0001, 0xCAFE_0001, 0); + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(owner), + grab_window: win, + button: 1, + modifiers: 0x8000, + owner_events: false, + event_mask, + pointer_mode: 1, + keyboard_mode: 1, + confine_to: yserver_protocol::x11::ResourceId(0), + via_xi2, + }); + win +} + +#[test] +fn passive_grab_activation_populates_and_final_release_clears_record() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let _peer = install_client(&mut state, 1); + let mut xid_map = HostXidMap::new(); + let win = install_passive_test_grab(&mut state, &mut xid_map, 1, 0x000c, false); + + let fan = |state: &mut ServerState, backend: &mut RecordingBackend, kind, button, time| { + let event = button_event(kind, 0xCAFE_0001, button, time); + let _ = pointer_event_fanout_to_state(state, backend, &xid_map, event, true, false); + }; + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonPress, + 1, + 1000, + ); + assert!(state.active_pointer_grab.is_some_and(|grab| { + grab.owner == ClientId(1) && grab.grab_window == win && grab.passive && !grab.implicit + })); + + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonPress, + 3, + 1001, + ); + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonRelease, + 1, + 1002, + ); + assert!( + state.active_pointer_grab.is_some_and(|grab| grab.passive), + "a non-final release must not deactivate the passive grab" + ); + + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonRelease, + 3, + 1003, + ); + assert!( + state.active_pointer_grab.is_none(), + "the final release must clear the passive grab" + ); +} + +#[test] +fn active_grab_target_uses_matched_passive_grab_not_last_registered() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let _peer = install_client(&mut state, 1); + let mut xid_map = HostXidMap::new(); + let win = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); + for (modifiers, event_mask) in [(0, 0x000c), (1, 0x0040)] { + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(1), + grab_window: win, + button: 1, + modifiers, + owner_events: false, + event_mask, + pointer_mode: 1, + keyboard_mode: 1, + confine_to: yserver_protocol::x11::ResourceId(0), + via_xi2: false, + }); + } + let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + let (_, _, _, _, _, _, mask) = active_grab_target(&state).expect("passive grab active"); + assert_eq!( + mask, 0x000c, + "the active record must snapshot the grab that matched, not the last registration" + ); +} + +#[test] +fn xi2_passive_grab_delivers_final_release_before_teardown() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let mut peer = install_client(&mut state, 1); + let mut xid_map = HostXidMap::new(); + let win = install_passive_test_grab(&mut state, &mut xid_map, 1, (1 << 4) | (1 << 5), true); + + let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let _ = read_all_available(&mut peer); + let mut release = button_event(PointerEventKind::ButtonRelease, 0xCAFE_0001, 1, 1001); + release.state = 0x0100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let bytes = read_all_available(&mut peer); + assert!(bytes.windows(28).any(|event| { + event[0] == 35 + && u16::from_le_bytes([event[8], event[9]]) == 5 + && u32::from_le_bytes(event[24..28].try_into().unwrap()) == win.0 + })); + assert!(state.active_pointer_grab.is_none()); +} + +/// Xorg gate is `if (deliveries)` (dix/events.c:2415): a press nobody +/// selected installs nothing. +#[test] +fn implicit_grab_not_installed_when_press_undelivered() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let _peer = install_client(&mut state, 1); + let mut xid_map = HostXidMap::new(); + // Window exists but no client selects button events anywhere. + let _w = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); + let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!(state.active_pointer_grab.is_none()); +} + +/// A press while an explicit grab is active never installs (Xorg +/// `if (!grab ...)`) — and must not clobber the explicit record. +#[test] +fn implicit_grab_not_installed_under_explicit_grab() { + use crate::server::ActivePointerGrab; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let _peer = install_client(&mut state, 1); + let mut xid_map = HostXidMap::new(); + let w = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(w, 0x0000_000c); + let explicit = ActivePointerGrab { + owner: ClientId(1), + grab_window: w, + event_mask: 0x000c, + cursor: yserver_protocol::x11::ResourceId(0), + time: 500, + owner_events: false, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }; + state.active_pointer_grab = Some(explicit); + let press = button_event(PointerEventKind::ButtonPress, 0xCAFE_0001, 1, 1000); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!( + state + .active_pointer_grab + .is_some_and(|g| !g.implicit && g.time == 500), + "explicit grab record must be untouched by the press" + ); + // And the explicit grab does NOT auto-release on the final release. + let release = button_event(PointerEventKind::ButtonRelease, 0xCAFE_0001, 1, 1010); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + assert!( + state.active_pointer_grab.is_some(), + "explicit grabs persist until UngrabPointer (only implicit auto-releases)" + ); +} + +/// Multi-button click: the grab holds until ALL buttons release +/// (Xi/exevents.c:1935 `!b->buttonsDown`), a second press neither +/// reinstalls nor activates passive grabs (dix `if (!grab && +/// CheckDeviceGrabs...)`, yserver's active_grab_present gate), and +/// pressing again after a partial release still doesn't reinstall +/// (pins the no-transition-gate model). +#[test] +fn implicit_grab_multi_button_lifecycle() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::default(); + let _peer = install_client(&mut state, 1); + let _wm = install_client(&mut state, 2); + let mut xid_map = HostXidMap::new(); + let w = implicit_test_window(&mut state, &mut xid_map, 1, 0x0010_0001, 0xCAFE_0001, 0); + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(w, 0x0000_000c); + // A passive grab that WOULD match button 3 — it must not activate + // while the implicit grab holds the device. + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(2), + grab_window: w, + button: 3, + modifiers: 0x8000, // AnyModifier + owner_events: false, + event_mask: 0x0000_000c, + pointer_mode: 1, + keyboard_mode: 1, + confine_to: yserver_protocol::x11::ResourceId(0), + via_xi2: false, + }); + + let fan = |state: &mut ServerState, backend: &mut RecordingBackend, kind, button, time| { + let ev = button_event(kind, 0xCAFE_0001, button, time); + let _ = pointer_event_fanout_to_state(state, backend, &xid_map, ev, true, false); + }; + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonPress, + 1, + 1000, + ); + assert!(state.active_pointer_grab.is_some_and(|g| g.implicit)); + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonPress, + 3, + 1005, + ); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && !g.passive), + "second press: no passive activation, implicit grab unchanged" + ); + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonRelease, + 1, + 1010, + ); + assert!( + state.active_pointer_grab.is_some(), + "grab persists while button 3 is still down" + ); + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonPress, + 1, + 1015, + ); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && g.time == 1000), + "re-press during the grab must not reinstall (time unchanged)" + ); + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonRelease, + 1, + 1020, + ); + fan( + &mut state, + &mut backend, + PointerEventKind::ButtonRelease, + 3, + 1025, + ); + assert!( + state.active_pointer_grab.is_none(), + "final release tears down" + ); +} + +mod passive_grab_activation; +mod server_events; diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/tests/passive_grab_activation.rs b/crates/yserver-core/src/core_loop/pointer_fanout/tests/passive_grab_activation.rs new file mode 100644 index 000000000..f67b936a0 --- /dev/null +++ b/crates/yserver-core/src/core_loop/pointer_fanout/tests/passive_grab_activation.rs @@ -0,0 +1,103 @@ +//! Where a passive button grab's activating press is reported (GH #277). + +use super::*; + +/// GH #277 (probe V9, measured on Xorg in +/// `tools/vng-scenarios/key-grab-activation`): Xorg `ActivatePassiveGrab` +/// (dix/events.c) delivers the activating press with +/// `FixUpEventFromWindow(grab->window)` + `TryClientEvents` — no +/// `owner_events` walk. The grab client selects ButtonPress on the root +/// and on `bar` but not on the grab window `top`; the press is still +/// reported on `top`, child `bar`. The release, under the active grab, +/// takes the owner_events walk to `bar`. +#[test] +fn passive_grab_activating_press_skips_owner_events_walk() { + use yserver_protocol::x11::ResourceId; + + let mut state = ServerState::new(); + let top = ResourceId(0x0020_0001); + let bar = ResourceId(0x0020_0002); + let mut peer = install_client(&mut state, 1); + for (win, parent, x, y, w, h) in [ + (top, crate::resources::ROOT_WINDOW, 100, 100, 400, 300), + (bar, top, 0, 250, 400, 50), + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: win, + parent, + x, + y, + width: w, + height: h, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + } + let masks = &mut state.clients.get_mut(&1).unwrap().event_masks; + masks.insert(crate::resources::ROOT_WINDOW, 0x0000_000C); + masks.insert(bar, 0x0000_000C); + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(1), + grab_window: top, + button: 1, + modifiers: 0x8000, + owner_events: true, + event_mask: 0x0000_000C, + pointer_mode: 1, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + let mut xid_map = HostXidMap::new(); + xid_map.insert(0xCAFE_u32, crate::resources::ROOT_WINDOW); + let mut backend = crate::backend::recording::RecordingBackend::default(); + let mut press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: 0xCAFE, + detail: 1, + time: 0, + root_x: 300, + root_y: 375, + event_x: 300, + event_y: 375, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let fields = |bytes: &[u8], code: u8| -> Vec<(u32, u32, i16, i16)> { + bytes + .chunks(32) + .filter(|e| e[0] & 0x7f == code) + .map(|e| { + let u32_at = |at: usize| u32::from_le_bytes(e[at..at + 4].try_into().unwrap()); + let i16_at = |at: usize| i16::from_le_bytes([e[at], e[at + 1]]); + (u32_at(12), u32_at(16), i16_at(24), i16_at(26)) + }) + .collect() + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert_eq!( + fields(&read_all_available(&mut peer), 4), + [(top.0, bar.0, 200, 275)], + "activating press: event=top child=bar ev=200,275 (Xorg probe V9)", + ); + press.kind = PointerEventKind::ButtonRelease; + press.state = 0x100; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert_eq!( + fields(&read_all_available(&mut peer), 5), + [(bar.0, 0, 200, 25)], + "release under the grab walks to bar (Xorg probe V9)", + ); +} diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/tests/server_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/tests/server_events.rs new file mode 100644 index 000000000..88d65fc20 --- /dev/null +++ b/crates/yserver-core/src/core_loop/pointer_fanout/tests/server_events.rs @@ -0,0 +1,149 @@ +//! Pointer events whose window or raw form depends on who made the motion: +//! a grab's pick (the grab window's child) and a warp (no raw motion). + +use super::*; + +/// xwininfo, xprop and xkill grab the pointer on the root and take the +/// window clicked from the ButtonPress's `child`, which Xorg's +/// `FixUpEventFromWindow` fills with the grab window's child toward the +/// pointer's window. With `child` 0 they picked the root. +#[test] +fn a_grabbed_press_names_the_grab_windows_child_under_the_pointer() { + use crate::{backend::Backend, resources::ROOT_VISUAL, server::ActivePointerGrab}; + + const PICKER: u32 = 1; + const APP: u32 = 2; + const APP_WIN: u32 = 0x0020_0091; + const APP_CHILD: u32 = 0x0020_0092; + const HOST_APP_XID: u32 = 0xCAFE_0091; + + let mut state = ServerState::new(); + let mut picker = install_client(&mut state, PICKER); + let _app = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + for (window, parent, x, y) in [ + (APP_WIN, ROOT_WINDOW, 400, 300), + (APP_CHILD, ResourceId(APP_WIN), 10, 10), + ] { + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent, + x, + y, + width: 100, + height: 100, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(window)); + } + Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP_XID) + .expect("register app host xid"); + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(PICKER), + grab_window: ROOT_WINDOW, + event_mask: 0x0000_0004 | 0x0000_0008, // ButtonPress | ButtonRelease + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + let xid_map = backend.xid_map().clone(); + let press = HostPointerEvent { + kind: PointerEventKind::ButtonPress, + host_xid: HOST_APP_XID, + detail: 1, + time: 0x1000, + root_x: 420, + root_y: 320, + event_x: 20, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + origin: crate::core_loop::message::InputOrigin::XTest(4), + tree_change: false, + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let bytes = read_all_available(&mut picker); + assert!(bytes.len() >= 32, "the grab client gets the press"); + assert_eq!(bytes[0] & 0x7f, 4, "ButtonPress"); + let event = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + let child = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]); + assert_eq!(event, ROOT_WINDOW.0, "reported on the grab window"); + assert_eq!( + child, APP_WIN, + "the root's child under the pointer, not its child's child" + ); +} + +/// The XI2 event types of a stream of GenericEvents. +fn xi2_evtypes(bytes: &[u8]) -> Vec { + let mut evtypes = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + if bytes[off] == 35 { + evtypes.push(u16::from_le_bytes([bytes[off + 8], bytes[off + 9]])); + let length = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize; + off += 32 + length * 4; + } else { + off += 32; + } + } + evtypes +} + +#[test] +fn a_warp_moves_the_pointer_with_no_raw_motion() { + // Xorg: WarpPointer -> miPointerMove -> GetPointerEvents with + // POINTER_NORAW; raw events come only from the device. + let mut state = ServerState::new(); + let mut backend = crate::backend::recording::RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + state + .clients + .get_mut(&1) + .expect("client") + .xi2_masks + .insert((ROOT_WINDOW, 0), (1 << 6) | (1 << 17)); + let dropped = warp_pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + motion_event(), + ); + assert!(dropped.is_empty()); + let evtypes = xi2_evtypes(&read_all_available(&mut peer)); + assert!(evtypes.contains(&6), "the warp's XI_Motion: {evtypes:?}"); + assert!(!evtypes.contains(&17), "no XI_RawMotion: {evtypes:?}"); + + // A motion from the device has its raw event. + let mut device = motion_event(); + device.root_x += 1; + device.event_x += 1; + device.raw_dx = 1; + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + device, + true, + false, + ); + assert!(dropped.is_empty()); + let evtypes = xi2_evtypes(&read_all_available(&mut peer)); + assert!( + evtypes.contains(&17), + "the device's XI_RawMotion: {evtypes:?}" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_disconnect.rs b/crates/yserver-core/src/core_loop/process_disconnect.rs index 51431e731..b4e93dac8 100644 --- a/crates/yserver-core/src/core_loop/process_disconnect.rs +++ b/crates/yserver-core/src/core_loop/process_disconnect.rs @@ -10,61 +10,7 @@ use yserver_protocol::x11::{ClientId, ResourceId}; -use crate::{ - backend::Backend, - core_loop::fanout::{fanout_event_to_clients, subscribers_by_id}, - resources::{MapState, ROOT_WINDOW}, - server::ServerState, -}; - -/// One window's identity captured before the resource table forgets -/// it, so the post-mutation UnmapNotify+DestroyNotify fanout has -/// stable subscriber lists. -struct PendingDestroy { - window: ResourceId, - parent: ResourceId, - was_mapped: bool, - host_xid: Option, - on_window: Vec, - on_parent: Vec, -} - -fn collect_destroy_order( - table: &crate::resources::ResourceTable, - root: ResourceId, - out: &mut Vec, -) { - let Some(w) = table.window(root) else { - return; - }; - for child in w.children.clone() { - collect_destroy_order(table, child, out); - } - out.push(root); -} - -fn fanout_destroy_sequence(state: &mut ServerState, pending: &PendingDestroy) { - let window = pending.window; - let parent = pending.parent; - if pending.was_mapped { - let _dropped = fanout_event_to_clients(state, &pending.on_window, |buf, seq, order| { - yserver_protocol::x11::encode_unmap_notify_event( - buf, seq, order, window, window, false, - ); - }); - let _dropped = fanout_event_to_clients(state, &pending.on_parent, |buf, seq, order| { - yserver_protocol::x11::encode_unmap_notify_event( - buf, seq, order, parent, window, false, - ); - }); - } - let _dropped = fanout_event_to_clients(state, &pending.on_window, |buf, seq, order| { - yserver_protocol::x11::encode_destroy_notify_event(buf, seq, order, window, window); - }); - let _dropped = fanout_event_to_clients(state, &pending.on_parent, |buf, seq, order| { - yserver_protocol::x11::encode_destroy_notify_event(buf, seq, order, parent, window); - }); -} +use crate::{backend::Backend, resources::MapState, server::ServerState}; /// The host-pixmap frees one teardown made: `freed` went back to the backend, /// `deferred` was held because [`ResourceTable::host_xid_still_referenced`] @@ -192,9 +138,18 @@ pub fn process_disconnect_reporting( // (write-side EPIPE from process_request races the reader thread's // EOF → Message::ClientDisconnected). The first call removes the // entry from state.clients; the second sees None and bails. - if !state.clients.contains_key(&client_id.0) { + let Some(client) = state.clients.get_mut(&client_id.0) else { + return; + }; + // Already gone and still here: an earlier teardown of this client hit a + // fatal failure and stopped (`fatal_teardown`); the server is shutting + // down, and nothing may run that teardown again. + if client.gone { return; } + // Xorg `clientGone` (`dix/dispatch.c:3518`): nothing emitted from here on + // reaches the departing client. + client.gone = true; let close_mode = state.close_down_modes.remove(&client_id.0).unwrap_or(0); let retain = close_mode == 1 || close_mode == 2; if state.server_grab_owner == Some(client_id) { @@ -216,18 +171,46 @@ pub fn process_disconnect_reporting( } } - // Audit #9 (docs/protocol-audit-2026-05-19.md) — before the - // disconnecting client's windows are destroyed, fire - // `XFixesSelectionNotify(SelectionClientClose)` to any subscriber - // whose mask includes the ClientClose bit, then clear those - // ownership entries. This must run BEFORE the destroy loop below - // because `fanout_xfixes_selection_client_close_for_client` - // resolves selection owners via `state.resources.window_owner`, - // and the destroy loop is about to evict those windows. + // RECORD: Xorg's ClientStateGone callback runs before any resource is + // freed, and needs the client's base and sequence. + crate::core_loop::record::client_disconnected(state, client_id); + state.notify_policies(|policy, context| policy.connection_gone(context, client_id)); + + // Xorg `DeleteClientFromAnySelections` (`dix/dispatch.c:3495`), before + // any of the client's resources go: the selections this client set + // send SelectionClientClose and are cleared. Selections other clients + // set on its windows go with those windows (SelectionWindowDestroy). crate::core_loop::process_request::fanout_xfixes_selection_client_close_for_client( state, client_id, ); + // Xorg `ReleaseActiveGrabs` (`dix/dispatch.c:3496`) runs before + // `FreeClientResources` (`:3551`): the client's own grabs are gone before + // any of its windows, with the survivors told as for an ungrab. + state.button_grabs.retain(|g| g.owner != client_id); + state.key_grabs.retain(|g| g.owner != client_id); + state.xi1_passive_grabs.retain(|g| g.owner != client_id); + let released_xi1 = + crate::core_loop::process_request::release_active_grabs(state, backend, client_id); + if !released_xi1 && state.xi1_active_grabs.is_empty() { + // No active grabs anywhere, yet freezes linger (e.g. a sync + // passive grab's owner died between activation and release): + // clear them, or device events queue forever and every later + // client waiting on input hangs. + let devs: Vec = state + .xi1_frozen + .iter() + .filter(|(_, f)| f.frozen()) + .map(|(d, _)| *d) + .collect(); + for dev in devs { + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_thaw_device(state, backend, &xid_map, dev); + } + } + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_compute_freezes(state, backend, &xid_map); + let hit_barriers: Vec<(u32, crate::server::PointerBarrier)> = state .pointer_barriers .iter() @@ -258,67 +241,13 @@ pub fn process_disconnect_reporting( ); } - let mut owned_roots: Vec = Vec::new(); - state - .resources - .collect_owned_window_roots(client_id, &mut owned_roots); - - let mut pending: Vec = Vec::new(); - let mut all_destroyed: Vec = Vec::new(); - // Attribute pixmaps of the dying subtrees, snapshotted BEFORE the windows - // go away — the same thing `destroy_window_subtree` does. Without it a - // tile whose only reference was a destroyed window's background or border - // leaks: its pixmap resource may already be gone (FreePixmap retained it - // through the window), so `remove_non_window_resources_owned_by` has - // nothing to hand back and nothing is left to notice (#133). - let mut attr_pixmap_xids: Vec = Vec::new(); - for root in owned_roots { - // XI1 device focus on a window in this dying subtree reverts - // while the tree is still intact (RevertToParent walks the - // surviving ancestors). A leaked focus on a destroyed window - // would silently eat all later DeviceKey events. - crate::core_loop::xi1_focus::revert_focus_for_dying_subtree(state, root); - let mut order: Vec = Vec::new(); - collect_destroy_order(&state.resources, root, &mut order); - for w in &order { - let (parent, was_mapped, host_xid) = - state - .resources - .window(*w) - .map_or((ROOT_WINDOW, false, None), |win| { - ( - win.parent, - win.map_state != MapState::Unmapped, - win.host_xid, - ) - }); - let on_window = subscribers_by_id(state, *w, 0x0002_0000); - let on_parent = subscribers_by_id(state, parent, 0x0008_0000); - pending.push(PendingDestroy { - window: *w, - parent, - was_mapped, - host_xid, - on_window, - on_parent, - }); + let (all_destroyed, attr_pixmap_xids) = match destroy_owned_windows(state, backend, client_id) { + Ok(destroyed) => destroyed, + Err(err) => { + abort_teardown(state, "disconnect", client_id, &err); + return; } - attr_pixmap_xids.extend(state.resources.collect_attribute_pixmap_host_xids(root)); - crate::core_loop::process_request::free_pictures_on_destroyed_windows( - state, backend, None, &order, - ); - crate::core_loop::process_request::release_redirects_on_destroyed_windows( - state, backend, None, &order, - ); - let _ = state.resources.destroy_window(root); - all_destroyed.extend(order); - } - crate::core_loop::process_request::purge_present_for_destroyed_windows( - state, - backend, - &all_destroyed, - ); - state.drop_window_subscriptions(&all_destroyed); + }; let removed = if retain { // Resources keep their original `owner: ClientId`. Tracking @@ -411,37 +340,31 @@ pub fn process_disconnect_reporting( state .damage_objects .retain(|_, damage| damage.owner != client_id && !dead_windows.contains(&damage.drawable)); - // L2 plan B.1b: walk redirects owned by the departing client and - // tear each one down (the helper handles `Window.redirected_backing` - // reset + alias_registry refcount decrement when B.6c lands; for - // now it's a logged no-op so the wiring is in place when the - // backing-allocation tasks land). Then filter by both ownership - // and dead-window so any leftovers caught by the previous rule - // are still removed. - let owned_redirects: Vec<(ResourceId, bool)> = state - .composite_redirects - .iter() - .filter(|(_, rec)| rec.owner == client_id) - .map(|((win, sub), _)| (*win, *sub)) - .collect(); - // Stage 4b: symmetric to the COMPOSITE `UnredirectSubwindows` - // dispatch arm in `process_request.rs` — a subtree entry tears - // down each *child*, not the parent itself (the parent's own - // `redirected_backing` belongs to a separate `(parent, false)` - // entry, if any). - for (window, subwindows) in &owned_redirects { - if *subwindows { - let kids: Vec = state.resources.children(*window).to_vec(); - for child in kids { - teardown_redirect_for_window(state, backend, None, child); - } - } else { - teardown_redirect_for_window(state, backend, None, *window); - } + // The departing client's redirect records go with its resources (Xorg + // frees each CompClientWindowRec / CompSubwindowsRec resource); every + // window that lost one is re-checked, so one left unredirected gets its + // scene participation back (an abnormal compositor exit would otherwise + // leave every Manual window invisible). + let dead: Vec = dead_windows.iter().copied().collect(); + state.composite_redirects.forget_windows(&dead); + let parents = state.composite_redirects.subwindows_parents_of(client_id); + let released = crate::core_loop::process_request::manual_subwindows_release_regions( + state, client_id, &parents, + ); + let changed = state.composite_redirects.forget_client(client_id); + crate::core_loop::process_request::clear_after_manual_subwindows_release( + state, backend, None, &released, + ); + for (window, before) in changed { + crate::core_loop::process_request::sync_redirect_backing( + state, + backend, + None, + window, + before, + crate::core_loop::process_request::BackingDamage::Allocation, + ); } - state - .composite_redirects - .retain(|(window, _), rec| rec.owner != client_id && !dead_windows.contains(window)); state.present_event_selections.retain(|_, selection| { selection.owner != client_id && !dead_windows.contains(&selection.window) }); @@ -490,6 +413,7 @@ pub fn process_disconnect_reporting( .mit_shm_segments .retain(|_, seg| seg.owner != client_id); state.vidmode_client_versions.remove(&client_id); + state.randr_client_versions.remove(&client_id); state.xi2_client_versions.remove(&client_id); state .randr_select_masks @@ -500,6 +424,7 @@ pub fn process_disconnect_reporting( .retain(|(owner, _), _| *owner != client_id.0); state.dpms.selected_by.remove(&client_id); state.screensaver.selected_by.remove(&client_id); + crate::core_loop::process_request::unset_screen_saver_attributes(state, backend, client_id); let was_suspending = state .screensaver .suspend_counts @@ -519,91 +444,7 @@ pub fn process_disconnect_reporting( state.dpms.last_activity = std::time::Instant::now(); crate::core_loop::process_request::reset_idletime_state_after_suspend_release(state); } - state.button_grabs.retain(|g| g.owner != client_id); - state.key_grabs.retain(|g| g.owner != client_id); - let released_pointer_grab = state - .active_pointer_grab - .is_some_and(|grab| grab.owner == client_id); - if released_pointer_grab { - state.clear_pointer_grab(); - if let Some(freeze) = state - .xi1_frozen - .get_mut(&crate::xinput::DEVICEID_SLAVE_POINTER) - { - freeze.stored = None; - freeze.state = crate::server::Xi1SyncState::Thawed; - freeze.other = None; - } - } - // Xorg ReleaseActiveGrabs (CloseDownClient): a disconnecting - // client's ACTIVE grabs must go too, or the stale record makes - // every later GrabPointer/GrabKeyboard return AlreadyGrabbed. - if released_pointer_grab { - // Xorg DeactivatePointerGrab on client teardown reverts the - // sprite from the grab cursor back to the window/default cursor. - let _ = backend.set_grab_cursor(None, None); - } - if state - .active_keyboard_grab - .is_some_and(|g| g.owner == client_id) - { - state.active_keyboard_grab = None; - if let Some(freeze) = state - .xi1_frozen - .get_mut(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - { - freeze.stored = None; - } - } - // XI 1.x grab teardown: drop the client's passive grabs, release - // its active device grabs, and thaw any devices its grabs froze — - // a leaked freeze queues device events forever and hangs every - // later test/client waiting on input. - state.xi1_passive_grabs.retain(|g| g.owner != client_id); - let released: Vec = state - .xi1_active_grabs - .iter() - .filter(|(_, g)| g.owner == client_id) - .map(|(d, _)| *d) - .collect(); - for dev in &released { - // Deactivation resets the device's sync state, releases the - // paired device if it was held on this grab's behalf - // (other_devices_mode), and flushes the queues. - crate::core_loop::pointer_fanout::xi1_deactivate_device_grab(state, *dev); - } - if released.is_empty() && state.xi1_active_grabs.is_empty() { - // No active grabs anywhere, yet freezes linger (e.g. a sync - // passive grab's owner died between activation and release): - // clear them, or device events queue forever and every later - // client waiting on input hangs. - let devs: Vec = state - .xi1_frozen - .iter() - .filter(|(_, f)| f.frozen()) - .map(|(d, _)| *d) - .collect(); - for dev in devs { - let xid_map = backend.xid_map().clone(); - crate::core_loop::pointer_fanout::xi1_thaw_device(state, backend, &xid_map, dev); - } - } - state - .selections - .retain(|_, entry| !dead_windows.contains(&entry.0)); - - // Host-side teardown. Order matches `nested::handle_client`'s tail - // so behavior is bit-identical. - for entry in pending { - if let Some(xid) = entry.host_xid { - let _ = backend.destroy_subwindow(None, xid.as_raw()); - backend.unregister_host_window(xid.as_raw()); - } - fanout_destroy_sequence(state, &entry); - } - // Step 2 (DRIFT 2): destroyed top-levels changed root's child set; - // reproject the backend top-level order from core. - backend.sync_top_level_order(state); + for xid in removed.closed_fonts { let _ = backend.close_font(None, xid); } @@ -635,6 +476,7 @@ pub fn process_disconnect_reporting( for cursor_xid in removed.freed_cursors { let _ = backend.free_cursor(None, cursor_xid); } + crate::core_loop::process_request::release_dropped_cursors(state, backend, None); for syncobj_xid in removed.freed_dri3_syncobjs { if let Err(e) = backend.dri3_free_syncobj(client_id, syncobj_xid) { log::warn!( @@ -657,9 +499,13 @@ pub fn process_disconnect_reporting( // clears the scene's `root_overlay` contribution: a different concept // with a confusingly similar name. crate::core_loop::composite_overlay::release_client_overlay_claims(state, backend, client_id); + backend.sync_floating_keyboard_states(state); // Drop any per-client transient backend state (e.g. the root-overlay // contribution) so a crashed/killed client can't strand it. backend.client_disconnected(client_id); + if !retain { + state.notify_policies(|policy, _context| policy.owner_gone(client_id)); + } } /// L2 plan B.6c — release the redirect's reason-1 hold on a @@ -735,6 +581,8 @@ pub(crate) fn unrealize_redirect_backing( .retain(|alias| alias.host_pixmap != backing.host_pixmap); backing }; + // compSetParentPixmap (`composite/compalloc.c:641-665`). + crate::core_loop::damage_fanout::move_window_damage_to_list_head(state, window); if let Err(err) = backend.release_redirected_backing(origin, backing.host_pixmap) { log::warn!( "release_redirected_backing(0x{:x}) failed: {err}", @@ -744,6 +592,62 @@ pub(crate) fn unrealize_redirect_backing( Some(backing.host_pixmap) } +/// Destroy every window `client` owns, one owned root at a time, each run to +/// completion before the next (Xorg `FreeClientResources` deletes each window +/// resource through `DeleteWindow`, `dix/resource.c:1146-1154`). Returns the +/// destroyed windows, survivors' windows under them included, and their +/// attribute pixmaps for the orphan gate. +/// +/// # Errors +/// A plan holding the COW (the compositor reparented it under one of +/// `client`'s windows) failed to prepare. That root goes first, so nothing +/// was destroyed. +fn destroy_owned_windows( + state: &mut ServerState, + backend: &mut dyn Backend, + client: ClientId, +) -> std::io::Result<(Vec, Vec)> { + let mut owned_roots: Vec = Vec::new(); + state + .resources + .collect_owned_window_roots(client, &mut owned_roots); + // Root order is free (hash order in Xorg too); the only fallible one + // goes first. + owned_roots.sort_by_key(|root| { + !state + .resources + .plan_destroy(*root) + .is_some_and(|plan| plan.contains_cow()) + }); + let mut destroyed = Vec::new(); + let mut attr_pixmaps = Vec::new(); + for root in owned_roots { + // An earlier root's plan already took a root nested under it. + let Some(plan) = state.resources.plan_destroy(root) else { + continue; + }; + let prepared = plan.prepare(backend).map_err(|err| { + std::io::Error::other(format!( + "cannot destroy window 0x{:x}, which holds the composite overlay: {err}", + root.0 + )) + })?; + let outcome = + crate::core_loop::process_request::execute_destroy(state, backend, None, prepared); + destroyed.extend(outcome.windows); + attr_pixmaps.extend(outcome.attr_pixmaps); + } + Ok((destroyed, attr_pixmaps)) +} + +/// A client teardown that cannot complete: leave its record, resources and +/// resource-ID range in place and have the core loop shut the server down. +fn abort_teardown(state: &mut ServerState, what: &str, client: ClientId, err: &std::io::Error) { + let cause = format!("{what} of client {}: {err}", client.0); + log::error!("{cause}; teardown stopped, shutting the server down"); + state.fatal_teardown.get_or_insert(cause); +} + /// Destroy every resource owned by a zombie client — invoked by /// `KillClient(AllTemporary)` (for each RetainTemporary zombie) and by /// `KillClient(resource_owned_by_a_zombie)`. Mirrors the resource- @@ -751,97 +655,40 @@ pub(crate) fn unrealize_redirect_backing( /// (there is no `state.clients` entry, no reader thread, no /// connection-tied extension state — those were torn down at the /// original disconnect). The caller must remove `zombie` from -/// `state.zombie_clients` after this returns. +/// `state.zombie_clients` after this returns `Ok`. +/// +/// # Errors +/// The zombie's windows could not be destroyed; nothing of it was freed and +/// `state.fatal_teardown` is set. The zombie must stay recorded. pub fn destroy_zombie_resources( state: &mut ServerState, backend: &mut dyn Backend, zombie: ClientId, -) { - destroy_zombie_resources_reporting(state, backend, zombie, None); +) -> std::io::Result<()> { + destroy_zombie_resources_reporting(state, backend, zombie, None) } /// [`destroy_zombie_resources`], reporting its host-pixmap frees the same way /// [`process_disconnect_reporting`] does. +/// +/// # Errors +/// As [`destroy_zombie_resources`]. pub fn destroy_zombie_resources_reporting( state: &mut ServerState, backend: &mut dyn Backend, zombie: ClientId, host_pixmap_frees: Option<&mut HostPixmapFrees>, -) { - let mut owned_roots: Vec = Vec::new(); - state - .resources - .collect_owned_window_roots(zombie, &mut owned_roots); - - let mut pending: Vec = Vec::new(); - let mut all_destroyed: Vec = Vec::new(); - // Attribute pixmaps of the dying subtrees, snapshotted BEFORE the windows - // go away — the same thing `destroy_window_subtree` does. Without it a - // tile whose only reference was a destroyed window's background or border - // leaks: its pixmap resource may already be gone (FreePixmap retained it - // through the window), so `remove_non_window_resources_owned_by` has - // nothing to hand back and nothing is left to notice (#133). - let mut attr_pixmap_xids: Vec = Vec::new(); - for root in owned_roots { - // XI1 device focus on a window in this dying subtree reverts - // while the tree is still intact (RevertToParent walks the - // surviving ancestors). A leaked focus on a destroyed window - // would silently eat all later DeviceKey events. - crate::core_loop::xi1_focus::revert_focus_for_dying_subtree(state, root); - let mut order: Vec = Vec::new(); - collect_destroy_order(&state.resources, root, &mut order); - for w in &order { - let (parent, was_mapped, host_xid) = - state - .resources - .window(*w) - .map_or((ROOT_WINDOW, false, None), |win| { - ( - win.parent, - win.map_state != MapState::Unmapped, - win.host_xid, - ) - }); - let on_window = subscribers_by_id(state, *w, 0x0002_0000); - let on_parent = subscribers_by_id(state, parent, 0x0008_0000); - pending.push(PendingDestroy { - window: *w, - parent, - was_mapped, - host_xid, - on_window, - on_parent, - }); +) -> std::io::Result<()> { + let (_destroyed, attr_pixmap_xids) = match destroy_owned_windows(state, backend, zombie) { + Ok(destroyed) => destroyed, + Err(err) => { + abort_teardown(state, "zombie cleanup", zombie, &err); + return Err(err); } - attr_pixmap_xids.extend(state.resources.collect_attribute_pixmap_host_xids(root)); - crate::core_loop::process_request::free_pictures_on_destroyed_windows( - state, backend, None, &order, - ); - crate::core_loop::process_request::release_redirects_on_destroyed_windows( - state, backend, None, &order, - ); - let _ = state.resources.destroy_window(root); - all_destroyed.extend(order); - } - crate::core_loop::process_request::purge_present_for_destroyed_windows( - state, - backend, - &all_destroyed, - ); - state.drop_window_subscriptions(&all_destroyed); + }; let removed = state.resources.remove_non_window_resources_owned_by(zombie); - for entry in pending { - if let Some(xid) = entry.host_xid { - let _ = backend.destroy_subwindow(None, xid.as_raw()); - backend.unregister_host_window(xid.as_raw()); - } - fanout_destroy_sequence(state, &entry); - } - // Step 2 (DRIFT 2): destroyed top-levels changed root's child set; - // reproject the backend top-level order from core. - backend.sync_top_level_order(state); for xid in removed.closed_fonts { let _ = backend.close_font(None, xid); } @@ -873,6 +720,7 @@ pub fn destroy_zombie_resources_reporting( for cursor_xid in removed.freed_cursors { let _ = backend.free_cursor(None, cursor_xid); } + crate::core_loop::process_request::release_dropped_cursors(state, backend, None); for syncobj_xid in removed.freed_dri3_syncobjs { if let Err(e) = backend.dri3_free_syncobj(zombie, syncobj_xid) { log::warn!( @@ -881,6 +729,8 @@ pub fn destroy_zombie_resources_reporting( ); } } + state.notify_policies(|policy, _context| policy.owner_gone(zombie)); + Ok(()) } #[cfg(test)] @@ -896,7 +746,7 @@ mod tests { ClientByteOrder, ClientId, CreatePixmapRequest, CreateWindowRequest, ResourceId, }; - use super::{destroy_zombie_resources, process_disconnect}; + use super::{destroy_zombie_resources, destroy_zombie_resources_reporting, process_disconnect}; use crate::{ backend::recording::{RecordedCall, RecordingBackend}, resources::ROOT_WINDOW, @@ -908,6 +758,7 @@ mod tests { state.clients.insert( id, ClientState { + admission: crate::access::Admission::Internal, writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -920,11 +771,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), }, ); } @@ -933,6 +789,7 @@ mod tests { state.clients.insert( id, ClientState { + admission: crate::access::Admission::Internal, writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(writer))), byte_order: ClientByteOrder::LittleEndian, last_sequence: Arc::new(AtomicU16::new(0)), @@ -945,11 +802,16 @@ mod tests { xi1_event_classes: HashSet::new(), xi1_window_event_classes: HashMap::new(), outbound: VecDeque::new(), + outbound_fds: Default::default(), watching_writable: false, + write_failed: false, + gone: false, focused_window: ROOT_WINDOW, reader_control: None, is_local: true, fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), }, ); } @@ -960,19 +822,23 @@ mod tests { install_client(&mut state, 1); install_client(&mut state, 2); // Client A redirects window W. - state.composite_redirects.insert( - (ResourceId(0x1234), false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); + state + .composite_redirects + .redirect_window( + ResourceId(0x1234), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); let mut backend = RecordingBackend::new(); process_disconnect(&mut state, &mut backend, ClientId(2)); assert!( state .composite_redirects - .contains_key(&(ResourceId(0x1234), false)) + .window_mode(ResourceId(0x1234)) + .is_some() ); } @@ -994,13 +860,16 @@ mod tests { fn disconnect_tears_down_owned_redirect() { let mut state = ServerState::new(); install_client(&mut state, 1); - state.composite_redirects.insert( - (ResourceId(0x5678), false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); + state + .composite_redirects + .redirect_window( + ResourceId(0x5678), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); let mut backend = RecordingBackend::new(); process_disconnect(&mut state, &mut backend, ClientId(1)); assert!(state.composite_redirects.is_empty()); @@ -1072,6 +941,7 @@ mod tests { PendingPresentEntry { pending, source_ready: false, + superseded_by_executed_present_id: None, wait_id: Some(WAIT_ID), pin: Some(PIN_ID), }, @@ -1398,6 +1268,152 @@ mod tests { } } + /// `HostPixmapFrees` for a tile that only a destroyed window's border + /// still held: freed when nothing else names it, deferred while another + /// client's border does. + #[test] + fn disconnect_reports_a_border_only_tile_freed_or_deferred() { + for shared in [false, true] { + const HOST_TILE: u32 = 0x9999_0061; + let host = crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"); + let tile = ResourceId(0x0070_0061); + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + install_client(&mut state, 7); + install_client(&mut state, 8); + state.resources.create_pixmap( + ClientId(7), + CreatePixmapRequest { + pixmap: tile, + drawable: ROOT_WINDOW, + width: 16, + height: 16, + depth: 24, + }, + ); + assert!(state.resources.set_pixmap_host_xid(tile, host)); + let windows: &[(u32, u32)] = if shared { + &[(7, 0x0070_0062), (8, 0x0080_0062)] + } else { + &[(7, 0x0070_0062)] + }; + for &(owner, window) in windows { + state.resources.create_window( + ClientId(owner), + CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent: ROOT_WINDOW, + width: 100, + height: 100, + border_width: 4, + class: 1, + visual: crate::resources::ROOT_VISUAL, + border_pixmap: Some(tile), + ..Default::default() + }, + ); + } + assert!(state.resources.free_pixmap(tile).is_some()); + + let mut frees = super::HostPixmapFrees::default(); + super::process_disconnect_reporting( + &mut state, + &mut backend, + ClientId(7), + Some(&mut frees), + ); + + let (freed, deferred) = if shared { + (vec![], vec![HOST_TILE]) + } else { + (vec![HOST_TILE], vec![]) + }; + assert_eq!(frees.freed, freed, "shared={shared}"); + assert_eq!(frees.deferred, deferred, "shared={shared}"); + } + } + + /// #196: a pixmap the client freed while its GC still held it (as tile, + /// stipple or clip mask) dies with the GC at disconnect — Xorg's `FreeGC` + /// drops those refs (`dix/gc.c:776-781`). The pixmap resource was already + /// gone, so `freed_pixmaps` never named it and it leaked for the session. + #[test] + fn disconnect_releases_pixmaps_its_gc_held_past_free_pixmap() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + install_client(&mut state, 7); + let mut hosts = Vec::new(); + for (i, depth) in [24u8, 1, 1].into_iter().enumerate() { + let pixmap = ResourceId(0x0070_0051 + i as u32); + let host = 0x9999_0051 + i as u32; + state.resources.create_pixmap( + ClientId(7), + CreatePixmapRequest { + pixmap, + drawable: ROOT_WINDOW, + width: 16, + height: 16, + depth, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + pixmap, + crate::backend::PixmapHandle::from_raw(host).expect("non-zero") + )); + hosts.push(host); + } + state.resources.create_gc( + ClientId(7), + yserver_protocol::x11::CreateGcRequest { + gc: ResourceId(0x0070_0050), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: Some(ResourceId(0x0070_0051)), + stipple: Some(ResourceId(0x0070_0052)), + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: Some(Some(ResourceId(0x0070_0053))), + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + for i in 0..3 { + assert!( + state + .resources + .free_pixmap(ResourceId(0x0070_0051 + i)) + .is_some() + ); + } + process_disconnect(&mut state, &mut backend, ClientId(7)); + let mut freed: Vec = backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::FreePixmap(xid) => Some(*xid), + _ => None, + }) + .collect(); + freed.sort_unstable(); + assert_eq!(freed, hosts, "each released exactly once"); + } + /// The zombie variant: a RetainPermanent client's pixmap survives its /// disconnect, and `KillClient` later runs `destroy_zombie_resources`. /// That release path must apply the same gate — another client's window @@ -1449,7 +1465,7 @@ mod tests { ); let mut backend = RecordingBackend::new(); - destroy_zombie_resources(&mut state, &mut backend, ClientId(7)); + destroy_zombie_resources(&mut state, &mut backend, ClientId(7)).expect("zombie cleanup"); assert!( !backend .calls() @@ -1506,11 +1522,68 @@ mod tests { assert!(backend.dri3_syncobj_owners.contains_key(&XID)); assert_eq!(state.zombie_clients.get(&7), Some(&1)); - destroy_zombie_resources(&mut state, &mut backend, ClientId(7)); + destroy_zombie_resources(&mut state, &mut backend, ClientId(7)).expect("zombie cleanup"); assert!(!state.resources.xid_in_use(ResourceId(XID))); assert!(!backend.dri3_syncobj_owners.contains_key(&XID)); } + // Mutation: omit owner_gone from the successful zombie-destruction path; the second event assertion fails. + #[test] + fn zombie_owner_notification_follows_successful_resource_destruction() { + use crate::access::{AccessContext, AccessPolicy}; + + struct Recorder(Arc>>); + impl AccessPolicy for Recorder { + fn connection_gone(&self, _ctx: &AccessContext<'_>, client: ClientId) { + self.0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(("connection_gone", client)); + } + + fn owner_gone(&self, client: ClientId) { + self.0 + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(("owner_gone", client)); + } + } + + let id = ClientId(7); + let pixmap = ResourceId(0x0070_0051); + let events = Arc::new(Mutex::new(Vec::new())); + let mut state = ServerState::new(); + state.install_access_policy(Arc::new(Recorder(events.clone()))); + install_client(&mut state, id.0); + state.close_down_modes.insert(id.0, 1); + state.resources.create_pixmap( + id, + CreatePixmapRequest { + pixmap, + drawable: ROOT_WINDOW, + width: 16, + height: 16, + depth: 24, + }, + ); + let mut backend = RecordingBackend::new(); + + process_disconnect(&mut state, &mut backend, id); + + assert_eq!(*events.lock().unwrap(), vec![("connection_gone", id)]); + assert_eq!(state.zombie_clients.get(&id.0), Some(&1)); + destroy_zombie_resources_reporting(&mut state, &mut backend, id, None) + .expect("zombie resources are destroyed"); + assert_eq!( + *events.lock().unwrap(), + vec![("connection_gone", id), ("owner_gone", id)], + ); + state.zombie_clients.remove(&id.0); + assert!(!state.clients.contains_key(&id.0)); + assert!(!state.zombie_clients.contains_key(&id.0)); + assert!(!state.resources.xid_in_use(pixmap)); + } + #[test] fn temporary_dri3_syncobj_survives_until_all_temporary_cleanup() { const XID: u32 = 0x0070_0093; @@ -1531,7 +1604,7 @@ mod tests { // This is the operation KillClient(AllTemporary) performs for each // mode-2 zombie. - destroy_zombie_resources(&mut state, &mut backend, ClientId(7)); + destroy_zombie_resources(&mut state, &mut backend, ClientId(7)).expect("zombie cleanup"); assert!(!state.resources.xid_in_use(ResourceId(XID))); assert!(!backend.dri3_syncobj_owners.contains_key(&XID)); } @@ -1567,7 +1640,7 @@ mod tests { state.zombie_clients.insert(32, 1); state.zombie_clients.insert(33, 1); - destroy_zombie_resources(&mut state, &mut backend, ClientId(32)); + destroy_zombie_resources(&mut state, &mut backend, ClientId(32)).expect("zombie cleanup"); assert!( state @@ -1721,13 +1794,17 @@ mod tests { }); } // The compositor owns `RedirectSubwindows(root, Manual)`. - state.composite_redirects.insert( - (ROOT_WINDOW, true), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(compositor), - }, - ); + state + .composite_redirects + .redirect_subwindows( + ROOT_WINDOW, + state.resources.children(ROOT_WINDOW), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(compositor), + }, + ) + .unwrap(); let mut backend = RecordingBackend::new(); process_disconnect(&mut state, &mut backend, ClientId(compositor)); @@ -1802,8 +1879,8 @@ mod tests { }; state .composite_redirects - .insert((ROOT_WINDOW, true), record); - state.composite_redirects.insert((window_id, false), record); + .redirect_subwindows(ROOT_WINDOW, &[window_id], record) + .unwrap(); let mut backend = RecordingBackend::new(); process_disconnect(&mut state, &mut backend, ClientId(app)); @@ -1815,9 +1892,12 @@ mod tests { .count(); assert_eq!(releases, 1, "calls={:#?}", backend.calls()); assert!(state.resources.window(window_id).is_none()); - assert!(!state.composite_redirects.contains_key(&(window_id, false))); + assert!(state.composite_redirects.window_mode(window_id).is_none()); assert!( - state.composite_redirects.contains_key(&(ROOT_WINDOW, true)), + state + .composite_redirects + .subwindows_mode(ROOT_WINDOW) + .is_some(), "the compositor's root redirect outlives the app" ); } @@ -1848,4 +1928,169 @@ mod tests { process_disconnect(&mut state, &mut backend, ClientId(1)); assert!(state.pointer_barriers.is_empty()); } + + /// Drive one core or extension request from `client`. + fn request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + opcode: u8, + data: u8, + body: &[u8], + ) { + crate::core_loop::process_request::process_request( + state, + backend, + ClientId(client), + yserver_protocol::x11::SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len().div_ceil(4)).expect("length"), + }, + body, + None, + ) + .expect("process_request"); + } + + /// Compositor client 2 takes the overlay and reparents it under `w` + /// (ReparentWindow, opcode 7); then the overlay release starts failing. + fn cow_under(state: &mut ServerState, backend: &mut RecordingBackend, w: u32) { + use crate::resources::COMPOSITE_OVERLAY_WINDOW; + request( + state, + backend, + 2, + 144, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &ROOT_WINDOW.0.to_le_bytes(), + ); + let mut body = COMPOSITE_OVERLAY_WINDOW.0.to_le_bytes().to_vec(); + body.extend_from_slice(&w.to_le_bytes()); + body.extend_from_slice(&[0; 4]); + request(state, backend, 2, 7, 0, &body); + assert_eq!( + state + .resources + .window(COMPOSITE_OVERLAY_WINDOW) + .map(|cow| cow.parent), + Some(ResourceId(w)), + "precondition: the COW is under the client's window" + ); + backend.cow_teardown_fails = true; + } + + fn create_window_owned_by(state: &mut ServerState, owner: u32, w: u32, pixmap: u32) { + state.resources.create_window( + ClientId(owner), + CreateWindowRequest { + depth: 24, + window: ResourceId(w), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(w)); + state.resources.create_pixmap( + ClientId(owner), + CreatePixmapRequest { + pixmap: ResourceId(pixmap), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + depth: 24, + }, + ); + } + + fn assert_teardown_stopped_intact(state: &ServerState, owner: u32, w: u32, pixmap: u32) { + use crate::resources::COMPOSITE_OVERLAY_WINDOW; + assert_eq!( + state.resources.window(ResourceId(w)).map(|w| w.owner), + Some(ClientId(owner)), + "the client's window survives, still its own" + ); + assert_eq!( + state + .resources + .window(COMPOSITE_OVERLAY_WINDOW) + .map(|cow| cow.parent), + Some(ResourceId(w)), + "the COW survives where it was" + ); + assert_eq!( + state.resources.resource_owner(ResourceId(pixmap)), + Some(ClientId(owner)), + "the client's other resources were not freed" + ); + assert!( + state.fatal_teardown.is_some(), + "the shutdown request is raised" + ); + } + + /// A disconnect whose window holds the COW, with the overlay release + /// failing: the teardown stops before anything of the client is freed, + /// its record and resource-ID range stay, and the server is asked to + /// shut down (the terminal policy in + /// `docs/superpowers/plans/2026-10-27-window-destroy-plan.md`). + #[test] + fn disconnect_whose_window_holds_a_cow_that_cannot_be_released_stops_and_terminates() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let (base, mask) = state.id_allocator.allocate().expect("a base"); + install_client(&mut state, 1); + let client = state.clients.get_mut(&1).expect("client 1"); + client.resource_id_base = base; + client.resource_id_mask = mask; + install_client(&mut state, 2); + let (w, pixmap) = (base | 1, base | 2); + create_window_owned_by(&mut state, 1, w, pixmap); + cow_under(&mut state, &mut backend, w); + + process_disconnect(&mut state, &mut backend, ClientId(1)); + + assert_teardown_stopped_intact(&state, 1, w, pixmap); + assert!(state.clients.contains_key(&1), "the client record stays"); + assert_ne!( + state.id_allocator.allocate().map(|(b, _)| b), + Some(base), + "the client's resource-ID range is not handed out again" + ); + + // A second disconnect of the same client (the reader's EOF racing + // the first) does not run the teardown again. + backend.calls.lock().expect("calls").clear(); + process_disconnect(&mut state, &mut backend, ClientId(1)); + let calls = backend.calls.lock().expect("calls"); + assert!(calls.is_empty(), "nothing ran: {calls:?}"); + } + + /// The same failure on a zombie's window, through KillClient (opcode + /// 113) of a resource the zombie owns: nothing is freed and the zombie + /// stays recorded. + #[test] + fn zombie_cleanup_whose_window_holds_a_cow_that_cannot_be_released_stops_and_terminates() { + const ZOMBIE: u32 = 7; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + install_client(&mut state, 2); + let (w, pixmap) = (0x0070_0001, 0x0070_0002); + create_window_owned_by(&mut state, ZOMBIE, w, pixmap); + state.zombie_clients.insert(ZOMBIE, 1); + cow_under(&mut state, &mut backend, w); + + request(&mut state, &mut backend, 2, 113, 0, &pixmap.to_le_bytes()); + + assert_teardown_stopped_intact(&state, ZOMBIE, w, pixmap); + assert!( + state.zombie_clients.contains_key(&ZOMBIE), + "the zombie stays recorded" + ); + } } diff --git a/crates/yserver-core/src/core_loop/process_request.rs b/crates/yserver-core/src/core_loop/process_request.rs index f368196a6..d8ccf3c34 100644 --- a/crates/yserver-core/src/core_loop/process_request.rs +++ b/crates/yserver-core/src/core_loop/process_request.rs @@ -1,67 +1,150 @@ -//! Single-threaded entry point for X11 request dispatch. +//! Single-threaded X11 request dispatch: `process_request` matches the +//! opcode and hands the request to a handler. State mutations go through +//! `&mut ServerState`, backend calls through `&mut dyn Backend`, reply and +//! event bytes through `client_io::write_or_buffer`. This file keeps the +//! dispatch `match` and the shared validation/error helpers; handlers live +//! in: //! -//! `process_request` is the new home of the opcode `match` that today -//! still lives in `nested::handle_request`. Its signature is the one -//! D4 wires to `Message::Request` arms in `run_core` — every state -//! mutation goes through `&mut ServerState`, every backend call goes -//! through `&mut dyn Backend`, and every reply/event byte is pushed -//! out via `client_io::write_or_buffer` (no more -//! `Arc>` snapshots). +//! Core protocol +//! - `windows`: window create/destroy/reparent, exposures. +//! - `drawing`: PutImage/GetImage, image text, XY↔Z conversion. +//! - `gc_pixmap_cursor`: GC, pixmap and cursor resources. +//! - `colormaps`, `fonts`, `props` (properties and atoms), `selection` +//! (selections, SendEvent). +//! - `focus_pointer`: input focus, QueryPointer, WarpPointer. +//! - `grabs`: core grabs and AllowEvents. +//! - `input_ctl`: keyboard/pointer control and mappings, Bell. +//! - `misc`: QueryExtension, server grabs, hosts, KillClient, BIG-REQUESTS, +//! Generic Event, X-Resource. //! -//! ## Migration status +//! Extensions +//! - `render`, `shape_xfixes`, `composite_damage`, `redirect` (Composite +//! backing storage), `present_ext`, `dri3`, `xshm`, `glx`, `sync_ext`. +//! - `xi` (XInput), `xkb`, `xtest`. +//! - `randr_ext` (RANDR, Xinerama), `vidmode`, `saver_dpms` +//! (MIT-SCREEN-SAVER, DPMS, IDLETIME counter). //! -//! D2 finished the additive part of the lift: every fanout helper -//! has a state-borrowing twin. D3 then moved every opcode dispatch -//! arm off `Arc>` and onto `&mut`-borrowed types. Every -//! arm `nested::handle_request` had — including all 11 extension -//! dispatchers (RANDR / MIT-SHM / RENDER / XKB / XI2 / XFIXES / -//! SHAPE / SYNC / DAMAGE / COMPOSITE / PRESENT) — has a -//! state-borrowing implementation here. The `nested::handle_request` -//! path is dead-code from D4 forward and gets retired in H1. - -use std::{ - collections::{HashMap, HashSet}, - io, - os::fd::OwnedFd, +//! Tests: `tests/*` per area, `get_image_reply_tests`, +//! `largest_free_xid_gap_tests`. + +mod colormaps; +mod composite_damage; +mod drawing; +mod dri3; +mod focus_pointer; +mod fonts; +mod gc_pixmap_cursor; +mod glx; +mod grabs; +mod input_ctl; +mod misc; +mod present_ext; +mod props; +mod randr_ext; +mod redirect; +mod render; +mod saver_dpms; +mod selection; +mod shape_xfixes; +mod sync_ext; +mod vidmode; +mod window_destroy; +pub(crate) use window_destroy::{destroy_window_subtree, execute_destroy}; +mod windows; +mod xi; +mod xkb; +#[cfg(unix)] +mod xshm; +mod xtest; + +#[cfg(unix)] +use crate::core_loop::process_request::xshm::handle_mit_shm_request; +use crate::core_loop::process_request::{ + colormaps::{ + handle_alloc_color, handle_alloc_color_cells, handle_alloc_color_planes, + handle_alloc_named_color, handle_copy_colormap_and_free, handle_create_colormap, + handle_free_colormap, handle_free_colors, handle_install_colormap, + handle_list_installed_colormaps, handle_lookup_color, handle_query_colors, + handle_store_colors, handle_store_named_color, handle_uninstall_colormap, + }, + composite_damage::{handle_composite_request, handle_damage_request}, + drawing::{ + handle_clear_area, handle_copy_area, handle_copy_plane, handle_fill_poly, handle_get_image, + handle_image_text8, handle_image_text16, handle_poly_arc, handle_poly_fill_arc, + handle_poly_fill_rectangle, handle_poly_line, handle_poly_point, handle_poly_rectangle, + handle_poly_segment, handle_poly_text8, handle_poly_text16, handle_put_image, + zpixmap_row_stride, + }, + dri3::handle_dri3_request, + fonts::{ + handle_close_font, handle_get_font_path, handle_list_fonts, handle_list_fonts_with_info, + handle_open_font, handle_query_font, handle_query_text_extents, handle_set_font_path, + }, + gc_pixmap_cursor::{ + handle_change_gc, handle_copy_gc, handle_create_cursor, handle_create_gc, + handle_create_glyph_cursor, handle_create_pixmap, handle_free_cursor, handle_free_gc, + handle_free_pixmap, handle_query_best_size, handle_recolor_cursor, + handle_set_clip_rectangles, handle_set_dashes, + }, + glx::handle_glx_request, + input_ctl::{ + handle_bell, handle_change_keyboard_control, handle_change_keyboard_mapping, + handle_change_pointer_control, handle_get_keyboard_control, handle_get_keyboard_mapping, + handle_get_modifier_mapping, handle_get_pointer_control, handle_get_pointer_mapping, + handle_query_keymap, handle_set_modifier_mapping, handle_set_pointer_mapping, + }, + misc::{ + handle_big_requests_request, handle_change_hosts, handle_ge_request, + handle_get_motion_events, handle_grab_server, handle_kill_client, handle_list_extensions, + handle_list_hosts, handle_query_extension, handle_set_access_control, + handle_set_close_down_mode, handle_ungrab_server, handle_x_resource_request, + handle_xcmisc_request, + }, + render::handle_render_request, + vidmode::handle_xf86vidmode_request, + xkb::handle_xkb_request, + xtest::handle_xtest_request, }; +pub(crate) use dri3::complete_dri3_export; +pub use dri3::{Dri3ExportOp, PendingDri3Export}; +pub(crate) use focus_pointer::*; +pub use fonts::install_default_font; +pub(crate) use grabs::*; +pub use present_ext::*; +pub(crate) use props::*; +pub use randr_ext::*; +pub(crate) use redirect::*; +pub(crate) use saver_dpms::*; +pub(crate) use selection::*; +pub(crate) use shape_xfixes::*; +pub(crate) use sync_ext::*; +pub(crate) use vidmode::reinstall_vidmode_gamma; +pub(crate) use windows::*; +pub(crate) use xi::*; + +#[cfg(test)] +mod get_image_reply_tests; +#[cfg(test)] +mod largest_free_xid_gap_tests; +#[cfg(test)] +mod tests; + +use std::io; -use log::{debug, trace}; -use yserver_protocol::x11::{self, AtomId, ClientId, RequestHeader, ResourceId, SequenceNumber}; +use log::debug; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; #[cfg(test)] use crate::core_loop::pointer_fanout::pointer_event_fanout_to_state; use crate::{ - backend::{ - Backend, CrtcConfigApply, CrtcConfigToken, ModeSpec, OriginContext, params::FillState, - }, - core_loop::{ - client_io::{self, WriteOutcome}, - damage_fanout::{ - accumulate_damage_border_to_state, accumulate_damage_clip_by_children_to_state, - accumulate_damage_full_to_state, accumulate_damage_to_state, - report_existing_damage_to_state, - }, - fanout::{ - client_target_id, emit_expose_subtree_to_state, - emit_visibility_unobscured_subtree_to_state, emit_window_event_to_state, - emit_xi2_focus_event_to_state, fanout_event_to_clients, fanout_raw_event_to_clients, - selection_owner_target_id, subscribers_by_id, - }, - key_fanout::replay_frozen_key_to_focus, - pointer_fanout::replay_frozen_pointer_event_to_state, - }, - properties, - resources::{ - BorderSource, COMPOSITE_OVERLAY_WINDOW, MapState, Pixmap, ROOT_WINDOW, ViewabilityDelta, - Window, - }, - server::{ - PendingPresentPixmap, PendingPresentRequest, ScreenSaverActive, ServerState, XI_FIRST_EVENT, - }, - xinput::{ - XI_DEVICE_KEY_PRESS_OFFSET, XI_DEVICE_PROPERTY_NOTIFY_OFFSET, XI2_DEVICE_CHANGED_MASK, - XI2_PROPERTY_EVENT_MASK, - }, + access::{AccessMode, Decision, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext}, + core_loop::{client_io, client_io::WriteOutcome}, + fd::OwnedFd, + server::ServerState, }; /// XI2 major opcode assigned by `extension_metadata("XInputExtension")`. @@ -103,6 +186,8 @@ const XKB_LAST_REQUEST: u8 = 25; /// XKB request minors (`X_kb*`). const X_KB_USE_EXTENSION: u8 = 0; const X_KB_SELECT_EVENTS: u8 = 1; +const X_KB_GET_CONTROLS: u8 = 6; +const X_KB_SET_CONTROLS: u8 = 7; const X_KB_SET_MAP: u8 = 9; const X_KB_SET_COMPAT_MAP: u8 = 11; const X_KB_SET_INDICATOR_MAP: u8 = 14; @@ -124,25 +209,12 @@ pub enum RequestOutcome { /// request's flow-control credit and park later requests from the same /// client until the token becomes ready. PendingCrtcConfig(PendingCrtcConfig), -} - -/// Continuation data needed to finish an asynchronous `RRSetCrtcConfig` -/// without redispatching the original request. -#[derive(Debug, Clone, Copy)] -pub struct PendingCrtcConfig { - pub token: CrtcConfigToken, - pub completion: CrtcConfigCompletion, -} - -/// Protocol continuation shared by synchronous and asynchronous CRTC apply -/// paths. It contains no backend token, so immediate completion never needs a -/// sentinel token value. -#[derive(Debug, Clone, Copy)] -pub struct CrtcConfigCompletion { - pub output_id: u32, - pub set_time: u32, - pub output_bbox_before: Option<(u16, u16)>, - pub byte_order: yserver_protocol::x11::ClientByteOrder, + /// A DRI3 export waits until its pixmap leaves every CRTC. Parked like + /// [`Self::PendingCrtcConfig`]. + PendingDri3Export(PendingDri3Export), + /// A recognized physical libinput property write. The core runner owns + /// validation, source-targeted application, and commit ordering. + PendingXiConfig(crate::core_loop::message::XiConfigRequest), } /// Dispatch one X11 request entirely on the core thread. @@ -169,6 +241,7 @@ pub fn process_request( nested_seq: sequence.0, opcode: header.opcode, }); + let access_request = RequestOpcodes::for_request(header); // Stamp the per-client sequence counter so any event fanouts // generated by this request encode the correct `seq` field. // Pre-F2 the legacy `nested::handle_client` did this after each @@ -204,6 +277,10 @@ pub fn process_request( u32::from(u16::MAX) }; if header.length_units > max_length_units { + // The reader parks on every Enable until the core answers it. + if header.opcode == 135 && header.data == 0 { + misc::release_big_requests_reader(state, client_id); + } return emit_x11_error( state, client_id, @@ -213,6 +290,32 @@ pub fn process_request( header.opcode, ); } + if header.opcode >= 128 + && state.policies_installed() + && let Some(extension) = misc::extension_by_opcode(header.opcode) + && let Decision::Deny(_) = state.check_extension_dispatch( + client_id, + extension.name, + Some(RequestOpcodes::for_request(header)), + ) + { + debug!( + "client {} #{} {} request (major {} minor {}) denied by access policy -> BadRequest", + client_id.0, sequence.0, extension.name, header.opcode, header.data + ); + if extension.name == "BIG-REQUESTS" && header.data == 0 { + misc::release_big_requests_reader(state, client_id); + } + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(header.data), + header.opcode, + ); + } // Phase F: variable-length opcodes need content-derived exact-length // validation (the spec's `length one less/greater than the minimum // required to contain the request` xts probes). @@ -270,13 +373,28 @@ pub fn process_request( header.opcode, ); } - match header.opcode { + let outcome = match header.opcode { // ── server scheduling grab ── 36 => handle_grab_server(state, client_id, sequence), 37 => handle_ungrab_server(state, client_id, sequence), // ── void requests with local state/backend handling ── - 96 => handle_recolor_cursor(state, backend, origin, client_id, sequence, body), - 102 => handle_change_keyboard_control(state, client_id, sequence, header, body), + 96 => handle_recolor_cursor( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 102 => { + // Xorg's XkbSetRepeatKeys: the RepeatKeys control follows the + // global auto-repeat, with a ControlsNotify for what changed. + let old = crate::core_loop::xkb_controls::RepeatControls::of(state); + let outcome = handle_change_keyboard_control(state, client_id, sequence, header, body); + crate::core_loop::xkb_controls::send_controls_notify(state, &*backend, old, (0, 0)); + outcome + } 104 => handle_bell(state, client_id, sequence, header), 105 => handle_change_pointer_control(state, client_id, sequence, header, body), 107 => handle_set_screen_saver(state, client_id, sequence, header, body), @@ -289,111 +407,259 @@ pub fn process_request( 106 => handle_get_pointer_control(state, client_id, sequence), 108 => handle_get_screen_saver(state, client_id, sequence), 110 => handle_list_hosts(state, client_id, sequence), + // ── host access control (`xhost`) ── + 109 => handle_change_hosts(state, client_id, sequence, header, body), + 111 => handle_set_access_control(state, client_id, sequence, header), 117 => handle_get_pointer_mapping(state, client_id, sequence), // ── replies backed by small or backend-owned state ── - 39 => handle_get_motion_events(state, client_id, sequence, body), + 39 => handle_get_motion_events(state, client_id, sequence, access_request, body), 51 => handle_set_font_path(state, backend, origin, client_id, sequence, header, body), 52 => handle_get_font_path(state, backend, client_id, sequence), - 83 => handle_list_installed_colormaps(state, client_id, sequence, body), + 83 => handle_list_installed_colormaps(state, client_id, sequence, access_request, body), // ── GC dashes (multi-byte pattern; opcode 58 is its own request, // distinct from the single-byte CreateGC/ChangeGC dash form). ── - 58 => handle_set_dashes(state, client_id, sequence, body), + 58 => handle_set_dashes(state, client_id, sequence, access_request, body), // ── colormap lifecycle (BadIDChoice on duplicate ID) ── - 78 => handle_create_colormap(state, client_id, sequence, body), - 79 => handle_free_colormap(state, client_id, sequence, body), - 80 => handle_copy_colormap_and_free(state, client_id, sequence, body), - 81 => handle_install_colormap(state, client_id, sequence, body), - 82 => handle_uninstall_colormap(state, client_id, sequence, body), + 78 => handle_create_colormap(state, client_id, sequence, access_request, body), + 79 => handle_free_colormap(state, client_id, sequence, access_request, body), + 80 => handle_copy_colormap_and_free(state, client_id, sequence, access_request, body), + 81 => handle_install_colormap(state, client_id, sequence, access_request, body), + 82 => handle_uninstall_colormap(state, client_id, sequence, access_request, body), // ── SetCloseDownMode: validate mode (0/1/2 valid) ── 112 => handle_set_close_down_mode(state, client_id, sequence, header), // ── KillClient (AllTemporary or by resource owner) ── - 113 => handle_kill_client(state, backend, client_id, sequence, body), + 113 => handle_kill_client(state, backend, client_id, sequence, access_request, body), // ── pointer/modifier mapping (reply + MappingNotify fanout) ── 116 => handle_set_pointer_mapping(state, client_id, sequence, header, body), 118 => { handle_set_modifier_mapping(state, backend, origin, client_id, sequence, header, body) } // ── state-read replies (read state, no backend, no mutation) ── - 14 => handle_get_geometry(state, client_id, sequence, body), - 15 => handle_query_tree(state, client_id, sequence, body), + 14 => handle_get_geometry(state, client_id, sequence, access_request, body), + 15 => handle_query_tree(state, client_id, sequence, access_request, body), 16 => handle_intern_atom(state, client_id, sequence, header, body), - 21 => handle_list_properties(state, client_id, sequence, body), + 21 => handle_list_properties(state, client_id, sequence, header, body), 23 => handle_get_selection_owner(state, client_id, sequence, body), - 40 => handle_translate_coordinates(state, client_id, sequence, body), + 40 => handle_translate_coordinates(state, client_id, sequence, access_request, body), // ── grabs (pure state mutation on ServerState.{pointer,key}_grabs) ── 26 => handle_grab_pointer(state, backend, client_id, sequence, header, body), 27 => handle_ungrab_pointer(state, backend, client_id, sequence, body), 28 => handle_grab_button(state, client_id, sequence, header, body), 29 => handle_ungrab_button(state, client_id, sequence, header, body), - 30 => handle_change_active_pointer_grab(state, client_id, sequence, body), + 30 => handle_change_active_pointer_grab(state, client_id, sequence, access_request, body), 31 => handle_grab_keyboard(state, client_id, sequence, header, body), 32 => handle_ungrab_keyboard(state, client_id, sequence, body), 33 => handle_grab_key(state, client_id, sequence, header, body), 34 => handle_ungrab_key(state, client_id, sequence, header, body), // ── font / size queries (pure state-read replies) ── - 47 => handle_query_font(state, client_id, sequence, body), + 47 => handle_query_font(state, client_id, sequence, access_request, body), 48 => handle_query_text_extents(state, client_id, sequence, header, body), - 97 => handle_query_best_size(state, client_id, sequence, body), + 97 => handle_query_best_size(state, client_id, sequence, access_request, body), // ── properties (state mutation + PropertyNotify fanout) ── 18 => handle_change_property(state, backend, client_id, sequence, header, body), - 19 => handle_delete_property(state, backend, client_id, sequence, body), + 19 => handle_delete_property(state, backend, client_id, sequence, header, body), + 114 => handle_rotate_properties(state, backend, client_id, sequence, header, body), 20 => handle_get_property(state, backend, client_id, sequence, header, body), // ── backend-proxy replies (state-light, host-RPC) ── 17 => handle_get_atom_name(state, backend, origin, client_id, sequence, body), - 38 => handle_query_pointer(state, backend, origin, client_id, sequence, body), - 41 => handle_warp_pointer(state, backend, origin, client_id, sequence, body), + 38 => handle_query_pointer( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 41 => handle_warp_pointer( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), 119 => handle_get_modifier_mapping(state, backend, origin, client_id, sequence), // ── selections + SendEvent (cross-client fanout) ── - 22 => handle_set_selection_owner(state, client_id, sequence, body), - 24 => handle_convert_selection(state, client_id, sequence, body), - 25 => handle_send_event(state, client_id, sequence, header, body), + 22 => handle_set_selection_owner(state, client_id, sequence, access_request, body), + 24 => handle_convert_selection(state, client_id, sequence, access_request, body), + 25 => handle_send_event(state, backend, client_id, sequence, header, body), // ── fonts (state mutation + backend lifecycle) ── - 45 => handle_open_font(state, backend, origin, client_id, sequence, body), - 46 => handle_close_font(state, backend, origin, client_id, sequence, body), + 45 => handle_open_font( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 46 => handle_close_font( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── color queries (no state, just protocol replies) ── - 84 => handle_alloc_color(state, client_id, sequence, body), - 85 => handle_alloc_named_color(state, client_id, sequence, body), - 86 => handle_alloc_color_cells(state, client_id, sequence, body), - 87 => handle_alloc_color_planes(state, client_id, sequence, body), - 88 => handle_free_colors(state, client_id, sequence, body), - 89 => handle_store_colors(state, client_id, sequence), - 90 => handle_store_named_color(state, client_id, sequence), - 91 => handle_query_colors(state, client_id, sequence, body), - 92 => handle_lookup_color(state, client_id, sequence, body), + 84 => handle_alloc_color(state, client_id, sequence, access_request, body), + 85 => handle_alloc_named_color(state, client_id, sequence, access_request, body), + 86 => handle_alloc_color_cells(state, client_id, sequence, access_request, body), + 87 => handle_alloc_color_planes(state, client_id, sequence, access_request, body), + 88 => handle_free_colors(state, client_id, sequence, access_request, body), + 89 => handle_store_colors(state, client_id, sequence, access_request, body), + 90 => handle_store_named_color(state, client_id, sequence, access_request, body), + 91 => handle_query_colors(state, client_id, sequence, access_request, body), + 92 => handle_lookup_color(state, client_id, sequence, access_request, body), // ── keyboard mapping (server-wide MappingNotify + backend proxy) ── 100 => handle_change_keyboard_mapping(state, backend, client_id, sequence, header, body), 101 => handle_get_keyboard_mapping(state, backend, origin, client_id, sequence, body), // ── save-set + cursor lifecycle ── 6 => handle_change_save_set(state, client_id, sequence, header, body), - 95 => handle_free_cursor(state, backend, origin, client_id, sequence, body), + 95 => handle_free_cursor( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── pixmaps (state + backend lifecycle) ── 53 => handle_create_pixmap(state, backend, origin, client_id, sequence, header, body), - 54 => handle_free_pixmap(state, backend, origin, client_id, sequence, body), + 54 => handle_free_pixmap( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── font listing (backend proxy with reply sequence rewrite) ── 49 => handle_list_fonts(state, backend, origin, client_id, sequence, body), 50 => handle_list_fonts_with_info(state, backend, origin, client_id, sequence, body), // ── GContext (pure state mutation) ── - 55 => handle_create_gc(state, client_id, sequence, body), - 56 => handle_change_gc(state, client_id, sequence, body), - 57 => handle_copy_gc(state, client_id, sequence, body), - 59 => handle_set_clip_rectangles(state, client_id, sequence, header, body), - 60 => handle_free_gc(state, client_id, sequence, body), + 55 => handle_create_gc(state, client_id, sequence, access_request, body), + 56 => handle_change_gc(state, backend, origin, client_id, sequence, header, body), + 57 => handle_copy_gc( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 59 => handle_set_clip_rectangles(state, backend, origin, client_id, sequence, header, body), + 60 => handle_free_gc( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── drawing (state read + backend RPC + damage) ── 61 => handle_clear_area(state, backend, origin, client_id, sequence, header, body), - 62 => handle_copy_area(state, backend, origin, client_id, sequence, body), - 63 => handle_copy_plane(state, backend, origin, client_id, sequence, body), + 62 => handle_copy_area( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 63 => handle_copy_plane( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), 64 => handle_poly_point(state, backend, origin, client_id, sequence, header, body), 65 => handle_poly_line(state, backend, origin, client_id, sequence, header, body), - 66 => handle_poly_segment(state, backend, origin, client_id, sequence, body), - 67 => handle_poly_rectangle(state, backend, origin, client_id, sequence, body), - 68 => handle_poly_arc(state, backend, origin, client_id, sequence, body), - 69 => handle_fill_poly(state, backend, origin, client_id, sequence, body), - 70 => handle_poly_fill_rectangle(state, backend, origin, client_id, sequence, body), - 71 => handle_poly_fill_arc(state, backend, origin, client_id, sequence, body), + 66 => handle_poly_segment( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 67 => handle_poly_rectangle( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 68 => handle_poly_arc( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 69 => handle_fill_poly( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 70 => handle_poly_fill_rectangle( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 71 => handle_poly_fill_arc( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), 72 => handle_put_image(state, backend, origin, client_id, sequence, header, body), 73 => handle_get_image(state, backend, origin, client_id, sequence, header, body), - 74 => handle_poly_text8(state, backend, origin, client_id, sequence, body), - 75 => handle_poly_text16(state, backend, origin, client_id, sequence, body), + 74 => handle_poly_text8( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 75 => handle_poly_text16( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), 76 => handle_image_text8(state, backend, origin, client_id, sequence, header, body), 77 => handle_image_text16(state, backend, origin, client_id, sequence, header, body), // ── focus + AllowEvents ── @@ -403,32 +669,98 @@ pub fn process_request( 98 => handle_query_extension(state, backend, client_id, sequence, body), 99 => handle_list_extensions(state, backend, client_id, sequence), // ── cursor creation ── - 93 => handle_create_cursor(state, backend, origin, client_id, sequence, body), - 94 => handle_create_glyph_cursor(state, backend, origin, client_id, sequence, body), + 93 => handle_create_cursor( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 94 => handle_create_glyph_cursor( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── window queries / circulation ── - 3 => handle_get_window_attributes(state, client_id, sequence, body), - 13 => handle_circulate_window(state, client_id, sequence, header, body), + 3 => handle_get_window_attributes(state, client_id, sequence, header, body), + 13 => handle_circulate_window(state, backend, client_id, sequence, header, body), // ── extension extension-protocol arms (standalone, not full // extension dispatchers) ── 138 => handle_ge_request(state, client_id, sequence, header), // GE 135 => handle_big_requests_request(state, client_id, sequence, header), // BIG-REQUESTS // ── unmap (window lifecycle) ── - 10 => handle_unmap_window(state, backend, origin, client_id, sequence, body), - 11 => handle_unmap_subwindows(state, backend, origin, client_id, sequence, body), + 10 => handle_unmap_window( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 11 => handle_unmap_subwindows( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── map (window lifecycle) ── - 8 => handle_map_window(state, backend, origin, client_id, sequence, body), - 9 => handle_map_subwindows(state, backend, origin, client_id, sequence, body), + 8 => handle_map_window( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), + 9 => handle_map_subwindows( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── destroy (window lifecycle) ── - 4 => handle_destroy_window(state, backend, origin, client_id, sequence, body), - 5 => handle_destroy_subwindows(state, backend, origin, client_id, sequence, body), + 4 => handle_destroy_window(state, backend, origin, client_id, sequence, header, body), + 5 => handle_destroy_subwindows(state, backend, origin, client_id, sequence, header, body), // ── configure (window geometry/stacking) ── - 12 => handle_configure_window(state, backend, origin, client_id, sequence, body), + 12 => handle_configure_window( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── attributes ── - 2 => handle_change_window_attributes(state, backend, origin, client_id, sequence, body), + 2 => handle_change_window_attributes( + state, backend, origin, client_id, sequence, header, body, + ), // ── window create ── 1 => handle_create_window(state, backend, origin, client_id, sequence, header, body), // ── reparent ── - 7 => handle_reparent_window(state, backend, origin, client_id, sequence, body), + 7 => handle_reparent_window( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ), // ── XKB extension proxy ── 136 => handle_xkb_request(state, backend, origin, client_id, sequence, header, body), // ── XI2 extension dispatcher ── @@ -437,8 +769,9 @@ pub fn process_request( 145 => handle_present_request(state, backend, origin, client_id, sequence, header, body), 151 => handle_xinerama_request(state, client_id, sequence, header, body), // XINERAMA // ── DAMAGE extension dispatcher ── - 143 => handle_damage_request(state, client_id, sequence, header, body), + 143 => handle_damage_request(state, backend, client_id, sequence, header, body), // ── MIT-SHM extension dispatcher ── + #[cfg(unix)] 130 => handle_mit_shm_request( state, backend, @@ -485,6 +818,10 @@ pub fn process_request( 152 => handle_xcmisc_request(state, client_id, sequence, header, body), // ── XFree86-VidModeExtension dispatcher ── 153 => handle_xf86vidmode_request(state, backend, client_id, sequence, header, body), + // ── RECORD extension dispatcher ── + 154 => crate::core_loop::record::handle_record_request( + state, client_id, sequence, header, body, + ), opcode => { debug!( "client {} #{} unknown opcode {} ({} bytes) -> BadRequest", @@ -502,7 +839,9 @@ pub fn process_request( opcode, ) } - } + }; + backend.sync_floating_keyboard_states(state); + outcome } /// Apply Xorg's per-client locality policy before an extension handler sees a @@ -648,77538 +987,382 @@ fn reject_non_local_extension_request( } } -fn mirror_shape_to_host_state( - state: &ServerState, - backend: &mut dyn Backend, - origin: Option, - window: ResourceId, - kind: u8, -) { - use yserver_protocol::x11::shape as x11shape; - // Mirror Bounding, Clip, AND Input shapes to the backend. Pre-fix - // (2026-05-26 adapta-nokto investigation): only Bounding/Clip were - // mirrored, so the backend's `core.shape_input` never reflected a - // window's SHAPE Input region. That broke v2's `cursor_inside_shape` - // hit-test for windows with non-default Input shapes — notably - // adapta-nokto's MATE panel menu, which sets a shrunken Input shape - // (`{x=16, y=12, w=188, h=227}` inside a 220x260 window) to make - // the CSS box-shadow margin click-through. Without the Input shape - // in the backend, `window_under_cursor` HIT the menu in its shadow - // zone (window-local Y < 12), the protocol-layer fanout's hit-test - // disagreed (it correctly excluded the shadow), and the Enter - // event yserver emitted on the menu's host xid got re-routed by - // the fanout to whatever's structurally under the cursor (the - // panel) — never reaching the menu's client. GTK menu hover - // state machine never engaged → no highlight, no click. - if kind != x11shape::KIND_BOUNDING - && kind != x11shape::KIND_CLIP - && kind != x11shape::KIND_INPUT - { - return; +/// Special-case writer for MIT-SHM CreateSegment: sends a normal X11 +/// reply alongside an SCM_RIGHTS file descriptor. This is the one path +/// where the lifted code reaches around `client_io::write_or_buffer` +/// because the kernel only delivers the fd if it accompanies inline +/// bytes — buffering would split them apart. Once the outbound buffer +/// is non-empty we can't insert an FD-carrying frame, so we drain +/// first. +fn send_reply_with_fd( + client: &mut crate::server::ClientState, + bytes: &[u8], + fd: crate::fd::RawFd, +) -> io::Result<()> { + if client.gone { + return Ok(()); } - let Some(w) = state.resources.window(window) else { - return; - }; - let Some(host_xid) = w.host_xid else { - return; - }; - // Multi-monitor Bug A: a window with NO explicitly-set Bounding shape - // is unshaped — its effective bounding region is the *live* window - // geometry, which the backend scene already honors via the full-window - // emit path. `shape_rects_for` would instead materialize - // `default_shape_rect` (the geometry at THIS instant) into a concrete - // rect; mirroring that freezes a fixed extent into the backend's - // `shape_bounding` that goes stale when the window is later resized. - // The Composite Overlay Window is the load-bearing case: marco resets - // its Bounding shape to None while the screen is single-head, we froze - // (0,0 2560x1440), then RANDR grew the COW to 5120 on apply — the scene - // kept clipping the now-5120 COW to the stale 2560 rect, so the 2nd - // output sampled the wrong (left) half placed off-screen and screen 2 - // went dark. For an unset Bounding shape, mirror EMPTY rects so the - // backend drops the entry and the scene tracks live geometry (Xorg - // parity: a None bounding region is never materialized into a rect). - // - // CLIP joined Bounding on 2026-09-08 (#133). The note here used to say - // "Clip/Input keep mirroring the default rect — the scene's compose clip - // only consults Bounding"; #133 step 5 made the walk clip DESCENDANTS to - // the parent's clip shape (`SetWinSize` intersects winSize with it, - // `dix/window.c:1735`), which retired that premise and turned the frozen - // rect into a visible defect. Measured in vng: awesome resets its client - // frame's clip shape with `ShapeMask(Clip, src=None)` while the frame is - // 820x583, we froze that rect, and after the tiling resize to 608x734 the - // client was clipped 168 rows short — leaving the frame's uninitialised - // storage on screen as a white block. Xorg on the identical scenario has - // no white pixel at all, because an unset clip region is never - // materialized there either. - // - // Input still mirrors the default rect: it drives the cursor hit-test, - // which wants a concrete region and does not clip descendants. - if (kind == x11shape::KIND_BOUNDING || kind == x11shape::KIND_CLIP) - && !crate::nested::shape_kind_is_set(state, window, kind) - { - // Unset Bounding/Clip shape → None (drop the backend entry; the scene - // tracks live window geometry). Distinct from an explicit empty - // region — see set_shape_rectangles' Option contract (DRIFT 1). - let _ = backend.set_shape_rectangles(origin, host_xid.as_raw(), kind, None); - return; + if !client.fd_passing { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "file descriptor passing is unavailable on this transport", + )); } - let rects = crate::nested::shape_rects_for(state, window, kind); - // Explicit shape (Some), possibly empty — `Some(&[])` is an empty - // region (click-through / drawn-as-nothing), NOT unset. - let _ = backend.set_shape_rectangles(origin, host_xid.as_raw(), kind, Some(&rects)); -} - -fn drawable_full_rect_xfixes( - state: &ServerState, - drawable: ResourceId, -) -> yserver_protocol::x11::xfixes::RegionRect { - use yserver_protocol::x11::xfixes; - if let Some(window) = state.resources.window(drawable) { - return xfixes::RegionRect { - x: 0, - y: 0, - width: window.width, - height: window.height, - }; + // Queued with the client's output, as Xorg's `WriteFdToClient`: a + // client that reads slowly holds up only itself. + match client_io::write_with_fd(client, bytes, fd)? { + client_io::WriteOutcome::Done | client_io::WriteOutcome::WouldBlock => Ok(()), + client_io::WriteOutcome::Disconnect => Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "client outbound disconnect during fd send", + )), } - state.resources.pixmap(drawable).map_or( - xfixes::RegionRect { - x: 0, - y: 0, - width: 0, - height: 0, - }, - |pixmap| xfixes::RegionRect { - x: 0, - y: 0, - width: pixmap.width, - height: pixmap.height, - }, - ) } -fn normalize_region_rects( - rects: Vec, -) -> Vec { - crate::nested::normalize_region_rects(rects) +/// A window or pixmap of that id. +fn drawable_exists(state: &ServerState, id: ResourceId) -> bool { + state.resources.window(id).is_some() || state.resources.pixmap(id).is_some() } -/// Clip RENDER `FillRectangles` wire rects (8-byte `xRectangle`s) to a -/// `ClipByChildren` window's effective region — i.e. subtract the -/// window's mapped `InputOutput` children. Returns the surviving rects -/// re-encoded as wire bytes; an empty `Vec` means the paint is a no-op -/// (window fully covered by a child, as with a systray socket under its -/// XEMBED icon — Xorg's empty composite clip → nothing drawn, icon -/// preserved). For pixmaps / childless windows the rects pass through -/// unchanged. -fn clip_fill_rects_by_children( - state: &ServerState, - dst_drawable: ResourceId, - rects: &[u8], -) -> Vec { - use yserver_protocol::x11::xfixes; - - let child_rects = crate::core_loop::damage_fanout::mapped_child_clip_rects(state, dst_drawable); - if child_rects.is_empty() { - return rects.to_vec(); - } - - let requested: Vec = rects - .chunks_exact(8) - .map(|c| xfixes::RegionRect { - x: i16::from_le_bytes([c[0], c[1]]), - y: i16::from_le_bytes([c[2], c[3]]), - width: u16::from_le_bytes([c[4], c[5]]), - height: u16::from_le_bytes([c[6], c[7]]), - }) - .collect(); - - let clipped = crate::nested::subtract_regions(&requested, &child_rects); - - crate::core_loop::damage_fanout::log_clip_by_children_debug( - state, - dst_drawable, - "fill", - &requested, - &clipped, - ); - - let mut out = Vec::with_capacity(clipped.len() * 8); - for r in clipped { - out.extend_from_slice(&r.x.to_le_bytes()); - out.extend_from_slice(&r.y.to_le_bytes()); - out.extend_from_slice(&r.width.to_le_bytes()); - out.extend_from_slice(&r.height.to_le_bytes()); - } - out +#[derive(Debug, Clone, Copy)] +struct PresentDomainSelection { + crtc_id: u32, + crtc_epoch: u64, + msc_offset: u64, + raw_msc: u64, + raw_ust: u64, } -fn format_region_rects(rects: &[yserver_protocol::x11::xfixes::RegionRect]) -> String { - use std::fmt::Write as _; - - let mut out = String::from("["); - for (i, rect) in rects.iter().enumerate() { - if i > 0 { - out.push(' '); - } - let _ = write!( - out, - "({},{} {}x{})", - rect.x, rect.y, rect.width, rect.height - ); - } - out.push(']'); - out +#[derive(Debug)] +struct CurrentVidModeOutput { + output_id: u32, + crtc_id: u32, + connector: String, + mode: yserver_protocol::x11::xf86vidmode::ModeLine, } -fn resolve_host_subwindow_visual_to_state( +fn motion_history_range( state: &ServerState, - window: ResourceId, -) -> crate::host_x11::HostSubwindowVisual { - use crate::host_x11::HostSubwindowVisual; - let Some(window) = state.resources.window(window) else { - return HostSubwindowVisual::CopyFromParent; - }; - if window.visual == crate::resources::ROOT_VISUAL { - return HostSubwindowVisual::CopyFromParent; - } - let Some(visual) = state.resources.visual(window.visual) else { - return HostSubwindowVisual::CopyFromParent; - }; - let Some(visual_xid) = visual.host_visual_xid else { - return HostSubwindowVisual::DepthOnly { - depth: window.depth, - }; - }; - let Some(colormap) = state.resources.colormap_for_visual(window.visual) else { - return HostSubwindowVisual::DepthOnly { - depth: window.depth, - }; - }; - let Some(colormap_xid) = colormap.host_colormap_xid else { - return HostSubwindowVisual::DepthOnly { - depth: window.depth, - }; - }; - HostSubwindowVisual::Explicit { - depth: visual.depth, - visual_xid: visual_xid.as_raw(), - colormap_xid: colormap_xid.as_raw(), + start: u32, + stop: u32, +) -> Vec { + let now = state.timestamp_now(); + let start = if start == 0 { now } else { start }; + let stop = if stop == 0 { now } else { stop.min(now) }; + if start > stop || start > now { + return Vec::new(); } + state + .pointer_motion_history + .iter() + .copied() + .filter(|record| (start..=stop).contains(&record.time)) + .collect() } -/// Allocate the redirect's reason-1 backing for `window` and set -/// `Window.redirected_backing`. Shared between B.6a (single-window -/// REDIRECT_WINDOW), B.6b (REDIRECT_SUBWINDOWS walking children), -/// and the CreateWindow child-of-redirected hook. -/// -/// Silently no-ops if the window doesn't exist, has no host XID -/// yet, or the backend rejects the allocation. The caller doesn't -/// emit a protocol error in any of those cases — the redirect -/// record is already in place, so a later paint via -/// `host_drawable_target` will simply fall back to the window's -/// own host XID until a future event populates the backing. -/// -/// Stage 4b: wired into the COMPOSITE `RedirectWindow` / -/// `RedirectSubwindows` dispatch, gated on -/// `Backend::supports_redirect_activation()`. v1 (`KmsBackend`) -/// returns `false`, preserving the post-`3751c11` revert that -/// fixed MATE; v2 (`KmsBackend`) overrides to `true` and the -/// full allocate + participation-flip path runs. -/// -/// `mode` drives the scene-participation flip after a successful -/// allocate: Manual → window participating=false (the external -/// compositor drives presentation), Automatic → window -/// participating=true AND backing participating=true (paint -/// resolves through the backing and the scene walk picks it up -/// via W's `redirected_target` indirection in 4c). -fn activate_redirect_backing_for( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - window: ResourceId, - mode: crate::server::CompositeRedirectMode, -) { - // Xorg compCheckRedirect (composite/compwindow.c:156-170): the - // overlay window is NEVER actually redirected — should=FALSE for - // pWin == cs->pOverlayWin — regardless of trigger - // (RedirectSubwindows(root), explicit RedirectWindow, or - // auto-redirect-on-map). The COW is a real child of root (Phase 2), - // so RedirectSubwindows(root, Manual) would otherwise hand it a - // Manual backing + scene_participating=false, and the Phase 3 - // Manual-skip would drop the whole composited desktop from scanout. - // The COW reaches scanout via the normal paint path. - if window == COMPOSITE_OVERLAY_WINDOW { - return; - } - // compCheckRedirect allocates only for a realized window (compwindow.c:162); realize does it later. - if state - .resources - .window(window) - .is_none_or(|w| w.map_state != MapState::Viewable) - { - return; - } - // Mode-flip on an existing redirect is routed through - // `flip_redirect_target_mode` upstream — don't reallocate - // here (Xorg preserves the backing per - // `xserver/composite/compwindow.c:172` + - // `compositeproto.txt:80`). If the caller reaches us with a - // populated `redirected_backing` it's a same-mode idempotent - // call (or a stale handoff — log + skip rather than crash). - if state - .resources - .window(window) - .is_some_and(|w| w.redirected_backing.is_some()) - { - log::debug!( - "activate_redirect_backing_for(0x{:x}): backing already present (same-mode \ - idempotent); skipping reallocation", - window.0 - ); - return; - } - let snapshot = state - .resources - .window(window) - .map(|w| (w.host_xid, w.width, w.height, w.border_width, w.depth)); - let Some((Some(host_window), w_width, w_height, w_border, w_depth)) = snapshot else { - return; - }; - // #133 step 3 (3.3) — a redirect backing is allocated at the - // BORDERED extent, `(w + 2bw) x (h + 2bw)`, and holds the window at - // its OUTER origin with the content `bw` inside: Xorg - // `compAllocPixmap` computes exactly `w = width + (bw << 1)` / - // `h = height + (bw << 1)` and hands that to `compNewPixmap` - // (`composite/compalloc.c:608-618`). The render backend's seed / - // inferior-reconstruct paths place content at `(bw, bw)` in this - // pixmap, and `NameWindowPixmap` hands the whole bordered image to - // the compositor, so the border is part of it by design. - // `bordered_backing_extent` is the identity at `bw == 0`. - let (w_width, w_height) = bordered_backing_extent(w_width, w_height, w_border); - match backend.allocate_redirected_backing(origin, host_window, w_width, w_height, w_depth) { - Ok(host_pixmap) => { - if let Some(w) = state.resources.window_mut(window) { - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap, - width: w_width, - height: w_height, - depth: w_depth, - }); - } - // YSERVER_TRAY_DEBUG: capture-side timeline for the systray - // sliver/blank race — when each (socket) window's redirect - // backing is allocated, its size, and the mode. Correlate - // against the `TRAY fill/damage` lines (which carry the plug - // child geometry at Clear time). REMOVE with the rest of the - // tray diag once the redirect-backing race is fixed. - if std::env::var_os("YSERVER_TRAY_DEBUG").is_some() { - log::info!( - target: "yserver_core::core_loop::tray", - "TRAY redirect-alloc win=0x{:x} backing={w_width}x{w_height}d{w_depth} mode={mode:?}", - window.0, - ); - } - // Scene-participation flip. Spec §285+360 names - // redirect-state change as a scene-structure damage - // source; the v2 impl of these setters fires that - // damage internally so the protocol handler just - // makes the calls. - // - // W: Automatic → true (scene walks W, samples B via - // 4c.3 indirection). Manual → false (the external - // compositor owns presentation and reintroduces the - // window via its own output/COW surface, while the - // post-6ffd370 scene still emits W's own backing as - // its source — both controlled by the B flag below). - // - // B: always true. Post-6ffd370 the scene samples B - // through W's `redirected_target` in both modes - // (Automatic via W's own entry, Manual via the parent - // backing emit), so `store.damage(B_id, ..)` from - // every paint into the backing must accumulate. - // Leaving B non-participating in Manual mode silently - // drops all those damages and buffer-age compose - // retains stale BO pixels except where cursor damage - // happens to overlap. - let window_participating = - matches!(mode, crate::server::CompositeRedirectMode::Automatic); - if let Err(err) = - backend.set_window_scene_participation(origin, host_window, window_participating) - { - log::warn!( - "set_window_scene_participation(0x{:x}, {window_participating}) failed: {err}", - window.0 - ); - } - if let Err(err) = backend.set_backing_scene_participation(origin, host_pixmap, true) { - log::warn!( - "set_backing_scene_participation(0x{:x}, true) failed: {err}", - host_pixmap.as_raw() - ); - } - // Redirecting an already-viewable window hands the compositor a - // valid NameWindowPixmap source immediately, but the backing seed - // above happened before any later client paint. If we don't emit an - // initial full-window damage wakeup here, compositors such as picom - // can leave the freshly-redirected window absent from the COW until - // some unrelated later event (click, move, resize) dirties it. - // - // This mirrors the "first viewable contents need one wakeup" rule - // on MapWindow: once the redirected backing exists and participation - // flips are installed, wake DAMAGE subscribers so they pull the - // seeded pixels into their own composite output immediately. - if state - .resources - .window(window) - .is_some_and(|w| w.map_state == MapState::Viewable) - { - let _dropped = accumulate_damage_full_to_state(state, window); - // #143 — and the RING, which `accumulate_damage_full_to_state` - // cannot express: its rect is `(0, 0, width, height)`, i.e. - // `winSize`, which excludes the border by construction. The - // backing we just allocated is the BORDERED extent and - // `allocate_redirected_backing` paints the ring into it, so - // the compositor has to be told about those pixels too. - // Xorg gets this for free — `compSetPixmapVisitWindow` queues - // `compRepaintBorder` whenever `bw != 0` - // (`composite/compwindow.c:137-139`), and that repaint is an - // ordinary GC op the DAMAGE wrapper sees. Identity at - // `bw == 0`. - let _dropped = accumulate_damage_border_to_state(state, window); - } - } - Err(err) => { - log::warn!( - "activate_redirect_backing_for(0x{:x}): allocate failed: {err}", - window.0 - ); - } - } +fn supported_pixmap_depth(depth: u8) -> bool { + matches!(depth, 1 | 4 | 8 | 24 | 32) } -/// Stage 4b.8: same-owner mode-flip handler. When a client -/// re-issues `Redirect{Window,Subwindows}(W, new_mode)` while it -/// already owns a record at the same key with a different mode, -/// Xorg's `compCheckRedirect` -/// (`xserver/composite/compwindow.c:172`) preserves the backing -/// pixmap and every `NameWindowPixmap` alias; only `redirectDraw` -/// flips. Composite spec line 80: "old named pixmaps remain -/// allocated until FreePixmap." -/// -/// In v2 the equivalent is: keep `Window.redirected_backing` + -/// `KmsCore.alias_registry` + `KmsCore.host_window_to_backing` + -/// `Drawable.redirected_target` untouched; only fire the -/// participation-flip pair for the new mode. -/// -/// **No re-seed** per the plan's codex-round-6 decision: the -/// backing's current content is whatever the compositor has been -/// reading from (Automatic) or the still-frozen pre-redirect snapshot -/// (Manual just-flipped-from-Automatic). Running `copy_area(W, B)` -/// would replace that with W's storage which under Manual is empty — -/// strictly worse than the existing backing contents. -fn flip_redirect_target_mode( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - target: ResourceId, - new_mode: crate::server::CompositeRedirectMode, -) { - let snapshot = state.resources.window(target).map(|w| { - ( - w.host_xid, - w.redirected_backing.as_ref().map(|b| b.host_pixmap), - ) - }); - let Some((Some(host_window), Some(backing))) = snapshot else { - // No existing backing → fall back to a fresh activation. - // This shouldn't normally fire (the caller gates on - // `prev.mode != new_mode` which implies a prior record - // existed, and any prior record under - // `supports_redirect_activation()` allocated a backing), - // but stay defensive. - log::debug!( - "flip_redirect_target_mode(0x{:x}): no existing backing; falling back to allocate", - target.0 - ); - activate_redirect_backing_for(state, backend, origin, target, new_mode); - return; - }; - // See activate_redirect_backing_for for the rationale: B is - // always scene-participating because the post-6ffd370 scene - // samples B via `redirected_target` in both modes; only W's - // own scene presence toggles with mode. - let window_participating = matches!(new_mode, crate::server::CompositeRedirectMode::Automatic); - if let Err(err) = - backend.set_window_scene_participation(origin, host_window, window_participating) - { - log::warn!( - "flip_redirect_target_mode(0x{:x}, {window_participating}): \ - set_window_scene_participation failed: {err}", - target.0 - ); - } - if let Err(err) = backend.set_backing_scene_participation(origin, backing, true) { - log::warn!( - "flip_redirect_target_mode(0x{:x}, true): \ - set_backing_scene_participation failed: {err}", - target.0 - ); - } +/// Resolve a `Drawable` resource id to its kind + depth for error +/// validation. Mirrors Xorg's `dixLookupDrawable` shape: the four +/// outcomes the spec distinguishes. +enum DrawableLookup { + InputOutputWindow { depth: u8 }, + InputOnlyWindow, + Pixmap { depth: u8 }, + Missing, } -/// Point GLX pixmap `glx_xid` at `new_host`, moving its export-lifetime ref along (acquire NEW, release OLD). -fn retarget_glx_pixmap_export( - state: &mut ServerState, - backend: &mut dyn Backend, - glx_xid: u32, - new_host: u32, -) { - let Some(drawable) = state.glx_drawables.get_mut(&glx_xid) else { - return; - }; - let old_host = drawable.glx_export_host_xid.replace(new_host); - if old_host == Some(new_host) { - return; +fn drawable_lookup(state: &ServerState, id: ResourceId) -> DrawableLookup { + if let Some(w) = state.resources.window(id) { + return match w.class { + crate::resources::WindowClass::InputOnly => DrawableLookup::InputOnlyWindow, + // `CopyFromParent` / `Other` only show up pre-CreateWindow + // resolution and shouldn't be reachable for a registered window; + // treat them the same as the regular InputOutput case. + crate::resources::WindowClass::InputOutput + | crate::resources::WindowClass::CopyFromParent + | crate::resources::WindowClass::Other(_) => { + DrawableLookup::InputOutputWindow { depth: w.depth } + } + }; } - backend.acquire_glx_pixmap_export(new_host); - if let Some(old_host) = old_host { - backend.release_glx_pixmap_export(old_host); + if let Some(p) = state.resources.pixmap(id) { + return DrawableLookup::Pixmap { depth: p.depth }; } + DrawableLookup::Missing } -/// A window that just became viewable under an existing redirect (its own -/// `RedirectWindow`, or its parent's `RedirectSubwindows`) gets a fresh -/// backing, as Xorg's `compRealizeWindow` → `compCheckRedirect` → -/// `compAllocPixmap` does (`composite/compwindow.c:274`, `:173-174`). +/// Result of validating (drawable, gc) for a paint request. The +/// shape mirrors Xorg's `VALIDATE_DRAWABLE_AND_GC` macro: emit +/// BadDrawable, BadMatch (inputonly), BadGC, or BadMatch +/// (gc-drawable-depth) in that priority order. +/// Optional access modes let callers that share this structural check +/// defer or omit policy checks while retaining the request's site order. /// -/// Must be called AFTER `backend.map_subwindow`: `map_subwindow` blindly -/// sets `scene_participating = true`, and the Manual participation flip -/// inside `activate_redirect_backing_for` must land last. Callers walk the -/// delta's `became_viewable` parent first, so the seed finds the parent's -/// storage (or backing) already in place. -fn realize_redirect_backing( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - window: ResourceId, -) { - if !backend.supports_redirect_activation() { - return; - } - if state - .resources - .window(window) - .is_none_or(|w| w.redirected_backing.is_some()) - { - return; +/// `gc-drawable-screen` is not modelled — yserver has one screen +/// so the BadMatch-screen case is structurally unreachable, and +/// XTS marks the corresponding TPs UNSUPPORTED on a single-screen +/// server already. +fn validate_drawable_and_gc( + state: &ServerState, + client: ClientId, + request: RequestOpcodes, + drawable: ResourceId, + gc: ResourceId, + drawable_mode: Option, + gc_mode: Option, +) -> Result<(), (u8, u32)> { + let (target_depth, drawable_kind) = match drawable_lookup(state, drawable) { + DrawableLookup::InputOutputWindow { depth } => (depth, ResourceKind::Window), + DrawableLookup::Pixmap { depth } => (depth, ResourceKind::Pixmap), + DrawableLookup::InputOnlyWindow => return Err((x11::error::BAD_MATCH, 0)), + DrawableLookup::Missing => return Err((x11::error::BAD_DRAWABLE, drawable.0)), + }; + if let Some(mode) = drawable_mode { + validate_resource_access( + state, + client, + ResourceTarget { + id: drawable, + kind: drawable_kind, + creation: None, + }, + mode, + request, + )?; } - let Some(mode) = effective_redirect_mode_for_window(state, window) else { - return; + let Some(gc_entry) = state.resources.gc(gc) else { + return Err((x11::error::BAD_GC, gc.0)); }; - activate_redirect_backing_for(state, backend, origin, window, mode); -} - -/// Apply a viewability delta to COMPOSITE backings: the windows that became -/// unviewable (child first) drop theirs, those that became viewable (parent -/// first) get a fresh one. The redirect records are untouched. -fn apply_viewability_delta_to_redirects( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - delta: &ViewabilityDelta, -) { - for window in &delta.became_unviewable { - let _ = crate::core_loop::process_disconnect::unrealize_redirect_backing( - state, backend, origin, *window, - ); + if let Some(mode) = gc_mode { + validate_resource_access( + state, + client, + ResourceTarget { + id: gc, + kind: ResourceKind::Gc, + creation: None, + }, + mode, + request, + )?; } - for window in &delta.became_viewable { - realize_redirect_backing(state, backend, origin, *window); + // GC depth is fixed at CreateGC to the depth of the origin drawable + // (X11 spec). Stored on the GC entry directly so it survives the + // origin drawable being freed. `depth == 0` means "GC was created + // before the depth field was tracked" — skip the check rather than + // emit a spurious BadMatch. + if gc_entry.depth != 0 && gc_entry.depth != target_depth { + return Err((x11::error::BAD_MATCH, 0)); } + Ok(()) } -/// Host xid of a window whose storage follows its viewability; the root and the COW own theirs. -fn storage_lifecycle_host_xid(state: &ServerState, window: ResourceId) -> Option { - if window == ROOT_WINDOW || window == COMPOSITE_OVERLAY_WINDOW { - return None; - } - state - .resources - .window(window) - .and_then(|w| w.host_xid) - .map(|h| h.as_raw()) +/// Sibling of [`validate_drawable_and_gc`] for paint ops that consume +/// a drawable WITHOUT a GC depth-match constraint — the `src` side of +/// `CopyPlane`, for instance, where any depth is acceptable because +/// the plane mask extracts a single bit from whatever the source is. +/// Still emits BadDrawable for missing and BadMatch for `InputOnly` +/// windows. +fn validate_drawable_only( + state: &ServerState, + client: ClientId, + request: RequestOpcodes, + drawable: ResourceId, + mode: AccessMode, +) -> Result<(), (u8, u32)> { + let kind = match drawable_lookup(state, drawable) { + DrawableLookup::InputOutputWindow { .. } => Ok(ResourceKind::Window), + DrawableLookup::Pixmap { .. } => Ok(ResourceKind::Pixmap), + DrawableLookup::InputOnlyWindow => Err((x11::error::BAD_MATCH, 0)), + DrawableLookup::Missing => Err((x11::error::BAD_DRAWABLE, drawable.0)), + }?; + validate_resource_access( + state, + client, + ResourceTarget { + id: drawable, + kind, + creation: None, + }, + mode, + request, + ) } -/// Windows that became viewable get storage, parent first; call before their redirect backings. -fn realize_storage_for_delta( +/// Sibling for ChangeGC / SetDashes / SetClipRectangles: BadGC on +/// missing id, no drawable involvement. When a mode is supplied, it +/// asks the resource policy after resolving the GC. Mirrors Xorg's +/// `dixLookupGC` gate (`dix/dispatch.c:1589,1639,1664`). +fn validate_gc_only( state: &ServerState, - backend: &mut dyn Backend, - origin: Option, - delta: &ViewabilityDelta, -) { - for window in &delta.became_viewable { - if let Some(xid) = storage_lifecycle_host_xid(state, *window) - && let Err(err) = backend.realize_window_storage(origin, xid) - { - log::warn!("realize_window_storage(0x{xid:x}) failed: {err}"); + client: ClientId, + request: RequestOpcodes, + gc: ResourceId, + mode: Option, +) -> Result<(), (u8, u32)> { + if state.resources.gc(gc).is_some() { + if let Some(mode) = mode { + validate_resource_access( + state, + client, + ResourceTarget { + id: gc, + kind: ResourceKind::Gc, + creation: None, + }, + mode, + request, + ) + } else { + Ok(()) } + } else { + Err((x11::error::BAD_GC, gc.0)) } } -/// Windows that became unviewable drop storage, child first; call after their redirect backings. -fn release_storage_for_delta( +fn validate_resource_access( state: &ServerState, - backend: &mut dyn Backend, - origin: Option, - delta: &ViewabilityDelta, -) { - for window in &delta.became_unviewable { - if let Some(xid) = storage_lifecycle_host_xid(state, *window) - && let Err(err) = backend.release_window_storage(origin, xid) - { - log::warn!("release_window_storage(0x{xid:x}) failed: {err}"); - } + client: ClientId, + target: ResourceTarget, + mode: AccessMode, + request: RequestOpcodes, +) -> Result<(), (u8, u32)> { + match state.check_resource(client, &target, mode, Some(request)) { + Decision::Allow => Ok(()), + Decision::Deny(error) => Err((error.code, error.value)), } } -/// Re-apply a window's effective COMPOSITE redirect mode after a -/// map operation. `map_subwindow` flips storage visible by default; -/// Manual-redirected windows must be forced back to -/// `scene_participating=false`, while Automatic windows stay on-scene. -fn reapply_redirect_mode_after_map( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - window: ResourceId, -) { - let Some(mode) = effective_redirect_mode_for_window(state, window) else { - return; - }; - let Some(host_xid) = state.resources.window(window).and_then(|w| w.host_xid) else { - return; - }; - let participating = matches!(mode, crate::server::CompositeRedirectMode::Automatic); - if let Err(err) = backend.set_window_scene_participation(origin, host_xid, participating) { - log::warn!( - "reapply_redirect_mode_after_map(0x{:x}): \ - set_window_scene_participation({participating}) failed: {err}", - window.0 - ); +/// Check an operand whose historical validation is missing, without +/// introducing a new error when its id does not resolve to this type. +pub(super) fn validate_resource_if_present( + state: &ServerState, + client: ClientId, + id: ResourceId, + kind: ResourceKind, + mode: AccessMode, + request: RequestOpcodes, +) -> Result<(), (u8, u32)> { + if !state.policies_installed() || client == crate::resources::SERVER_OWNER { + return Ok(()); } + if state.access_resource_owner(id, kind).is_none() { + return Ok(()); + } + validate_resource_access( + state, + client, + ResourceTarget { + id, + kind, + creation: None, + }, + mode, + request, + ) } -/// Resize-time bookkeeping for COMPOSITE-redirected windows. yserver -/// rotates the redirected backing to fresh storage sized to the new -/// geometry. Existing `NameWindowPixmap` aliases are also retargeted -/// onto the new backing as a compatibility measure for picom/openbox: -/// in hardware repros picom kept sampling the pre-resize backing for -/// many seconds after ConfigureNotify, leaving white right/bottom -/// strips and frozen content. Following Xorg compatibility here is -/// more important than the earlier frozen-alias theory. -/// -/// On pure moves, `force_reallocate=true` routes through the same -/// rotate path even when the size is unchanged. That hands the -/// compositor a fresh backing object at the window's new position -/// instead of reusing the original named pixmap indefinitely. -/// -/// Sequence when the window is redirected (release-then-allocate -/// order is load-bearing — see below): -/// 1. Snapshot the existing backing handle. -/// 2. Release the old backing's reason-1 hold via -/// `release_redirected_backing`. If `composite_named_pixmaps` -/// aliases still reference it, refcount stays > 0 and the -/// backing survives — its content is frozen at pre-resize. -/// If no aliases hold it, the backing is freed. This also -/// clears the backend's `host_window_to_backing[W]` slot so the -/// next allocate doesn't short-circuit on the now-stale entry. -/// 3. Allocate a new backing at the new (width, height, depth). -/// With the slot cleared in step 2, the backend's idempotent -/// lookup misses and we actually get fresh storage sized to -/// `new_width × new_height`. -/// 4. Repoint `Window.redirected_backing` at the new backing. -/// -/// Release-then-allocate order is mandatory because the backend's -/// `allocate_redirected_backing` is idempotent on -/// `host_window_to_backing[W]`: an allocate-then-release pass would -/// return the EXISTING backing handle (ignoring `new_width` / -/// `new_height`), and the subsequent release would then destroy the -/// very pixmap we just decided to keep. Hardware smoke caught this -/// when marco resized a 25-tall mate-panel to 28 tall: the next -/// `NameWindowPixmap` returned `NotFound` because the backing had -/// been freed under it. -/// -/// `composite_named_pixmaps` is updated to point at the new backing -/// and new geometry. Each alias drops one hold on OLD and takes one -/// hold on NEW in the backend alias registry so the lifetime model -/// stays balanced. -/// -/// When the window is **not** redirected (no backing), this is a -/// no-op — `composite_named_pixmaps` should be empty by -/// construction (the protocol layer only creates aliases on -/// redirected windows). -/// #133 step 3 (3.3) — a COMPOSITE redirect backing's extent: -/// `(w + 2bw) x (h + 2bw)`, mirroring Xorg `compAllocPixmap` -/// (`composite/compalloc.c:608-618`, `w = width + (bw << 1)`). The -/// window sits at its OUTER origin inside it with the client content -/// `bw` in, so the border is part of the named pixmap by design. -/// Identity at `bw == 0`. -fn bordered_backing_extent(width: u16, height: u16, border_width: u16) -> (u16, u16) { - let bw2 = border_width.saturating_mul(2); - (width.saturating_add(bw2), height.saturating_add(bw2)) +/// Encode an X11 protocol error and ship it to the client through +/// `client_io::write_or_buffer`. Mirrors `nested::emit_x11_error` but +/// operates on the new `&mut ClientState` plumbing. +fn emit_x11_error( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + code: u8, + bad_value: u32, + major_opcode: u8, +) -> io::Result { + emit_x11_error_with_minor(state, client_id, sequence, code, bad_value, 0, major_opcode) } -fn rotate_redirected_backing_on_resize( +pub(super) fn emit_x11_error_with_minor( state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - window: ResourceId, - new_width: u16, - new_height: u16, - force_reallocate: bool, - old_border_width: u16, -) { - let snapshot = state.resources.window(window).and_then(|w| { - w.redirected_backing.as_ref().map(|b| { - ( - b.host_pixmap, - b.width, - b.height, - w.host_xid, - w.depth, - w.border_width, - ) - }) - }); - let Some((old_backing, old_width, old_height, host_window, depth, border_width)) = snapshot - else { - return; - }; - let Some(host_window) = host_window else { - return; - }; - // #133 step 3 (3.3): the caller's `new_width`/`new_height` are the - // window's CONTENT size; the backing is the bordered extent (see - // `activate_redirect_backing_for`). Identity at `bw == 0`. - let (new_width, new_height) = bordered_backing_extent(new_width, new_height, border_width); - - if !force_reallocate - && old_border_width == border_width - && backend.redirected_backing_can_fit(old_backing, new_width, new_height, depth) - { - if let Some(w) = state.resources.window_mut(window) - && let Some(backing) = &mut w.redirected_backing - { - backing.width = new_width; - backing.height = new_height; - backing.depth = depth; - } - let _ = backend.update_redirected_backing_geometry( - origin, - old_backing, - new_width, - new_height, - depth, - ); - let aliases_to_retarget = state - .resources - .window(window) - .map(|w| w.composite_named_pixmaps.clone()) - .unwrap_or_default(); - for alias in &aliases_to_retarget { - let _ = state.resources.update_pixmap_geometry( - alias.client_pixmap, - new_width, - new_height, - depth, - ); - } - if let Some(w) = state.resources.window_mut(window) { - for alias in &mut w.composite_named_pixmaps { - alias.width = new_width; - alias.height = new_height; - } - } - return; - } - - // Take a rotate-scoped retain on OLD's storage BEFORE the - // release. Without it, the no-alias case (no NameWindowPixmap - // outstanding on this backing) sees release_redirected_backing's - // alias_registry.decref hit refcount=0 → free_pixmap → store - // entry dropped → the copy_area below reads from a freed handle - // (observed as `copy_area dropped — src unknown` in HW smoke - // 2026-05-20 17:28:10Z). Paired with `drop_backing_storage` - // after the copy. - if let Err(err) = backend.retain_backing_storage(origin, old_backing) { - log::warn!( - "rotate_redirected_backing_on_resize: retain_backing_storage(0x{:x}) failed: {err}", - old_backing.as_raw() - ); - } - - // Release the old backing FIRST so the backend's - // `host_window_to_backing[W]` slot is clear before the allocate - // below — otherwise allocate's idempotent short-circuit would - // hand back the about-to-be-released handle and we'd free the - // very pixmap we just chose to keep. Composite spec lets the - // backing survive (alias-frozen) if `NameWindowPixmap` references - // still hold it via the alias registry; the rotate-retain above - // covers the no-alias case. - if let Err(err) = backend.release_redirected_backing(origin, old_backing) { - log::warn!( - "rotate_redirected_backing_on_resize: release_redirected_backing(0x{:x}) failed: {err}", - old_backing.as_raw() - ); - // Don't bail — try the allocate anyway. Worst case the - // allocate also fails and we just leave the window unrouted; - // better than leaving the OLD backing pointing somewhere - // stale. - } - - // Now allocate fresh at the new size. With the slot cleared by - // the release above, the idempotent short-circuit misses and we - // get a backing actually sized to `new_width × new_height`. - let new_backing = match backend.allocate_redirected_backing( - origin, - host_window, - new_width, - new_height, - depth, - ) { - Ok(h) => h, - Err(err) => { - log::warn!( - "rotate_redirected_backing_on_resize(0x{:x}, {new_width}x{new_height}): \ - allocate failed: {err}", - window.0 - ); - // Clear redirected_backing on the resource since we no - // longer have a valid backing — the old one was just - // released and the new allocate failed. - if let Some(w) = state.resources.window_mut(window) { - w.redirected_backing = None; - } - return; - } + client_id: ClientId, + sequence: SequenceNumber, + code: u8, + bad_value: u32, + minor_opcode: u16, + major_opcode: u8, +) -> io::Result { + debug!( + "emit_x11_error: client={} seq={} code={} bad_value=0x{:x} minor={} major_opcode={}", + client_id.0, sequence.0, code, bad_value, minor_opcode, major_opcode + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); }; - if let Some(w) = state.resources.window_mut(window) { - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: new_backing, - width: new_width, - height: new_height, - depth, - }); - } - // Compatibility retarget: existing NameWindowPixmap aliases on this - // window must follow the new backing + geometry, or compositors can - // keep sampling the pre-resize backing for seconds after the frame - // has already resized (observed with picom under openbox: white - // right/bottom strip and frozen btop content). Keep the backend - // alias-registry balanced by moving one hold per alias from OLD to - // NEW. - let aliases_to_retarget = state - .resources - .window(window) - .map(|w| w.composite_named_pixmaps.clone()) - .unwrap_or_default(); - for alias in &aliases_to_retarget { - if let Err(err) = backend.retain_backing_storage(origin, new_backing) { - log::warn!( - "rotate_redirected_backing_on_resize(0x{:x}): retain NEW alias backing 0x{:x} failed: {err}", - window.0, - new_backing.as_raw(), - ); - } - if let Err(err) = backend.drop_backing_storage(origin, alias.host_pixmap) { - log::warn!( - "rotate_redirected_backing_on_resize(0x{:x}): drop OLD alias backing 0x{:x} failed: {err}", - window.0, - alias.host_pixmap.as_raw(), - ); - } - let _ = state - .resources - .set_pixmap_host_xid(alias.client_pixmap, new_backing); - let _ = state.resources.update_pixmap_geometry( - alias.client_pixmap, - new_width, - new_height, - depth, - ); - let glx_pixmaps: Vec = state - .glx_drawables - .iter() - .filter(|(_, d)| d.x_drawable == alias.client_pixmap.0) - .map(|(xid, _)| *xid) - .collect(); - for glx_xid in glx_pixmaps { - retarget_glx_pixmap_export(state, backend, glx_xid, new_backing.as_raw()); - } - } - if let Some(w) = state.resources.window_mut(window) { - for alias in &mut w.composite_named_pixmaps { - alias.host_pixmap = new_backing; - alias.width = new_width; - alias.height = new_height; - } - } - - // compCopyWindow analog: carry pre-resize bits from OLD into NEW - // for the overlap rect. Xorg does this via `compCopyWindow` - // (composite/compwindow.c:376-388) after `compReallocPixmap` - // (compalloc.c:680-712). Without it, any compositor that re-Names - // the post-resize backing (marco on mate-panel-top during the - // 25→28-px grow) reads an empty buffer and the tray icons that - // were painted into the pre-resize backing vanish. - // - // Storage-alive contract: OLD's backend storage must remain - // readable across this call. `release_redirected_backing` above - // only frees when `alias_registry.decref` returns true (refcount - // hits 0). NameWindowPixmap aliases keep it alive through this - // path; the v2 backend's lifecycle for the no-alias case is - // tightened separately. - // - // #143: the copy carries CONTENT only. Since #133 the ring lives - // INSIDE the storage at `(0,0)..(bw,bw)` and the allocate above has - // already painted NEW's ring at the NEW extent; copying the full - // `min(old, new)` box from OLD's origin would paint over it — and on - // a SHRINK that box is the whole new backing, so NEW's right/bottom - // ring columns would get OLD's *interior* pixels. Xorg reaches the - // same end state from the other side: `compCopyWindow` copies first - // and `compSetPixmap` queues `compRepaintBorder` afterwards - // (../xserver/composite/compwindow.c:137-139), so the ring is always - // the freshly painted one. Each backing uses its allocation-time - // border inset; a border-width change moves the content between them. - let old_inset = old_border_width.saturating_mul(2); - let new_inset = border_width.saturating_mul(2); - let copy_w = old_width - .saturating_sub(old_inset) - .min(new_width.saturating_sub(new_inset)); - let copy_h = old_height - .saturating_sub(old_inset) - .min(new_height.saturating_sub(new_inset)); - let old_content_origin = i16::try_from(old_border_width).unwrap_or(i16::MAX); - let content_origin = i16::try_from(border_width).unwrap_or(i16::MAX); - // Storage preservation has no client GC, just like Present's copy. - let copy_gc = crate::backend::DrawState::default(); - if copy_w > 0 - && copy_h > 0 - && let Err(err) = backend - .apply_clip_state(origin, ©_gc.clip) - .and_then(|()| backend.apply_draw_state(origin, ©_gc)) - .and_then(|()| { - backend.copy_area( - origin, - old_backing.as_raw(), - new_backing.as_raw(), - old_content_origin, - old_content_origin, - content_origin, - content_origin, - copy_w, - copy_h, - ) - }) - { - log::warn!( - "rotate_redirected_backing_on_resize(0x{:x}): \ - copy_area(OLD=0x{:x} → NEW=0x{:x}, {copy_w}x{copy_h}) failed: {err}", - window.0, - old_backing.as_raw(), - new_backing.as_raw(), - ); - } - - // Drop the rotate-scoped retain we took before release. If no - // other holds remain (no NameWindowPixmap aliases), this is the - // final ref and OLD's storage is freed here. - if let Err(err) = backend.drop_backing_storage(origin, old_backing) { - log::warn!( - "rotate_redirected_backing_on_resize: drop_backing_storage(0x{:x}) failed: {err}", - old_backing.as_raw() - ); - } - - if let Some(mode) = effective_redirect_mode_for_window(state, window) { - // See activate_redirect_backing_for: B always scene- - // participating so the post-6ffd370 scene's damage - // harvest sees paints through `redirected_target`. - let window_participating = matches!(mode, crate::server::CompositeRedirectMode::Automatic); - if let Err(err) = - backend.set_window_scene_participation(origin, host_window, window_participating) - { - log::warn!( - "rotate_redirected_backing_on_resize(0x{:x}): \ - set_window_scene_participation({window_participating}) failed: {err}", - window.0 - ); - } - if let Err(err) = backend.set_backing_scene_participation(origin, new_backing, true) { - log::warn!( - "rotate_redirected_backing_on_resize(0x{:x}): \ - set_backing_scene_participation(true) failed: {err}", - window.0 - ); - } - } - - // #143 — report protocol DAMAGE over the ring the reallocate above - // just repainted, at the NEW geometry. - // - // This is the realloc path only, and that is exactly Xorg's gate: - // `compReallocPixmap` allocates a new pixmap only when the BORDERED - // extent differs (`pix_w != pOld->drawable.width || pix_h != - // pOld->drawable.height`, `../xserver/composite/compalloc.c:698`, - // with `pix_w = w + (bw << 1)`), and only that branch calls - // `compSetPixmap(pWin, pNew, bw)` (`:700`). `compSetPixmapVisitWindow` - // then queues `compRepaintBorder` whenever `bw != 0` - // (`../xserver/composite/compwindow.c:137-139`), which subtracts - // `winSize` from `borderClip` and `PaintWindow(..., PW_BORDER)`s the - // difference (`:113-117`). That paint is an ordinary `PolyFillRect` - // on the window's pixmap (`../xserver/mi/miexpose.c:558`), so - // `damagePolyFillRect` (`../xserver/miext/damage/damage.c:1194`) - // reports it. The same-extent branch (`compalloc.c:702-705`) keeps - // `pOld`, never calls `compSetPixmap` and therefore reports nothing — - // which is our `redirected_backing_can_fit` early-return above, - // deliberately an EXACT extent match (`kms/render/backend.rs:20563`). - // - // Ordering matches Xorg's too: `compCopyWindow` carries the bits - // across first and the border repaint is a WorkProc that runs after, - // so the ring is always the freshly painted one. - // - // We only damage the NEW ring. The region the OLD ring vacated on a - // shrink lies outside the window's new outer extent, i.e. in the - // PARENT's area, and Xorg reports it against the parent, never - // against the shrinking window: `miComputeClips` puts the vacated - // area into `pParent->valdata->after.exposed` - // (`../xserver/mi/mivaltree.c:453-460`) and - // `miHandleValidateExposures` hands it to `miWindowExposures` - // (`../xserver/mi/miwindow.c:226`), which paints the PARENT's - // background over it (`../xserver/mi/miexpose.c:387`) — a GC op on - // the parent's drawable, so the damage lands on the parent. - // - // No-op for an unbordered window, for the root and for a - // non-viewable one (the gate lives in `accumulate_damage_to_state`). - let _dropped = accumulate_damage_border_to_state(state, window); -} - -fn effective_redirect_mode_for_window( - state: &ServerState, - window: ResourceId, -) -> Option { - if let Some(record) = state.composite_redirects.get(&(window, false)) { - return Some(record.mode); - } - let parent = state.resources.window(window)?.parent; - state - .composite_redirects - .get(&(parent, true)) - .map(|record| record.mode) + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_error( + &mut buf, + byte_order, + sequence, + code, + bad_value, + minor_opcode, + major_opcode, + )?; + Ok(write_to_client(client, client_id, &buf)) } -/// One window's worth of identity captured *before* destroy_window -/// runs, so the subsequent UnmapNotify+DestroyNotify fanout has stable -/// targets even though the resource table has already let go of the -/// Window struct. -struct PendingDestroy { - window: ResourceId, - parent: ResourceId, - was_mapped: bool, - host_xid: Option, - on_window: Vec, - on_parent: Vec, +fn log_void( + client_id: ClientId, + sequence: SequenceNumber, + name: &str, +) -> io::Result { + debug!("client {} #{} {name}", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) } -fn collect_destroy_order( - table: &crate::resources::ResourceTable, - root: ResourceId, - out: &mut Vec, -) { - let Some(w) = table.window(root) else { - return; +fn xid_out_of_client_range(state: &ServerState, client_id: ClientId, xid: u32) -> bool { + let Some(client) = state.clients.get(&client_id.0) else { + return false; }; - for child in w.children.clone() { - collect_destroy_order(table, child, out); - } - out.push(root); -} - -fn fanout_destroy_sequence_to_state(state: &mut ServerState, pending: &PendingDestroy) { - let window = pending.window; - let parent = pending.parent; - if pending.was_mapped { - let _dropped = fanout_event_to_clients(state, &pending.on_window, |buf, seq, order| { - x11::encode_unmap_notify_event(buf, seq, order, window, window, false); - }); - let _dropped = fanout_event_to_clients(state, &pending.on_parent, |buf, seq, order| { - x11::encode_unmap_notify_event(buf, seq, order, parent, window, false); - }); - } - let _dropped = fanout_event_to_clients(state, &pending.on_window, |buf, seq, order| { - x11::encode_destroy_notify_event(buf, seq, order, window, window); - }); - let _dropped = fanout_event_to_clients(state, &pending.on_parent, |buf, seq, order| { - x11::encode_destroy_notify_event(buf, seq, order, parent, window); - }); -} - -/// Purge every core-visible Present population targeting a destroyed window -/// subtree. Backend-hidden GPU/direct events cannot be cancelled here; the -/// removed window generation makes their later drain discard wire delivery and -/// release only at a safe retirement (direct sources wait for retired-idle). -/// Shared by explicit/COW destruction and both disconnect/zombie paths so -/// numeric XID reuse always starts with fresh CRTC/MSC state. -pub(crate) fn purge_present_for_destroyed_windows( - state: &mut ServerState, - backend: &mut dyn Backend, - windows: &[ResourceId], -) { - let destroyed: HashSet = windows.iter().map(|window| window.0).collect(); - if destroyed.is_empty() { - return; - } - - state - .present_pending_msc - .retain(|pending| !destroyed.contains(&pending.window)); - state - .present_window_msc - .retain(|window, _| !destroyed.contains(window)); - state - .present_window_generations - .retain(|window, _| !destroyed.contains(window)); - state - .present_event_selections - .retain(|_, selection| !destroyed.contains(&selection.window.0)); - - let stale_present_ids: Vec = state - .present_pending_exec - .iter() - .filter_map(|(&pid, entry)| { - destroyed - .contains(&entry.pending.request.window()) - .then_some(pid) - }) - .collect(); - for pid in stale_present_ids { - let Some(entry) = state.present_pending_exec.remove(&pid) else { - continue; - }; - match &entry.pending.wake { - crate::backend::PresentWake::Pixmap { idle_fence_xid } if *idle_fence_xid != 0 => { - if let Err(error) = backend.dri3_trigger_fence(*idle_fence_xid) { - log::warn!( - "PRESENT teardown: trigger idle fence 0x{idle_fence_xid:x} failed: {error}" - ); - } - crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); - } - crate::backend::PresentWake::PixmapSynced { - release, - release_value, - release_syncobj, - } => { - if let Err(error) = release.signal(*release_value) { - log::warn!( - "PRESENT teardown: signal release syncobj 0x{release_syncobj:x}@\ - {release_value} failed: {error}" - ); - } - } - _ => {} - } - if let Some(wait_id) = entry.wait_id { - backend.finish_present_source_wait(wait_id); - state.present_wait_to_id.remove(&wait_id); - } - if let Some(pin) = entry.pin { - backend.release_present_source(pin); - } - } - - let stale_completions: Vec<_> = state - .present_pending_complete - .iter() - .filter(|pending| destroyed.contains(&pending.event.dst_host_xid)) - .map(|pending| pending.event.clone()) - .collect(); - for event in &stale_completions { - // Copy completions (`emit_idle=true`) have already retired their GPU - // read and may release now. Direct completions deliberately remain - // busy until their later retired-idle event; releasing them here could - // hand a still-scanned buffer back to the client. - discard_stale_present_event(state, backend, event, false); - } - state - .present_pending_complete - .retain(|pending| !destroyed.contains(&pending.event.dst_host_xid)); - - let stale_gate_ids: Vec = state - .present_complete_gate - .iter() - .filter_map(|(&id, gate)| destroyed.contains(&gate.dst_window_xid).then_some(id)) - .collect(); - for id in stale_gate_ids { - // The backend completion is still in flight. It is not safe to release - // either a copy source (GPU may still read it) or a direct source - // (scanout may still own it). The generation check in the backend-event - // drain discards its eventual wire event and releases at the matching - // retirement instead. - state.present_complete_gate.remove(&id); - } + let base = client.resource_id_base; + let mask = client.resource_id_mask; + (xid & !mask) != base } -/// Common subtree-destroy used by both DestroyWindow (root = the -/// requested window) and DestroySubwindows (each child of the -/// requested parent). -/// Free every Picture on the doomed `windows`, whichever client owns it, while the -/// window records still exist (Xorg `PictureDestroyWindow`, `render/picture.c:67`). -pub(crate) fn free_pictures_on_destroyed_windows( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - windows: &[ResourceId], -) { - for (pic_xid, owned_pix) in state.resources.remove_pictures_on_windows(windows) { - let _ = backend.render_free_picture(origin, pic_xid); - if let Some(pix_xid) = owned_pix { - let _ = backend.free_pixmap(origin, pix_xid); - } - } +/// Compute the expected ZPixmap data length for `width × height` at +/// `depth`, returning `None` for unsupported depths or arithmetic +/// overflow. Mirrors `nested::zpixmap_expected_len`. +fn zpixmap_expected_len(width: u16, height: u16, depth: u8) -> Option { + let stride_bytes = zpixmap_row_stride(width, depth)?; + stride_bytes.checked_mul(usize::from(height)) } -/// Release each doomed window's redirect backing and drop every redirect record keyed on it, -/// while the window records still exist (Xorg `compDestroyWindow`, `composite/compwindow.c:600`). -/// Surviving `NameWindowPixmap` aliases keep the backing alive until their `FreePixmap`. -pub(crate) fn release_redirects_on_destroyed_windows( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - windows: &[ResourceId], -) { - for window in windows { - crate::core_loop::process_disconnect::unrealize_redirect_backing( - state, backend, origin, *window, - ); - } +/// True for a window that is not viewable (Xorg: not realized); false for pixmaps. +fn window_unviewable(state: &ServerState, id: ResourceId) -> bool { state - .composite_redirects - .retain(|(window, _), _| !windows.contains(window)); + .resources + .window(id) + .is_some_and(|w| w.map_state != crate::resources::MapState::Viewable) } -fn destroy_window_subtree( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - root: ResourceId, -) { - // XI1 device focus inside the dying subtree reverts before the - // tree is torn down (the RevertToParent walk needs the surviving - // ancestors) — Xorg DeleteWindowFromAnyEvents shape. - crate::core_loop::xi1_focus::revert_focus_for_dying_subtree(state, root); - let mut order: Vec = Vec::new(); - collect_destroy_order(&state.resources, root, &mut order); - // Core focus inside the dying subtree reverts before teardown — - // Xorg DeleteWindowFromAnyEvents, same shape as the XI1 revert - // above (the RevertToParent walk needs the surviving ancestors). - if state.core_focus.raw > 1 { - let focus_win = ResourceId(state.core_focus.raw); - if order.contains(&focus_win) { - revert_core_focus_from(state, focus_win, &order); - } - } - let mut pending: Vec = Vec::new(); - for w in &order { - let (parent, was_mapped, host_xid) = - state - .resources - .window(*w) - .map_or((ROOT_WINDOW, false, None), |win| { - ( - win.parent, - win.map_state != MapState::Unmapped, - win.host_xid, - ) - }); - let on_window = subscribers_by_id(state, *w, 0x0002_0000); - let on_parent = subscribers_by_id(state, parent, 0x0008_0000); - pending.push(PendingDestroy { - window: *w, - parent, - was_mapped, - host_xid, - on_window, - on_parent, - }); - } - let attr_pixmap_xids = state.resources.collect_attribute_pixmap_host_xids(root); - free_pictures_on_destroyed_windows(state, backend, origin, &order); - purge_present_for_destroyed_windows(state, backend, &order); - release_redirects_on_destroyed_windows(state, backend, origin, &order); - // Audit #9 — selections owned by any destroyed window in this - // subtree must fire `XFixesSelectionNotify(SelectionWindowDestroy)` - // and clear ownership (Xorg `xfixes/select.c` registers a - // `SelectionWindowDestroy` callback against the resource-delete - // path). MUST run before `destroy_window` drops the resource (so - // subscribers don't reference a half-destroyed window) and BEFORE - // `drop_window_subscriptions` (which clears xfixes_selection_masks - // entries owned by the destroyed window). - drop_selections_owned_by_windows( - state, - &order, - yserver_protocol::x11::xfixes::SELECTION_NOTIFY_WINDOW_DESTROY, - ); - let _ = state.resources.destroy_window(root); - state.drop_window_subscriptions(&order); - // Step 2 (DRIFT 2): the destroyed subtree may have removed a root - // child; reproject the backend top-level order from core (the backend - // backing teardown already ran above). - backend.sync_top_level_order(state); - - // Same orphan rule as every other release site: the destroyed subtree's - // retained background AND border pixmaps may still be client-owned - // (FreePixmap not yet issued) or referenced by windows OUTSIDE the subtree - // (`resources.destroy_window` already ran, so the check sees only - // survivors). Free only the fully orphaned ones. - // - // Borders used to be collected by neither half of this (#133): the - // subtree walk skipped them and so did the gate, so a tile whose only - // remaining reference was a border died with its window and leaked. - for xid in &attr_pixmap_xids { - let Some(handle) = crate::backend::PixmapHandle::from_raw(*xid) else { - continue; - }; - if state.resources.host_xid_still_referenced(handle) { - continue; - } - let _ = backend.free_pixmap(origin, *xid); - state.resources.host_pixmap_freed(*xid); - } - for entry in pending { - if let Some(xid) = entry.host_xid { - backend.unregister_host_window(xid.as_raw()); - let _ = backend.update_host_event_mask( - origin, - xid.as_raw(), - crate::host_x11::POINTER_EVENT_MASK, - false, - ); - let _ = backend.update_host_event_mask( - origin, - xid.as_raw(), - crate::host_x11::SUBWINDOW_EVENT_MASK, - false, - ); - let _ = backend.destroy_subwindow(origin, xid.as_raw()); - } - fanout_destroy_sequence_to_state(state, &entry); - } - // Active core grabs whose grab window just died deactivate (Xorg - // DeleteWindowFromAnyEvents) — the destroyed windows are gone from - // the resource table now, so the viewability probe sees them off. - release_core_grabs_for_unviewable(state, backend); +/// Rectangle in destination-window-local coordinates, used by the +/// X11 CopyArea clipping pipeline. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct CopyAreaSubRect { + x: i16, + y: i16, + width: u16, + height: u16, } -#[allow(clippy::too_many_arguments, clippy::too_many_lines)] -fn handle_render_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, +pub(super) fn write_to_client( + client: &mut crate::server::ClientState, client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use crate::{ - nested::{ChangePictureAttr, change_picture_translate_xids}, - resources::{ARGB_VISUAL, GlyphSetState, PictureState}, - }; - use yserver_protocol::x11::ClientByteOrder; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - // RenderErrBase + BadPicture for the first unknown Picture, in Xorg's per-request order. - macro_rules! verify_pictures { - ($($id:expr),+) => { - if let Some(bad) = first_missing_picture(state, &[$($id),+]) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::RENDER_FIRST_ERROR + 1, - bad.0, - u16::from(minor), - header.opcode, - ); - } - }; - } - match minor { - 0 => { - let (major, minor_ver) = backend.render_query_version(origin).unwrap_or((0, 11)); - let mut buf: Vec = Vec::with_capacity(32); - x11::write_render_query_version_reply( - &mut buf, byte_order, sequence, major, minor_ver, - )?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - 1 => { - let mut buf: Vec = Vec::with_capacity(256); - x11::write_render_query_pict_formats_reply( - &mut buf, - byte_order, - sequence, - crate::resources::ROOT_VISUAL, - ARGB_VISUAL, - crate::resources::GLMARK_VISUAL, - )?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - 2 => { - let mut buf: Vec = Vec::with_capacity(32); - x11::write_render_query_pict_index_values_reply(&mut buf, byte_order, sequence)?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - 4 => { - let Some(req) = x11::render_create_picture_request(body) else { - return Ok(RequestOutcome::Handled); - }; - // Xorg dixLookupDrawable (render.c:575): BadDrawable if unknown, BadMatch for - // an InputOnly window (dix/dixutils.c:208-213). - let input_only = match state.resources.window(req.drawable) { - Some(w) => w.class == crate::resources::WindowClass::InputOnly, - None if state.resources.pixmap(req.drawable).is_some() => false, - None => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.drawable.0, - u16::from(minor), - header.opcode, - ); - } - }; - if input_only { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.drawable.0, - u16::from(minor), - header.opcode, - ); - } - let damage_drawable = render_picture_damage_drawable(state, req.drawable); - let drawable_origin = state - .resources - .window(req.drawable) - .map(|w| (w.x, w.y)) - .unwrap_or((0, 0)); - // A window Picture names the window itself, never its redirect backing: the - // backend resolves the window's current storage or backing at each use. - let picture_window = state.resources.window(req.drawable).map(|_| req.drawable); - let host_drawable_handle = match state.resources.window(req.drawable) { - Some(w) => w.host_xid.map(crate::backend::AnyHandle::Window), - None => state - .resources - .host_drawable_target(req.drawable) - .map(|t| t.host_handle()), - }; - let host_pic = host_drawable_handle.and_then(|host_drawable| { - backend - .render_create_picture( - origin, - host_drawable, - req.format, - req.value_mask, - &req.values, - ) - .ok() - .flatten() - }); - // Core's registry is authoritative: no X error was sent, so the Picture exists. - match host_pic { - Some(hp) => backend.set_picture_drawable_origin(hp.as_raw(), drawable_origin), - None => debug!( - "client {} #{} RENDER::CreatePicture 0x{:x}: backend could not back it; ops on it are no-ops", - client_id.0, sequence.0, req.picture.0 - ), - } - state.resources.create_picture( - req.picture, - PictureState { - client: client_id, - host_picture_xid: host_pic, - host_owned_pixmap: None, - kind: crate::resources::PictureKind::Drawable, - drawable: Some(damage_drawable), - window: picture_window, - }, - ); - } - 5 => { - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - verify_pictures!(pic_id); - let value_mask = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let translated = change_picture_translate_xids(value_mask, &body[8..], |attr, xid| { - let resource = ResourceId(xid); - match attr { - ChangePictureAttr::ClipMask => state - .resources - .pixmap(resource) - .and_then(|p| p.host_xid) - .map(|h| h.as_raw()), - ChangePictureAttr::AlphaMap => state - .resources - .picture(resource) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()), - } - }); - let Some(translated_values) = translated else { - return Ok(RequestOutcome::Handled); - }; - let mut patched = Vec::with_capacity(8 + translated_values.len()); - patched.extend_from_slice(&body[..8]); - patched.extend_from_slice(&translated_values); - let host_pic = state - .resources - .picture(pic_id) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let Some(hp) = host_pic { - let _ = backend.render_change_picture(origin, hp, &patched); - } - } - 6 => { - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - verify_pictures!(pic_id); - let host_pic = state - .resources - .picture(pic_id) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let Some(hp) = host_pic { - let _ = backend.render_set_picture_clip_rectangles(origin, hp, body); - } - } - 7 => { - let Some(pic_id) = x11::render_free_resource_id(body) else { - return Ok(RequestOutcome::Handled); - }; - verify_pictures!(pic_id); - let st = state.resources.free_picture(pic_id); - if let Some(st) = st { - if let Some(hp) = st.host_picture_xid { - let _ = backend.render_free_picture(origin, hp.as_raw()); - } - if let Some(pix) = st.host_owned_pixmap { - let _ = backend.free_pixmap(origin, pix.as_raw()); - } - } - } - 8 => { - let Some(req) = x11::render_composite_request(body) else { - return Ok(RequestOutcome::Handled); - }; - verify_pictures!(req.dst); - if dst_picture_is_sourceless(state, req.dst) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.dst.0, - u16::from(minor), - header.opcode, - ); - } - verify_pictures!(req.src); - if req.mask.0 != 0 { - verify_pictures!(req.mask); - } - if dst_picture_window_unviewable(state, req.dst) { - return Ok(RequestOutcome::Handled); - } - let host_src = state - .resources - .picture(req.src) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - let host_mask = if req.mask.0 == 0 { - Some(0) - } else { - state - .resources - .picture(req.mask) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()) - }; - let host_dst = state - .resources - .picture(req.dst) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let (Some(host_src), Some(host_mask), Some(host_dst)) = - (host_src, host_mask, host_dst) - { - let painted = backend - .render_composite( - origin, req.op, host_src, host_mask, host_dst, req.src_x, req.src_y, - req.mask_x, req.mask_y, req.dst_x, req.dst_y, req.width, req.height, - ) - .unwrap_or_default(); - if let Some(dst_drawable) = - state.resources.picture(req.dst).and_then(|p| p.drawable) - { - for r in &painted { - let _dropped = accumulate_damage_to_state( - state, - dst_drawable, - r.x, - r.y, - r.width, - r.height, - ); - } - } - } - } - 10..=13 => { - // Trapezoids (10), Triangles (11), TriStrip (12), TriFan (13). - // All four share the same fixed prefix; the variable body - // layout differs and is handled by the backend. - if body.len() < 20 { - return Ok(RequestOutcome::Handled); - } - let op = body[0]; - let src = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let dst = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let ynest_mask_format = u32::from_le_bytes([body[12], body[13], body[14], body[15]]); - let src_x = i16::from_le_bytes([body[16], body[17]]); - let src_y = i16::from_le_bytes([body[18], body[19]]); - let primitives = &body[20..]; - verify_pictures!(src, dst); - if dst_picture_is_sourceless(state, dst) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - dst.0, - u16::from(minor), - header.opcode, - ); - } - if dst_picture_window_unviewable(state, dst) { - return Ok(RequestOutcome::Handled); - } - let host_src = state - .resources - .picture(src) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - let host_dst = state - .resources - .picture(dst) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - let host_mask_format = if ynest_mask_format == 0 { - Some(0u32) - } else { - backend.render_format_for_ynest_id(ynest_mask_format) - }; - if let (Some(host_src), Some(host_dst), Some(host_mask_fmt)) = - (host_src, host_dst, host_mask_format) - { - let painted = if minor == 10 { - backend - .render_trapezoids( - origin, - op, - host_src, - host_dst, - host_mask_fmt, - src_x, - src_y, - primitives, - 0, - 0, - ) - .unwrap_or_default() - } else { - backend - .render_triangles_op( - origin, - minor, - op, - host_src, - host_dst, - host_mask_fmt, - src_x, - src_y, - primitives, - 0, - 0, - ) - .unwrap_or_default() - }; - if let Some(dst_drawable) = state.resources.picture(dst).and_then(|p| p.drawable) { - for r in &painted { - let _dropped = accumulate_damage_to_state( - state, - dst_drawable, - r.x, - r.y, - r.width, - r.height, - ); - } - } - } - } - 17 => { - let Some((gs_id, fmt)) = x11::render_create_glyphset_request(body) else { - return Ok(RequestOutcome::Handled); - }; - let host_gs = backend.render_create_glyphset(origin, fmt).ok().flatten(); - if let Some(host_gs) = host_gs { - state.resources.create_glyphset( - gs_id, - GlyphSetState { - client: client_id, - host_glyphset_xid: host_gs, - }, - ); - } - } - 18 => { - let Some((new_glyphset, existing)) = x11::render_reference_glyphset_request(body) - else { - return Ok(RequestOutcome::Handled); - }; - let _ = state - .resources - .reference_glyphset(client_id, new_glyphset, existing); - } - 19 => { - let Some(gs_id) = x11::render_free_resource_id(body) else { - return Ok(RequestOutcome::Handled); - }; - let st = state.resources.free_glyphset(gs_id); - if let Some(st) = st { - let _ = backend.render_free_glyphset(origin, st.host_glyphset_xid.as_raw()); - } - } - 20 => { - let Some((gs_id, tail)) = x11::render_add_glyphs_request(body) else { - return Ok(RequestOutcome::Handled); - }; - let host_gs = state - .resources - .glyphset(gs_id) - .map(|g| g.host_glyphset_xid.as_raw()); - if let Some(host_gs) = host_gs { - let _ = backend.render_add_glyphs(origin, host_gs, &tail); - } - } - 22 => { - let Some((gs_id, glyph_ids)) = x11::render_free_glyphs_request(body) else { - return Ok(RequestOutcome::Handled); - }; - let host_gs = state - .resources - .glyphset(gs_id) - .map(|g| g.host_glyphset_xid.as_raw()); - if let Some(host_gs) = host_gs { - let _ = backend.render_free_glyphs(origin, host_gs, &glyph_ids); - } - } - 23..=25 => { - let Some(req) = x11::render_composite_glyphs_request(body) else { - // Silently dropping this draws nothing and reports no - // error, which looks exactly like "the text is invisible" - // (#137). Say so. - debug!( - "client {} #{} RENDER::CompositeGlyphs{} -> DROPPED (body not parsed, {} bytes)", - client_id.0, - sequence.0, - 8u16 << (u16::from(minor) - 23), - body.len(), - ); - return Ok(RequestOutcome::Handled); - }; - verify_pictures!(req.src, req.dst); - if dst_picture_is_sourceless(state, req.dst) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.dst.0, - u16::from(minor), - header.opcode, - ); - } - if dst_picture_window_unviewable(state, req.dst) { - return Ok(RequestOutcome::Handled); - } - let host_src = state - .resources - .picture(req.src) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - let host_dst = state - .resources - .picture(req.dst) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - let host_gs = state - .resources - .glyphset(req.glyphset) - .map(|g| g.host_glyphset_xid.as_raw()); - if host_src.is_none() || host_dst.is_none() || host_gs.is_none() { - debug!( - "client {} #{} RENDER::CompositeGlyphs src=0x{:x}{} dst=0x{:x}{} glyphset=0x{:x}{} \ - -> DROPPED (unresolved resource)", - client_id.0, - sequence.0, - req.src.0, - if host_src.is_none() { " MISSING" } else { "" }, - req.dst.0, - if host_dst.is_none() { " MISSING" } else { "" }, - req.glyphset.0, - if host_gs.is_none() { " MISSING" } else { "" }, - ); - } - if let (Some(host_src), Some(host_dst), Some(host_gs)) = (host_src, host_dst, host_gs) { - let mask_fmt = if req.mask_format == 0 { - 0 - } else { - backend - .render_format_for_ynest_id(req.mask_format) - .unwrap_or(0) - }; - let painted = backend - .render_composite_glyphs( - origin, minor, req.op, host_src, host_dst, mask_fmt, host_gs, req.src_x, - req.src_y, &req.items, 0, 0, - ) - .unwrap_or_default(); - debug!( - "client {} #{} RENDER::CompositeGlyphs{} op={} src=0x{:x} dst=0x{:x} gs=0x{:x} \ - mask_format={}->{} items={} src_xy=({},{}) -> painted {} rect(s)", - client_id.0, - sequence.0, - 8u16 << (u16::from(minor) - 23), - req.op, - req.src.0, - req.dst.0, - req.glyphset.0, - req.mask_format, - mask_fmt, - req.items.len(), - req.src_x, - req.src_y, - painted.len(), - ); - if let Some(dst_drawable) = - state.resources.picture(req.dst).and_then(|p| p.drawable) - { - for r in &painted { - let _dropped = accumulate_damage_to_state( - state, - dst_drawable, - r.x, - r.y, - r.width, - r.height, - ); - } - } - } - } - 26 => { - let Some(req) = x11::render_fill_rectangles_request(body) else { - return Ok(RequestOutcome::Handled); - }; - verify_pictures!(req.dst); - if dst_picture_is_sourceless(state, req.dst) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.dst.0, - u16::from(minor), - header.opcode, - ); - } - if dst_picture_window_unviewable(state, req.dst) { - return Ok(RequestOutcome::Handled); - } - let host_dst = state - .resources - .picture(req.dst) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let Some(host_dst) = host_dst { - // ClipByChildren: a FillRectangles op=Clear on a window - // fully covered by a mapped child (mate-panel systray - // socket under its XEMBED icon) is a no-op in Xorg — - // empty composite clip → nothing painted, no damage. We - // historically painted + damaged the full drawable, which - // both wiped the embedded icon's backing AND drove the - // per-frame tray recomposite loop. Clip the paint rects to - // window-minus-children; if the result is empty the whole - // op is skipped. Pixmaps / childless windows pass through - // unchanged. - let dst_drawable = state.resources.picture(req.dst).and_then(|p| p.drawable); - let painted_rects = match dst_drawable { - Some(d) => clip_fill_rects_by_children(state, d, &req.rects), - None => req.rects.clone(), - }; - if !painted_rects.is_empty() { - let _ = backend.render_fill_rectangles( - origin, - host_dst, - req.op, - req.color, - &painted_rects, - 0, - 0, - ); - if let Some(d) = dst_drawable { - let _dropped = accumulate_damage_clip_by_children_to_state(state, d); - } - } - } - } - 27 => { - if body.len() < 12 { - return Ok(RequestOutcome::Handled); - } - let cursor_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let src_pic_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - verify_pictures!(src_pic_id); - let x = u16::from_le_bytes([body[8], body[9]]); - let y = u16::from_le_bytes([body[10], body[11]]); - let host_src = state - .resources - .picture(src_pic_id) - .and_then(|p| p.host_picture_xid); - if let Some(host_src) = host_src - && let Some(cursor_handle) = backend - .render_create_cursor(origin, host_src, x, y) - .ok() - .flatten() - { - state.resources.create_glyph_cursor(client_id, cursor_id); - state - .resources - .set_cursor_host_xid(cursor_id, cursor_handle); - } - } - 28 => { - if body.len() < 40 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - verify_pictures!(pic_id); - let host_pic = state - .resources - .picture(pic_id) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let Some(hp) = host_pic { - let _ = backend.render_set_picture_transform(origin, hp, body); - } - } - 29 => { - let mut buf: Vec = Vec::with_capacity(64); - x11::write_render_query_filters_reply(&mut buf, byte_order, sequence)?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - 30 => { - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - verify_pictures!(pic_id); - let host_pic = state - .resources - .picture(pic_id) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let Some(hp) = host_pic { - let _ = backend.render_set_picture_filter(origin, hp, body); - } - } - 33 => { - let Some((pic_id, color)) = x11::render_create_solid_fill_request(body) else { - return Ok(RequestOutcome::Handled); - }; - let host_pic = backend - .render_create_solid_fill(origin, color) - .ok() - .flatten(); - state.resources.create_picture( - pic_id, - PictureState { - client: client_id, - host_picture_xid: host_pic, - host_owned_pixmap: None, - kind: crate::resources::PictureKind::Sourceless, - drawable: None, - window: None, - }, - ); - } - 34 => { - if body.len() < 24 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let host_pic = backend - .render_create_linear_gradient(origin, body) - .ok() - .flatten(); - state.resources.create_picture( - pic_id, - PictureState { - client: client_id, - host_picture_xid: host_pic, - host_owned_pixmap: None, - kind: crate::resources::PictureKind::Sourceless, - drawable: None, - window: None, - }, - ); - } - 35 => { - if body.len() < 32 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let host_pic = backend - .render_create_radial_gradient(origin, body) - .ok() - .flatten(); - state.resources.create_picture( - pic_id, - PictureState { - client: client_id, - host_picture_xid: host_pic, - host_owned_pixmap: None, - kind: crate::resources::PictureKind::Sourceless, - drawable: None, - window: None, - }, - ); - } - 31 => { - // RENDER::CreateAnimCursor — body: cid(4), [cursor(4), - // delay(4)]*N. Port of Xorg - // `render/render.c::ProcRenderCreateAnimCursor:1783`: - // validate cid is a fresh client-range xid, validate every - // sub-cursor exists, register the cid as a real Cursor - // resource so downstream CWA(CWCursor=this) / - // XFixesSetCursorName / DefineCursor see a live xid. - // - // Validation: odd pair bytes → BadLength; zero frames → - // BadValue; nested animated sub-cursor → BadMatch (Xorg - // animcur.c:316). - // - // Animation is delegated to `backend.create_anim_cursor`; - // backends returning `Ok(None)` (default / ynest) degenerate - // to frame 0's handle. Previously this arm was a stub that - // silently dropped the xid — combined with the BadCursor gate - // in handle_change_window_attributes, that wedged caja / - // thunar on every app launch via marco's busy-cursor path. - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let cursor_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let validation_failed = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - let owned = crate::server::IdAllocator::validate_owned( - cursor_id.0, - handle.resource_id_base, - handle.resource_id_mask, - ); - !owned || state.resources.xid_in_use(cursor_id) - }; - if validation_failed { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - cursor_id.0, - u16::from(minor), - header.opcode, - ); - } - let pairs = &body[4..]; - // Xorg fidelity (render.c:1796,1801): odd request length - // → BadLength; zero frames → BadValue. - if !pairs.len().is_multiple_of(8) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - if pairs.is_empty() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(minor), - header.opcode, - ); - } - let mut first_host: Option = None; - let mut frames: Vec<(crate::backend::CursorHandle, u32)> = - Vec::with_capacity(pairs.len() / 8); - for chunk in pairs.chunks_exact(8) { - let sub = ResourceId(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])); - let delay = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); - if !state.resources.cursor_exists(sub) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - sub.0, - u16::from(minor), - header.opcode, - ); - } - // Xorg refuses nested animated cursors (animcur.c:316). - // bad_value stays 0: AnimCursorCreate returns BadMatch - // without setting client->errorValue. - if state.resources.cursor_is_anim(sub) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - u16::from(minor), - header.opcode, - ); - } - if let Some(host_raw) = state.resources.cursor_host_xid(sub) { - if first_host.is_none() { - first_host = Some(host_raw); - } - if let Some(h) = crate::backend::CursorHandle::from_raw(host_raw) { - frames.push((h, delay)); - } - } - } - // Backend-side animation. `Ok(None)` (default impl / - // ynest) → static degeneration to frame 0's handle. A - // backend Err is "can't happen" after the validation - // above — log and degenerate rather than swallowing - // silently (spec "Error handling"). - let anim_handle = if frames.is_empty() { - log::warn!( - "client {} RENDER::CreateAnimCursor: no sub-cursor has a host handle; \ - cursor 0x{:x} registered without backend animation", - client_id.0, - cursor_id.0, - ); - None - } else { - match backend.create_anim_cursor(origin, &frames) { - Ok(handle) => handle, - Err(e) => { - log::warn!( - "client {} RENDER::CreateAnimCursor backend failure ({e}); \ - degenerating to first frame", - client_id.0, - ); - None - } - } - }; - state.resources.create_glyph_cursor(client_id, cursor_id); - state.resources.set_cursor_anim(cursor_id); - if let Some(handle) = anim_handle { - state.resources.set_cursor_host_xid(cursor_id, handle); - log::debug!( - "client {} RENDER::CreateAnimCursor cursor=0x{:x} animated \ - ({} frames, backend handle 0x{:x})", - client_id.0, - cursor_id.0, - frames.len(), - handle.as_raw(), - ); - } else if let Some(host_raw) = first_host - && let Some(handle) = crate::backend::CursorHandle::from_raw(host_raw) - { - state.resources.set_cursor_host_xid(cursor_id, handle); - log::debug!( - "client {} RENDER::CreateAnimCursor cursor=0x{:x} (static \ - degeneration to first sub-cursor host_xid=0x{host_raw:x})", - client_id.0, - cursor_id.0, - ); - } - } - 36 => { - // CreateConicalGradient: registered so the client can name it; rendering with it - // is not implemented, so ops that use it stay no-ops. - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - state.resources.create_picture( - pic_id, - PictureState { - client: client_id, - host_picture_xid: None, - host_owned_pixmap: None, - kind: crate::resources::PictureKind::Sourceless, - drawable: None, - window: None, - }, - ); - } - 32 => { - // AddTraps — backend dispatch is a stub, but match the - // damage pattern of the other paint vectors so a future - // real impl doesn't silently miss compositor wakeups. - // Wasted compositor recomposite on a no-op paint is - // harmless; the alternative (no damage call) is a - // silent gap on a real impl. Body: pic(4) x_off(2) - // y_off(2) then variable trapezoid list. - if body.len() >= 4 { - let pic = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - verify_pictures!(pic); - if let Some(dst_drawable) = state.resources.picture(pic).and_then(|p| p.drawable) { - let _dropped = accumulate_damage_full_to_state(state, dst_drawable); - } - } - } - other if other > RENDER_LAST_REQUEST => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - _ => { - debug!( - "client {} #{} RENDER::known unsupported minor={}", - client_id.0, sequence.0, minor - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// One monitor as reported by both RANDR `GetMonitors` and the XINERAMA -/// extension. This is the single source of truth so their counts/order cannot -/// diverge. -#[derive(Clone)] -pub(crate) struct ActiveMonitor { - pub name: String, - pub output_id: u32, - pub primary: bool, - pub x: i16, - pub y: i16, - pub width: u16, - pub height: u16, - pub width_mm: u32, - pub height_mm: u32, -} - -fn active_monitors(state: &ServerState) -> Vec { - // One automatic monitor per ASSIGNED output (Xorg builds an automatic - // monitor for an output with a current CRTC). A lightweight connection - // query does not detach that CRTC, so a transient disconnected+assigned - // output remains present until the heavy topology path turns it off. - // `primary` is the RANDR primary output, which itself prefers an assigned - // output — the first output in the list may be off, so `i == 0` is wrong. - let primary = state.randr.primary_output; - state - .randr - .enabled_outputs() - .map(|output| { - let width_mm = if output.mm_width > 0 { - output.mm_width - } else { - ((u32::from(output.width) * 254 + 480) / 960).max(1) - }; - let height_mm = if output.mm_height > 0 { - output.mm_height - } else { - ((u32::from(output.height) * 254 + 480) / 960).max(1) - }; - ActiveMonitor { - name: output.name.clone(), - output_id: output.output_id, - primary: output.output_id == primary, - x: output.x, - y: output.y, - width: output.width, - height: output.height, - width_mm, - height_mm, - } - }) - .collect() -} - -/// Record an unsupported RANDR minor and report whether this is the first -/// occurrence for this server instance. -fn mark_randr_unsupported_warned(state: &mut ServerState, minor: u8) -> bool { - let Some(bit) = 1u64.checked_shl(u32::from(minor)) else { - return true; - }; - let first = state.randr_unsupported_warned_mask & bit == 0; - state.randr_unsupported_warned_mask |= bit; - first -} - -fn warn_randr_unsupported_once( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - minor: u8, - request_name: &str, - action: &str, -) { - if mark_randr_unsupported_warned(state, minor) { - log::warn!( - "client {} #{} RANDR::{} is unsupported; {}", - client_id.0, - sequence.0, - request_name, - action, - ); - } else { - debug!( - "client {} #{} RANDR::{} remains unsupported; {}", - client_id.0, sequence.0, request_name, action, - ); - } -} - -fn handle_randr_request( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, randr as x11randr}; - const RANDR_MAJOR_OPCODE: u8 = 128; - fn crtc_is_leased(_state: &ServerState, _crtc: u32) -> bool { - false - } - fn provider_relationship_protocol_error( - error: crate::randr::ProviderRelationshipError, - ) -> (u8, u32) { - match error { - crate::randr::ProviderRelationshipError::UnknownProvider(provider) => { - (RANDR_BAD_PROVIDER, provider) - } - // Xorg returns BadValue for a missing provider capability or an - // initiating provider that is not a GPU screen without assigning - // client->errorValue, so the wire value remains zero. - crate::randr::ProviderRelationshipError::MissingCapability(_) - | crate::randr::ProviderRelationshipError::NotGpuProvider(_) => { - (x11::error::BAD_VALUE, 0) - } - } - } - fn request_xid(body: &[u8]) -> u32 { - body.get(0..4) - .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) - .unwrap_or(0) - } - fn output_exists(state: &ServerState, output: u32) -> bool { - state - .randr - .outputs - .iter() - .any(|candidate| candidate.output_id == output) - } - fn crtc_exists(state: &ServerState, crtc: u32) -> bool { - state - .randr - .outputs - .iter() - .any(|output| output.crtc_id == crtc) - } - /// Backend-synthesized read-only identity properties (`EDID` / - /// `EDID_DATA` / `ConnectorType`), resolved live from - /// `Backend::output_identity` rather than stored. Consulted only when - /// `output_id` has no matching entry in `state.randr_output_properties` - /// — a real store entry always shadows the synthesized value, matching - /// Xorg's generic property store (a client `ChangeOutputProperty` on - /// e.g. `EDID` overwrites whatever the driver put there). - fn synthetic_output_property( - state: &mut ServerState, - backend: &mut dyn Backend, - output_id: u32, - property: AtomId, - ) -> Option<(u32, u8, Vec)> { - const XA_ATOM: u32 = 4; - const XA_INTEGER: u32 = 19; - let prop_name = state.atoms.name(property).map(str::to_owned); - let identity = backend.output_identity(output_id); - match (prop_name.as_deref(), identity) { - (Some("EDID" | "EDID_DATA"), Some((edid, _))) if !edid.is_empty() => { - Some((XA_INTEGER, 8, edid)) - } - (Some("ConnectorType"), Some((_, ctype))) if !ctype.is_empty() => { - let atom = state.atoms.intern(&ctype, false).0; - Some((XA_ATOM, 32, atom.to_le_bytes().to_vec())) - } - _ => None, - } - } - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - match minor { - x11randr::RR_QUERY_VERSION => { - let (reply_major, reply_minor) = x11randr::parse_query_version(body) - .map(|r| { - let reply_major = x11randr::MAJOR_VERSION; - let reply_minor = if r.major < x11randr::MAJOR_VERSION { - r.minor - } else { - x11randr::MINOR_VERSION - }; - (reply_major, reply_minor) - }) - .unwrap_or((x11randr::MAJOR_VERSION, x11randr::MINOR_VERSION)); - let buf = x11randr::encode_query_version_reply( - byte_order, - sequence, - reply_major, - reply_minor, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_SCREEN_SIZE_RANGE => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let (min_w, min_h, max_w, max_h) = state.randr.screen_size_range(); - let buf = x11randr::encode_get_screen_size_range_reply( - byte_order, sequence, min_w, min_h, max_w, max_h, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_SCREEN_RESOURCES => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // Force a connector re-probe before replying (Xorg - // RRGetInfo force_query=TRUE). A probe failure surfaces as - // BadAlloc, matching Xorg. GetScreenResourcesCurrent below - // skips this and serves the cached view. - if let Err(e) = backend.reprobe_connectors(state) { - log::warn!("RRGetScreenResources reprobe failed: {e}"); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - let resources = state.randr.screen_resources_current(); - let buf = x11randr::encode_get_screen_resources_current_reply( - byte_order, sequence, &resources, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_SCREEN_RESOURCES_CURRENT => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let resources = state.randr.screen_resources_current(); - let buf = x11randr::encode_get_screen_resources_current_reply( - byte_order, sequence, &resources, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_OUTPUT_INFO => { - let Some(req) = x11randr::parse_output_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(info_data) = state.randr.output_info(req.output, req.config_timestamp) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - req.output, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - // The `crtcs` array is the output's *possible* CRTCs, not the - // currently-assigned one (which is 0 for a connected-but-off - // output and would advertise an invalid crtcs=[0]). - let crtc_ids = info_data.possible_crtcs.as_slice(); - let mode_ids = info_data.mode_ids.as_slice(); - let name_bytes = info_data.name.as_bytes(); - let buf = x11randr::encode_get_output_info_reply( - byte_order, - sequence, - &x11randr::OutputInfoReply { - timestamp: info_data.timestamp, - crtc: info_data.crtc, - width_mm: info_data.width_mm, - height_mm: info_data.height_mm, - connection: info_data.connection, - subpixel_order: 0, - crtcs: crtc_ids, - modes: mode_ids, - num_preferred: info_data.num_preferred, - clones: &[], - name: name_bytes, - }, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_CRTC_INFO => { - let Some(req) = x11randr::parse_crtc_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(crtc_data) = state.randr.crtc_info(req.crtc, req.config_timestamp) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - req.crtc, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - let buf = x11randr::encode_get_crtc_info_reply( - byte_order, - sequence, - &x11randr::CrtcInfoReply { - timestamp: crtc_data.timestamp, - x: crtc_data.x, - y: crtc_data.y, - width: crtc_data.width, - height: crtc_data.height, - mode: crtc_data.mode_id, - rotation: 1, - rotations: 1, - outputs: &crtc_data.outputs, - possible: &crtc_data.possible_outputs, - }, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SET_CRTC_TRANSFORM => { - let Some(req) = x11randr::parse_set_crtc_transform_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if !crtc_exists(state, req.crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - req.crtc, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - if !req.is_identity_transform() { - // Arbitrary projective transforms need an internal - // composition path; they cannot be represented as direct - // KMS CRTC state. - warn_randr_unsupported_once( - state, - client_id, - sequence, - minor, - "SetCrtcTransform", - "rejecting non-identity transform with BadMatch", - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.crtc, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - if req.filter_name_len != 0 || req.filter_param_count != 0 { - // The filter has no observable effect for an identity - // transform, but yserver does not retain it for GetCrtcTransform. - warn_randr_unsupported_once( - state, - client_id, - sequence, - minor, - "SetCrtcTransform", - "accepting identity transform but not retaining its filter", - ); - } - return Ok(RequestOutcome::Handled); - } - x11randr::RR_GET_CRTC_TRANSFORM => { - let crtc = request_xid(body); - if !crtc_exists(state, crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - crtc, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let buf = x11randr::encode_get_crtc_transform_reply(byte_order, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_LIST_OUTPUT_PROPERTIES => { - let output_id = request_xid(body); - if !output_exists(state, output_id) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - output_id, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // Real client-set properties first, then the backend-synthesized - // identity properties (EDID + EDID_DATA + ConnectorType) iff the - // backend has EDID for this output and no real entry already - // shadows that atom name. - let mut atoms: Vec = state - .randr_output_properties - .get(&output_id) - .map(|entries| entries.iter().map(|(atom, _)| atom.0).collect()) - .unwrap_or_default(); - if let Some((edid, _)) = backend.output_identity(output_id) - && !edid.is_empty() - { - for name in ["EDID", "EDID_DATA", "ConnectorType"] { - let atom = state.atoms.intern(name, false).0; - if !atoms.contains(&atom) { - atoms.push(atom); - } - } - } - let buf = x11randr::encode_list_output_properties_reply(byte_order, sequence, &atoms); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_QUERY_OUTPUT_PROPERTY => { - // Error packets carry the EXTENSION major opcode (128) with - // the request's minor in the minor field — passing the minor - // as `major_opcode` (pre-fix) made xtrace print "major=11, - // minor=0" for this BadName. - let Some(req) = x11randr::parse_output_property_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(x11randr::RR_QUERY_OUTPUT_PROPERTY), - RANDR_MAJOR_OPCODE, - ); - }; - if !output_exists(state, req.output) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let property = AtomId(req.property); - let real = state - .randr_output_properties - .get(&req.output) - .and_then(|entries| entries.iter().find(|(atom, _)| *atom == property)); - let buf = if let Some((_, prop)) = real { - x11randr::encode_query_output_property_reply( - byte_order, - sequence, - prop.is_pending, - prop.range, - prop.immutable, - &prop.valid_values, - ) - } else if synthetic_output_property(state, backend, req.output, property).is_some() { - x11randr::encode_query_output_property_reply( - byte_order, - sequence, - false, - false, - true, - &[], - ) - } else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_NAME, - req.property, - u16::from(x11randr::RR_QUERY_OUTPUT_PROPERTY), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_CONFIGURE_OUTPUT_PROPERTY => { - // No lease check (real output leases can't exist — CreateLease - // always fails) and no immutable check: Xorg's wire handler - // hardcodes `immutable = FALSE` for a client-issued Configure, so - // `prop->immutable && !immutable` can only fire for a - // driver-marked property, which yserver never creates. - let Some(req) = x11randr::parse_configure_output_property_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if !output_exists(state, req.output) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // Ranges must have an even number of values (min,max pairs). - if req.range && req.valid_values.len() % 2 != 0 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let property = AtomId(req.property); - let entries = state.randr_output_properties.entry(req.output).or_default(); - let prop = match entries.iter_mut().find(|(atom, _)| *atom == property) { - Some((_, prop)) => prop, - None => { - // Prepend, matching Xorg's RRCreateOutputProperty list - // insertion (see the ChangeOutputProperty handler above). - entries.insert(0, (property, crate::randr::RandrOutputProperty::default())); - &mut entries[0].1 - } - }; - // "Property moving from pending to non-pending loses any pending - // values" (Xorg RRConfigureOutputProperty). - if prop.is_pending && !req.pending { - prop.pending = None; - } - prop.is_pending = req.pending; - prop.range = req.range; - prop.valid_values = req.valid_values; - return Ok(RequestOutcome::Handled); - } - x11randr::RR_CHANGE_OUTPUT_PROPERTY => { - // Order mirrors Xorg's ProcRRChangeOutputProperty: mode, then - // format, then length consistency, then output, then the - // property/type atoms — a request that violates several of - // these at once must fail with the same error Xorg reports. - let Some(req) = x11randr::parse_change_output_property_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(mode) = properties::ChangeMode::from_protocol(req.mode) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.mode), - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(format) = properties::PropertyFormat::from_protocol(req.format) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.format), - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let expected_bytes = (req.n_units as usize).checked_mul(format.bytes()); - if expected_bytes != Some(req.data.len()) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - if !output_exists(state, req.output) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let property = AtomId(req.property); - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.property, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let prop_type = AtomId(req.prop_type); - if !state.atoms.exists(prop_type) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.prop_type, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let entries = state.randr_output_properties.entry(req.output).or_default(); - let slot = entries.iter().position(|(atom, _)| *atom == property); - // Only a property previously marked pending-capable via - // ConfigureOutputProperty writes into `.pending` (and skips the - // notify) — the wire request itself has no pending flag; Xorg's - // ProcRRChangeOutputProperty always passes `pending=TRUE` - // internally, and RRChangeOutputProperty reduces that to - // `prop->is_pending`. - let is_pending_configured = slot.is_some_and(|i| entries[i].1.is_pending); - let existing_value = slot.and_then(|i| { - if is_pending_configured { - entries[i].1.pending.clone() - } else { - entries[i].1.current.clone() - } - }); - let new_value = match properties::apply_change( - existing_value.as_ref(), - mode, - prop_type, - format, - &req.data, - ) { - Ok(v) => v, - Err(properties::ChangePropertyError::BadMatch) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - Err(properties::ChangePropertyError::BadAlloc) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - Err(properties::ChangePropertyError::BadValue) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - }; - match slot { - Some(i) => { - if is_pending_configured { - entries[i].1.pending = Some(new_value); - } else { - entries[i].1.current = Some(new_value); - } - } - // Xorg's RRCreateOutputProperty prepends a newly created - // property onto the output's property list, so - // ListOutputProperties enumerates newest-first. - None => entries.insert( - 0, - ( - property, - crate::randr::RandrOutputProperty { - current: Some(new_value), - ..Default::default() - }, - ), - ), - } - // Xorg's `sendevent` is unconditional in `RRChangeOutputProperty` - // (`ProcRRChangeOutputProperty` always passes `sendevent=TRUE`) - // — only the unrelated `RRNoticePropertyChange` driver hook is - // gated on `is_pending`. The wire notify fires regardless of - // whether this write landed in `.current` or `.pending`. - state.randr.timestamp = state.timestamp_now(); - super::run::notify_randr_output_property_changed( - state, - req.output, - property, - x11randr::PROPERTY_NEW_VALUE, - ); - return Ok(RequestOutcome::Handled); - } - x11randr::RR_DELETE_OUTPUT_PROPERTY => { - // No lease check: real output leases can't exist. - let Some(req) = x11randr::parse_output_property_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if !output_exists(state, req.output) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let property = AtomId(req.property); - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.property, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let entries = state.randr_output_properties.entry(req.output).or_default(); - let Some(index) = entries.iter().position(|(atom, _)| *atom == property) else { - // Known caveat: a synthetic-only identity atom (EDID / - // EDID_DATA / ConnectorType) with no real store entry - // returns BadName here rather than Xorg's BadAccess for an - // immutable driver property — no real caller deletes - // output identity metadata. - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_NAME, - req.property, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if entries[index].1.immutable { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - req.property, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - entries.remove(index); - state.randr.timestamp = state.timestamp_now(); - super::run::notify_randr_output_property_changed( - state, - req.output, - property, - x11randr::PROPERTY_DELETE, - ); - return Ok(RequestOutcome::Handled); - } - x11randr::RR_GET_PANNING => { - let crtc = request_xid(body); - if !crtc_exists(state, crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - crtc, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let timestamp = state.randr.timestamp; - let buf = x11randr::encode_get_panning_reply(byte_order, sequence, timestamp); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SET_PANNING => { - let Some(req) = x11randr::parse_set_panning_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if !crtc_exists(state, req.crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - req.crtc, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let status = if req.is_disabled() { - x11randr::SET_CONFIG_SUCCESS - } else { - // A live panning viewport needs transformed/composited - // scanout. Report a RANDR configuration failure rather than - // claiming the requested geometry was installed. - warn_randr_unsupported_once( - state, - client_id, - sequence, - minor, - "SetPanning", - "returning SetConfigFailed for active panning", - ); - x11randr::SET_CONFIG_FAILED - }; - let buf = x11randr::encode_set_panning_reply( - byte_order, - sequence, - status, - state.randr.timestamp, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SET_OUTPUT_PRIMARY => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let output = body - .get(4..8) - .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) - .unwrap_or(0); - if output != 0 && !output_exists(state, output) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // None (0) clears the primary output. A nonzero id is already - // validated above; yserver has one screen and no leased outputs, - // so Xorg's remaining cross-screen/lease checks are vacuous. - let previous = state.randr.primary_output; - // Even an idempotent request turns the topology-derived default - // into an explicit client choice that must survive rebuilds. - state.randr_primary_output_explicit = true; - if previous == output { - // Xorg's RRSetPrimaryOutput returns early when nothing moves, - // so no notify storm from an idempotent set. - return Ok(RequestOutcome::Handled); - } - state.randr.primary_output = output; - // A primary change is a LAYOUT change in Xorg: RROutputChanged on - // the affected outputs + layoutChanged, then RRTellChanged - // (randr/rroutput.c). Both the old and new primary changed, so both - // are announced; clients learn about this by notify, not polling. - let changed: Vec = [previous, output].into_iter().filter(|o| *o != 0).collect(); - super::run::notify_randr_layout_changed(state, &changed); - return Ok(RequestOutcome::Handled); - } - x11randr::RR_GET_OUTPUT_PRIMARY => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let primary = state.randr.primary_output; - let buf = x11randr::encode_get_output_primary_reply(byte_order, sequence, primary); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_PROVIDERS => { - // Xorg uses REQUEST_SIZE_MATCH for this fixed-size request. - if body.len() != 4 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let timestamp = state.randr.timestamp; - let providers: Vec = state - .randr - .providers - .iter() - .map(|provider| provider.provider_id) - .collect(); - let buf = - x11randr::encode_get_providers_reply(byte_order, sequence, timestamp, &providers); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_PROVIDER_INFO => { - let Some(req) = x11randr::parse_provider_info_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(provider) = state.randr.provider(req.provider) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_PROVIDER, - req.provider, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - // Xorg accepts config_timestamp but does not use it for this - // request; a live provider always reports RRSetConfigSuccess. - let _ = req.config_timestamp; - let associated_providers: Vec = provider - .associations - .iter() - .map(|association| association.provider_id) - .collect(); - let associated_capabilities: Vec = provider - .associations - .iter() - .map(|association| association.capability) - .collect(); - let buf = x11randr::encode_get_provider_info_reply( - byte_order, - sequence, - &x11randr::ProviderInfoReply { - status: x11randr::SET_CONFIG_SUCCESS, - timestamp: state.randr.timestamp, - capabilities: provider.capabilities, - crtcs: &provider.crtcs, - outputs: &provider.outputs, - associated_providers: &associated_providers, - associated_capabilities: &associated_capabilities, - name: provider.name.as_bytes(), - }, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK => { - let Some(req) = x11randr::parse_set_provider_offload_sink_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if let Err(error) = state - .randr - .validate_provider_offload_sink(req.provider, req.sink_provider) - { - let (error_code, error_value) = provider_relationship_protocol_error(error); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error_code, - error_value, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let _ = req.config_timestamp; - warn_randr_unsupported_once( - state, - client_id, - sequence, - minor, - "SetProviderOffloadSink", - "rejecting a validated relationship because offload transport is unavailable", - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE => { - let Some(req) = x11randr::parse_set_provider_output_source_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - if let Err(error) = state - .randr - .validate_provider_output_source(req.provider, req.source_provider) - { - let (error_code, error_value) = provider_relationship_protocol_error(error); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error_code, - error_value, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let _ = req.config_timestamp; - let changed = match backend.set_provider_output_source( - state, - req.provider, - (req.source_provider != 0).then_some(req.source_provider), - ) { - Ok(changed) => changed, - Err(err) => { - log::warn!( - "client {} #{} RANDR::SetProviderOutputSource provider={} source={} failed: {err}", - client_id.0, - sequence.0, - req.provider, - req.source_provider, - ); - let (error_code, error_value) = if err.kind() == io::ErrorKind::InvalidInput { - (x11::error::BAD_MATCH, req.provider) - } else { - (x11::error::BAD_IMPLEMENTATION, 0) - }; - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error_code, - error_value, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - }; - if changed { - super::run::notify_randr_provider_changed(state, req.provider); - } - return Ok(RequestOutcome::Handled); - } - x11randr::RR_GET_MONITORS => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let t = state.randr.timestamp; - struct MonitorRow { - name_atom: u32, - primary: bool, - automatic: bool, - x: i16, - y: i16, - width: u16, - height: u16, - width_mm: u32, - height_mm: u32, - outputs: Vec, - } - let monitors_list = active_monitors(state); - let rows: Vec = monitors_list - .iter() - .map(|monitor| MonitorRow { - name_atom: state.atoms.intern(&monitor.name, false).0, - primary: monitor.primary, - automatic: true, - x: monitor.x, - y: monitor.y, - width: monitor.width, - height: monitor.height, - width_mm: monitor.width_mm, - height_mm: monitor.height_mm, - outputs: vec![monitor.output_id], - }) - .collect(); - let monitors: Vec> = rows - .iter() - .map(|r| x11randr::MonitorInfo { - name: r.name_atom, - primary: r.primary, - automatic: r.automatic, - x: r.x, - y: r.y, - width: r.width, - height: r.height, - width_mm: r.width_mm, - height_mm: r.height_mm, - outputs: &r.outputs, - }) - .collect(); - let buf = x11randr::encode_get_monitors_reply(byte_order, sequence, t, &monitors); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_CRTC_GAMMA_SIZE => { - let Some(req) = x11randr::parse_crtc_id_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - if !crtc_exists(state, req.crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - req.crtc, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - let buf = x11randr::encode_get_crtc_gamma_size_reply( - byte_order, - sequence, - backend.crtc_gamma_size(req.crtc), - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_GET_CRTC_GAMMA => { - let Some(req) = x11randr::parse_crtc_id_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - if !crtc_exists(state, req.crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - req.crtc, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - let (red, green, blue) = backend.get_crtc_gamma(req.crtc); - let buf = - x11randr::encode_get_crtc_gamma_reply(byte_order, sequence, &red, &green, &blue); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SET_CRTC_GAMMA => { - let Some(crtc_bytes) = body.get(0..4) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - let crtc = u32::from_le_bytes(crtc_bytes.try_into().unwrap()); - if !crtc_exists(state, crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - crtc, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if crtc_is_leased(state, crtc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - crtc, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - let Some(size_bytes) = body.get(4..6) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - let size = u16::from_le_bytes(size_bytes.try_into().unwrap()); - let expected_units = (3 * u32::from(size) + 1) >> 1; - let expected_bytes = 8usize.saturating_add(usize::from(size).saturating_mul(6)); - if header.length_units.saturating_sub(3) < expected_units || body.len() < expected_bytes - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - let gamma_size = backend.crtc_gamma_size(crtc); - if size != gamma_size { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - - let channel_bytes = usize::from(size) * 2; - let red: Vec = body[8..8 + channel_bytes] - .chunks_exact(2) - .map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap())) - .collect(); - let green_start = 8 + channel_bytes; - let green_end = green_start + channel_bytes; - let green: Vec = body[green_start..green_end] - .chunks_exact(2) - .map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap())) - .collect(); - let blue: Vec = body[green_end..green_end + channel_bytes] - .chunks_exact(2) - .map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap())) - .collect(); - - if let Err(e) = backend.set_crtc_gamma(crtc, &red, &green, &blue) { - log::warn!("RRSetCrtcGamma apply failed for CRTC 0x{crtc:x}: {e}"); - } - return Ok(RequestOutcome::Handled); - } - x11randr::RR_GET_OUTPUT_PROPERTY => { - let Some(req) = x11randr::parse_get_output_property_request(body) else { - let buf = - x11randr::encode_get_output_property_reply(byte_order, sequence, 0, 0, 0, &[]); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &buf)); - }; - if !output_exists(state, req.output) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_OUTPUT, - req.output, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let property = AtomId(req.property); - // Xorg validates the property atom, then the delete BOOL, then - // the requested type atom, all before ever looking up the - // property (`ProcRRGetOutputProperty`, randr/rrproperty.c). - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.property, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - if req.delete_raw != 0 && req.delete_raw != 1 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.delete_raw), - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - if req.prop_type != 0 && !state.atoms.exists(AtomId(req.prop_type)) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.prop_type, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // A real store entry always shadows the backend-synthesized - // identity properties (EDID / EDID_DATA / ConnectorType). - let real = state - .randr_output_properties - .get(&req.output) - .and_then(|entries| entries.iter().find(|(atom, _)| *atom == property)) - .map(|(_, prop)| prop.clone()); - let (served, immutable): (Option<(u32, u8, Vec)>, bool) = - if let Some(prop) = real.as_ref() { - let value = if req.pending && prop.is_pending { - prop.pending.as_ref() - } else { - prop.current.as_ref() - }; - ( - value.map(|v| (v.r#type.0, v.format.protocol_value(), v.data.clone())), - prop.immutable, - ) - } else if let Some(syn) = - synthetic_output_property(state, backend, req.output, property) - { - (Some(syn), true) - } else { - (None, false) - }; - if req.delete && immutable { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - req.property, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let (buf, bytes_after): (Vec, u32) = match served { - // Type-mismatch (client asked for a specific, different type): - // reply with the real type + empty value + full bytes_after. - // `bytes_after` is an ELEMENT count here (Xorg: - // `reply.bytesAfter = prop_value->size`, and `size` is - // stored in format-units — see `RRChangeOutputProperty`'s - // `new_value.size = total_len` where `total_len` counts - // `nUnits`, not bytes), not `full.len()`. - Some((ptype, format, full)) if req.prop_type != 0 && req.prop_type != ptype => { - let unit = (format as usize / 8).max(1); - let bytes_after = u32::try_from(full.len() / unit).unwrap_or(u32::MAX); - ( - x11randr::encode_get_output_property_reply( - byte_order, - sequence, - ptype, - format, - bytes_after, - &[], - ), - bytes_after, - ) - } - Some((ptype, format, full)) => { - // Windowing: long-offset / long-length are in 32-bit units. - let total = full.len(); - let start = (req.long_offset as usize).saturating_mul(4); - if start > total { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.long_offset, - u16::from(x11randr::RR_GET_OUTPUT_PROPERTY), - RANDR_MAJOR_OPCODE, - ); - } - let avail = total - start; - let take = avail.min((req.long_length as usize).saturating_mul(4)); - let bytes_after = u32::try_from(avail - take).unwrap_or(u32::MAX); - ( - x11randr::encode_get_output_property_reply( - byte_order, - sequence, - ptype, - format, - bytes_after, - &full[start..start + take], - ), - bytes_after, - ) - } - None => ( - x11randr::encode_get_output_property_reply(byte_order, sequence, 0, 0, 0, &[]), - 0, - ), - }; - // Xorg fires the delete notify before writing the reply, then - // physically removes the property once bytesAfter==0 — reachable - // only for a real (non-immutable) store entry, since the - // immutable check above already rejected a synthetic property. - if req.delete && bytes_after == 0 && real.is_some() { - super::run::notify_randr_output_property_changed( - state, - req.output, - property, - x11randr::PROPERTY_DELETE, - ); - if let Some(entries) = state.randr_output_properties.get_mut(&req.output) { - entries.retain(|(atom, _)| *atom != property); - } - } - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SELECT_INPUT => { - if let Some(req) = x11randr::parse_select_input(body) { - if state.resources.window(ResourceId(req.window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - if req.enable == 0 { - state - .randr_select_masks - .remove(&(client_id.0, ResourceId(req.window))); - } else { - state - .randr_select_masks - .insert((client_id.0, ResourceId(req.window)), req.enable); - } - } - } - x11randr::RR_GET_SCREEN_INFO => { - let window = request_xid(body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let timestamp = state.randr.timestamp; - let config_timestamp = state.randr.config_timestamp; - let width = state.randr.screen_width; - let height = state.randr.screen_height; - let mwidth = u16::try_from(state.randr.width_mm).unwrap_or(u16::MAX); - let mheight = u16::try_from(state.randr.height_mm).unwrap_or(u16::MAX); - let buf = x11randr::encode_get_screen_info_reply( - byte_order, - sequence, - ROOT_WINDOW.0, - timestamp, - config_timestamp, - width, - height, - mwidth, - mheight, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &buf)); - } - x11randr::RR_SET_SCREEN_SIZE => { - let Some(req) = x11randr::parse_set_screen_size_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - if state.resources.window(ResourceId(req.window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // Validation order matches rrscreen.c: width range → - // height range → crop → zero-mm. errorValue is the - // offending dimension (width vs height reported - // separately), not always width. - let (min_w, min_h, max_w, max_h) = state.randr.screen_size_range(); - if req.width < min_w || req.width > max_w { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.width), - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if req.height < min_h || req.height > max_h { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.height), - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if state.randr.screen_size_would_crop(req.width, req.height) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if req.mm_width == 0 || req.mm_height == 0 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if let Err(e) = backend.set_logical_screen_size(req.width, req.height) { - log::warn!("RRSetScreenSize: backend resize failed: {e}"); - // Xorg ProcRRSetScreenSize returns BadMatch when - // RRScreenSizeSet fails (rrscreen.c). Silently - // succeeding would make the client believe the - // resize took. Leave prior state intact + report. - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - let ts = state.timestamp_now(); - state - .randr - .set_logical_size(ts, req.width, req.height, req.mm_width, req.mm_height); - // Pure screen-size change: fire root ConfigureNotify + - // ScreenChangeNotify ONLY — no per-CRTC/Output change - // (CRTC positions are unchanged). Pass an empty changed - // list so only ScreenChangeNotify + root ConfigureNotify fire. - super::run::apply_screen_size_side_effects(state, backend, req.width, req.height, &[]); - // RRSetScreenSize has NO reply (it is a void request). - return Ok(RequestOutcome::Handled); - } - x11randr::RR_SET_SCREEN_CONFIG => { - // Xorg looks this up as a DRAWABLE, not a window - // (`dixLookupDrawable`, rrscreen.c), so a pixmap is a legal - // target — it just resolves to its screen. An unknown xid comes - // back as `BadDrawable`, because dixLookupDrawable remaps - // dix's `BadValue` (dix/dixutils.c). Measured on real Xorg with - // `tools/randr-probe`: bogus xid -> code=9 (BadDrawable), and a - // real pixmap -> Success. - let drawable = request_xid(body); - let id = ResourceId(drawable); - if state.resources.window(id).is_none() && state.resources.pixmap(id).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - drawable, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // Legacy RANDR 1.0 form: SizeID + Rotation. yserver has a - // single screen size. mate's restore path passes the size - // we advertised, so accept across the board (no-op accept). - // - // SetScreenConfig reply (32 bytes): status (in data byte) + - // length=0 + new_timestamp(4) + config_timestamp(4) + - // root(4) + subpixel_order(2) + pad(10). - let ts = state.timestamp_now(); - let mut reply = x11::fixed_reply(byte_order, sequence, 0u8, 0); - x11::write_u32(byte_order, &mut reply, ts); - x11::write_u32(byte_order, &mut reply, state.randr.timestamp); - x11::write_u32(byte_order, &mut reply, ROOT_WINDOW.0); - x11::write_u16(byte_order, &mut reply, 0); // SubPixelUnknown - reply.extend_from_slice(&[0u8; 10]); - debug_assert_eq!(reply.len(), 32); - debug!( - "client {} #{} RANDR::SetScreenConfig -> status=0 timestamp={} (no-op accept)", - client_id.0, sequence.0, ts, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11randr::RR_SET_CRTC_CONFIG => { - // Body layout (post-header): - // crtc(4) timestamp(4) config_timestamp(4) x(2) y(2) - // mode(4) rotation(2) pad(2) outputs(4*N) - // config_timestamp is parsed but NOT validated — rrcrtc.c - // does not gate SetCrtcConfig on it (only the 1.0 - // SetScreenConfig uses InvalidConfigTime/InvalidTime). - let Some(crtc_bytes) = body.get(0..4) else { - return Ok(RequestOutcome::Handled); - }; - let crtc = u32::from_le_bytes(crtc_bytes.try_into().unwrap()); - let req_timestamp = body - .get(4..8) - .map(|b| u32::from_le_bytes(b.try_into().unwrap())) - .unwrap_or(0); - let x = body - .get(12..14) - .map(|b| i16::from_le_bytes(b.try_into().unwrap())) - .unwrap_or(0); - let y = body - .get(14..16) - .map(|b| i16::from_le_bytes(b.try_into().unwrap())) - .unwrap_or(0); - let mode = body - .get(16..20) - .map(|b| u32::from_le_bytes(b.try_into().unwrap())) - .unwrap_or(0); - let rotation = body - .get(20..22) - .map(|b| u16::from_le_bytes(b.try_into().unwrap())) - .unwrap_or(1); - let outputs: Vec = body - .get(24..) - .map(|tail| { - tail.chunks_exact(4) - .map(|c| u32::from_le_bytes(c.try_into().unwrap())) - .collect() - }) - .unwrap_or_default(); - - // (1) arity + output + mode resolution FIRST (Xorg rrcrtc.c order). - let resolved = match state.randr.validate_set_crtc_config(crtc, mode, &outputs) { - Err((code, error_value)) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - error_value, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - Ok(r) => r, - }; - // (2)+(3) rotation + bounds only when enabling. - if let Some(ref m) = resolved { - if !matches!(rotation & 0xf, 1 | 2 | 4 | 8) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(rotation), - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if rotation != 1 { - // RR_Rotate_0 only — our CRTC is identity-only. - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - u32::from(rotation), - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - if let Err((code, error_value)) = state.randr.screen_encompasses(m, x, y) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - error_value, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - } - } - - // Resolve connector name from crtc_id (validated above → - // guaranteed to exist). - let output_row = state.randr.outputs.iter().find(|o| o.crtc_id == crtc); - let Some(output_row) = output_row else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - crtc, - u16::from(header.data), - RANDR_MAJOR_OPCODE, - ); - }; - let output_id = output_row.output_id; - let connector = output_row.name.clone(); - let mode_spec = resolved.map(|m| ModeSpec { - width: m.width, - height: m.height, - vrefresh: m.vrefresh, - }); - // lastSetTime = client timestamp (0/CurrentTime ⇒ server now). - let set_time = if req_timestamp == 0 { - state.timestamp_now() - } else { - req_timestamp - }; - let output_bbox_before = super::run::enabled_output_bbox(state); - let completion = CrtcConfigCompletion { - output_id, - set_time, - output_bbox_before, - byte_order, - }; - match backend.begin_crtc_config( - output_id, - &connector, - mode_spec, - i32::from(x), - i32::from(y), - ) { - Ok(CrtcConfigApply::Applied(changed)) => { - return complete_crtc_config( - state, - backend, - client_id, - sequence, - completion, - Ok(changed), - ); - } - Ok(CrtcConfigApply::Pending(token)) => { - return Ok(RequestOutcome::PendingCrtcConfig(PendingCrtcConfig { - token, - completion, - })); - } - Err(e) => { - return complete_crtc_config( - state, - backend, - client_id, - sequence, - completion, - Err(e), - ); - } - } - } - 16 | 45 => { - // TODO(unimplemented): RRCreateMode (16) / RRCreateLease (45) - // are NOT actually implemented. This - // BadImplementation is a STOPGAP to stop the client hanging on a - // reply that never comes — it is NOT protocol-correct: Xorg - // implements both and returns real data. Replace with real - // implementations (custom modes / DRM lease). - // - // Void unimplemented RANDR requests remain wire-success no-ops - // via `other` below — Xorg implements those as success, so - // erroring them would be a new Xorg-divergence. Their first use - // is nevertheless warned so the unsupported behavior is visible. - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - x11randr::RR_LIST_PROVIDER_PROPERTIES - | x11randr::RR_QUERY_PROVIDER_PROPERTY - | x11randr::RR_CONFIGURE_PROVIDER_PROPERTY - | x11randr::RR_CHANGE_PROVIDER_PROPERTY - | x11randr::RR_DELETE_PROVIDER_PROPERTY - | x11randr::RR_GET_PROVIDER_PROPERTY => { - // These requests remain deliberately unsupported, but now that - // providers are live we must preserve Xorg's validation order: - // request shape first, then provider lookup, then the unsupported - // result. ChangeProviderProperty additionally validates mode and - // format before its computed-length check and provider lookup. - let provider = match minor { - x11randr::RR_LIST_PROVIDER_PROPERTIES if body.len() == 4 => request_xid(body), - x11randr::RR_QUERY_PROVIDER_PROPERTY | x11randr::RR_DELETE_PROVIDER_PROPERTY - if body.len() == 8 => - { - request_xid(body) - } - x11randr::RR_CONFIGURE_PROVIDER_PROPERTY - if body.len() >= 12 && body.len().is_multiple_of(4) => - { - request_xid(body) - } - x11randr::RR_GET_PROVIDER_PROPERTY if body.len() == 24 => request_xid(body), - x11randr::RR_CHANGE_PROVIDER_PROPERTY => { - let Some(req) = x11randr::parse_change_provider_property_header(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(_mode) = properties::ChangeMode::from_protocol(req.mode) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.mode), - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let Some(format) = properties::PropertyFormat::from_protocol(req.format) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.format), - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - }; - let expected_len = usize::try_from(req.n_units) - .ok() - .and_then(|units| units.checked_mul(format.bytes())) - .and_then(|bytes| bytes.checked_add(3)) - .map(|bytes| bytes & !3) - .and_then(|bytes| 20usize.checked_add(bytes)); - if expected_len != Some(body.len()) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - req.provider - } - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - }; - if state.randr.provider(provider).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_PROVIDER, - provider, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - let request_name = match minor { - x11randr::RR_LIST_PROVIDER_PROPERTIES => "ListProviderProperties", - x11randr::RR_QUERY_PROVIDER_PROPERTY => "QueryProviderProperty", - x11randr::RR_CONFIGURE_PROVIDER_PROPERTY => "ConfigureProviderProperty", - x11randr::RR_CHANGE_PROVIDER_PROPERTY => "ChangeProviderProperty", - x11randr::RR_DELETE_PROVIDER_PROPERTY => "DeleteProviderProperty", - x11randr::RR_GET_PROVIDER_PROPERTY => "GetProviderProperty", - _ => unreachable!(), - }; - warn_randr_unsupported_once( - state, - client_id, - sequence, - minor, - request_name, - "rejecting request because provider properties are unavailable", - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - 46 => { - // CreateLease is not implemented and cannot create a live lease, - // so FreeLease always follows Xorg's failed lease lookup. - // - // That lookup yields plain `BadValue`, NOT `BadRRLease`. Xorg - // registers RRLeaseType with `CreateNewResourceType` (rrlease.c) - // and never calls `SetResourceTypeErrorValue` for it, so the type - // keeps dix's default `errorValue = BadValue` (dix/resource.c); - // `BadRRLease` is defined in randr.h but referenced nowhere in the - // Xorg tree. Measured on real Xorg with `tools/randr-probe`: - // RRFreeLease(bogus) -> code=2 (BadValue), not 151. - let lease = body - .get(0..4) - .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) - .unwrap_or(0); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - lease, - u16::from(minor), - RANDR_MAJOR_OPCODE, - ); - } - // 1 RROldGetScreenInfo and 3 RROldScreenChangeSelectInput are literal - // NULL entries in Xorg's ProcRandrVector (randr/rrdispatch.c), and - // ProcRRDispatch rejects a NULL slot exactly like an out-of-range - // minor: `if (stuff->data >= RRNumberRequests || - // !ProcRandrVector[stuff->data]) return BadRequest;` (randr/randr.c). - // They are request numbers that were never assigned, not requests we - // have yet to write. - 1 | 3 => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(minor), - header.opcode, - ); - } - other if other >= RANDR_REQUEST_COUNT => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - other => { - let request_name = match other { - 17 => "DestroyMode", - 18 => "AddOutputMode", - 19 => "DeleteOutputMode", - 43 => "SetMonitor", - 44 => "DeleteMonitor", - _ => "known request", - }; - warn_randr_unsupported_once( - state, - client_id, - sequence, - other, - request_name, - "accepting void request as a compatibility no-op", - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// Complete the protocol-visible half of `RRSetCrtcConfig` after either a -/// synchronous apply or an asynchronous backend result. Keeping this as one -/// continuation prevents the async path from redispatching validation or -/// accidentally diverging in notification/timestamp behavior. -pub(crate) fn complete_crtc_config( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - completion: CrtcConfigCompletion, - result: io::Result, -) -> io::Result { - let status = match result { - Ok(true) => { - // Something actually changed. Single rebuild path: a CRTC set - // bumps lastSetTime (to the client timestamp) but NOT - // lastConfigTime. - backend.refresh_randr_state_set_time(state, completion.set_time); - let changed: Vec<(u32, u32, u32)> = state - .randr - .outputs - .iter() - .find(|o| o.output_id == completion.output_id) - .map(|o| (o.output_id, o.crtc_id, o.mode_id)) - .into_iter() - .collect(); - super::run::emit_randr_change_notifications(state, &changed); - super::run::emit_screen_resize_window_notifications_if_outputs_caught_up( - state, - completion.output_bbox_before, - ); - 0 - } - Ok(false) => { - // A no-op succeeds without a rebuild or change notification. - 0 - } - Err(e) => { - log::warn!("RRSetCrtcConfig apply failed: {e}"); - // RRSetConfigFailed=3 (a status reply, not a protocol error). - 3 - } - }; - let timestamp = state.randr.timestamp; - reply_set_crtc_config( - state, - client_id, - sequence, - completion.byte_order, - status, - timestamp, - ) -} - -/// Build and send the 32-byte `SetCrtcConfig` reply. -/// -/// Wire format: `status` (data byte) + length=0 + `new_timestamp`(4) + -/// pad(20). On success `new_timestamp` is the post-set `state.randr.timestamp`; -/// on failure it is the unmodified existing value (caller resolves which). -fn reply_set_crtc_config( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - byte_order: yserver_protocol::x11::ClientByteOrder, - status: u8, - new_timestamp: u32, -) -> io::Result { - let mut reply = x11::fixed_reply(byte_order, sequence, status, 0); - x11::write_u32(byte_order, &mut reply, new_timestamp); - reply.extend_from_slice(&[0u8; 20]); - debug_assert_eq!(reply.len(), 32); - debug!( - "client {} #{} RANDR::SetCrtcConfig -> status={} new_timestamp={}", - client_id.0, sequence.0, status, new_timestamp, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, &reply)) -} - -/// A SYNC protocol error: `code` is either a core error or -/// `SYNC_FIRST_ERROR + x11sync::BAD_*`. -fn sync_error( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - code: u8, - value: u32, -) -> io::Result { - emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(header.data), - header.opcode, - ) -} - -/// Xorg's lookup of a client-writable counter for SetCounter / -/// ChangeCounter / DestroyCounter: an unknown XID is BadCounter, a system -/// counter BadAccess (both naming the counter; captured on Xvfb). -fn sync_writable_counter( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - counter: u32, -) -> Result> { - use yserver_protocol::x11::sync as x11sync; - if crate::core_loop::sync_await::is_system_counter(counter) { - return Err(sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_ACCESS, - counter, - )); - } - match state.sync_counters.get(&counter) { - Some(c) => Ok(c.value), - None => Err(sync_error( - state, - client_id, - sequence, - header, - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, - counter, - )), - } -} - -/// Xorg `RTFence` lookup: an unknown fence is BadFence naming it. -fn sync_known_fence( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - fence: u32, -) -> Result<(), io::Result> { - use yserver_protocol::x11::sync as x11sync; - if state.sync_fences.contains_key(&fence) { - return Ok(()); - } - Err(sync_error( - state, - client_id, - sequence, - header, - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_FENCE, - fence, - )) -} - -/// Xorg's `RTAlarm` lookup: an alarm that does not exist (never created, -/// None, or destroyed) is BadAlarm naming it. -fn sync_known_alarm( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - alarm: u32, -) -> Result<(), io::Result> { - use yserver_protocol::x11::sync as x11sync; - if state.sync_alarms.contains_key(&alarm) { - return Ok(()); - } - Err(sync_error( - state, - client_id, - sequence, - header, - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_ALARM, - alarm, - )) -} - -fn handle_sync_request( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, sync as x11sync}; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - match minor { - x11sync::INITIALIZE => { - // Xorg `ProcSyncInitialize` always answers its own version - // (Xvfb: client 3.1 / 3.0 / 2.0 / 4.0 all get 3.1). - let reply = x11sync::encode_initialize_reply( - byte_order, - sequence, - x11sync::MAJOR_VERSION, - x11sync::MINOR_VERSION, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11sync::LIST_SYSTEM_COUNTERS => { - let reply = x11sync::encode_list_system_counters_reply(byte_order, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11sync::CREATE_COUNTER => { - if let Some((counter, value)) = x11sync::parse_counter_value(body) { - state.sync_counters.insert( - counter, - crate::server::SyncCounter { - owner: client_id, - value, - }, - ); - } - } - x11sync::SET_COUNTER => { - if let Some((counter, value)) = x11sync::parse_counter_value(body) { - let old = match sync_writable_counter(state, client_id, sequence, header, counter) { - Ok(old) => old, - Err(outcome) => return outcome, - }; - if let Some(c) = state.sync_counters.get_mut(&counter) { - c.value = value; - } - crate::core_loop::sync_await::counter_changed(state, counter, old, value); - } - } - x11sync::CHANGE_COUNTER => { - if let Some((counter, delta)) = x11sync::parse_counter_value(body) { - let old = match sync_writable_counter(state, client_id, sequence, header, counter) { - Ok(old) => old, - Err(outcome) => return outcome, - }; - // Xorg: an INT64 overflow is BadValue naming the high half - // of the delta (Xvfb: value 0x7fffffff for i64::MAX). - let Some(new) = old.checked_add(delta) else { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let value_hi = (delta >> 32) as u32; - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_VALUE, - value_hi, - ); - }; - if let Some(c) = state.sync_counters.get_mut(&counter) { - c.value = new; - } - crate::core_loop::sync_await::counter_changed(state, counter, old, new); - } - } - x11sync::QUERY_COUNTER => { - let counter = x11sync::parse_resource(body).unwrap_or(0); - // IDLETIME saturates at u32::MAX ms (~49 days) inside - // `idletime_current_idle`. An unknown counter is BadCounter. - let Some(value) = crate::core_loop::sync_await::counter_value(state, counter) else { - return sync_error( - state, - client_id, - sequence, - header, - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, - counter, - ); - }; - let reply = x11sync::encode_query_counter_reply(byte_order, sequence, value); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11sync::DESTROY_COUNTER => { - if let Some(counter) = x11sync::parse_resource(body) { - let last = match sync_writable_counter(state, client_id, sequence, header, counter) - { - Ok(last) => last, - Err(outcome) => return outcome, - }; - state.sync_counters.remove(&counter); - crate::core_loop::sync_await::counter_destroyed(state, counter, last); - } - } - x11sync::AWAIT => { - // Xorg `ProcSyncAwait`: validate every wait condition, then - // suspend the client until one of the triggers fires. Its later - // requests stay queued behind this one (see `sync_await`). - let Some(conditions) = x11sync::parse_await(byte_order, body) else { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - 0, - ); - }; - if conditions.is_empty() { - return sync_error(state, client_id, sequence, header, x11::error::BAD_VALUE, 0); - } - let mut waits = Vec::with_capacity(conditions.len()); - for c in conditions { - // `SyncInitTrigger` order: counter, value type, value, test - // type. Captured on Xvfb: None / unknown → BadCounter, - // bad value type / test type → BadValue naming it, relative - // overflow → BadValue naming the high half of the wait. - let current = if c.counter == 0 { - None - } else { - crate::core_loop::sync_await::counter_value(state, c.counter) - }; - let Some(current) = current else { - return sync_error( - state, - client_id, - sequence, - header, - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, - c.counter, - ); - }; - let test_value = match c.value_type { - x11sync::VALUE_TYPE_ABSOLUTE => c.wait_value, - x11sync::VALUE_TYPE_RELATIVE => { - let Some(v) = current.checked_add(c.wait_value) else { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let value_hi = (c.wait_value >> 32) as u32; - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_VALUE, - value_hi, - ); - }; - v - } - other => { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_VALUE, - other, - ); - } - }; - if c.test_type > x11sync::TEST_NEGATIVE_COMPARISON { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_VALUE, - c.test_type, - ); - } - waits.push(crate::server::SyncAwaitCondition::Counter { - counter: c.counter, - test_type: c.test_type, - test_value, - event_threshold: c.event_threshold, - }); - } - debug!( - "client {} #{} SYNC::Await {} condition(s)", - client_id.0, - sequence.0, - waits.len() - ); - crate::core_loop::sync_await::begin_await(state, &*backend, client_id, waits); - } - x11sync::CREATE_ALARM => { - // Xorg `ProcSyncCreateAlarm`: the value list must match the mask. - let Some((alarm, mask)) = x11sync::parse_alarm_with_mask(body) else { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - 0, - ); - }; - if body.len() != x11sync::alarm_request_len(mask) { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - alarm, - ); - } - // Xorg's defaults (`ProcSyncCreateAlarm` + `SyncInitTrigger` on - // None): no counter, Absolute 0, PositiveComparison, delta 1, - // the owner selected for events. An error discards the alarm. - let mut a = crate::server::SyncAlarm { - owner: client_id, - state: x11sync::ALARM_STATE_INACTIVE, - events: true, - test_type: x11sync::TEST_POSITIVE_COMPARISON, - check_type: x11sync::TEST_POSITIVE_COMPARISON, - delta: 1, - ..crate::server::SyncAlarm::default() - }; - let values = alarm_value_words(body); - if let Err((code, value)) = - change_alarm_attributes(state, alarm, &mut a, client_id, mask, &values) - { - return sync_error(state, client_id, sequence, header, code, value); - } - let counter = a.counter; - let class = state - .client_wm_class - .get(&client_id.0) - .map(String::as_str) - .unwrap_or(""); - log::trace!( - "sync: client {}/{class:?} CreateAlarm 0x{alarm:x} \ - counter={cname}(0x{counter:x}) test={test} \ - wait_value={wait} delta={delta} events={events}", - client_id.0, - cname = sync_counter_name(counter), - test = sync_test_type_name(a.test_type), - wait = a.wait_value, - delta = a.delta, - events = a.events, - ); - if counter == 0 { - // "NULL counter will not trigger in CreateAlarm and sets - // alarm state to Inactive" (Xorg). - a.state = x11sync::ALARM_STATE_INACTIVE; - state.sync_alarms.insert(alarm, a); - return Ok(RequestOutcome::Handled); - } - state.sync_alarms.insert(alarm, a); - // The trigger is tested at creation: a comparison whose - // condition already holds fires at once. System counters - // (SERVERTIME, IDLETIME) read the clock. - check_new_alarm_trigger(state, alarm, counter); - } - x11sync::CHANGE_ALARM => { - // Xorg `ProcSyncChangeAlarm`: minimum size, then the alarm - // lookup (BadAlarm), then the value list against the mask - // (BadLength naming the alarm, captured on Xvfb). - let Some((alarm, mask)) = x11sync::parse_alarm_with_mask(body) else { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - 0, - ); - }; - if let Err(outcome) = sync_known_alarm(state, client_id, sequence, header, alarm) { - return outcome; - } - if body.len() != x11sync::alarm_request_len(mask) { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - alarm, - ); - } - // Xorg `SyncChangeAlarmAttributes`: any client may change an - // alarm; `events` selects AlarmNotify for the requesting client - // (the owner's own flag, or the event-client list). A failure - // part-way keeps what Xorg keeps (see change_alarm_attributes), - // so the copy is written back either way. - let Some(mut a) = state.sync_alarms.get(&alarm).cloned() else { - return Ok(RequestOutcome::Handled); - }; - let values = alarm_value_words(body); - let outcome = change_alarm_attributes(state, alarm, &mut a, client_id, mask, &values); - if let Err((code, value)) = outcome { - state.sync_alarms.insert(alarm, a); - return sync_error(state, client_id, sequence, header, code, value); - } - let counter = a.counter; - let class = state - .client_wm_class - .get(&client_id.0) - .map(String::as_str) - .unwrap_or(""); - log::trace!( - "sync: client {}/{class:?} ChangeAlarm 0x{alarm:x} \ - counter={cname}(0x{counter:x}) test={test} \ - wait_value={wait} delta={delta} events={events}", - client_id.0, - cname = sync_counter_name(counter), - test = sync_test_type_name(a.test_type), - wait = a.wait_value, - delta = a.delta, - events = a.events, - ); - state.sync_alarms.insert(alarm, a); - if counter == 0 { - // "NULL counter WILL trigger in ChangeAlarm" (Xorg): the - // alarm goes Inactive with an AlarmNotify. - alarm_trigger_fired(state, alarm, 0); - } else { - check_new_alarm_trigger(state, alarm, counter); - } - } - x11sync::QUERY_ALARM => { - // Xorg `ProcSyncQueryAlarm`: exact size, then the lookup. - if body.len() != 4 { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - 0, - ); - } - let alarm_id = x11sync::parse_resource(body).unwrap_or(0); - if let Err(outcome) = sync_known_alarm(state, client_id, sequence, header, alarm_id) { - return outcome; - } - let alarm = state - .sync_alarms - .get(&alarm_id) - .cloned() - .unwrap_or_default(); - let reply = x11sync::encode_query_alarm_reply( - byte_order, - sequence, - alarm.counter, - alarm.wait_value, - alarm.test_type, - alarm.delta, - alarm.events, - alarm.state, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11sync::DESTROY_ALARM => { - // Xorg `ProcSyncDestroyAlarm`: exact size, then the lookup. - if body.len() != 4 { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - 0, - ); - } - let alarm = x11sync::parse_resource(body).unwrap_or(0); - if let Err(outcome) = sync_known_alarm(state, client_id, sequence, header, alarm) { - return outcome; - } - // Xorg `FreeAlarm`: any client may destroy it; a Destroyed - // AlarmNotify goes to the owner and the selecting clients. - crate::core_loop::sync_await::destroy_alarm(state, alarm); - } - x11sync::CREATE_FENCE => { - if let Some(req) = x11sync::parse_create_fence(body) { - state.sync_fences.insert( - req.fence, - crate::server::SyncFence { - owner: client_id, - triggered: req.initially_triggered, - }, - ); - debug!( - "client {} #{} SYNC::CreateFence fence=0x{:x} initially_triggered={}", - client_id.0, sequence.0, req.fence, req.initially_triggered - ); - } - } - x11sync::DESTROY_FENCE => { - if let Some(fence) = x11sync::parse_resource(body) { - if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { - return outcome; - } - crate::core_loop::sync_await::fence_destroyed(state, fence); - state.sync_fences.remove(&fence); - backend.dri3_destroy_fence(fence); - debug!( - "client {} #{} SYNC::DestroyFence fence=0x{:x}", - client_id.0, sequence.0, fence - ); - } - } - x11sync::TRIGGER_FENCE => { - if let Some(fence) = x11sync::parse_resource(body) { - if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { - return outcome; - } - // For DRI3-imported xshmfence-backed fences, the - // server-side triggered bit is invisible to Mesa's local - // `xshmfence_await`. Forward the trigger to the backend so - // it writes the shared 4-byte counter + futex-wakes any - // local waiter — Mesa's `loader_dri3_copy_drawable` blocks - // on exactly that. - if let Err(e) = backend.dri3_trigger_fence(fence) { - log::warn!("SYNC::TriggerFence 0x{fence:x}: backend trigger failed: {e}"); - } - debug!( - "client {} #{} SYNC::TriggerFence fence=0x{:x}", - client_id.0, sequence.0, fence - ); - // Xorg `miSyncTriggerFence`: wakes every AwaitFence on it. - crate::core_loop::sync_await::fence_triggered(state, fence); - } - } - x11sync::RESET_FENCE => { - if let Some(fence) = x11sync::parse_resource(body) { - if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { - return outcome; - } - // Xorg `ProcSyncResetFence`: only a triggered fence can be - // reset (Xvfb: BadMatch naming the fence); a shared-memory - // fence is tested, and reset, in that memory. - if !crate::core_loop::sync_await::fence_is_triggered(state, &*backend, fence) { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_MATCH, - fence, - ); - } - backend.dri3_reset_fence(fence); - if let Some(f) = state.sync_fences.get_mut(&fence) { - f.triggered = false; - } - } - } - x11sync::QUERY_FENCE => { - let fence = x11sync::parse_resource(body).unwrap_or(0); - if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { - return outcome; - } - // Xorg `ProcSyncQueryFence` → `CheckTriggered`: shared memory - // for a DRI3 xshmfence, the server's bit otherwise. - let triggered = - crate::core_loop::sync_await::fence_is_triggered(state, &*backend, fence); - let reply = x11sync::encode_query_fence_reply(byte_order, sequence, triggered); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11sync::AWAIT_FENCE => { - // Xorg `ProcSyncAwaitFence`: suspend the client until any of - // the fences triggers (or is destroyed). Captured on Xvfb: - // empty list → BadValue, None / unknown fence → BadFence. - let Some(fences) = x11sync::parse_await_fence(byte_order, body) else { - return sync_error( - state, - client_id, - sequence, - header, - x11::error::BAD_LENGTH, - 0, - ); - }; - if fences.is_empty() { - return sync_error(state, client_id, sequence, header, x11::error::BAD_VALUE, 0); - } - for &fence in &fences { - if !state.sync_fences.contains_key(&fence) { - return sync_error( - state, - client_id, - sequence, - header, - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_FENCE, - fence, - ); - } - } - debug!( - "client {} #{} SYNC::AwaitFence n={}", - client_id.0, - sequence.0, - fences.len() - ); - let waits = fences - .into_iter() - .map(|fence| crate::server::SyncAwaitCondition::Fence { fence }) - .collect(); - crate::core_loop::sync_await::begin_await(state, &*backend, client_id, waits); - } - x11sync::SET_PRIORITY => { - // Stub. - } - x11sync::GET_PRIORITY => { - let reply = x11sync::encode_get_priority_reply(byte_order, sequence, 0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// Xorg `SyncChangeAlarmAttributes` + `SyncInitTrigger` for CreateAlarm -/// (on a fresh alarm) and ChangeAlarm (on a copy the caller writes back -/// whatever the outcome). `values` is the value list, one word each and -/// two for VALUE and DELTA, already length-checked against `mask`. -/// -/// Order and partial effects, as Xorg (captured on Xvfb): -/// 1. The list is walked in mask-bit order; an `events` word other than -/// True/False is BadValue naming it, an unknown bit BadValue naming the -/// mask bits above it. Nothing is changed yet. -/// 2. `events` selects AlarmNotify for `client` — it stays selected even -/// if the request then fails. -/// 3. With DELTA or TEST_TYPE in the mask, a positive test with a -/// negative delta or a negative test with a positive delta is -/// BadMatch; nothing else is changed. -/// 4. Delta, value type, value and test type are stored. -/// 5. The trigger is initialised: an unknown counter is BadCounter, an -/// invalid value type BadValue naming it; the wait value resolves -/// (Relative without a counter is BadMatch; an INT64 overflow is -/// BadValue naming the value's high word, with the wrapped sum stored); -/// an invalid test type is BadValue naming it. Only then do the counter -/// and the test the trigger runs change, and the alarm goes Active. -/// -/// So a failing ChangeAlarm can leave step 4 behind: a stored bad test -/// type is what QueryAlarm reports, while the alarm keeps running its old -/// test. -fn change_alarm_attributes( - state: &ServerState, - alarm_id: u32, - alarm: &mut crate::server::SyncAlarm, - client: ClientId, - mask: u32, - values: &[u32], -) -> Result<(), (u8, u32)> { - use yserver_protocol::x11::sync as x11sync; - let int64 = |hi: u32, lo: u32| (i64::from(hi.cast_signed()) << 32) | i64::from(lo); - let mut words = values.iter().copied(); - let mut next = || words.next().unwrap_or(0); - let (mut counter, mut value_type, mut raw_wait, mut test_type, mut delta) = ( - alarm.counter, - alarm.value_type, - alarm.raw_wait, - alarm.test_type, - alarm.delta, - ); - let mut select = None; - let mut remaining = mask; - while remaining != 0 { - let bit = 1u32 << remaining.trailing_zeros(); - remaining &= !bit; - match bit { - x11sync::CA_COUNTER => counter = next(), - x11sync::CA_VALUE_TYPE => value_type = next(), - x11sync::CA_VALUE => raw_wait = int64(next(), next()), - x11sync::CA_TEST_TYPE => test_type = next(), - x11sync::CA_DELTA => delta = int64(next(), next()), - x11sync::CA_EVENTS => { - let events = next(); - if events > 1 { - return Err((x11::error::BAD_VALUE, events)); - } - select = Some(events == 1); - } - _ => return Err((x11::error::BAD_VALUE, remaining)), - } - } - if let Some(want) = select { - crate::core_loop::sync_await::select_alarm_events(alarm, client, want); - } - if mask & (x11sync::CA_DELTA | x11sync::CA_TEST_TYPE) != 0 { - let positive = matches!( - test_type, - x11sync::TEST_POSITIVE_COMPARISON | x11sync::TEST_POSITIVE_TRANSITION - ); - let negative = matches!( - test_type, - x11sync::TEST_NEGATIVE_COMPARISON | x11sync::TEST_NEGATIVE_TRANSITION - ); - if (positive && delta < 0) || (negative && delta > 0) { - return Err((x11::error::BAD_MATCH, alarm_id)); - } - } - alarm.delta = delta; - alarm.value_type = value_type; - alarm.raw_wait = raw_wait; - alarm.test_type = test_type; - - let mut new_counter = alarm.counter; - if mask & x11sync::CA_COUNTER != 0 { - if counter != 0 - && !crate::core_loop::sync_await::is_system_counter(counter) - && !state.sync_counters.contains_key(&counter) - { - return Err(( - crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, - counter, - )); - } - new_counter = counter; - } - let current = if new_counter == 0 { - None - } else { - crate::core_loop::sync_await::counter_value(state, new_counter) - }; - if mask & x11sync::CA_VALUE_TYPE != 0 - && value_type != x11sync::VALUE_TYPE_ABSOLUTE - && value_type != x11sync::VALUE_TYPE_RELATIVE - { - return Err((x11::error::BAD_VALUE, value_type)); - } - if mask & (x11sync::CA_VALUE_TYPE | x11sync::CA_VALUE) != 0 { - if value_type == x11sync::VALUE_TYPE_ABSOLUTE { - alarm.wait_value = raw_wait; - } else { - let Some(value) = current else { - return Err((x11::error::BAD_MATCH, alarm_id)); - }; - let (sum, overflow) = value.overflowing_add(raw_wait); - alarm.wait_value = sum; - if overflow { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - return Err((x11::error::BAD_VALUE, (raw_wait >> 32) as u32)); - } - } - } - if mask & x11sync::CA_TEST_TYPE != 0 { - if test_type > x11sync::TEST_NEGATIVE_COMPARISON { - return Err((x11::error::BAD_VALUE, test_type)); - } - alarm.check_type = test_type; - } - alarm.counter = new_counter; - alarm.state = x11sync::ALARM_STATE_ACTIVE; - Ok(()) -} - -/// The value list of a length-checked CreateAlarm / ChangeAlarm body. -fn alarm_value_words(body: &[u8]) -> Vec { - body.get(8..) - .unwrap_or_default() - .chunks_exact(4) - .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])) - .collect() -} - -fn handle_xinerama_request( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, error, read_u32, xinerama as xin}; - - const XINERAMA_MAJOR_OPCODE: u8 = 151; - - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - - let screens: Vec = active_monitors(state) - .into_iter() - .map(|monitor| xin::ScreenInfo { - x_org: monitor.x, - y_org: monitor.y, - width: monitor.width, - height: monitor.height, - }) - .collect(); - - macro_rules! require_len { - ($n:expr) => { - if body.len() != $n { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error::BAD_LENGTH, - 0, - u16::from(minor), - XINERAMA_MAJOR_OPCODE, - ); - } - }; - } - - let buf = match minor { - xin::QUERY_VERSION => { - require_len!(4); - xin::encode_query_version_reply(byte_order, sequence) - } - xin::IS_ACTIVE => { - require_len!(0); - xin::encode_is_active_reply(byte_order, sequence, !screens.is_empty()) - } - xin::QUERY_SCREENS => { - require_len!(0); - xin::encode_query_screens_reply(byte_order, sequence, &screens) - } - xin::GET_STATE => { - require_len!(4); - let window = read_u32(byte_order, body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error::BAD_WINDOW, - window, - u16::from(minor), - XINERAMA_MAJOR_OPCODE, - ); - } - xin::encode_get_state_reply(byte_order, sequence, true, window) - } - xin::GET_SCREEN_COUNT => { - require_len!(4); - let window = read_u32(byte_order, body); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error::BAD_WINDOW, - window, - u16::from(minor), - XINERAMA_MAJOR_OPCODE, - ); - } - #[allow(clippy::cast_possible_truncation)] - let count = screens.len() as u8; - xin::encode_get_screen_count_reply(byte_order, sequence, count, window) - } - xin::GET_SCREEN_SIZE => { - require_len!(8); - let window = read_u32(byte_order, body); - let screen = read_u32(byte_order, &body[4..]); - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error::BAD_WINDOW, - window, - u16::from(minor), - XINERAMA_MAJOR_OPCODE, - ); - } - xin::encode_get_screen_size_reply( - byte_order, - sequence, - u32::from(state.randr.screen_width), - u32::from(state.randr.screen_height), - window, - screen, - ) - } - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error::BAD_REQUEST, - 0, - u16::from(minor), - XINERAMA_MAJOR_OPCODE, - ); - } - }; - - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, &buf)) -} - -/// Evaluate every active alarm watching `counter` after it moved from -/// `old` to `new`, firing `AlarmNotify` to each alarm's owner when its -/// trigger test crosses. -/// -/// Re-arm behaviour (Xorg sync.c:548-555, 589-597): -/// - `delta != 0`: advance `wait_value` past the current value so the -/// next crossing re-fires; on `i64` overflow transition to Inactive. -/// - `delta == 0` + Comparison test type: transition to Inactive. -/// - `delta == 0` + Transition test type: stay Active with `wait_value` -/// unchanged — the alarm quiesces until the next edge crossing. -/// -/// Human-friendly name for a SYNC counter id (system counters land -/// here; client-allocated counters fall through to ``). -fn sync_counter_name(counter: u32) -> &'static str { - use yserver_protocol::x11::sync as x11sync; - match counter { - x11sync::SERVERTIME_COUNTER => "SERVERTIME", - x11sync::IDLETIME_COUNTER => "IDLETIME", - x11sync::IDLETIME_DEVICE_VCP => "IDLETIME-VCP", - x11sync::IDLETIME_DEVICE_VCK => "IDLETIME-VCK", - _ => "", - } -} - -/// Human-friendly name for a SYNC alarm test type. -fn sync_test_type_name(test_type: u32) -> &'static str { - use yserver_protocol::x11::sync as x11sync; - match test_type { - x11sync::TEST_POSITIVE_TRANSITION => "PosTransition", - x11sync::TEST_NEGATIVE_TRANSITION => "NegTransition", - x11sync::TEST_POSITIVE_COMPARISON => "PosComparison", - x11sync::TEST_NEGATIVE_COMPARISON => "NegComparison", - _ => "?", - } -} - -/// Human-friendly name for a SYNC alarm state. -fn sync_alarm_state_name(state: u8) -> &'static str { - use yserver_protocol::x11::sync as x11sync; - match state { - x11sync::ALARM_STATE_ACTIVE => "Active", - x11sync::ALARM_STATE_INACTIVE => "Inactive", - x11sync::ALARM_STATE_DESTROYED => "Destroyed", - _ => "?", - } -} - -/// Run the alarms watching `counter` for a change from `old` to `new` -/// (Xorg `SyncChangeCounter` → each alarm trigger's `CheckTrigger`). This -/// is the frame-timing signal mutter/muffin waits on before compositing a -/// client frame and emitting `_NET_WM_FRAME_DRAWN`, and also the -/// idle/wake pair used by mate-power-manager. -pub(crate) fn evaluate_alarms_for_counter( - state: &mut ServerState, - counter: u32, - old: i64, - new: i64, -) { - use yserver_protocol::x11::sync as x11sync; - let mut candidates: Vec = state - .sync_alarms - .iter() - .filter(|(_, a)| { - a.counter == counter - && a.state == x11sync::ALARM_STATE_ACTIVE - && x11sync::trigger_fires(a.check_type, old, new, a.wait_value) - }) - .map(|(id, _)| *id) - .collect(); - candidates.sort_unstable(); - for alarm_id in candidates { - alarm_trigger_fired(state, alarm_id, new); - } -} - -/// The trigger test CreateAlarm / ChangeAlarm run on the one alarm they -/// set up: its counter's current value, as both old and new (so only a -/// comparison can already hold). -fn check_new_alarm_trigger(state: &mut ServerState, alarm_id: u32, counter: u32) { - use yserver_protocol::x11::sync as x11sync; - let now_value = crate::core_loop::sync_await::counter_value(state, counter).unwrap_or(0); - if counter == x11sync::SERVERTIME_COUNTER { - state.sync_servertime_last = Some(now_value); - } - let holds = state - .sync_alarms - .get(&alarm_id) - .is_some_and(|a| x11sync::trigger_fires(a.check_type, now_value, now_value, a.wait_value)); - if holds { - alarm_trigger_fired(state, alarm_id, now_value); - } -} - -/// Xorg `SyncAlarmTriggerFired`: alarm `alarm_id` went off with its -/// counter at `value` (0 and no counter for a counterless alarm). A -/// counterless alarm, or a comparison with delta 0, goes Inactive; -/// otherwise the wait value advances by delta until the test no longer -/// holds (Inactive, value kept, on INT64 overflow). The `AlarmNotify` -/// carries the new state and the old wait value; the new wait value is -/// stored after it is sent. -pub(crate) fn alarm_trigger_fired(state: &mut ServerState, alarm_id: u32, value: i64) { - use yserver_protocol::x11::sync as x11sync; - let Some(a) = state.sync_alarms.get(&alarm_id) else { - return; - }; - if a.state != x11sync::ALARM_STATE_ACTIVE { - return; - } - // Xorg reads the stored test type for the "delta 0 on a comparison" - // rule but re-arms with the trigger's check function; the two differ - // only after a ChangeAlarm that failed on an invalid test type. - let (test_type, check_type) = (a.test_type, a.check_type); - let (owner, counter, fired_wait, delta) = (a.owner, a.counter, a.wait_value, a.delta); - let is_comparison = matches!( - test_type, - x11sync::TEST_POSITIVE_COMPARISON | x11sync::TEST_NEGATIVE_COMPARISON - ); - let (new_wait, new_state) = if counter == 0 || (delta == 0 && is_comparison) { - (fired_wait, x11sync::ALARM_STATE_INACTIVE) - } else if delta == 0 { - // Transition + delta 0: stays Active with the same wait value; - // it fires again on the next crossing. - (fired_wait, x11sync::ALARM_STATE_ACTIVE) - } else { - let mut w = fired_wait; - let mut guard = 0u32; - let mut overflowed = false; - // The guard bounds what Xorg does not: after that failed - // ChangeAlarm a delta of the wrong sign passes the (unmatched) - // sign check, and Xorg's loop then steps toward INT64 overflow - // one delta at a time — a hung server (seen on Xvfb). - while x11sync::comparison_satisfied(check_type, value, w) && guard < 1_000_000 { - match w.checked_add(delta) { - Some(next) => { - w = next; - guard += 1; - } - None => { - overflowed = true; - break; - } - } - } - if overflowed { - (fired_wait, x11sync::ALARM_STATE_INACTIVE) - } else { - (w, x11sync::ALARM_STATE_ACTIVE) - } - }; - let owner_class = state - .client_wm_class - .get(&owner.0) - .map(String::as_str) - .unwrap_or(""); - log::debug!( - "sync: alarm 0x{alarm_id:x} fired client {owner_id}/{owner_class:?} \ - counter={counter_name}(0x{counter:x}) test={test} \ - value={value} wait={fired_wait} → state={state_name}", - owner_id = owner.0, - counter_name = sync_counter_name(counter), - test = sync_test_type_name(test_type), - state_name = sync_alarm_state_name(new_state), - ); - if let Some(a) = state.sync_alarms.get_mut(&alarm_id) { - a.state = new_state; - } - crate::core_loop::sync_await::send_alarm_notify(state, alarm_id, value); - if let Some(a) = state.sync_alarms.get_mut(&alarm_id) { - a.wait_value = new_wait; - } -} - -#[allow(clippy::too_many_arguments)] -/// Emit a `ShapeNotify` event to every client that `ShapeSelectInput`'d -/// `window`, after its `kind` region (bounding/clip/input) changed. Xorg's -/// `SendShapeNotify` does this on every shape mutation; yserver previously -/// applied the change to its own store (so its hit-test stayed correct) but -/// never told subscribers, so a compositing WM's cached input region went -/// permanently stale — clicks over the grown region fell through to the -/// window below (cinnamon "nemo rises"). No-op when nobody selected. -fn emit_shape_notify(state: &mut ServerState, window: ResourceId, kind: u8) { - let targets: Vec = state - .shape_select_masks - .iter() - .filter_map(|((cid, w), enabled)| (*enabled && *w == window).then_some(ClientId(*cid))) - .collect(); - if targets.is_empty() { - return; - } - let rects = crate::nested::shape_rects_for(state, window, kind); - let shaped = crate::nested::shape_kind_is_set(state, window, kind); - let extents = crate::nested::region_extents(&rects); - let server_time = state.timestamp_now(); - let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { - yserver_protocol::x11::shape::encode_shape_notify_event( - buf, - seq, - order, - crate::nested::SHAPE_FIRST_EVENT, - kind, - window.0, - extents, - shaped, - server_time, - ); - }); -} - -/// Compact one-line dump of a SHAPE region's rectangles for the -/// `shape diag` traces, e.g. `[(0,0 306x49)]`. Truncates past 8 rects. -fn fmt_shape_rects(rects: &[yserver_protocol::x11::xfixes::RegionRect]) -> String { - let mut s = String::from("["); - for (i, r) in rects.iter().enumerate() { - if i > 0 { - s.push(' '); - } - if i == 8 { - s.push_str(&format!("…+{}", rects.len() - 8)); - break; - } - s.push_str(&format!("({},{} {}x{})", r.x, r.y, r.width, r.height)); - } - s.push(']'); - s -} - -fn handle_shape_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, shape as x11shape}; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - debug!( - "client {} #{} SHAPE::minor={} body_len={}", - client_id.0, - sequence.0, - minor, - body.len() - ); - match minor { - x11shape::QUERY_VERSION => { - let reply = x11shape::encode_query_version_reply(byte_order, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11shape::RECTANGLES => { - if let Some((req, rects)) = x11shape::parse_rectangles_request(body) { - let window = ResourceId(req.dest); - debug!( - "client {} SHAPE::Rectangles dest=0x{:x} kind={} op={} off=({},{}) nrects={}", - client_id.0, - req.dest, - req.dest_kind, - req.op, - req.x_off, - req.y_off, - rects.len(), - ); - let source = crate::nested::offset_rects(rects, req.x_off, req.y_off); - let current = crate::nested::shape_rects_for(state, window, req.dest_kind); - let new_rects = crate::nested::apply_shape_op(current, source, req.op); - let changed = - crate::nested::set_shape_rects(state, window, req.dest_kind, new_rects); - mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); - if changed { - emit_shape_notify(state, window, req.dest_kind); - } - } - } - x11shape::MASK => { - if let Some(req) = x11shape::parse_mask_request(body) { - let window = ResourceId(req.dest); - debug!( - "client {} SHAPE::Mask dest=0x{:x} kind={} op={} src=0x{:x} off=({},{})", - client_id.0, req.dest, req.dest_kind, req.op, req.src, req.x_off, req.y_off, - ); - if req.src == 0 { - let changed = crate::nested::clear_shape_rects(state, window, req.dest_kind); - mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); - if changed { - emit_shape_notify(state, window, req.dest_kind); - } - return Ok(RequestOutcome::Handled); - } - // Read the depth-1 mask pixels and YX-band them into - // rectangles. Falls back to the source pixmap's - // bounding-box rect if the backend can't introspect - // (host-X11 proxy mode), preserving the previous - // best-effort behaviour for that path. - let src_id = ResourceId(req.src); - let host_xid = state.resources.pixmap(src_id).and_then(|p| p.host_xid); - let banded = if let Some(host) = host_xid { - match backend.read_depth1_pixmap(origin, host.as_raw()) { - Ok(Some((w, h, bytes))) => { - let rects = crate::nested::bitmap_to_yx_banded_rects(&bytes, w, h); - log::debug!( - "shape diag: MASK src=0x{:x} read_depth1_pixmap ok ({}x{} \ - bytes={}) banded_rects={}", - req.src, - w, - h, - bytes.len(), - rects.len() - ); - Some(rects) - } - Ok(None) => { - log::debug!( - "shape diag: MASK src=0x{:x} read_depth1_pixmap returned None \ - (no pixmap mirror)", - req.src - ); - None - } - Err(e) => { - log::debug!( - "shape diag: MASK src=0x{:x} read_depth1_pixmap err: {e}", - req.src - ); - None - } - } - } else { - log::debug!( - "shape diag: MASK src=0x{:x} no host_xid for source pixmap (fallback to \ - bounding-box rect)", - req.src - ); - None - }; - let source = - banded.unwrap_or_else(|| crate::nested::shape_mask_source_rects(state, src_id)); - let pre_off_count = source.len(); - let source = crate::nested::offset_rects(source, req.x_off, req.y_off); - let current = crate::nested::shape_rects_for(state, window, req.dest_kind); - let current_count = current.len(); - let new_rects = crate::nested::apply_shape_op(current, source, req.op); - log::debug!( - "shape diag: MASK dest=0x{:x} kind={} op={} source_rects(pre_offset)={} \ - current_rects={} new_rects={}", - req.dest, - req.dest_kind, - req.op, - pre_off_count, - current_count, - new_rects.len() - ); - let changed = - crate::nested::set_shape_rects(state, window, req.dest_kind, new_rects); - mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); - if changed { - emit_shape_notify(state, window, req.dest_kind); - } - } - } - x11shape::COMBINE => { - if let Some(req) = x11shape::parse_combine_request(body) { - let dest = ResourceId(req.dest); - let src = ResourceId(req.src); - debug!( - "client {} SHAPE::Combine dest=0x{:x} dest_kind={} src=0x{:x} src_kind={} op={} off=({},{})", - client_id.0, - req.dest, - req.dest_kind, - req.src, - req.src_kind, - req.op, - req.x_off, - req.y_off, - ); - let src_rects = crate::nested::shape_rects_for(state, src, req.src_kind); - let src_count = src_rects.len(); - let src_dims = fmt_shape_rects(&src_rects); - let source = crate::nested::offset_rects(src_rects, req.x_off, req.y_off); - let current = crate::nested::shape_rects_for(state, dest, req.dest_kind); - let current_count = current.len(); - let new_rects = crate::nested::apply_shape_op(current, source, req.op); - let new_count = new_rects.len(); - log::debug!( - "shape diag: COMBINE dest=0x{:x}(kind={}) src=0x{:x}(kind={}) op={} \ - src_rects={src_count} src_dims={src_dims} current_rects={current_count} \ - new_rects={new_count} new_dims={}", - req.dest, - req.dest_kind, - req.src, - req.src_kind, - req.op, - fmt_shape_rects(&new_rects), - ); - let changed = crate::nested::set_shape_rects(state, dest, req.dest_kind, new_rects); - mirror_shape_to_host_state(state, backend, origin, dest, req.dest_kind); - if changed { - emit_shape_notify(state, dest, req.dest_kind); - } - } - } - x11shape::OFFSET => { - if let Some(req) = x11shape::parse_offset_request(body) { - let dest = ResourceId(req.dest); - let mut translated = false; - if let Some(s) = state.shape_windows.get_mut(&dest) - && let Some(slot) = s.rects_mut(req.dest_kind) - && let Some(rects) = slot.as_mut() - { - crate::nested::translate_region(rects, req.x_off, req.y_off); - translated = true; - } - if translated { - mirror_shape_to_host_state(state, backend, origin, dest, req.dest_kind); - emit_shape_notify(state, dest, req.dest_kind); - } - } - } - x11shape::QUERY_EXTENTS => { - let window = ResourceId(x11shape::parse_window(body).unwrap_or(ROOT_WINDOW.0)); - let bounding_rects = - crate::nested::shape_rects_for(state, window, x11shape::KIND_BOUNDING); - let clip_rects = crate::nested::shape_rects_for(state, window, x11shape::KIND_CLIP); - let bounding_shaped = - crate::nested::shape_kind_is_set(state, window, x11shape::KIND_BOUNDING); - let clip_shaped = crate::nested::shape_kind_is_set(state, window, x11shape::KIND_CLIP); - let bounding = crate::nested::region_extents(&bounding_rects); - let clip = crate::nested::region_extents(&clip_rects); - let reply = x11shape::encode_query_extents_reply( - byte_order, - sequence, - bounding_shaped, - clip_shaped, - bounding, - clip, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11shape::SELECT_INPUT => { - if let Some(req) = x11shape::parse_select_input_request(body) { - let key = (client_id.0, ResourceId(req.window)); - if req.enable { - state.shape_select_masks.insert(key, true); - } else { - state.shape_select_masks.remove(&key); - } - } - } - x11shape::INPUT_SELECTED => { - let window = ResourceId(x11shape::parse_window(body).unwrap_or(ROOT_WINDOW.0)); - let enabled = state - .shape_select_masks - .get(&(client_id.0, window)) - .copied() - .unwrap_or(false); - let reply = x11shape::encode_input_selected_reply(byte_order, sequence, enabled); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11shape::GET_RECTANGLES => { - let (window, kind) = x11shape::parse_get_rectangles_request(body) - .map(|(w, k)| (ResourceId(w), k)) - .unwrap_or((ROOT_WINDOW, x11shape::KIND_BOUNDING)); - let rects = crate::nested::shape_rects_for(state, window, kind); - let reply = x11shape::encode_get_rectangles_reply( - byte_order, - sequence, - x11shape::ORDERING_YX_BANDED, - &rects, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// Xorg `ProcXFixesDispatch`: a client may only use the requests of the -/// XFIXES major version it negotiated — before its first `QueryVersion` -/// that is `QueryVersion` alone. Anything else is BadRequest. -fn dispatch_xfixes_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::xfixes as x11xfixes; - let client_major = state - .xfixes_client_major - .get(&client_id.0) - .copied() - .unwrap_or(0); - if !x11xfixes::request_allowed(client_major, header.data) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(header.data), - header.opcode, - ); - } - handle_xfixes_request(state, backend, origin, client_id, sequence, header, body) -} - -/// Xorg `VERIFY_CURSOR` for XFIXES: resolve a cursor XID to its host -/// handle, or send BadCursor naming it. `Err(outcome)` carries the error -/// already written. -fn xfixes_verify_cursor( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - cursor: u32, -) -> Result, io::Result> { - if state.resources.cursor_exists(ResourceId(cursor)) { - return Ok(state.resources.cursor_host_xid(ResourceId(cursor))); - } - Err(emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor, - u16::from(header.data), - header.opcode, - )) -} - -/// Xorg `ReplaceCursor` for XFIXES `ChangeCursor` / `ChangeCursorByName`: -/// every cursor XID and every displayed use of host cursor `old_host` -/// switches to `source`'s cursor. Replacing a cursor with itself is a -/// no-op, and the old host cursor is released once nothing names it. -fn xfixes_replace_cursor( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - old_host: u32, - source: ResourceId, -) { - let Some(new_host) = state.resources.cursor_host_xid(source) else { - return; - }; - if old_host == new_host { - return; - } - state.resources.retarget_cursor_host(old_host, source); - let _ = backend.replace_cursor(origin, old_host, new_host); - if !state.resources.cursor_host_referenced(old_host) { - let _ = backend.free_cursor(origin, old_host); - } -} - -/// Xorg `ExpandRegion` (`xfixes/region.c`): grow each rectangle of -/// `source` by the four margins and union the results. Coordinates are -/// computed wide and clamped to the protocol's 16-bit range. -fn xfixes_expand_region_rects( - source: &[yserver_protocol::x11::xfixes::RegionRect], - left: u16, - right: u16, - top: u16, - bottom: u16, -) -> Vec { - use yserver_protocol::x11::xfixes::RegionRect; - let clamp_i16 = |v: i32| { - i16::try_from(v.clamp(i32::from(i16::MIN), i32::from(i16::MAX))).unwrap_or_default() - }; - let grown: Vec = source - .iter() - .map(|r| { - let x1 = i32::from(r.x) - i32::from(left); - let y1 = i32::from(r.y) - i32::from(top); - let x2 = i32::from(r.x) + i32::from(r.width) + i32::from(right); - let y2 = i32::from(r.y) + i32::from(r.height) + i32::from(bottom); - let (x1, y1, x2, y2) = (clamp_i16(x1), clamp_i16(y1), clamp_i16(x2), clamp_i16(y2)); - RegionRect { - x: x1, - y: y1, - width: u16::try_from(i32::from(x2) - i32::from(x1)).unwrap_or(0), - height: u16::try_from(i32::from(y2) - i32::from(y1)).unwrap_or(0), - } - }) - .collect(); - grown.iter().fold(Vec::new(), |acc, rect| { - crate::nested::union_regions(&acc, &[*rect]) - }) -} - -/// Send XFIXES `DisplayCursorNotify` for a backend-reported sprite change -/// to every (client, window) that selected it — one event per selection, -/// as Xorg's `CursorDisplayCursor` walks its `cursorEvents` list. Called -/// after each request and at the end of each loop iteration. -pub(crate) fn emit_xfixes_cursor_notify(state: &mut ServerState, backend: &mut dyn Backend) { - use yserver_protocol::x11::xfixes as x11xfixes; - let Some(change) = backend.take_displayed_cursor_change() else { - return; - }; - let mut selections: Vec<(u32, u32)> = state - .xfixes_cursor_masks - .iter() - .filter(|(_, mask)| **mask & x11xfixes::DISPLAY_CURSOR_NOTIFY_MASK != 0) - .map(|((client, window), _)| (*client, window.0)) - .collect(); - if selections.is_empty() { - return; - } - selections.sort_unstable(); - let name = state - .resources - .cursor_name_for_host(change.host_xid) - .map_or(0, |atom| atom.0); - let timestamp = state.timestamp_now(); - for (client, window) in selections { - let _dropped = fanout_event_to_clients(state, &[ClientId(client)], |buf, seq, order| { - x11xfixes::encode_cursor_notify_event( - buf, - order, - crate::nested::XFIXES_FIRST_EVENT, - seq, - window, - change.serial, - timestamp, - name, - ); - }); - } -} - -/// Drop `client`'s XFIXES per-client state on disconnect. Xorg frees the -/// client's `CursorHideCountRec` resource, which re-displays the sprite -/// once no other client holds a hide. -pub(crate) fn release_xfixes_client_state( - state: &mut ServerState, - backend: &mut dyn Backend, - client: ClientId, -) { - state.xfixes_client_major.remove(&client.0); - if state.xfixes_cursor_hide_counts.remove(&client.0).is_some() - && state.xfixes_cursor_hide_counts.is_empty() - { - backend.set_cursor_hidden(false); - } -} - -#[allow(clippy::too_many_arguments)] -fn handle_xfixes_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, xfixes as x11xfixes}; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - match minor { - x11xfixes::QUERY_VERSION => { - // Xorg `ProcXFixesQueryVersion`: REQUEST_SIZE_MATCH, then the - // lower-of-the-two rule with a sticky per-client major. - let Some((client_major, client_minor)) = - x11xfixes::parse_query_version(byte_order, body) - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - }; - let previous = state - .xfixes_client_major - .get(&client_id.0) - .copied() - .unwrap_or(0); - let negotiated = x11xfixes::negotiate_version(previous, client_major, client_minor); - state - .xfixes_client_major - .insert(client_id.0, negotiated.client_major); - debug!( - "client {} #{} XFIXES::QueryVersion client={client_major}.{client_minor} -> {}.{}", - client_id.0, sequence.0, negotiated.reply_major, negotiated.reply_minor, - ); - let reply = x11xfixes::encode_query_version_reply( - byte_order, - sequence, - negotiated.reply_major, - negotiated.reply_minor, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11xfixes::SELECT_SELECTION_INPUT => { - if let Some(req) = x11xfixes::parse_select_selection_input(body) { - // Xorg `ProcXFixesSelectSelectionInput` - // (xfixes/select.c:189-196): validate the window - // first, then the mask, before mutating state. - if state.resources.window(ResourceId(req.window)).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - XFIXES_MAJOR_OPCODE, - ); - } - if req.event_mask & !x11xfixes::SELECTION_ALL_EVENTS_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.event_mask, - XFIXES_MAJOR_OPCODE, - ); - } - let key = ( - client_id.0, - ResourceId(req.window), - yserver_protocol::x11::AtomId(req.selection), - ); - if req.event_mask == 0 { - state.xfixes_selection_masks.remove(&key); - } else { - state.xfixes_selection_masks.insert(key, req.event_mask); - } - } - } - x11xfixes::SELECT_CURSOR_INPUT => { - if let Some(req) = x11xfixes::parse_select_cursor_input(body) { - // Xorg `ProcXFixesSelectCursorInput`: window first, then - // the mask (captured on Xvfb: BadWindow, BadValue). - if state.resources.window(ResourceId(req.window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - u16::from(minor), - header.opcode, - ); - } - if req.event_mask & !x11xfixes::CURSOR_ALL_EVENTS_MASK != 0 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.event_mask, - u16::from(minor), - header.opcode, - ); - } - let key = (client_id.0, ResourceId(req.window)); - if req.event_mask == 0 { - state.xfixes_cursor_masks.remove(&key); - } else { - state.xfixes_cursor_masks.insert(key, req.event_mask); - } - } - } - x11xfixes::GET_CURSOR_IMAGE => { - // Stage 5 unblock for audit #14: source the active - // cursor from the backend. Pre-Stage-5 backends - // (`ynest`, `RecordingBackend`) return `None` — fall - // back to the empty reply so existing client behaviour - // doesn't regress (a 0×0 reply is still a valid X11 - // GetCursorImage response). - let reply = match backend.get_active_cursor_image() { - Some(img) => x11xfixes::encode_get_cursor_image_reply( - byte_order, - sequence, - img.x, - img.y, - img.width, - img.height, - img.hot_x, - img.hot_y, - img.serial, - img.bgra_bytes.as_ref(), - ), - None => x11xfixes::encode_get_cursor_image_empty_reply(byte_order, sequence), - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11xfixes::GET_CURSOR_IMAGE_AND_NAME => { - // Superset of GetCursorImage (opcode 25). Real X screen - // recorders (gpu-screen-recorder, …) call this to grab the - // cursor; with no reply they block forever in poll(). The - // name is the displayed cursor's XFIXES name (Xorg - // `pCursor->name`), empty when it was never named. - let reply = match backend.get_active_cursor_image() { - Some(img) => { - let atom = state - .resources - .cursor_name_for_host(img.host_xid) - .unwrap_or(AtomId(0)); - let name = state.atoms.name(atom).map(str::as_bytes).unwrap_or(&[]); - x11xfixes::encode_get_cursor_image_and_name_reply( - byte_order, - sequence, - img.x, - img.y, - img.width, - img.height, - img.hot_x, - img.hot_y, - img.serial, - atom.0, - name, - img.bgra_bytes.as_ref(), - ) - } - None => { - x11xfixes::encode_get_cursor_image_and_name_empty_reply(byte_order, sequence) - } - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11xfixes::CREATE_REGION => { - if let Some((region, rects)) = x11xfixes::parse_create_region(body) { - if xfixes_region_xid_already_taken(state, region) - || xid_out_of_client_range(state, client_id, region) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - region, - XFIXES_MAJOR_OPCODE, - ); - } - state.xfixes_regions.insert( - region, - crate::server::XFixesRegion { - owner: client_id, - rects: normalize_region_rects(rects), - }, - ); - } - } - x11xfixes::CREATE_POINTER_BARRIER => { - if let Some(req) = x11xfixes::parse_create_pointer_barrier(body) { - // Xorg XICreatePointerBarrier validation order: - // geometry -> negative-on-own-axis -> window -> devices -> xid. - let horizontal = req.y1 == req.y2; - let vertical = req.x1 == req.x2; - if horizontal == vertical { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.barrier, - XFIXES_MAJOR_OPCODE, - ); - } - if (horizontal && (req.y1 < 0 || req.y2 < 0)) - || (vertical && (req.x1 < 0 || req.x2 < 0)) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.barrier, - XFIXES_MAJOR_OPCODE, - ); - } - if state.resources.window(ResourceId(req.window)).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - XFIXES_MAJOR_OPCODE, - ); - } - for &d in &req.devices { - if !(d == 0 || d == 1 || d == 2) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, - u32::from(d), - u16::from(x11xfixes::CREATE_POINTER_BARRIER), - XFIXES_MAJOR_OPCODE, - ); - } - } - if state.xid_occupied(req.barrier) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.barrier, - XFIXES_MAJOR_OPCODE, - ); - } - if xid_out_of_client_range(state, client_id, req.barrier) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - req.barrier, - XFIXES_MAJOR_OPCODE, - ); - } - let (mut x1, mut x2) = (req.x1, req.x2); - let (mut y1, mut y2) = (req.y1, req.y2); - if x1 >= 0 && x2 >= 0 && x1 > x2 { - std::mem::swap(&mut x1, &mut x2); - } - if y1 >= 0 && y2 >= 0 && y1 > y2 { - std::mem::swap(&mut y1, &mut y2); - } - let directions = if horizontal { - req.directions & !(1 | 4) - } else { - req.directions & !(2 | 8) - }; - state.pointer_barriers.insert( - req.barrier, - crate::server::PointerBarrier { - owner: client_id, - window: ResourceId(req.window), - x1, - y1, - x2, - y2, - directions, - devices: req.devices, - hit: false, - seen: false, - event_id: 1, - release_event_id: 0, - last_timestamp: 0, - }, - ); - log::trace!( - target: "yserver_core::barriers", - "create barrier xid=0x{:x} window=0x{:x} ({x1},{y1})-({x2},{y2}) dirs={directions} -> {} active", - req.barrier, - req.window, - state.pointer_barriers.len(), - ); - } - } - x11xfixes::DELETE_POINTER_BARRIER => { - if let Some(bid) = x11xfixes::parse_delete_pointer_barrier(body) { - match state.pointer_barriers.get(&bid) { - None => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - bid, - XFIXES_MAJOR_OPCODE, - ); - } - Some(b) if b.owner != client_id => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - bid, - XFIXES_MAJOR_OPCODE, - ); - } - Some(barrier) => { - if barrier.hit { - // Xorg BarrierFreeBarrier emits the released leave - // with the CURRENT time + sprite position (not the - // last-hit values), xibarriers.c:668. Copy the - // barrier fields out first to release the borrow. - let (owner, window, eid) = - (barrier.owner, barrier.window, barrier.event_id); - let time = state.timestamp_now(); - let (rx, ry) = state.pointer_root; - let _dropped = crate::core_loop::pointer_fanout::emit_barrier_event( - state, - bid, - owner, - window, - 26, - time, - eid, - 0, - 1, - 0, - i32::from(rx), - i32::from(ry), - 0.0, - 0.0, - ); - } - state.pointer_barriers.remove(&bid); - } - } - } - } - x11xfixes::CREATE_REGION_FROM_BITMAP | x11xfixes::CREATE_REGION_FROM_GC => { - if let Some((region, source)) = x11xfixes::parse_u32_pair(body) { - if xfixes_region_xid_already_taken(state, region) - || xid_out_of_client_range(state, client_id, region) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - region, - XFIXES_MAJOR_OPCODE, - ); - } - if minor == x11xfixes::CREATE_REGION_FROM_GC { - let gc = ResourceId(source); - let Some(g) = state.resources.gc(gc) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_GC, - source, - XFIXES_MAJOR_OPCODE, - ); - }; - let Some(clip) = g.clip_rectangles.clone() else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - source, - XFIXES_MAJOR_OPCODE, - ); - }; - // Audit #7 (docs/protocol-audit-2026-05-19.md): - // copy the GC's clip rects RAW — Xorg's - // `ProcXFixesCreateRegionFromGC` - // (`xfixes/region.c:219-226`) does - // `XFixesRegionCopy(pGC->clientClip)` with no - // translation. `clip.x_origin` / `clip.y_origin` - // are properties of the GC's USE, not part of - // the region's content; otherwise a subsequent - // `SetGcClipRegion(gc, region, x_origin, - // y_origin)` double-translates. - let rects = x11xfixes::parse_rectangles(&clip.rectangles); - state.xfixes_regions.insert( - region, - crate::server::XFixesRegion { - owner: client_id, - rects, - }, - ); - } else { - state.xfixes_regions.insert( - region, - crate::server::XFixesRegion { - owner: client_id, - rects: Vec::new(), - }, - ); - } - } - } - x11xfixes::CREATE_REGION_FROM_WINDOW => { - if let Some((region, window, kind)) = x11xfixes::parse_create_region_from_window(body) { - if xfixes_region_xid_already_taken(state, region) - || xid_out_of_client_range(state, client_id, region) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - region, - XFIXES_MAJOR_OPCODE, - ); - } - // BadWindow on unknown window xid - // (`xfixes/region.c:158-163`) — Xorg sets - // `client->error_value = stuff->window`. - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - XFIXES_MAJOR_OPCODE, - ); - } - // BadValue on `kind` outside {Bounding=0, Clip=1} - // (`xfixes/region.c:164-181`). The SHAPE-shaped - // Input(2) is explicitly rejected by Xorg here. - if kind > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(kind), - XFIXES_MAJOR_OPCODE, - ); - } - let rects = crate::nested::shape_rects_for(state, ResourceId(window), kind); - trace!( - target: "yserver::xfixes::region", - "CreateRegionFromWindow region=0x{region:08x} window=0x{window:08x} kind={} rects{}", - kind, - format_region_rects(&rects), - ); - state.xfixes_regions.insert( - region, - crate::server::XFixesRegion { - owner: client_id, - rects, - }, - ); - } - } - x11xfixes::CREATE_REGION_FROM_PICTURE => { - if let Some((region, picture)) = x11xfixes::parse_create_region_from_picture(body) { - if xfixes_region_xid_already_taken(state, region) - || xid_out_of_client_range(state, client_id, region) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - region, - XFIXES_MAJOR_OPCODE, - ); - } - // VERIFY_PICTURE (`xfixes/region.c:255`) returns - // `RenderErrBase + BadPicture` on an unknown - // picture xid — NOT BadDrawable. - let bad_picture = crate::nested::RENDER_FIRST_ERROR + 1; - let Some(picture_state) = state.resources.picture(ResourceId(picture)) else { - return emit_x11_error( - state, - client_id, - sequence, - bad_picture, - picture, - XFIXES_MAJOR_OPCODE, - ); - }; - // `if (!pPicture->pDrawable) return RenderErrBase + - // BadPicture` at `xfixes/region.c:257-258`. yserver's - // `PictureKind::Sourceless` (SolidFill / gradient - // pictures) is exactly that case. - if matches!( - picture_state.kind, - crate::resources::PictureKind::Sourceless - ) { - return emit_x11_error( - state, - client_id, - sequence, - bad_picture, - picture, - XFIXES_MAJOR_OPCODE, - ); - } - // An unbacked Picture has no clip set, like a fresh one. - let client_clip = match picture_state.host_picture_xid { - Some(hp) => backend.picture_client_clip_rects(hp.as_raw()), - None => Some(None), - }; - let Some(client_clip) = client_clip else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - picture, - XFIXES_MAJOR_OPCODE, - ); - }; - let Some(rects) = client_clip else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - picture, - XFIXES_MAJOR_OPCODE, - ); - }; - state.xfixes_regions.insert( - region, - crate::server::XFixesRegion { - owner: client_id, - rects: normalize_region_rects(rects), - }, - ); - } - } - x11xfixes::DESTROY_REGION => { - if let Some((region, _)) = x11xfixes::parse_u32_pair(body) { - state.xfixes_regions.remove(®ion); - } else if body.len() >= 4 { - let region = u32::from_le_bytes(body[0..4].try_into().unwrap()); - state.xfixes_regions.remove(®ion); - } - } - x11xfixes::SET_REGION => { - if let Some((region, rects)) = x11xfixes::parse_create_region(body) { - state - .xfixes_regions - .entry(region) - .and_modify(|r| r.rects = normalize_region_rects(rects.clone())) - .or_insert_with(|| crate::server::XFixesRegion { - owner: client_id, - rects: normalize_region_rects(rects), - }); - } - } - x11xfixes::COPY_REGION => { - if let Some((source, dest)) = x11xfixes::parse_u32_pair(body) { - let rects = state - .xfixes_regions - .get(&source) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - trace!( - target: "yserver::xfixes::region", - "CopyRegion src=0x{source:08x} dst=0x{dest:08x} rects{}", - format_region_rects(&rects), - ); - state.xfixes_regions.insert( - dest, - crate::server::XFixesRegion { - owner: client_id, - rects, - }, - ); - } - } - x11xfixes::UNION_REGION | x11xfixes::INTERSECT_REGION | x11xfixes::SUBTRACT_REGION => { - if let Some((source1, source2, dest)) = x11xfixes::parse_u32_triplet(body) { - let a = state - .xfixes_regions - .get(&source1) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - let b = state - .xfixes_regions - .get(&source2) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - let op_name = match minor { - x11xfixes::UNION_REGION => "UnionRegion", - x11xfixes::INTERSECT_REGION => "IntersectRegion", - x11xfixes::SUBTRACT_REGION => "SubtractRegion", - _ => unreachable!(), - }; - let rects = match minor { - x11xfixes::UNION_REGION => crate::nested::union_regions(&a, &b), - x11xfixes::INTERSECT_REGION => crate::nested::intersect_regions(&a, &b), - x11xfixes::SUBTRACT_REGION => { - // Real rect-band subtraction (a - b). The - // previous implementation collapsed any - // overlap to an empty result — wrong for - // any compositor that builds a wallpaper - // clip via SubtractRegion(screen, windows). - crate::nested::subtract_regions(&a, &b) - } - _ => unreachable!(), - }; - trace!( - target: "yserver::xfixes::region", - "{op_name} a=0x{source1:08x} rects{} b=0x{source2:08x} rects{} dst=0x{dest:08x} rects{}", - format_region_rects(&a), - format_region_rects(&b), - format_region_rects(&rects), - ); - state.xfixes_regions.insert( - dest, - crate::server::XFixesRegion { - owner: client_id, - rects, - }, - ); - } - } - x11xfixes::INVERT_REGION => { - if let Some((source, bounds, dest)) = x11xfixes::parse_invert_region(body) { - let source_rects = state - .xfixes_regions - .get(&source) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - state.xfixes_regions.insert( - dest, - crate::server::XFixesRegion { - owner: client_id, - rects: crate::nested::subtract_regions( - &normalize_region_rects(vec![bounds]), - &source_rects, - ), - }, - ); - } - } - x11xfixes::TRANSLATE_REGION => { - if let Some((region_id, dx, dy)) = x11xfixes::parse_translate_region(body) - && let Some(region) = state.xfixes_regions.get_mut(®ion_id) - { - let before = region.rects.clone(); - crate::nested::translate_region(&mut region.rects, dx, dy); - trace!( - target: "yserver::xfixes::region", - "TranslateRegion region=0x{region_id:08x} delta=({dx}, {dy}) before{} after{}", - format_region_rects(&before), - format_region_rects(®ion.rects), - ); - } - } - x11xfixes::REGION_EXTENTS => { - if let Some((source, dest)) = x11xfixes::parse_u32_pair(body) { - let rect = state - .xfixes_regions - .get(&source) - .map(|r| crate::nested::region_extents(&r.rects)) - .unwrap_or(x11xfixes::RegionRect { - x: 0, - y: 0, - width: 0, - height: 0, - }); - state.xfixes_regions.insert( - dest, - crate::server::XFixesRegion { - owner: client_id, - rects: normalize_region_rects(vec![rect]), - }, - ); - } - } - x11xfixes::FETCH_REGION => { - let region = body - .get(0..4) - .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) - .unwrap_or(0); - let rects = state - .xfixes_regions - .get(®ion) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - let extents = crate::nested::region_extents(&rects); - let reply = x11xfixes::encode_fetch_region_reply(byte_order, sequence, extents, &rects); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11xfixes::CHANGE_SAVE_SET => { - if let Some(req) = x11xfixes::parse_change_save_set(body) - && let Some(c) = state.clients.get_mut(&client_id.0) - { - let win = ResourceId(req.window); - match req.mode { - 0 => { - c.save_set.insert(win); - } - 1 => { - c.save_set.remove(&win); - } - _ => {} - } - // target (Nearest/Root) and map (Map/Unmap) parameters affect - // disconnect-time reparent/remap behaviour; that path is - // already deferred from the Phase 2 wrap-up. Ignore for now. - } - } - x11xfixes::SET_GC_CLIP_REGION => { - if let Some(req) = x11xfixes::parse_set_gc_clip_region(body) { - let gc_id = ResourceId(req.gc); - if req.region == 0 { - state.resources.clear_gc_clip(gc_id); - } else { - let rects = state - .xfixes_regions - .get(&req.region) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - let mut rectangles = Vec::with_capacity(rects.len() * 8); - for rect in &rects { - rectangles.extend_from_slice(&rect.x.to_le_bytes()); - rectangles.extend_from_slice(&rect.y.to_le_bytes()); - rectangles.extend_from_slice(&rect.width.to_le_bytes()); - rectangles.extend_from_slice(&rect.height.to_le_bytes()); - } - state.resources.set_clip_rectangles( - client_id, - yserver_protocol::x11::SetClipRectanglesRequest { - gc: gc_id, - clip: yserver_protocol::x11::ClipRectangles { - ordering: 0, // Unsorted; matches xfixes region semantics. - x_origin: req.x_origin, - y_origin: req.y_origin, - rectangles, - }, - }, - ); - } - } - } - x11xfixes::SET_WINDOW_SHAPE_REGION => { - if let Some(req) = x11xfixes::parse_set_window_shape_region(body) { - let window = ResourceId(req.dest); - if req.region == 0 { - crate::nested::clear_shape_rects(state, window, req.dest_kind); - } else { - let rects = state - .xfixes_regions - .get(&req.region) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - let source = crate::nested::offset_rects(rects, req.x_offset, req.y_offset); - crate::nested::set_shape_rects(state, window, req.dest_kind, source); - } - mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); - } - } - x11xfixes::SET_PICTURE_CLIP_REGION => { - if let Some(req) = x11xfixes::parse_set_picture_clip_region(body) { - let pic_id = ResourceId(req.picture); - let host_pic = state - .resources - .picture(pic_id) - .and_then(|p| p.host_picture_xid) - .map(|h| h.as_raw()); - if let Some(hp) = host_pic { - if req.region == 0 { - // RENDER CPClipMask = 0x40; value=None clears the clip. - let mut out = Vec::with_capacity(12); - out.extend_from_slice(&req.picture.to_le_bytes()); - out.extend_from_slice(&0x40_u32.to_le_bytes()); - out.extend_from_slice(&0_u32.to_le_bytes()); - let _ = backend.render_change_picture(origin, hp, &out); - } else { - let rects = state - .xfixes_regions - .get(&req.region) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - trace!( - target: "yserver::xfixes::clip", - "SetPictureClipRegion client_pic=0x{:08x} host_pic=0x{hp:08x} region=0x{:08x} origin=({}, {}) n={} rects{}", - req.picture, - req.region, - req.x_origin, - req.y_origin, - rects.len(), - format_region_rects(&rects), - ); - // RENDER SetPictureClipRectangles body layout: - // picture(4) | x_origin(2) | y_origin(2) | rects(8*N). - let mut out = Vec::with_capacity(8 + rects.len() * 8); - out.extend_from_slice(&req.picture.to_le_bytes()); - out.extend_from_slice(&req.x_origin.to_le_bytes()); - out.extend_from_slice(&req.y_origin.to_le_bytes()); - for rect in &rects { - out.extend_from_slice(&rect.x.to_le_bytes()); - out.extend_from_slice(&rect.y.to_le_bytes()); - out.extend_from_slice(&rect.width.to_le_bytes()); - out.extend_from_slice(&rect.height.to_le_bytes()); - } - let _ = backend.render_set_picture_clip_rectangles(origin, hp, &out); - } - } - } - } - x11xfixes::CHANGE_CURSOR => { - // Xorg `ProcXFixesChangeCursor`: both cursors must exist - // (source checked first), then every use of `destination` — - // its XIDs, window cursors, grabs — becomes `source`. - let Some((source, destination)) = x11xfixes::parse_change_cursor(byte_order, body) - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - }; - if let Err(outcome) = xfixes_verify_cursor(state, client_id, sequence, header, source) { - return outcome; - } - let dest_host = - match xfixes_verify_cursor(state, client_id, sequence, header, destination) { - Ok(host) => host, - Err(outcome) => return outcome, - }; - if let Some(dest_host) = dest_host { - xfixes_replace_cursor(state, backend, origin, dest_host, ResourceId(source)); - } - } - x11xfixes::CHANGE_CURSOR_BY_NAME => { - // Xorg `ProcXFixesChangeCursorByName`: the source must exist; - // a name that was never interned matches nothing (MakeAtom - // with create=FALSE) and succeeds silently. - if let Some((cursor_xid, name_bytes)) = x11xfixes::parse_change_cursor_by_name(body) { - if let Err(outcome) = - xfixes_verify_cursor(state, client_id, sequence, header, cursor_xid) - { - return outcome; - } - let name = std::str::from_utf8(name_bytes).unwrap_or(""); - let atom = state.atoms.intern(name, true); - if atom.0 != 0 { - for host in state.resources.cursor_hosts_named(atom) { - xfixes_replace_cursor(state, backend, origin, host, ResourceId(cursor_xid)); - } - } - } - } - x11xfixes::EXPAND_REGION => { - let Some(req) = x11xfixes::parse_expand_region(byte_order, body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - }; - // VERIFY_REGION source then destination: XFixes BadRegion - // (error base + 0). - for region in [req.source, req.destination] { - if !state.xfixes_regions.contains_key(®ion) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::XFIXES_FIRST_ERROR, - region, - u16::from(minor), - header.opcode, - ); - } - } - let source = state.xfixes_regions[&req.source].rects.clone(); - // An empty source leaves the destination untouched (Xorg only - // rewrites it inside `if (nBoxes)`; confirmed on Xvfb). - if !source.is_empty() { - let rects = - xfixes_expand_region_rects(&source, req.left, req.right, req.top, req.bottom); - trace!( - target: "yserver::xfixes::region", - "ExpandRegion src=0x{:08x} dst=0x{:08x} l={} r={} t={} b={} rects{}", - req.source, - req.destination, - req.left, - req.right, - req.top, - req.bottom, - format_region_rects(&rects), - ); - if let Some(dest) = state.xfixes_regions.get_mut(&req.destination) { - dest.rects = rects; - } - } - } - x11xfixes::SET_CURSOR_NAME => { - // SetCursorName(cursor, name) — XFixes 2.0: tag a cursor - // with a name string. Xorg interns the name as an atom and - // stores it on the cursor (`pCursor->name = atom`) so - // GetCursorName can read it back. yserver mirrors the same - // shape: intern, store on `Cursor.name_atom`. - if let Some((cursor_xid, name_bytes)) = x11xfixes::parse_set_cursor_name(body) { - if let Err(outcome) = - xfixes_verify_cursor(state, client_id, sequence, header, cursor_xid) - { - return outcome; - } - let name = std::str::from_utf8(name_bytes).unwrap_or(""); - let atom = state.atoms.intern(name, false); - state - .resources - .set_cursor_name_atom(ResourceId(cursor_xid), atom); - debug!( - "client {} #{} XFIXES::SetCursorName cursor=0x{:x} atom={} \"{}\"", - client_id.0, sequence.0, cursor_xid, atom.0, name, - ); - } else { - debug!( - "client {} #{} XFIXES::SetCursorName (malformed body, ignored)", - client_id.0, sequence.0, - ); - } - } - x11xfixes::GET_CURSOR_NAME => { - // GetCursorName(cursor) — reply with atom + name string. - // If no name was ever set, return atom=None(0) and an - // empty name, matching Xorg's behaviour for cursors with - // `pCursor->name == 0`. - let cursor_xid = body - .get(0..4) - .map(|b| u32::from_le_bytes(b.try_into().unwrap())) - .unwrap_or(0); - if let Err(outcome) = - xfixes_verify_cursor(state, client_id, sequence, header, cursor_xid) - { - return outcome; - } - let atom = state - .resources - .cursor_name_atom(ResourceId(cursor_xid)) - .unwrap_or(AtomId(0)); - let name = state.atoms.name(atom).map(str::as_bytes).unwrap_or(&[]); - debug!( - "client {} #{} XFIXES::GetCursorName cursor=0x{:x} atom={} ({} bytes)", - client_id.0, - sequence.0, - cursor_xid, - atom.0, - name.len(), - ); - let reply = x11xfixes::encode_get_cursor_name_reply(byte_order, sequence, atom.0, name); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11xfixes::HIDE_CURSOR | x11xfixes::SHOW_CURSOR => { - // Xorg `ProcXFixesHideCursor` / `ProcXFixesShowCursor`: the - // window only names the screen (one here); the hide count is - // per client. The sprite hides on the first count anywhere and - // returns when the last one goes (ShowCursor to zero, or the - // client disconnecting). - let Some(window) = x11xfixes::parse_window(byte_order, body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - }; - if state.resources.window(ResourceId(window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window, - u16::from(minor), - header.opcode, - ); - } - if minor == x11xfixes::HIDE_CURSOR { - let was_visible = state.xfixes_cursor_hide_counts.is_empty(); - *state - .xfixes_cursor_hide_counts - .entry(client_id.0) - .or_insert(0) += 1; - if was_visible { - backend.set_cursor_hidden(true); - } - } else { - // Showing without a prior hide is BadMatch (Xvfb: error 8, - // value = the window). - let Some(count) = state.xfixes_cursor_hide_counts.get_mut(&client_id.0) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - window, - u16::from(minor), - header.opcode, - ); - }; - *count -= 1; - if *count == 0 { - state.xfixes_cursor_hide_counts.remove(&client_id.0); - if state.xfixes_cursor_hide_counts.is_empty() { - backend.set_cursor_hidden(false); - } - } - } - debug!( - "client {} #{} XFIXES::{}Cursor window=0x{window:x} hide_counts={:?}", - client_id.0, - sequence.0, - if minor == x11xfixes::HIDE_CURSOR { - "Hide" - } else { - "Show" - }, - state.xfixes_cursor_hide_counts, - ); - } - other if other > x11xfixes::DELETE_POINTER_BARRIER => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - other => { - // Every 5.0 request has an arm above; the gate in - // `dispatch_xfixes_request` keeps higher minors out. - debug!( - "client {} #{} XFIXES::unexpected minor={}", - client_id.0, sequence.0, other - ); - } - } - Ok(RequestOutcome::Handled) -} - -#[allow(clippy::too_many_arguments)] -fn handle_composite_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, composite as x11composite}; - const COMPOSITE_MAJOR_OPCODE: u8 = 144; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - match minor { - x11composite::QUERY_VERSION => { - let _ = x11composite::parse_query_version(body); - let major = x11composite::MAJOR_VERSION; - let minor_ver = x11composite::MINOR_VERSION; - debug!( - "client {} #{} COMPOSITE::QueryVersion -> {}.{}", - client_id.0, sequence.0, major, minor_ver - ); - let reply = - x11composite::encode_query_version_reply(byte_order, sequence, major, minor_ver); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11composite::REDIRECT_WINDOW | x11composite::REDIRECT_SUBWINDOWS => { - if let Some((window, update)) = x11composite::parse_window_update(body) { - let subwindows = minor == x11composite::REDIRECT_SUBWINDOWS; - // Xorg compRedirectWindow (composite/compalloc.c:145-147): a - // client request to redirect the overlay window returns - // Success without installing any redirect. The COW reaches - // scanout via the normal paint path; it is never itself - // redirected. Match that exactly — NOT BadMatch (which would - // be a yserver-invented error). Scoped to RedirectWindow; - // RedirectSubwindows(COW) is benign (COW has no children to - // redirect) and Xorg doesn't special-case it either. - if !subwindows && ResourceId(window) == COMPOSITE_OVERLAY_WINDOW { - return Ok(RequestOutcome::Handled); - } - // compositeproto: update=0 → Automatic, update=1 → Manual. - // Both wire constants are spec-legal; reject anything else - // with BadValue. We don't yet have a compositor consumer - // for the redirected-backing pixmap, so registering the - // record is enough — NameWindowPixmap consults the record - // and that's the part real compositing WMs need to make - // progress (xfwm4, picom, xcompmgr, mate-panel's - // notification-area-applet for its tray window). - let mode = match update { - 0 => crate::server::CompositeRedirectMode::Automatic, - 1 => crate::server::CompositeRedirectMode::Manual, - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(update), - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - }; - let key = (ResourceId(window), subwindows); - let prev = state.composite_redirects.get(&key).copied(); - // Xorg compRedirectWindow (composite/compalloc.c:155-158) - // permits only one Manual redirect on a window, regardless - // of whether the existing redirect came from RedirectWindow - // or was inherited from RedirectSubwindows(parent). Muffin - // deliberately probes with RedirectWindow(frame, Manual) - // after root RedirectSubwindows(Manual); Xorg returns - // BadAccess even though both requests are from Muffin. - // - // Treating the two key shapes as independent is not merely - // an error-code mismatch: a root child can inherit Manual, - // receive the redundant direct record, and later be - // reparented below a frame. The direct record then makes - // reparent reconciliation preserve a stale inner backing, - // so the application paints frames that the compositor - // never samples (Warframe fullscreen -> windowed: black). - let inherited_manual = !subwindows - && state - .resources - .window(ResourceId(window)) - .and_then(|w| state.composite_redirects.get(&(w.parent, true))) - .is_some_and(|record| { - matches!(record.mode, crate::server::CompositeRedirectMode::Manual) - }); - let same_key_manual = prev.is_some_and(|record| { - matches!(record.mode, crate::server::CompositeRedirectMode::Manual) - }); - if matches!(mode, crate::server::CompositeRedirectMode::Manual) - && (same_key_manual || inherited_manual) - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - window, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - if let Some(existing) = prev - && existing.owner != client_id - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - window, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - let mode_flip = matches!(prev, Some(p) if p.mode != mode); - let mode_flip_suffix = if mode_flip { - match prev { - Some(p) => format!(" [mode-flip from {:?}]", p.mode), - None => String::new(), - } - } else { - String::new() - }; - debug!( - "client {} #{} COMPOSITE::Redirect{}(0x{:x}, mode={:?}{})", - client_id.0, - sequence.0, - if subwindows { "Subwindows" } else { "Window" }, - window, - mode, - mode_flip_suffix, - ); - state.composite_redirects.insert( - key, - crate::server::RedirectRecord { - mode, - owner: client_id, - }, - ); - // Stage 4b: backing activation + scene-participation - // flip, gated on `Backend::supports_redirect_activation()`. - // v1 returns `false` (keeping the post-`3751c11` - // MATE-fix shape: record only, no backing routing); - // v2 returns `true` and the helper allocates + flips - // participation. - if backend.supports_redirect_activation() { - // Stage 4b.8: same-owner mode-flip is preserved - // across the flip per Xorg's compCheckRedirect - // (`xserver/composite/compwindow.c:172` + - // `compositeproto.txt:80`). Backing pixmap + - // NameWindowPixmap aliases survive; only the - // window's + backing's `scene_participating` - // flags flip. No re-seed (B's content is - // preserved as-is — re-running the seed-copy - // would clobber the compositor's in-flight - // paint per the plan's codex-round-6 decision). - let targets: Vec = if subwindows { - // Snapshot children to a Vec — the helper takes - // `&mut state`, so the borrow on `state.resources` - // from `children(..)` can't be held across calls. - state.resources.children(ResourceId(window)).to_vec() - } else { - vec![ResourceId(window)] - }; - for target in targets { - if mode_flip { - flip_redirect_target_mode(state, backend, origin, target, mode); - } else { - activate_redirect_backing_for(state, backend, origin, target, mode); - } - } - } - } - } - x11composite::UNREDIRECT_WINDOW | x11composite::UNREDIRECT_SUBWINDOWS => { - if let Some((window, _update)) = x11composite::parse_window_update(body) { - let subwindows = minor == x11composite::UNREDIRECT_SUBWINDOWS; - state - .composite_redirects - .remove(&(ResourceId(window), subwindows)); - // L2 plan B.6c + Stage 4b: release each affected - // backing's reason-1 hold. Single-window: just the - // named window. Subtree: walk children of the - // parent symmetric to the RedirectSubwindows arm - // above. Backing-side participation drop happens - // inside `release_redirected_backing` per the - // Stage-4 round-3 finding; the window-side - // participation restore happens below, gated on - // `supports_redirect_activation()`. - let targets: Vec = if subwindows { - state.resources.children(ResourceId(window)).to_vec() - } else { - vec![ResourceId(window)] - }; - debug!( - "client {} #{} COMPOSITE::Unredirect{}(0x{:x}) targets={}", - client_id.0, - sequence.0, - if subwindows { "Subwindows" } else { "Window" }, - window, - targets.len(), - ); - for target in &targets { - crate::core_loop::process_disconnect::teardown_redirect_for_window( - state, backend, None, *target, - ); - } - if backend.supports_redirect_activation() { - // Restore window scene-participation to the - // window's `mapped` state. Spec §285+360 — - // redirect-state change as scene-structure - // damage source; the v2 setter fires that - // damage internally. - for target in &targets { - let snap = state - .resources - .window(*target) - .map(|w| (w.host_xid, w.map_state != MapState::Unmapped)); - if let Some((Some(host), participating)) = snap - && let Err(err) = - backend.set_window_scene_participation(origin, host, participating) - { - log::warn!( - "unredirect: set_window_scene_participation(0x{:x}, {participating}) failed: {err}", - target.0 - ); - } - } - } - } - } - x11composite::CREATE_REGION_FROM_BORDER_CLIP => { - if let Some((region, window)) = x11composite::parse_u32_pair(body) { - let rects = vec![drawable_full_rect_xfixes(state, ResourceId(window))]; - state.xfixes_regions.insert( - region, - crate::server::XFixesRegion { - owner: client_id, - rects: normalize_region_rects(rects), - }, - ); - } - } - x11composite::NAME_WINDOW_PIXMAP => { - let Some((window_raw, pixmap_raw)) = x11composite::parse_u32_pair(body) else { - return Ok(RequestOutcome::Handled); - }; - let window = ResourceId(window_raw); - let pixmap = ResourceId(pixmap_raw); - debug!( - "client {} #{} COMPOSITE::NameWindowPixmap(window=0x{:x}, pixmap=0x{:x})", - client_id.0, sequence.0, window_raw, pixmap_raw, - ); - let snapshot = state.resources.window(window).map(|w| { - let parent_redirected = state - .composite_redirects - .keys() - .any(|(rwid, sub)| *sub && *rwid == w.parent); - let self_redirected = state.composite_redirects.contains_key(&(window, false)); - let (pixmap_width, pixmap_height) = w - .redirected_backing - .as_ref() - .map_or((w.width, w.height), |backing| { - (backing.width, backing.height) - }); - ( - w.host_xid, - pixmap_width, - pixmap_height, - w.depth, - parent_redirected || self_redirected, - w.map_state, - ) - }); - let Some((host_xid, w_width, w_height, w_depth, redirected, map_state)) = snapshot - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window_raw, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - }; - if !redirected { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - window_raw, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - // Xorg's `ProcCompositeNameWindowPixmap` refuses a non-viewable - // window (composite/compext.c:241 `if (!pWin->viewable) return - // BadMatch;`) — a non-viewable window has no off-screen backing to - // name. We honoured it instead, so in issue #97 fastcompmgr got a - // valid pixmap for i3's unmapped frame and kept compositing a - // window that had left the workspace. - if map_state != crate::resources::MapState::Viewable { - debug!( - "client {} #{} COMPOSITE::NameWindowPixmap(window=0x{:x}) -> BadMatch \ - (map_state={map_state:?}, Xorg requires Viewable)", - client_id.0, sequence.0, window_raw, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - window_raw, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - let Some(host_window_xid) = host_xid else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - pixmap_raw, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - }; - if backend.composite_opcode().is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - pixmap_raw, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - let host_pixmap_xid = match backend.name_window_pixmap(origin, host_window_xid) { - Ok(handle) => handle, - Err(err) => { - debug!( - "client {} #{} COMPOSITE::NameWindowPixmap(window=0x{:x}) -> Err: {err}", - client_id.0, sequence.0, window_raw, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - pixmap_raw, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - }; - state.resources.create_pixmap( - client_id, - x11::CreatePixmapRequest { - pixmap, - drawable: window, - width: w_width, - height: w_height, - depth: w_depth, - }, - ); - let _ = state.resources.set_pixmap_host_xid(pixmap, host_pixmap_xid); - state.resources.mark_pixmap_composite_name(pixmap); - if let Some(w) = state.resources.window_mut(window) { - w.composite_named_pixmaps - .push(crate::resources::NamedCompositePixmap { - client_pixmap: pixmap, - host_pixmap: host_pixmap_xid, - width: w_width, - height: w_height, - }); - } - } - x11composite::GET_OVERLAY_WINDOW => { - // Checked first, before anything else: a previous session's - // overlay could not be torn down and is still materialized - // with nobody owning it. Whatever we would hand this - // compositor is inherited state, so refuse. Sticky for the - // life of the process. - if state.cow_teardown_failed { - log::warn!( - "client {} #{} COMPOSITE::GetOverlayWindow refused: the \ - overlay is orphaned by a failed teardown", - client_id.0, - sequence.0, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - 0, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - let _window = x11composite::parse_window(body).unwrap_or(ROOT_WINDOW.0); - // Must return a distinct XID, not root. See COMPOSITE_OVERLAY_WINDOW - // for why — marco's compositor immediately calls XSelectInput on - // this XID and would otherwise wipe its own WM event mask on root. - let overlay = COMPOSITE_OVERLAY_WINDOW.0; - // Core owns the claim list; the backend counts nothing. Each - // Get records one claim owned by the calling client (Xorg's - // per-Get `CompOverlayClientRec`), and only the 0 → 1 edge - // reaches the backend. - // - // Transactional: record the claim, materialize, and roll the - // claim back if materialization fails. A claim recorded - // against an overlay that does not exist is the - // desynchronisation this design exists to remove. - let first_claim = state.cow_claims.is_empty(); - state.cow_claims.push(client_id); - if first_claim - && let Err(err) = - crate::core_loop::composite_overlay::materialize_overlay(state, backend, origin) - { - state.cow_claims.pop(); - log::warn!( - "client {} #{} COMPOSITE::GetOverlayWindow materialization failed: {err}", - client_id.0, - sequence.0, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - 0, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - debug!( - "client {} #{} COMPOSITE::GetOverlayWindow -> 0x{:x}", - client_id.0, sequence.0, overlay - ); - let reply = - x11composite::encode_get_overlay_window_reply(byte_order, sequence, overlay); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11composite::RELEASE_OVERLAY_WINDOW => { - debug!( - "client {} #{} COMPOSITE::ReleaseOverlayWindow", - client_id.0, sequence.0 - ); - // Ownership check, as Xorg's `ProcCompositeReleaseOverlayWindow` - // does via `compFindOverlayClient`: a client holding no claim - // gets BadMatch and nothing changes. Get and Release pair 1:1, - // so this drops exactly ONE of the caller's claims — never all - // of them, and never somebody else's. - let Some(claim_index) = state - .cow_claims - .iter() - .rposition(|owner| *owner == client_id) - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - }; - if state.cow_claims.len() == 1 { - // Final release: tear down FIRST and keep the claim unless - // it succeeds. The claim is what keeps the overlay alive, - // so dropping it before the overlay is gone is precisely - // the leak. - if let Err(err) = - crate::core_loop::composite_overlay::teardown_overlay(state, backend, origin) - { - log::warn!( - "client {} #{} COMPOSITE::ReleaseOverlayWindow teardown failed: {err}", - client_id.0, - sequence.0, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - 0, - u16::from(minor), - COMPOSITE_MAJOR_OPCODE, - ); - } - } - state.cow_claims.remove(claim_index); - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - COMPOSITE_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// Special-case writer for MIT-SHM CreateSegment: sends a normal X11 -/// reply alongside an SCM_RIGHTS file descriptor. This is the one path -/// where the lifted code reaches around `client_io::write_or_buffer` -/// because the kernel only delivers the fd if it accompanies inline -/// bytes — buffering would split them apart. Once the outbound buffer -/// is non-empty we can't insert an FD-carrying frame, so we drain -/// first. -fn send_reply_with_fd( - client: &mut crate::server::ClientState, - bytes: &[u8], - fd: std::os::fd::RawFd, -) -> io::Result<()> { - if !client.fd_passing { - return Err(io::Error::new( - io::ErrorKind::Unsupported, - "file descriptor passing is unavailable on this transport", - )); - } - // Drain whatever's pending so the SCM_RIGHTS frame lands in order. - while !client.outbound.is_empty() { - match client_io::drain_outbound(client)? { - client_io::WriteOutcome::Done => break, - client_io::WriteOutcome::WouldBlock => { - std::thread::yield_now(); - } - client_io::WriteOutcome::Disconnect => { - return Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "client outbound disconnect during fd send", - )); - } - } - } - let writer_arc = client.writer.clone(); - let mut w = writer_arc - .lock() - .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "client writer mutex poisoned"))?; - let crate::transport::Transport::Unix(stream) = &mut *w else { - return Err(io::Error::new( - io::ErrorKind::Unsupported, - "file descriptor passing is unavailable on this transport", - )); - }; - crate::unix_fd::send_with_fd(stream, bytes, fd) -} - -#[allow(clippy::too_many_arguments)] -fn handle_mit_shm_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], - attached_fd: Option, -) -> io::Result { - use yserver_protocol::x11::mit_shm as shm; - const MIT_SHM_MAJOR_OPCODE: u8 = 130; - let minor = header.data; - debug!( - "client {} #{} MIT-SHM dispatch minor={minor} body_len={}", - client_id.0, - sequence.0, - body.len() - ); - match minor { - shm::QUERY_VERSION => { - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - // Xorg reports the server's effective uid/gid, stored in the - // 16-bit wire fields (truncating, as the C assignment does). - // SAFETY: geteuid/getegid take no arguments and cannot fail. - let (euid, egid) = unsafe { (libc::geteuid(), libc::getegid()) }; - #[allow(clippy::cast_possible_truncation)] - let reply = shm::encode_query_version_reply( - byte_order, - sequence, - false, - euid as u16, - egid as u16, - ); - return Ok(write_to_client(client, client_id, &reply)); - } - shm::ATTACH => { - let Some(req) = shm::parse_attach(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - match crate::server::MitShmSegment::from_shmid(client_id, req.shmid, req.read_only) { - Ok(segment) => { - state.mit_shm_segments.insert(req.shmseg, segment); - debug!( - "client {} #{} MIT-SHM::Attach shmseg=0x{:x} shmid=0x{:x}", - client_id.0, sequence.0, req.shmseg, req.shmid - ); - } - Err(_) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - } - } - } - shm::ATTACH_FD => { - let Some(req) = shm::parse_attach_fd(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let Some(fd) = attached_fd else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - // OwnedFd carries an automatic close-on-drop; from_fd takes - // raw and assumes ownership transfer. - let raw = std::os::fd::IntoRawFd::into_raw_fd(fd); - match crate::server::MitShmSegment::from_fd(client_id, raw, req.read_only) { - Ok(segment) => { - state.mit_shm_segments.insert(req.shmseg, segment); - } - Err(_) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - } - } - } - shm::DETACH => { - if let Some(shmseg) = shm::parse_detach(body) { - state.mit_shm_segments.remove(&shmseg); - } - } - shm::CREATE_PIXMAP => { - let Some(req) = shm::parse_create_pixmap(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - return handle_mit_shm_create_pixmap(state, backend, origin, client_id, sequence, req); - } - shm::PUT_IMAGE => { - let Some(req) = shm::parse_put_image(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - return handle_mit_shm_put_image(state, backend, origin, client_id, sequence, req); - } - shm::GET_IMAGE => { - let Some(req) = shm::parse_get_image(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - return handle_mit_shm_get_image(state, backend, origin, client_id, sequence, req); - } - shm::CREATE_SEGMENT => { - let Some(req) = shm::parse_create_segment(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - MIT_SHM_MAJOR_OPCODE, - ); - }; - return handle_mit_shm_create_segment(state, client_id, sequence, req); - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - MIT_SHM_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -fn handle_mit_shm_create_pixmap( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - req: yserver_protocol::x11::mit_shm::CreatePixmapRequest, -) -> io::Result { - const MIT_SHM_MAJOR_OPCODE: u8 = 130; - use yserver_protocol::x11::mit_shm as shm; - debug!( - "client {} #{} MIT-SHM::CreatePixmap pid=0x{:x} drawable=0x{:x} {}x{} d{}", - client_id.0, sequence.0, req.pid, req.drawable, req.width, req.height, req.depth, - ); - let validation_failed = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - let owned = crate::server::IdAllocator::validate_owned( - req.pid, - handle.resource_id_base, - handle.resource_id_mask, - ); - let in_use = state.xid_occupied(req.pid); - !owned || in_use - }; - let drawable_exists = state.resources.window(ResourceId(req.drawable)).is_some() - || state.resources.pixmap(ResourceId(req.drawable)).is_some(); - if validation_failed { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - req.pid, - u16::from(shm::CREATE_PIXMAP), - MIT_SHM_MAJOR_OPCODE, - ); - } - if !drawable_exists { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.drawable, - u16::from(shm::CREATE_PIXMAP), - MIT_SHM_MAJOR_OPCODE, - ); - } - if !supported_pixmap_depth(req.depth) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.depth), - u16::from(shm::CREATE_PIXMAP), - MIT_SHM_MAJOR_OPCODE, - ); - } - let Some(expected_len) = zpixmap_expected_len(req.width, req.height, req.depth) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(shm::CREATE_PIXMAP), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let host_xid = match backend.create_pixmap(origin, req.depth, req.width, req.height) { - Ok(handle) => Some(handle), - Err(err) => { - log::warn!( - "client {} MIT-SHM::CreatePixmap host CreatePixmap failed: {err}", - client_id.0 - ); - None - } - }; - let snapshot: Vec = { - let Some(segment) = state.mit_shm_segments.get(&req.shmseg) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(shm::CREATE_PIXMAP), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let bytes = segment.as_slice(); - let start = req.offset as usize; - let end = start.saturating_add(expected_len); - if end > bytes.len() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.offset, - u16::from(shm::CREATE_PIXMAP), - MIT_SHM_MAJOR_OPCODE, - ); - } - bytes[start..end].to_vec() - }; - if let Some(host_xid) = host_xid { - let _ = backend.clear_clip_rectangles(origin); - if let Err(err) = backend.put_image( - origin, - host_xid.as_raw(), - req.depth, - req.width, - req.height, - 0, - 0, - &snapshot, - ) { - log::warn!( - "client {} MIT-SHM::CreatePixmap put_image failed: {err}", - client_id.0 - ); - } - } - state.resources.create_pixmap( - client_id, - x11::CreatePixmapRequest { - depth: req.depth, - pixmap: ResourceId(req.pid), - drawable: ResourceId(req.drawable), - width: req.width, - height: req.height, - }, - ); - if let Some(xid) = host_xid { - let updated = state - .resources - .set_pixmap_host_xid(ResourceId(req.pid), xid); - debug_assert!(updated, "pixmap was just inserted above"); - } - Ok(RequestOutcome::Handled) -} - -fn handle_mit_shm_put_image( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - req: yserver_protocol::x11::mit_shm::PutImageRequest, -) -> io::Result { - const MIT_SHM_MAJOR_OPCODE: u8 = 130; - use yserver_protocol::x11::mit_shm as shm; - // MIT-SHM PutImage perf-cliff diagnostic (2026-05-28 cinnamon - // telemetry: single op130 calls at 100-128ms blocking the core - // loop for ~6-8 vsync intervals). Section-time so we can pin - // which step dominates. Threshold-gated at exit; steady-state - // healthy calls (sub-100µs) stay silent. - let t_entry = std::time::Instant::now(); - debug!( - "client {} #{} MIT-SHM::PutImage drawable=0x{:x} {}x{} d{}", - client_id.0, sequence.0, req.drawable, req.src_width, req.src_height, req.depth - ); - let drawable = ResourceId(req.drawable); - let gc = ResourceId(req.gc); - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, gc) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - bad_value, - u16::from(shm::PUT_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - } - let draw_state = state.resources.resolve_draw_state(gc).unwrap_or_default(); - let target = state.resources.host_drawable_target(drawable); - let Some(target) = target else { - return Ok(RequestOutcome::Handled); - }; - let Some(segment) = state.mit_shm_segments.get(&req.shmseg) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(shm::PUT_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let Some(snapshot) = extract_shm_zpixmap_region( - segment.as_slice(), - req.offset, - req.total_width, - req.total_height, - req.src_x, - req.src_y, - req.src_width, - req.src_height, - req.depth, - ) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.offset, - u16::from(shm::PUT_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let t_after_extract = t_entry.elapsed(); - let snapshot_borrowed = matches!(snapshot, std::borrow::Cow::Borrowed(_)); - let snapshot_bytes = snapshot.len(); - backend.apply_clip_state(origin, &draw_state.clip)?; - backend.apply_draw_state(origin, &draw_state)?; - let t_after_apply_state = t_entry.elapsed(); - backend.put_image( - origin, - target.host_xid(), - req.depth, - req.src_width, - req.src_height, - req.dst_x, - req.dst_y, - &snapshot, - )?; - let t_after_put_image = t_entry.elapsed(); - let _dropped = accumulate_damage_to_state( - state, - ResourceId(req.drawable), - req.dst_x, - req.dst_y, - req.src_width, - req.src_height, - ); - // ShmPutImage with send_event=true obligates a ShmCompletion event - // once the transfer is done (shmproto.h). GTK/GDK pools SHM segments - // and blocks the next frame until the completion frees one — without - // this the render loop stalls after the pool is exhausted (the - // cinnamon-settings repaint freeze). MIT-SHM first-event base is 65; - // ShmCompletion offset is 0. - if req.send_event { - const MIT_SHM_FIRST_EVENT: u8 = 65; - let _dropped = fanout_event_to_clients(state, &[client_id], |buf, seq, order| { - x11::encode_shm_completion_event( - buf, - order, - seq, - MIT_SHM_FIRST_EVENT, - ResourceId(req.drawable), - u16::from(shm::PUT_IMAGE), - MIT_SHM_MAJOR_OPCODE, - req.shmseg, - req.offset, - ); - }); - } - let total = t_entry.elapsed(); - // 5ms threshold matches the suspected cliff territory; healthy - // PutImage steady-state is sub-100µs per call so threshold- - // gating keeps the log quiet. - if total >= std::time::Duration::from_millis(5) { - // CALLING client (the one issuing PutImage) is `client_id` — - // that's what we want to attribute the hot-path activity to. - // The drawable's OWNER (high bits of `req.drawable`) is a - // separate, less-actionable identity — typically a pixmap - // whose creator may have disconnected with the resource kept - // alive via X11 RetainTemporary / Permanent / SaveSet. So - // log the caller's WM_CLASS as the primary attribution and - // include the drawable XID for cross-reference. - let caller_class = state - .client_wm_class - .get(&client_id.0) - .map(String::as_str) - .unwrap_or(""); - log::debug!( - "MIT-SHM PutImage perf: total={total_us}us \ - [extract={ext_us}us apply_state+={state_us}us put_image+={pi_us}us] \ - {w}x{h} depth={depth} bytes={bytes} borrowed={borrowed} \ - drawable=0x{drawable:x} caller=client{caller_id}/{caller_class:?}", - total_us = total.as_micros(), - ext_us = t_after_extract.as_micros(), - state_us = t_after_apply_state - .saturating_sub(t_after_extract) - .as_micros(), - pi_us = t_after_put_image - .saturating_sub(t_after_apply_state) - .as_micros(), - w = req.src_width, - h = req.src_height, - depth = req.depth, - bytes = snapshot_bytes, - borrowed = snapshot_borrowed, - drawable = req.drawable, - caller_id = client_id.0, - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_mit_shm_get_image( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - req: yserver_protocol::x11::mit_shm::GetImageRequest, -) -> io::Result { - use yserver_protocol::x11::mit_shm as shm; - const MIT_SHM_MAJOR_OPCODE: u8 = 130; - { - let Some(segment) = state.mit_shm_segments.get(&req.shmseg) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - if segment.read_only { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - req.shmseg, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - } - } - let target = state - .resources - .host_drawable_target(ResourceId(req.drawable)); - let Some(target) = target else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.drawable, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let host_bytes = backend - .get_image( - origin, - target.host_xid(), - req.format, - req.x, - req.y, - req.width, - req.height, - req.plane_mask, - ) - .ok() - .flatten(); - let Some(host_reply_bytes) = host_bytes else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.drawable, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let pixel_data: Vec = host_reply_bytes.get(32..).unwrap_or(&[]).to_vec(); - { - let Some(segment) = state.mit_shm_segments.get_mut(&req.shmseg) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let Some(buf) = segment.as_mut_slice() else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - req.shmseg, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - }; - let start = req.offset as usize; - let end = start.saturating_add(pixel_data.len()); - if end > buf.len() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.offset, - u16::from(shm::GET_IMAGE), - MIT_SHM_MAJOR_OPCODE, - ); - } - buf[start..end].copy_from_slice(&pixel_data); - } - let depth = host_reply_bytes.first().copied().unwrap_or(24); - let visual = crate::resources::ROOT_VISUAL.0; - #[allow(clippy::cast_possible_truncation)] - let size = pixel_data.len() as u32; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let reply = shm::encode_get_image_reply(byte_order, sequence, depth, visual, size); - Ok(write_to_client(client, client_id, &reply)) -} - -fn handle_mit_shm_create_segment( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - req: yserver_protocol::x11::mit_shm::CreateSegmentRequest, -) -> io::Result { - const MIT_SHM_MAJOR_OPCODE: u8 = 130; - use yserver_protocol::x11::mit_shm as shm; - if req.size == 0 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.shmseg, - u16::from(shm::CREATE_SEGMENT), - MIT_SHM_MAJOR_OPCODE, - ); - } - let fd = unsafe { libc::memfd_create(c"yserver-shm".as_ptr(), libc::MFD_CLOEXEC) }; - if fd < 0 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.shmseg, - u16::from(shm::CREATE_SEGMENT), - MIT_SHM_MAJOR_OPCODE, - ); - } - if unsafe { libc::ftruncate(fd, libc::off_t::from(req.size as i32)) } < 0 { - unsafe { libc::close(fd) }; - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.shmseg, - u16::from(shm::CREATE_SEGMENT), - MIT_SHM_MAJOR_OPCODE, - ); - } - let fd_for_client = unsafe { libc::dup(fd) }; - if fd_for_client < 0 { - unsafe { libc::close(fd) }; - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.shmseg, - u16::from(shm::CREATE_SEGMENT), - MIT_SHM_MAJOR_OPCODE, - ); - } - let segment = match crate::server::MitShmSegment::from_fd(client_id, fd, req.read_only) { - Ok(s) => s, - Err(_) => { - unsafe { libc::close(fd_for_client) }; - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.shmseg, - u16::from(shm::CREATE_SEGMENT), - MIT_SHM_MAJOR_OPCODE, - ); - } - }; - state.mit_shm_segments.insert(req.shmseg, segment); - let send_res = match state.clients.get_mut(&client_id.0) { - Some(client) => { - let reply = yserver_protocol::x11::mit_shm::encode_create_segment_reply( - client.byte_order, - sequence, - ); - send_reply_with_fd(client, &reply, fd_for_client) - } - None => Ok(()), - }; - unsafe { libc::close(fd_for_client) }; - if send_res.is_err() { - // Xorg's `ProcShmCreateSegment` (`Xext/shm.c:1323`): - // - // if (WriteFdToClient(client, fd, TRUE) < 0) { - // FreeResource(stuff->shmseg, X11_RESTYPE_NONE); - // close(fd); - // return BadAlloc; - // } - // - // Both halves matter. Propagating the I/O error instead left the - // segment in `mit_shm_segments` with no client able to reach it, - // and sent no protocol reply at all — the client saw a request that - // neither succeeded nor failed. The dispatch gate above should mean - // this is now unreachable for the transport reason; it stays - // because a short write is not the only way to get here. - state.mit_shm_segments.remove(&req.shmseg); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.shmseg, - u16::from(shm::CREATE_SEGMENT), - MIT_SHM_MAJOR_OPCODE, - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_damage_request( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::damage as x11damage; - let minor = header.data; - match minor { - x11damage::QUERY_VERSION => { - let (client_major, client_minor) = x11damage::parse_query_version(body) - .unwrap_or((x11damage::MAJOR_VERSION, x11damage::MINOR_VERSION)); - let major = x11damage::MAJOR_VERSION.min(client_major); - let minor_ver = if major < x11damage::MAJOR_VERSION { - client_minor - } else { - x11damage::MINOR_VERSION.min(client_minor) - }; - debug!( - "client {} #{} DAMAGE::QueryVersion -> {}.{}", - client_id.0, sequence.0, major, minor_ver - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let reply = - x11damage::encode_query_version_reply(byte_order, sequence, major, minor_ver); - return Ok(write_to_client(client, client_id, &reply)); - } - x11damage::CREATE => { - if let Some((damage, drawable, level)) = x11damage::parse_create(body) { - let drawable_id = ResourceId(drawable); - state.damage_objects.insert( - damage, - crate::server::DamageObject { - owner: client_id, - drawable: drawable_id, - level, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - debug!( - "client {} #{} DAMAGE::Create damage=0x{damage:x} drawable=0x{drawable:x} level={level}", - client_id.0, sequence.0, - ); - let seed_initial_damage = state - .resources - .window(drawable_id) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable) - || state - .resources - .composite_named_pixmap_owner_window(drawable_id) - .and_then(|window_id| state.resources.window(window_id)) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - if seed_initial_damage { - log::trace!( - target: "yserver_core::core_loop::damage_fanout", - "damage_create_seed_full: damage=0x{:x} drawable=0x{:x} level={}", - damage, - drawable, - level, - ); - let _dropped = accumulate_damage_full_to_state(state, drawable_id); - } - } else { - debug!( - "client {} #{} DAMAGE::Create parse_failed", - client_id.0, sequence.0 - ); - } - } - x11damage::DESTROY => { - if let Some(damage) = x11damage::parse_resource(body) { - let drawable = state.damage_objects.remove(&damage).map(|d| d.drawable.0); - debug!( - "client {} #{} DAMAGE::Destroy damage=0x{damage:x} drawable=0x{:x}", - client_id.0, - sequence.0, - drawable.unwrap_or(0), - ); - } else { - debug!( - "client {} #{} DAMAGE::Destroy parse_failed", - client_id.0, sequence.0 - ); - } - } - x11damage::ADD => { - if let Some((drawable, region)) = x11damage::parse_add(body) { - let rects = if region == 0 { - vec![drawable_full_rect_xfixes(state, ResourceId(drawable))] - } else { - state - .xfixes_regions - .get(®ion) - .map(|r| r.rects.clone()) - .unwrap_or_default() - }; - for damage in state.damage_objects.values_mut() { - if damage.drawable == ResourceId(drawable) { - damage.rects.extend(rects.clone()); - damage.rects = normalize_region_rects(std::mem::take(&mut damage.rects)); - } - } - } - debug!("client {} #{} DAMAGE::Add", client_id.0, sequence.0); - } - x11damage::SUBTRACT => { - if let Some((damage_id, repair, parts)) = x11damage::parse_subtract(body) { - // Per X11 DAMAGE spec (cf. Xorg damageext.c:419 + - // miext/damage/damage.c:1854): - // if repair == None: parts ← old damage; damage ← empty - // else: parts ← old ∩ repair; damage ← old − repair - // The repair region is a read-only input filter — NEVER - // overwrite it. Compositors (marco, picom, ...) feed - // `parts` into `SetPictureClipRectangles`; an empty - // parts collapses every subsequent composite to a no-op - // and the screen freezes. - let old_damage = state - .damage_objects - .get(&damage_id) - .map(|d| normalize_region_rects(d.rects.clone())) - .unwrap_or_default(); - let drawable = state - .damage_objects - .get(&damage_id) - .map(|d| d.drawable.0) - .unwrap_or(0); - let level = state - .damage_objects - .get(&damage_id) - .map(|d| d.level) - .unwrap_or(0); - let owner = state - .damage_objects - .get(&damage_id) - .map(|d| d.owner.0) - .unwrap_or(0); - let (parts_rects, new_damage) = if repair == 0 { - (old_damage.clone(), Vec::new()) - } else { - let repair_rects = state - .xfixes_regions - .get(&repair) - .map(|r| r.rects.clone()) - .unwrap_or_default(); - ( - crate::nested::intersect_regions(&old_damage, &repair_rects), - crate::nested::subtract_regions(&old_damage, &repair_rects), - ) - }; - let repair_rects = if repair == 0 { - Vec::new() - } else { - state - .xfixes_regions - .get(&repair) - .map(|r| r.rects.clone()) - .unwrap_or_default() - }; - if parts != 0 { - state.xfixes_regions.insert( - parts, - crate::server::XFixesRegion { - owner: client_id, - rects: parts_rects, - }, - ); - } - if let Some(damage) = state.damage_objects.get_mut(&damage_id) { - damage.rects = new_damage; - damage.pending_notify_fired = false; - } - if repair != 0 - && level != x11damage::report_level::RAW_RECTANGLES - && state - .damage_objects - .get(&damage_id) - .is_some_and(|d| !d.rects.is_empty()) - { - let _dropped = report_existing_damage_to_state(state, damage_id); - } - let parts_owner = if parts == 0 { - 0 - } else { - state.xfixes_regions.get(&parts).map_or(0, |r| r.owner.0) - }; - trace!( - "client {} #{} DAMAGE::Subtract damage=0x{damage_id:x} drawable=0x{drawable:x} \ - owner={} level={} repair=0x{repair:x} parts=0x{parts:x} parts_owner={} \ - old_n={} old={} repair_n={} repair_rects={} parts_n={} parts_rects={} \ - new_n={} new_rects={}", - client_id.0, - sequence.0, - owner, - level, - parts_owner, - old_damage.len(), - format_region_rects(&old_damage), - repair_rects.len(), - format_region_rects(&repair_rects), - if parts == 0 { - 0 - } else { - state - .xfixes_regions - .get(&parts) - .map_or(0, |r| r.rects.len()) - }, - format_region_rects( - &state - .xfixes_regions - .get(&parts) - .map(|r| r.rects.clone()) - .unwrap_or_default() - ), - state - .damage_objects - .get(&damage_id) - .map_or(0, |d| d.rects.len()), - format_region_rects( - &state - .damage_objects - .get(&damage_id) - .map(|d| d.rects.clone()) - .unwrap_or_default() - ), - ); - } - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - } - Ok(RequestOutcome::Handled) -} - -fn effective_window_cursor(state: &ServerState, mut window: ResourceId) -> Option { - for _ in 0..256 { - let current = state.resources.window(window)?; - if let Some(cursor) = current.cursor { - return (cursor.0 != 0).then_some(cursor); - } - if current.parent == window { - break; - } - window = current.parent; - } - None -} - -fn current_pointer_cursor(state: &ServerState) -> Option { - if let Some(grab) = state.active_pointer_grab - && grab.cursor.0 != 0 - { - return Some(grab.cursor); - } - let pointer_window = crate::core_loop::key_fanout::deepest_window_at_pointer(state); - effective_window_cursor(state, pointer_window) -} - -fn handle_xtest_request( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::xtest as x11xtest; - let minor = header.data; - match minor { - x11xtest::GET_VERSION => { - let (cmaj, cmin) = x11xtest::parse_get_version(body).unwrap_or(( - u8::try_from(x11xtest::MAJOR_VERSION).unwrap_or(2), - x11xtest::MINOR_VERSION, - )); - debug!( - "client {} #{} XTEST::GetVersion client={cmaj}.{cmin} -> {}.{}", - client_id.0, - sequence.0, - x11xtest::MAJOR_VERSION, - x11xtest::MINOR_VERSION, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let reply = x11xtest::encode_get_version_reply( - byte_order, - sequence, - u8::try_from(x11xtest::MAJOR_VERSION).unwrap_or(2), - x11xtest::MINOR_VERSION, - ); - return Ok(write_to_client(client, client_id, &reply)); - } - x11xtest::COMPARE_CURSOR => { - let byte_order = state - .clients - .get(&client_id.0) - .map_or(x11::ClientByteOrder::LittleEndian, |client| { - client.byte_order - }); - let read_u32 = |slice: &[u8]| match byte_order { - x11::ClientByteOrder::LittleEndian => { - u32::from_le_bytes(slice.try_into().expect("four bytes")) - } - x11::ClientByteOrder::BigEndian => { - u32::from_be_bytes(slice.try_into().expect("four bytes")) - } - }; - let window = ResourceId(read_u32(&body[0..4])); - let cursor = ResourceId(read_u32(&body[4..8])); - if state.resources.window(window).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - u16::from(minor), - header.opcode, - ); - } - let comparison = if cursor.0 == 0 { - None - } else if cursor.0 == 1 { - current_pointer_cursor(state) - } else if state.resources.cursor_exists(cursor) { - Some(cursor) - } else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - u16::from(minor), - header.opcode, - ); - }; - // Xorg compares cursor objects: after XFIXES ChangeCursor two - // XIDs can name the same cursor, so compare their host handles. - let effective = effective_window_cursor(state, window); - let same = effective == comparison - || matches!((effective, comparison), (Some(a), Some(b)) - if state.resources.cursor_host_xid(a).is_some() - && state.resources.cursor_host_xid(a) - == state.resources.cursor_host_xid(b)); - debug!( - "client {} #{} XTEST::CompareCursor window=0x{:x} cursor=0x{:x} same={same}", - client_id.0, sequence.0, window.0, cursor.0, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let reply = x11xtest::encode_compare_cursor_reply(byte_order, sequence, same); - return Ok(write_to_client(client, client_id, &reply)); - } - x11xtest::FAKE_INPUT => { - let Some(fi) = x11xtest::parse_fake_input(body) else { - debug!( - "client {} #{} XTEST::FakeInput body too short ({} bytes), dropping", - client_id.0, - sequence.0, - body.len() - ); - return Ok(RequestOutcome::Handled); - }; - debug!( - "client {} #{} XTEST::FakeInput type={} detail={} root_xy=({},{})", - client_id.0, sequence.0, fi.event_type, fi.detail, fi.root_x, fi.root_y - ); - dispatch_fake_input_with_body(state, backend, fi, body); - } - x11xtest::GRAB_CONTROL => { - debug!( - "client {} #{} XTEST::GrabControl (no-op)", - client_id.0, sequence.0 - ); - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// `body` is the FakeInput request body (the 32-byte first xEvent plus -/// any follow-up events) — needed for the XI 1.x *device* fakes, where -/// libXtst packs the deviceid into byte 31 of the first event and -/// device-motion axes into trailing deviceValuator events (Xorg -/// Xext/xtest.c ProcXTestFakeInput). -fn dispatch_fake_input_with_body( - state: &mut ServerState, - backend: &mut dyn Backend, - fi: yserver_protocol::x11::xtest::FakeInput, - body: &[u8], -) { - use crate::{core_loop::HostInputEvent, host_x11::HostKeyEvent}; - use yserver_protocol::x11::xtest as x11xtest; - - // XTestFakeDevice{Key,Button,Motion}Event arrive with the XI 1.x - // wire event codes instead of the core FAKE_* codes. Route them - // through the same host-input pipeline — the input stack attributes - // events to the master + slave pair, and the XI1/XI2 fanouts report - // the slave, which is the device XTS fakes on. - let xi_first = crate::server::XI_FIRST_EVENT; - if fi.event_type >= xi_first { - let offset = fi.event_type - xi_first; - match offset { - crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET - | crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => { - let pressed = offset == crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; - backend.on_host_input( - state, - HostInputEvent::Key(HostKeyEvent { - pressed, - keycode: fi.detail, - time: fi.time, - root_x: 0, - root_y: 0, - event_x: 0, - event_y: 0, - state: 0, - }), - ); - } - crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET - | crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => { - let pressed = offset == crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; - let fake = yserver_protocol::x11::xtest::FakeInput { - event_type: if pressed { - x11xtest::FAKE_BUTTON_PRESS - } else { - x11xtest::FAKE_BUTTON_RELEASE - }, - ..fi - }; - dispatch_fake_input_with_body(state, backend, fake, &[]); - } - crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET => { - // Device-motion fakes are DEVICE-coordinate space and - // do NOT move the sprite — Xorg uses POINTER_ABSOLUTE - // without POINTER_DESKTOP (Xext/xtest.c:265), and a - // Xephyr probe confirms the cursor stays put while the - // DeviceMotionNotify is delivered at the CURRENT - // position with the axis payload riding the trailing - // deviceValuator chain. yserver pre-fix warped the - // cursor to (axis0, axis1), which tore the pointer off - // the XTS windows mid-test and starved every - // selection-walk delivery (the AllowDeviceEvents - // ispfrozen probes). - // - // fi.detail == 0 means absolute; relative device fakes - // stay unsupported (XTS uses absolute only). - if fi.detail != 0 { - log::debug!("XTEST FakeInput: relative device motion not supported, dropping"); - return; - } - // Collect axes from ALL trailing deviceValuator events - // (32-byte chunks: num at [6], first at [7], then up - // to six INT32 values). - let mut axes = crate::server::Xi1MotionAxes { - first: 0, - count: 0, - values: [0; 6], - }; - let mut chunk = 32; - let mut got_first = false; - while let Some(dv) = body.get(chunk..chunk + 32) { - let num = usize::from(dv[6].min(6)); - if !got_first { - axes.first = dv[7]; - got_first = true; - } - for i in 0..num { - let off = 8 + i * 4; - let slot = usize::from(axes.count); - if slot >= 6 { - break; - } - axes.values[slot] = - i32::from_le_bytes([dv[off], dv[off + 1], dv[off + 2], dv[off + 3]]); - #[allow(clippy::cast_possible_truncation)] - { - axes.count += 1; - } - } - chunk += 32; - } - if axes.count == 0 { - log::debug!("XTEST FakeInput: device motion without valuator event, dropping"); - return; - } - // Route the XI1 DeviceMotionNotify at the current - // sprite position. - let target = crate::core_loop::key_fanout::deepest_window_at_pointer(state); - let (ox, oy) = state.resources.window_absolute_position(target); - let (root_x, root_y) = state.pointer_root; - let event_x = i16::try_from(i32::from(root_x) - ox).unwrap_or(0); - let event_y = i16::try_from(i32::from(root_y) - oy).unwrap_or(0); - let _ = crate::core_loop::pointer_fanout::xi1_route_device_event( - state, - crate::server::Xi1QueuedEvent { - deviceid: crate::xinput::DEVICEID_SLAVE_POINTER, - evcode: crate::server::XI_FIRST_EVENT - + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, - detail: 0, - time: fi.time, - root_x, - root_y, - event_x, - event_y, - state_mask: 0, - natural_target: target, - focus_route: crate::server::Xi1FocusRoute::Walk, - axes: Some(axes), - replay_floor: None, - }, - true, - ); - } - _ => { - log::debug!( - "XTEST FakeInput: unsupported XI device fake event type {} (offset {offset}), dropping", - fi.event_type - ); - } - } - return; - } - - match fi.event_type { - x11xtest::FAKE_KEY_PRESS | x11xtest::FAKE_KEY_RELEASE => { - let pressed = fi.event_type == x11xtest::FAKE_KEY_PRESS; - backend.on_host_input( - state, - HostInputEvent::Key(HostKeyEvent { - pressed, - keycode: fi.detail, - time: fi.time, - root_x: fi.root_x, - root_y: fi.root_y, - event_x: 0, - event_y: 0, - state: 0, - }), - ); - } - x11xtest::FAKE_BUTTON_PRESS | x11xtest::FAKE_BUTTON_RELEASE => { - let pressed = fi.event_type == x11xtest::FAKE_BUTTON_PRESS; - // Translate X button number → Linux input code, since both - // backends' `on_host_input` paths consume Linux codes. - let linux_code = match fi.detail { - 1 => 0x110, // BTN_LEFT - 2 => 0x112, // BTN_MIDDLE - 3 => 0x111, // BTN_RIGHT - 4 => 0x180, // SYNTH_SCROLL_UP - 5 => 0x181, // SYNTH_SCROLL_DOWN - 6 => 0x182, // SYNTH_SCROLL_LEFT - 7 => 0x183, // SYNTH_SCROLL_RIGHT - 8 => 0x113, // BTN_SIDE - 9 => 0x114, // BTN_EXTRA - _ => { - log::debug!( - "XTEST FakeInput: dropping button event for unsupported X button {}", - fi.detail - ); - return; - } - }; - backend.on_host_input( - state, - HostInputEvent::PointerButton { - button: linux_code, - pressed, - time: fi.time, - }, - ); - } - x11xtest::FAKE_MOTION_NOTIFY => { - // detail 0 = absolute, detail 1 = relative (Xorg xtest.c: rootX/ - // rootY become the valuators, POINTER_ABSOLUTE only for 0). A - // relative fake moves the sprite by the delta from its current - // position, unaccelerated (XTEST doesn't set POINTER_ACCELERATE); - // the backend clips to the screen. The delta also rides as the - // raw relative motion, so XI2 RawMotion reports it. - let motion = if fi.detail == 0 { - HostInputEvent::PointerMotion { - x: i32::from(fi.root_x), - y: i32::from(fi.root_y), - time: fi.time, - relative: false, - dx: 0, - dy: 0, - } - } else { - let (x, y) = state.pointer_root; - let (dx, dy) = (i32::from(fi.root_x), i32::from(fi.root_y)); - HostInputEvent::PointerMotion { - x: i32::from(x) + dx, - y: i32::from(y) + dy, - time: fi.time, - relative: true, - dx, - dy, - } - }; - backend.on_host_input(state, motion); - // Like WarpPointer: the physical-input tracker must continue - // from the faked position, or the next real motion jumps back. - backend.resync_input_position(); - } - other => { - log::debug!("XTEST FakeInput: unknown event type {other}, dropping"); - } - } -} - -/// Apply a DPMS level transition. Updates `state.dpms.power_level` -/// **first** (so the page-flip gate trips immediately and an -/// interleaved composite tick can't submit a flip into a CRTC the -/// kernel is about to disable), then calls the backend, then emits -/// a notify iff the level actually changed. Backend errors are -/// logged but do not propagate — matches Xorg's "set it anyway" -/// posture (`Xext/dpms.c:262-293`). -pub(crate) fn apply_dpms_transition( - state: &mut ServerState, - backend: &mut dyn Backend, - new_level: u8, -) { - let old = state.dpms.power_level; - // ALWAYS call the backend, even when new_level == old. Matches Xorg - // DPMSSet (dpms.c:262-293), which gates only the notify on level - // change but always runs the per-screen DPMS hook. Two reasons this - // matters: - // (1) Recovery via reissue. If a previous transition advanced - // state.dpms.power_level but the backend errored (per the - // error contract, state advances anyway), a client can send - // DPMSForceLevel(same_level) to retry. The KMS backend's - // kms_outputs_active guard short-circuits idempotently when - // state IS consistent, and re-attempts when desynced. - // (2) Spam suppression is already handled at the backend level: - // KmsBackend::set_dpms_power early-returns when want_active - // equals self.kms_outputs_active. - if new_level != old { - log::info!( - "dpms: apply_dpms_transition {old} → {new_level} (enabled={}, kms_capable={})", - state.dpms.enabled, - state.dpms.kms_capable, - ); - } - state.dpms.power_level = new_level; - - // SS coupling — fires BEFORE backend hook and BEFORE DPMS notify - // (Xorg dpms.c:262-279 ordering). - // non-On + SS Off → SCREEN_SAVER_FORCER + Active → forced=true - // On + SS On → SCREEN_SAVER_OFF + Reset → forced=false - // Neither path resets last_activity (Xorg's NoticeTime only runs - // for the FORCER+Reset combination, window.c:3187-3193). - let dpms_on = new_level == 0; - match (dpms_on, state.screensaver.active) { - (false, ScreenSaverActive::Off) => { - apply_screen_saver_transition( - state, - backend, - ScreenSaverActive::On, - /*forced=*/ true, - ); - } - (true, ScreenSaverActive::On) => { - apply_screen_saver_transition( - state, - backend, - ScreenSaverActive::Off, - /*forced=*/ false, - ); - } - _ => {} - } - - if let Err(e) = backend.set_dpms_power(new_level) { - log::error!("set_dpms_power({new_level}) failed: {e}"); - // Intentionally swallowed: state still advances. See spec - // "Backend hook / Error contract". - } - if new_level != old { - emit_dpms_notify(state); - } -} - -/// Fan a `DPMSInfoNotify` GenericEvent out to every client -/// currently subscribed via `DPMSSelectInput(DPMS_INFO_NOTIFY_MASK)`. -/// Uses the existing `fanout_event_to_clients` helper for sequence -/// + byte-order + per-client write_or_buffer handling. -pub(crate) fn emit_dpms_notify(state: &mut ServerState) { - use crate::nested::DPMS_MAJOR_OPCODE; - use yserver_protocol::x11::dpms as x11dpms; - if state.dpms.selected_by.is_empty() { - return; - } - let ts = state.timestamp_now(); - let level = u16::from(state.dpms.power_level); - let enabled = state.dpms.enabled; - let subscribers: Vec = state.dpms.selected_by.iter().copied().collect(); - let dropped = crate::core_loop::fanout::fanout_event_to_clients( - state, - &subscribers, - |buf, seq, order| { - x11dpms::encode_dpms_info_notify_event( - buf, - order, - seq, - DPMS_MAJOR_OPCODE, - ts, - level, - enabled, - ); - }, - ); - // Reap subscribers whose outbound buffer overflowed — they're - // already on a path to disconnect via run.rs::reconcile_client_ - // writable_interest, and keeping them in selected_by would burn - // CPU on every subsequent notify until that finishes. - for cid in dropped { - state.dpms.selected_by.remove(&cid); - } -} - -/// Transition the screensaver to `new` (must be `Off` or `On`). -/// `Cycle` is an event-only value — it never appears in -/// `screensaver.active`. Passing it here is a programmer error; the -/// helper debug-asserts and no-ops in release builds. Idempotent on -/// same-state. On every Off↔On transition updates -/// `screensaver.active`, `screensaver.forced`, and -/// `screensaver.next_cycle`, then fires `ScreenSaverNotify` to -/// `SCREEN_SAVER_NOTIFY_MASK` subscribers. The `backend` parameter -/// is reserved for signature parity with `apply_dpms_transition` -/// and is currently unused (SS is purely server-side bookkeeping). -pub(crate) fn apply_screen_saver_transition( - state: &mut ServerState, - _backend: &mut dyn Backend, // reserved for future coupling (parity with apply_dpms_transition) - new: ScreenSaverActive, - forced: bool, -) { - debug_assert!( - !matches!(new, ScreenSaverActive::Cycle), - "Cycle is event-only and must never be written into screensaver.active — \ - route it through emit_screen_saver_notify instead" - ); - if matches!(new, ScreenSaverActive::Cycle) { - return; // release-build safety net - } - if state.screensaver.active == new { - return; - } - state.screensaver.active = new; - state.screensaver.forced = forced; - state.screensaver.next_cycle = match new { - ScreenSaverActive::On if state.screensaver.interval_ms > 0 => Some( - std::time::Instant::now() - + std::time::Duration::from_millis(u64::from(state.screensaver.interval_ms)), - ), - _ => None, - }; - emit_screen_saver_notify(state, new, forced); -} - -/// Fan a `ScreenSaverNotify` event out to subscribers. `notify_state` -/// and `forced` are passed explicitly so the cycle-timer path can -/// fire `Cycle` events without mutating `screensaver.active`. Cycle -/// events deliver to `CYCLE_MASK` subscribers; Off/On events deliver -/// to `NOTIFY_MASK` subscribers (Xorg `saver.c:389-391`). -pub(crate) fn emit_screen_saver_notify( - state: &mut ServerState, - notify_state: ScreenSaverActive, - forced: bool, -) { - use crate::nested::MIT_SCREEN_SAVER_FIRST_EVENT; - use yserver_protocol::x11::screensaver as x11ss; - let (active_state, deliver_mask) = match notify_state { - ScreenSaverActive::Off => (x11ss::SCREEN_SAVER_OFF, x11ss::SCREEN_SAVER_NOTIFY_MASK), - ScreenSaverActive::On => (x11ss::SCREEN_SAVER_ON, x11ss::SCREEN_SAVER_NOTIFY_MASK), - ScreenSaverActive::Cycle => (x11ss::SCREEN_SAVER_CYCLE, x11ss::SCREEN_SAVER_CYCLE_MASK), - }; - let subs: Vec = state - .screensaver - .selected_by - .iter() - .filter(|(_, mask)| **mask & deliver_mask != 0) - .map(|(c, _)| *c) - .collect(); - if subs.is_empty() { - return; - } - let ts = state.timestamp_now(); - let root = crate::resources::ROOT_WINDOW.0; - let kind = if state.screensaver.prefer_blanking { - x11ss::SCREEN_SAVER_BLANKED - } else { - x11ss::SCREEN_SAVER_INTERNAL - }; - let dropped = - crate::core_loop::fanout::fanout_event_to_clients(state, &subs, |buf, seq, order| { - x11ss::encode_screen_saver_notify_event( - buf, - order, - seq, - MIT_SCREEN_SAVER_FIRST_EVENT, - active_state, - ts, - root, - 0, // window — always 0 (no SetAttributes path) - kind, - forced, - ); - }); - for cid in dropped { - state.screensaver.selected_by.remove(&cid); - } -} - -/// Current idle value for an IDLETIME-family counter, expressed as -/// milliseconds since `state.idletime_baseline(counter)`. Used by -/// CREATE_ALARM / CHANGE_ALARM (Relative values, trigger checks) for -/// counter values that aren't stored in `state.sync_counters`. -pub(crate) fn idletime_current_idle(state: &ServerState, counter: u32) -> i64 { - let baseline = state.idletime_baseline(counter); - #[allow(clippy::cast_possible_truncation)] - let v = std::time::Instant::now() - .duration_since(baseline) - .as_millis() - .min(u128::from(u32::MAX)) as i64; - v -} - -/// Evaluate Negative-* alarms on IDLETIME-family counters after input -/// wake. Called from the key + pointer fanout prologues immediately -/// after `last_activity` is updated to "now". The semantic is: -/// `old_idle = (now - prior_last_activity)`, `new_idle = 0`. Fires any -/// alarms whose trigger crosses on this transition. -/// -/// `device_id` identifies which per-device counter to evaluate; pass -/// 2 for pointer events (drives IDLETIME_DEVICE_VCP), 3 for key events -/// (drives IDLETIME_DEVICE_VCK). The global IDLETIME counter is -/// evaluated unconditionally because any input resets the global -/// last_activity. -pub(crate) fn evaluate_idletime_negative_alarms_on_input_wake( - state: &mut ServerState, - device_id: u8, - prior_global_idle_ms: i64, - prior_device_idle_ms: i64, -) { - use yserver_protocol::x11::sync as x11sync; - // Suspend gate (Xorg WaitFor.c:519). When XScreenSaverSuspend is - // held, the unified timer is not armed in either direction — - // including the input-wake firing of Negative-* alarms. Without - // this gate, an input event during fullscreen video would still - // fire MATE's wake alarms and could prompt mate-power-manager to - // re-arm screen-blanking too aggressively. - if !state.screensaver.suspend_counts.is_empty() { - return; - } - // Global IDLETIME: always reset on any input. - crate::core_loop::sync_await::counter_changed( - state, - x11sync::IDLETIME_COUNTER, - prior_global_idle_ms, - 0, - ); - state - .idletime_last_evaluated - .insert(x11sync::IDLETIME_COUNTER, 0); - - // Per-device IDLETIME: only the affected device resets. - let device_counter = match device_id { - 2 => x11sync::IDLETIME_DEVICE_VCP, - 3 => x11sync::IDLETIME_DEVICE_VCK, - _ => return, - }; - crate::core_loop::sync_await::counter_changed(state, device_counter, prior_device_idle_ms, 0); - state.idletime_last_evaluated.insert(device_counter, 0); -} - -/// Reset IDLETIME bookkeeping when the suspend-counts table drains to -/// empty. Must be called at the SAME spot the existing MIT-SCREEN-SAVER -/// code resets `state.dpms.last_activity` (SS Suspend handler + -/// process_disconnect's last-suspender cleanup). -/// -/// Without this, IDLETIME alarms can be skipped post-suspend because -/// `idletime_last_evaluated` holds stale-high values from before the -/// suspend, causing `evaluate_alarms_for_counter`'s -/// `old < wait <= new` Transition check to never hold. -pub(crate) fn reset_idletime_state_after_suspend_release(state: &mut ServerState) { - let now = std::time::Instant::now(); - // dpms.last_activity is already reset by the caller. Reset the - // per-device baselines so post-resume per-device IDLETIME - // computation is consistent. - for entry in state.per_device_last_activity.values_mut() { - *entry = now; - } - // Clear the evaluator's last-seen cache so the next post-poll pass - // computes `(old=0, new=current)` from a clean slate, preserving - // the Transition `old < wait <= new` invariant. - state.idletime_last_evaluated.clear(); -} - -fn handle_dpms_request( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use crate::nested::DPMS_MAJOR_OPCODE; - use yserver_protocol::x11::{ClientByteOrder, dpms as x11dpms}; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - debug!( - "client {} #{} DPMS::minor={} body_len={}", - client_id.0, - sequence.0, - minor, - body.len() - ); - match minor { - x11dpms::GET_VERSION => { - let reply = x11dpms::encode_get_version_reply( - byte_order, - sequence, - x11dpms::MAJOR_VERSION, - x11dpms::MINOR_VERSION, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11dpms::CAPABLE => { - let reply = x11dpms::encode_capable_reply(byte_order, sequence, state.dpms.kms_capable); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11dpms::GET_TIMEOUTS => { - #[allow(clippy::cast_possible_truncation)] - let s = (state.dpms.standby_ms / 1000) as u16; - #[allow(clippy::cast_possible_truncation)] - let su = (state.dpms.suspend_ms / 1000) as u16; - #[allow(clippy::cast_possible_truncation)] - let o = (state.dpms.off_ms / 1000) as u16; - let reply = x11dpms::encode_get_timeouts_reply(byte_order, sequence, s, su, o); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11dpms::SET_TIMEOUTS => { - let Some((standby, suspend, off)) = x11dpms::parse_set_timeouts_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - }; - // Zero = "this level disabled". Among non-zero values - // require off >= suspend >= standby. Xorg `:370-376`. - let nonzero_violates = |a: u16, b: u16| a != 0 && b != 0 && a > b; - // Report the value being compared against (the one that - // "should have been bigger"), matching Xorg dpms.c:373. - if nonzero_violates(suspend, off) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(off), - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - } - if nonzero_violates(standby, suspend) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(suspend), - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - } - state.dpms.standby_ms = u32::from(standby) * 1000; - state.dpms.suspend_ms = u32::from(suspend) * 1000; - state.dpms.off_ms = u32::from(off) * 1000; - } - x11dpms::ENABLE => { - if !state.dpms.enabled { - state.dpms.enabled = true; - emit_dpms_notify(state); - } - } - x11dpms::DISABLE => { - let was_enabled = state.dpms.enabled; - // Force level back to On (calls notify iff level changed). - apply_dpms_transition(state, backend, 0); - if was_enabled { - state.dpms.enabled = false; - emit_dpms_notify(state); - } - } - x11dpms::FORCE_LEVEL => { - if !state.dpms.enabled { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - } - let Some(level) = x11dpms::parse_force_level_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - }; - if level > 3 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(level), - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - } - #[allow(clippy::cast_possible_truncation)] - apply_dpms_transition(state, backend, level as u8); - } - x11dpms::INFO => { - let reply = x11dpms::encode_info_reply( - byte_order, - sequence, - u16::from(state.dpms.power_level), - state.dpms.enabled, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11dpms::SELECT_INPUT => { - let Some(mask) = x11dpms::parse_select_input_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - }; - if mask & !x11dpms::DPMS_INFO_NOTIFY_MASK != 0 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - mask, - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - } - if mask & x11dpms::DPMS_INFO_NOTIFY_MASK != 0 { - state.dpms.selected_by.insert(client_id); - } else { - state.dpms.selected_by.remove(&client_id); - } - } - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(header.data), - DPMS_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -fn handle_screen_saver_request( - state: &mut ServerState, - _backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use crate::nested::MIT_SCREEN_SAVER_MAJOR_OPCODE; - use yserver_protocol::x11::{ClientByteOrder, screensaver as x11ss}; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - let minor_u16 = u16::from(minor); - debug!( - "client {} #{} ScreenSaver::minor={} body_len={}", - client_id.0, - sequence.0, - minor, - body.len() - ); - - match minor { - x11ss::QUERY_VERSION => { - let reply = x11ss::encode_query_version_reply( - byte_order, - sequence, - x11ss::SERVER_MAJOR_VERSION, - x11ss::SERVER_MINOR_VERSION, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11ss::QUERY_INFO => { - if x11ss::parse_query_info_request(body).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - minor_u16, - MIT_SCREEN_SAVER_MAJOR_OPCODE, - ); - } - debug_assert!( - !matches!(state.screensaver.active, ScreenSaverActive::Cycle), - "Cycle must never appear in screensaver.active — \ - see apply_screen_saver_transition guard" - ); - // X11 timestamps are 32-bit ms; wraps at ~49 days per X11 spec. - #[allow(clippy::cast_possible_truncation)] - let last_input = state.dpms.last_activity.elapsed().as_millis() as u32; - let timeout = state.screensaver.timeout_ms; - let (reply_state, til_or_since) = match state.screensaver.active { - ScreenSaverActive::On => { - let ts = last_input.wrapping_sub(timeout); - (x11ss::SCREEN_SAVER_ON, if timeout > 0 { ts } else { 0 }) - } - ScreenSaverActive::Off | ScreenSaverActive::Cycle => { - if timeout == 0 { - (x11ss::SCREEN_SAVER_DISABLED, 0) - } else if timeout < last_input { - (x11ss::SCREEN_SAVER_OFF, 0) - } else { - (x11ss::SCREEN_SAVER_OFF, timeout - last_input) - } - } - }; - let event_mask = state - .screensaver - .selected_by - .get(&client_id) - .copied() - .unwrap_or(0); - let kind = if state.screensaver.prefer_blanking { - x11ss::SCREEN_SAVER_BLANKED - } else { - x11ss::SCREEN_SAVER_INTERNAL - }; - let reply = x11ss::encode_query_info_reply( - byte_order, - sequence, - reply_state, - 0, /*window*/ - til_or_since, - last_input, - event_mask, - kind, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11ss::SELECT_INPUT => { - let Some((_drawable, mask)) = x11ss::parse_select_input_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - minor_u16, - MIT_SCREEN_SAVER_MAJOR_OPCODE, - ); - }; - if mask == 0 { - state.screensaver.selected_by.remove(&client_id); - } else { - state.screensaver.selected_by.insert(client_id, mask); - } - } - x11ss::SET_ATTRIBUTES => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - 0, - minor_u16, - MIT_SCREEN_SAVER_MAJOR_OPCODE, - ); - } - x11ss::UNSET_ATTRIBUTES => { - if x11ss::parse_unset_attributes_request(body).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - minor_u16, - MIT_SCREEN_SAVER_MAJOR_OPCODE, - ); - } - } - x11ss::SUSPEND => { - let Some(suspend) = x11ss::parse_suspend_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - minor_u16, - MIT_SCREEN_SAVER_MAJOR_OPCODE, - ); - }; - if suspend { - *state - .screensaver - .suspend_counts - .entry(client_id) - .or_insert(0) += 1; - } else { - let drained = match state.screensaver.suspend_counts.get_mut(&client_id) { - Some(c) if *c > 1 => { - *c -= 1; - false - } - Some(_) => { - state.screensaver.suspend_counts.remove(&client_id); - true - } - None => false, - }; - if drained - && state.screensaver.suspend_counts.is_empty() - && matches!(state.screensaver.active, ScreenSaverActive::Off) - && state.dpms.power_level == 0 - { - // Mirrors ScreenSaverFreeSuspend (saver.c:343-378): - // restart the idle clock from now. No notify fires. - state.dpms.last_activity = std::time::Instant::now(); - reset_idletime_state_after_suspend_release(state); - } - } - } - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - minor_u16, - MIT_SCREEN_SAVER_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// Task 13 (spec §"Amendment 2026-08-01 — successor-gate relaxation"): -/// single source of truth for whether `successor` provably presents its -/// full source extent, and therefore may act as a scrap successor at -/// all. MANDATORY shared helper — used by BOTH -/// `present_supersession_covers` (the coverage gate below) and -/// `supersede_covered_pending_presents`'s decline-telemetry guard; they -/// must agree on what "cleared the gate" means, or the telemetry -/// mislabels every full-extent-region decline as a coverage failure. -/// -/// `None` (unchanged Xorg gate, `present_scmd.c:802`) always passes. -/// `Some(rects)` passes iff at least one single rect `r` contains the -/// full source extent, every term explicitly widened to `i32` (as -/// literally written in `i16`/`u16` this would not compile, and `u16` -/// arithmetic would wrap on negative `r.x`): -/// -/// ```text -/// i32::from(r.x) <= 0 -/// && i32::from(r.y) <= 0 -/// && i32::from(r.x) + i32::from(r.width) >= i32::from(src_width) -/// && i32::from(r.y) + i32::from(r.height) >= i32::from(src_height) -/// ``` -/// -/// (pixmap coordinates, before `x_off`/`y_off` translation — Xorg -/// installs the update region as a `CT_REGION` clip with -/// `GCClipXOrigin/GCClipYOrigin = x_off/y_off`, `present.c:76-92`.) A -/// zero-area rect can never satisfy both `>=` conditions, so -/// `Some([zero-area rect])` and `Some(empty)` both decline via `.any()` -/// on an iterator that is either empty or has no satisfying element. -/// Union coverage across multiple rects is deliberately NOT computed (no -/// observed client needs it — see the spec amendment's rejected- -/// alternative note): a multi-rect region whose union but no single rect -/// covers the extent declines, conservatively. -fn successor_presents_full_extent(successor: &PendingPresentPixmap) -> bool { - match &successor.update_rects { - None => true, - Some(rects) => rects.iter().any(|r| { - i32::from(r.x) <= 0 - && i32::from(r.y) <= 0 - && i32::from(r.x) + i32::from(r.width) >= i32::from(successor.src_width) - && i32::from(r.y) + i32::from(r.height) >= i32::from(successor.src_height) - }), - } -} - -/// Task 8 §Supersession coverage predicate (spec §Supersession; Xorg -/// verification item (d), `present_scmd.c:802`). `successor` is the -/// newly-arriving present `B`; `predecessor` is a candidate victim `A` -/// already sitting unexecuted in `present_pending_exec`. Pure — no state -/// mutation, so the arrival-time coverage scan -/// (`supersede_covered_pending_presents`) can call it as a `.filter()` -/// predicate. -/// -/// Destination-coordinate arithmetic in `i32`: offsets (`x_off`/`y_off`) -/// are `i16` and may be negative (a present whose window is partially -/// off-screen), and must NOT saturate the way `execute_present_pixmap_copy`'s -/// copy-time math does (`saturating_add`) — a saturated coordinate could -/// make an uncovered predecessor look covered. -/// -/// The **successor gate comes first**, via `successor_presents_full_extent` -/// (spec §"Amendment 2026-08-01 — successor-gate relaxation"): Xorg's -/// scrap loop (`present_scmd.c:802`, `if (!update && pixmap)`) attempts -/// scrap only when the successor carries no update region; yserver -/// additionally accepts a `Some(rects)` successor when one single rect -/// provably covers the full source extent (the NVIDIA-WSI shape — a -/// full-extent single-rect update region where Mesa attaches none). A -/// successor whose update region does not clear that gate — including -/// the documented zero-pixel `Some(empty)` present and any partial or -/// multi-rect-union-only region — never scraps anything, regardless of -/// predecessor geometry; this still dissolves the marco/picom -/// drag-sliver risk (a sliver successor's region never clears the gate). -/// -/// Given the gate passes, coverage is yserver's strictly conservative -/// addition on top of Xorg (which is geometry-blind): the predecessor's -/// footprint, in destination coordinates, must fit entirely inside the -/// successor's full-extent rect (top-left `(x_off, y_off)`, bottom-right -/// `(x_off plus src_width, y_off plus src_height)`) — source-pixmap- -/// bounded, not window-bounded, which matters mid-resize when Mesa -/// reallocates swapchain pixmaps on `PresentConfigureNotify`. A -/// predecessor with `update_rects == None` is covered iff its own -/// full-extent rect fits; `Some(rects)` iff every destination rect fits; -/// `Some(empty)` is trivially covered (no content, so nothing can fail -/// to fit — falls out of `.all()` on an empty iterator). -fn present_supersession_covers( - successor: &PendingPresentPixmap, - predecessor: &PendingPresentPixmap, -) -> bool { - if !successor_presents_full_extent(successor) { - return false; - } - - let (succ_x, succ_y) = successor.request.offsets(); - let (succ_x, succ_y) = (i32::from(succ_x), i32::from(succ_y)); - let succ_right = succ_x + i32::from(successor.src_width); - let succ_bottom = succ_y + i32::from(successor.src_height); - - let fits = |x: i32, y: i32, w: i32, h: i32| -> bool { - x >= succ_x && y >= succ_y && x + w <= succ_right && y + h <= succ_bottom - }; - - let (pred_x_i16, pred_y_i16) = predecessor.request.offsets(); - let (pred_x, pred_y) = (i32::from(pred_x_i16), i32::from(pred_y_i16)); - match &predecessor.update_rects { - None => fits( - pred_x, - pred_y, - i32::from(predecessor.src_width), - i32::from(predecessor.src_height), - ), - Some(rects) => rects.iter().all(|r| { - // Evaluate exactly where the real copy lands - // (`execute_present_pixmap_copy`'s `x_off.saturating_add(rect.x)`, - // computed in `i16` — not unsaturated `i32` addition). Near - // `i16::MAX` the two disagree: an unsaturated `pred_x + r.x` - // can land past where the copy's saturated dest actually - // draws, so the predicate would judge "covered" at a - // position the copy never used (sliver loss). Saturate in - // `i16` first, exactly like the copy, then widen to `i32` - // only for the extent comparison. - fits( - i32::from(pred_x_i16.saturating_add(r.x)), - i32::from(pred_y_i16.saturating_add(r.y)), - i32::from(r.width), - i32::from(r.height), - ) - }), - } -} - -/// Task 8 §Supersession: build the `CompletedPresentEvent` a scrapped or -/// copy-failed entry would have produced had it reached -/// `execute_present_pixmap_copy`'s `enqueue_present_completion` call — -/// fields exactly as that function builds them (`host_xid` is the -/// client-visible pixmap XID, not the backend host xid, matching the -/// wire-event identity Mesa expects). -fn completed_event_for_pending( - pending: &PendingPresentPixmap, -) -> crate::backend::CompletedPresentEvent { - crate::backend::CompletedPresentEvent { - client_id: pending.client_id, - serial: pending.request.serial(), - host_xid: pending.request.pixmap(), - dst_host_xid: pending.request.window(), - options: pending.masked_options, - present_id: pending.present_id, - window_generation: pending.window_generation, - crtc_id: pending.crtc_id, - crtc_epoch: pending.crtc_epoch, - msc_offset: pending.msc_offset, - completion_clock: None, - wake: pending.wake.clone(), - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - } -} - -/// IdleNotify-only half of `fire_present_completion_events_at`, fired -/// immediately at supersession scrap and at the copy-failure reroute -/// (Task 8) — deliberately NOT reusing `fire_present_completion_events_at` -/// itself, whose `CompleteNotify` half must NOT fire at this point (the -/// completion is parked for ordered delivery at the target MSC instead). -/// Modeled on the `IdleNotify` branch of that function: same selection -/// lookup, same `encode_idle_notify` call, gated on `IDLE_NOTIFY_MASK`. -fn fire_present_idle_notify_now( - state: &mut ServerState, - event: &crate::backend::CompletedPresentEvent, -) { - use crate::backend::PresentWake; - use yserver_protocol::x11::present as x11present; - - /// PRESENT major opcode. - const PRESENT_MAJOR_OPCODE: u8 = 145; - /// `PresentEventMaskIdleNotify`. - const IDLE_NOTIFY_MASK: u32 = 0x4; - - let window = ResourceId(event.dst_host_xid); - let pixmap_xid = event.host_xid; - let idle_fence = match &event.wake { - PresentWake::Pixmap { idle_fence_xid } => *idle_fence_xid, - PresentWake::PixmapSynced { - release_syncobj, .. - } => *release_syncobj, - }; - - let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); - for (eid, sel) in &state.present_event_selections { - if sel.window == window { - targets.push((*eid, sel.owner, sel.event_mask)); - } - } - - for (eid, owner, mask) in targets { - if mask & IDLE_NOTIFY_MASK == 0 { - continue; - } - let Some(client) = state.clients.get_mut(&owner.0) else { - continue; - }; - let byte_order = client.byte_order; - let seq = SequenceNumber( - client - .last_sequence - .load(std::sync::atomic::Ordering::Relaxed), - ); - let ev = x11present::encode_idle_notify( - byte_order, - seq, - PRESENT_MAJOR_OPCODE, - eid, - window.0, - event.serial, - pixmap_xid, - idle_fence, - ); - let _ = write_to_client(client, owner, &ev); - } -} - -/// Task 8 §Supersession: scan `present_pending_exec` for entries covered -/// by the newly-arriving successor `successor` and scrap them. Called in -/// BOTH Present::Pixmap and Present::PixmapSynced handlers right after -/// `pending` is fully built and after the successor's own -/// `arm_present_source_wait` / `arm_present_syncobj_wait` has already -/// succeeded (arm-before-scrap: see the comment at each call site) — -/// scrap happens at arrival regardless of whether the successor's own -/// source was ready or deferred, and regardless of its own park/execute -/// msc-due classification. -/// -/// Gated on the successor having a known effective target. A successor -/// with `effective_target_msc = None` never scraps because target -/// equivalence is not known. Victims are entries in -/// `present_pending_exec` for the same window, CRTC domain, and effective -/// target whose coverage -/// (`present_supersession_covers`) passes — everything in the store is -/// unexecuted by definition, so no additional "not yet executed" check -/// is needed. -fn supersede_covered_pending_presents( - state: &mut ServerState, - backend: &mut dyn Backend, - successor: &PendingPresentPixmap, -) { - let Some(target) = successor.effective_target_msc else { - return; - }; - let window = successor.request.window(); - - let mut victim_ids: Vec = Vec::new(); - for (&pid, entry) in &state.present_pending_exec { - if entry.pending.request.window() != window - || entry.pending.crtc_id != successor.crtc_id - || entry.pending.crtc_epoch != successor.crtc_epoch - || entry.pending.effective_target_msc != Some(target) - { - continue; - } - if present_supersession_covers(successor, &entry.pending) { - victim_ids.push(pid); - } else if successor_presents_full_extent(successor) { - // Task 10 telemetry (spec §Telemetry / verification item (d)): - // the successor cleared the amended successor gate - // (`successor_presents_full_extent` — no update region, or a - // single rect covering the full source extent) but yserver's - // own extent-coverage check declined this candidate anyway — - // the empirical input for the future coverage-relaxation - // decision. Excluded here: successors whose update region - // does NOT clear the gate, which never even attempt scrap - // (the gate itself, `present_supersession_covers`'s first - // check) and would flood this log on every marco-style - // partial update. - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=supersede_declined by={} window=0x{:x} eff={}", - pace_instr_ms(), pid, successor.present_id, window, target - ); - } - } - - for pid in victim_ids { - let Some(entry) = state.present_pending_exec.remove(&pid) else { - continue; - }; - // Task 10 telemetry: one `note_present_skip` per scrapped victim - // — the copy that did NOT happen. KMS surfaces this as - // `present_skips/s` in `render_telemetry`. - backend.note_present_skip(); - // 1. Cancel the source/acquire wait if armed, and release the - // entry's own source pin. - if let Some(wid) = entry.wait_id { - backend.finish_present_source_wait(wid); - state.present_wait_to_id.remove(&wid); - } - if let Some(pin) = entry.pin { - backend.release_present_source(pin); - } - // 2. By-XID buffer release, immediately — the victim never - // reached `enqueue_present_completion`, so this is its sole - // release path (no backend `PinnedWake` / gate entry exists for - // it). The X11 fence mirror write is REQUIRED here, as it is in - // the window-destroy purge: without it a client's own fence query - // could disagree with its unblocked wait for up to a period. - match &entry.pending.wake { - crate::backend::PresentWake::Pixmap { idle_fence_xid } if *idle_fence_xid != 0 => { - if let Err(e) = backend.dri3_trigger_fence(*idle_fence_xid) { - log::warn!( - "PRESENT supersede: trigger idle fence 0x{idle_fence_xid:x} failed: {e}" - ); - } - crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); - } - crate::backend::PresentWake::PixmapSynced { - release, - release_syncobj, - release_value, - } => { - if let Err(e) = release.signal(*release_value) { - log::warn!( - "PRESENT supersede: signal release syncobj 0x{release_syncobj:x}@\ - {release_value} failed: {e}" - ); - } - } - _ => {} - } - let event = completed_event_for_pending(&entry.pending); - // 3. Fire IdleNotify only, now — CompleteNotify is parked below. - fire_present_idle_notify_now(state, &event); - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=superseded by={} window=0x{:x} eff={}", - pace_instr_ms(), pid, successor.present_id, window, target - ); - // 4. Park the Skip for ordered delivery at the target clock. - // 5. The entry + side-map row are already gone (removed above). - state - .present_pending_complete - .push(crate::server::PendingPresentComplete { - event, - effective_target_msc: target, - mode: yserver_protocol::x11::present::COMPLETE_MODE_SKIP, - emit_idle: false, - }); - } -} - -/// Arm a `Present::Pixmap` successor's own source-pixmap wait, then scrap -/// covered pending entries — **in this order, never reversed**. The arm -/// is client-reachably fallible; scrap is not reversible (it releases -/// victims' buffers and fires their IdleNotify/Skip immediately). Running -/// scrap first and then having the arm fail would unwind via `?` with the -/// victims already destroyed and nothing committed to replace them, -/// leaving the window with no frame at the target MSC where Xorg would -/// still have shown the victim. Factored out (rather than inlined at the -/// call site) so a regression test can exercise the exact production -/// ordering instead of calling the two steps itself. -fn arm_present_pixmap_source_then_supersede( - state: &mut ServerState, - backend: &mut dyn Backend, - pending: &PendingPresentPixmap, -) -> std::io::Result { - let armed = - backend.arm_present_source_wait(pending.src_host_xid, pending.paint_dst_host_xid)?; - supersede_covered_pending_presents(state, backend, pending); - Ok(armed) -} - -/// `Present::PixmapSynced` counterpart of -/// `arm_present_pixmap_source_then_supersede`: arms the explicit acquire -/// syncobj wait before scrapping covered pending entries, for the same -/// reason (an unknown/invalid acquire syncobj makes this arm fail in a -/// way clients can trigger, and scrap must not run ahead of a still- -/// fallible arm). -fn arm_present_pixmap_synced_source_then_supersede( - state: &mut ServerState, - backend: &mut dyn Backend, - acquire_syncobj: u32, - acquire_value: u64, - pending: &PendingPresentPixmap, -) -> std::io::Result { - let armed = backend.arm_present_syncobj_wait( - pending.src_host_xid, - pending.paint_dst_host_xid, - acquire_syncobj, - acquire_value, - )?; - supersede_covered_pending_presents(state, backend, pending); - Ok(armed) -} - -#[derive(Debug, Clone, Copy)] -struct PresentDomainSelection { - crtc_id: u32, - crtc_epoch: u64, - msc_offset: u64, - raw_msc: u64, - raw_ust: u64, -} - -fn present_crtc_is_enabled(state: &ServerState, crtc_id: u32) -> bool { - crtc_id != 0 - && state - .randr - .enabled_outputs() - .any(|output| output.crtc_id == crtc_id) -} - -fn present_crtc_exists(state: &ServerState, crtc_id: u32) -> bool { - state - .randr - .outputs - .iter() - .any(|output| output.crtc_id == crtc_id) -} - -/// Select an enabled output by greatest intersection with `window`. -/// RANDR primary wins equal-area ties (including the all-zero fallback), -/// then the stable `randr.outputs` order wins. With no enabled outputs the -/// synthetic headless domain 0 preserves zero-device operation. -fn default_present_crtc_for_window(state: &ServerState, window: ResourceId) -> u32 { - let Some(window_record) = state.resources.window(window) else { - return 0; - }; - let (window_x, window_y) = state.resources.window_absolute_position(window); - let window_right = window_x.saturating_add(i32::from(window_record.width)); - let window_bottom = window_y.saturating_add(i32::from(window_record.height)); - let primary = state.randr.primary_output; - - let mut best: Option<(u64, bool, u32)> = None; - for output in state.randr.enabled_outputs() { - let output_x = i32::from(output.x); - let output_y = i32::from(output.y); - let output_right = output_x.saturating_add(i32::from(output.width)); - let output_bottom = output_y.saturating_add(i32::from(output.height)); - let width = window_right.min(output_right) - window_x.max(output_x); - let height = window_bottom.min(output_bottom) - window_y.max(output_y); - let area = if width > 0 && height > 0 { - u64::try_from(width).unwrap_or(0) * u64::try_from(height).unwrap_or(0) - } else { - 0 - }; - let is_primary = output.output_id == primary; - let replace = best.is_none_or(|(best_area, best_primary, _)| { - area > best_area || (area == best_area && is_primary && !best_primary) - }); - if replace { - best = Some((area, is_primary, output.crtc_id)); - } - } - best.map_or(0, |(_, _, crtc_id)| crtc_id) -} - -pub(crate) fn cached_present_crtc_clock( - state: &ServerState, - crtc_id: u32, - crtc_epoch: u64, -) -> crate::server::PresentCrtcClock { - state - .present_crtc_clocks - .get(&(crtc_id, crtc_epoch)) - .copied() - .unwrap_or_else(|| crate::server::PresentCrtcClock { - epoch: crtc_epoch, - ..crate::server::PresentCrtcClock::default() - }) -} - -/// Refresh one current physical clock epoch. A valid-but-Off CRTC and the -/// headless domain stay at zero; they are accepted but deliberately unpaced. -pub(crate) fn refresh_present_crtc_general_clock( - state: &mut ServerState, - backend: &mut dyn Backend, - crtc_id: u32, - crtc_epoch: u64, -) -> crate::server::PresentCrtcClock { - if crtc_id == 0 - || !present_crtc_is_enabled(state, crtc_id) - || backend.present_crtc_clock_epoch(crtc_id) != crtc_epoch - { - return cached_present_crtc_clock(state, crtc_id, crtc_epoch); - } - let (msc, ust) = backend.present_get_ust_msc(crtc_id); - let clock = state - .present_crtc_clocks - .entry((crtc_id, crtc_epoch)) - .or_insert_with(|| crate::server::PresentCrtcClock { - epoch: crtc_epoch, - ..crate::server::PresentCrtcClock::default() - }); - if msc > 0 { - clock.msc = msc; - clock.ust = ust; - } - *clock -} - -pub(crate) fn refresh_present_crtc_completion_clock( - state: &mut ServerState, - backend: &mut dyn Backend, - crtc_id: u32, - crtc_epoch: u64, - exact: Option, -) -> crate::backend::PresentClockSample { - let has_exact = exact.is_some(); - let sample = if let Some(exact) = exact { - exact - } else if crtc_id != 0 - && present_crtc_is_enabled(state, crtc_id) - && backend.present_crtc_clock_epoch(crtc_id) == crtc_epoch - { - backend.present_get_completion_clock(crtc_id) - } else { - return cached_present_crtc_clock(state, crtc_id, crtc_epoch).completion; - }; - advance_present_crtc_completion_clock(state, crtc_id, crtc_epoch, sample); - let cached = state - .present_crtc_clocks - .get(&(crtc_id, crtc_epoch)) - .copied() - .unwrap_or_else(|| crate::server::PresentCrtcClock { - epoch: crtc_epoch, - ..crate::server::PresentCrtcClock::default() - }); - if has_exact { sample } else { cached.completion } -} - -fn advance_present_crtc_completion_clock( - state: &mut ServerState, - crtc_id: u32, - crtc_epoch: u64, - sample: crate::backend::PresentClockSample, -) { - let clock = state - .present_crtc_clocks - .entry((crtc_id, crtc_epoch)) - .or_insert_with(|| crate::server::PresentCrtcClock { - epoch: crtc_epoch, - ..crate::server::PresentCrtcClock::default() - }); - let advances_cache = sample.msc > 0 - && (clock.completion.msc == 0 - || sample.msc == clock.completion.msc - || crate::present_scheduler::msc_is_after(sample.msc, clock.completion.msc)); - if advances_cache { - clock.completion = sample; - } -} - -fn present_wire_clock( - raw: crate::backend::PresentClockSample, - msc_offset: u64, -) -> crate::backend::PresentClockSample { - crate::backend::PresentClockSample { - msc: raw.msc.wrapping_sub(msc_offset), - ..raw - } -} - -/// Bind a Present window to a CRTC clock while preserving Xorg's continuous -/// window MSC. `msc_offset` is defined by `wire_msc = raw_msc - offset`; -/// therefore a clock-domain switch applies `offset += new_raw - old_raw`. -fn bind_present_window_domain( - state: &mut ServerState, - backend: &mut dyn Backend, - window: u32, - crtc_id: u32, -) -> PresentDomainSelection { - let crtc_epoch = backend.present_crtc_clock_epoch(crtc_id); - let new_clock = refresh_present_crtc_general_clock(state, backend, crtc_id, crtc_epoch); - let previous = state.present_window_msc.get(&window).copied(); - - let next = match previous { - None => crate::server::PresentWindowMsc { - last_crtc: crtc_id, - last_crtc_epoch: crtc_epoch, - msc_offset: 0, - last_raw_msc: new_clock.msc, - }, - Some(mut window_clock) - if window_clock.last_crtc == crtc_id && window_clock.last_crtc_epoch == crtc_epoch => - { - if new_clock.msc > 0 { - window_clock.last_raw_msc = new_clock.msc; - } - window_clock - } - Some(mut window_clock) => { - let current_old_epoch = backend.present_crtc_clock_epoch(window_clock.last_crtc); - let old_raw = if current_old_epoch == window_clock.last_crtc_epoch { - let old_clock = refresh_present_crtc_general_clock( - state, - backend, - window_clock.last_crtc, - window_clock.last_crtc_epoch, - ); - if old_clock.msc > 0 { - old_clock.msc - } else { - window_clock.last_raw_msc - } - } else { - // The stable RANDR XID now names another physical counter. - // Never sample that replacement as the old side of the rebase. - let cached_old = cached_present_crtc_clock( - state, - window_clock.last_crtc, - window_clock.last_crtc_epoch, - ); - if cached_old.msc > 0 { - cached_old.msc - } else { - window_clock.last_raw_msc - } - }; - window_clock.msc_offset = window_clock - .msc_offset - .wrapping_add(new_clock.msc.wrapping_sub(old_raw)); - window_clock.last_crtc = crtc_id; - window_clock.last_crtc_epoch = crtc_epoch; - window_clock.last_raw_msc = new_clock.msc; - window_clock - } - }; - state.present_window_msc.insert(window, next); - PresentDomainSelection { - crtc_id, - crtc_epoch, - msc_offset: next.msc_offset, - raw_msc: new_clock.msc, - raw_ust: new_clock.ust, - } -} - -/// Resolve and bind a request domain. Explicit nonzero XIDs validate only -/// resource existence (Xorg accepts a valid-but-Off CRTC); implicit Pixmap -/// requests select by coverage every time, while NotifyMSC can request reuse -/// of the window's previous Present domain. -fn select_present_domain( - state: &mut ServerState, - backend: &mut dyn Backend, - window: u32, - target_crtc: u32, - reuse_previous: bool, -) -> Result { - let crtc_id = if target_crtc != 0 { - if !present_crtc_exists(state, target_crtc) { - return Err(target_crtc); - } - target_crtc - } else if reuse_previous { - state.present_window_msc.get(&window).map_or_else( - || default_present_crtc_for_window(state, ResourceId(window)), - |c| c.last_crtc, - ) - } else { - default_present_crtc_for_window(state, ResourceId(window)) - }; - Ok(bind_present_window_domain(state, backend, window, crtc_id)) -} - -fn effective_present_target_raw( - domain: PresentDomainSelection, - target_msc: u64, - divisor: u64, - remainder: u64, - options: u32, -) -> Option { - if domain.raw_msc == 0 { - return None; - } - // Xorg intentionally shifts only target_msc; divisor/remainder stay in - // the raw CRTC clock's residue class. - let effective = crate::present_scheduler::effective_target_msc( - target_msc.wrapping_add(domain.msc_offset), - domain.raw_msc, - divisor, - remainder, - options, - ); - // Xorg retains the target MSC even when an async request resolves to the - // current field. Besides being the protocol completion identity, that - // value groups same-target requests for supersession. `None` is reserved - // for a domain with no usable clock; collapsing current/past async targets - // to `None` makes the core park them behind an in-flight flip and prevents - // both core supersession and the backend's bounded successor queue. - Some(effective) -} - -/// Execute a batch of specific `present_pending_exec` entries by id — -/// shared by every msc-due execution site (the due-pass's normal -/// execute-due step, the idle-display fallback, the absolute-arm -/// Ok(0)/Err fallback, and the blackout flush). Missing ids (already -/// resolved by a concurrent path) are silently skipped. Mirrors -/// `drain_ready_present_pixmaps`'s execute/release/mark_dirty sequence: -/// the entry pin is released after `execute_present_pixmap_copy` -/// regardless of success or failure, and `mark_dirty` fires only on -/// success. -pub(crate) fn execute_parked_present_ids( - state: &mut ServerState, - backend: &mut dyn Backend, - ids: &[u64], - trigger: &str, -) { - for &pid in ids { - let Some(entry) = state.present_pending_exec.remove(&pid) else { - continue; - }; - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=exec_due trigger={trigger} eff={:?}", - pace_instr_ms(), - pid, - entry.pending.effective_target_msc - ); - let ok = execute_present_pixmap_copy_or_reroute(state, backend, entry.pending); - if let Some(pin) = entry.pin { - backend.release_present_source(pin); - } - if ok { - backend.mark_dirty(); - } - } -} - -/// msc-due-pass (spec §msc-due; Task 7): re-classify every msc-parked -/// source-ready entry against the fresh general clock and execute -/// whatever just became due, then run the two fallback-ladder rungs that -/// are execution decisions rather than arming (the third rung, the -/// absolute-vblank arm, is an arming call site and lives in -/// `run::arm_present_idle_vblanks`, post-compose, alongside the other two -/// arms). Called at the top of `drain_present_completions`, which Task 4 -/// hoisted above `maybe_composite`, so an entry executed here is visible -/// to THIS iteration's compose. -pub(crate) fn drain_due_present_pending_exec(state: &mut ServerState, backend: &mut dyn Backend) { - // Sampled up front (not just inside the blackout branch below): an - // empty `present_pending_exec` must NOT short-circuit past the - // blackout flush, or DPMS-off with a display that never accumulates - // a msc-parked entry (flips keep retiring normally, so every arrival - // classifies ExecuteNow and the store stays empty) would leave - // `present_pending_complete` entries gated against a frozen - // completion clock with nothing left to ever call - // `fire_all_present_completions_now` — they'd park forever. The - // sweep inside that call still early-returns on an empty queue, so - // this costs nothing on the common (non-blackout) empty-store path. - let blackout = backend.present_scanout_blackout(); - if state.present_pending_exec.is_empty() && !blackout { - return; - } - let mut domains: Vec<(u32, u64)> = state - .present_pending_exec - .values() - .map(|entry| (entry.pending.crtc_id, entry.pending.crtc_epoch)) - .collect(); - domains.sort_unstable(); - domains.dedup(); - for &(crtc_id, crtc_epoch) in &domains { - if backend.present_crtc_clock_epoch(crtc_id) == crtc_epoch { - refresh_present_crtc_general_clock(state, backend, crtc_id, crtc_epoch); - } - } - - let due: Vec = state - .present_pending_exec - .iter() - .filter(|(_, e)| { - if !e.source_ready { - return false; - } - let epoch_current = - backend.present_crtc_clock_epoch(e.pending.crtc_id) == e.pending.crtc_epoch; - if !epoch_current { - // A stable RANDR XID now names a replacement raw counter. - // The saved raw target is meaningless there; fail open - // unpaced instead of arming/comparing against the new epoch. - return true; - } - let clock_msc = - cached_present_crtc_clock(state, e.pending.crtc_id, e.pending.crtc_epoch).msc; - matches!( - crate::present_scheduler::classify_msc_due( - e.pending.effective_target_msc, - clock_msc, - backend.present_flip_in_flight(e.pending.crtc_id), - ), - crate::present_scheduler::MscDue::ExecuteNow - ) - }) - .map(|(&pid, _)| pid) - .collect(); - execute_parked_present_ids(state, backend, &due, "drain"); - - // Idle-display fallback (spec §msc-due, flip-driven drivers only): a - // parked entry normally becomes due as flips advance the clock — the - // next flip retirement wakes this same due-pass and the `due` filter - // above catches it. But if the display is fully idle (no flip in - // flight AND nothing composing), the clock can never advance at all, - // so waiting would deadlock forever; execute immediately instead. - // Gated to `!present_absolute_vblank_arm_supported()` drivers only — - // on sequence-capable drivers an idle display still ticks via the - // absolute arm, and applying this fallback there would reintroduce - // the early-frame bug for mpv (spec §msc-due). - let idle_fallback: Vec = state - .present_pending_exec - .iter() - .filter(|(_, e)| { - e.source_ready - && e.pending.effective_target_msc.is_some() - && !backend.present_absolute_vblank_arm_supported(e.pending.crtc_id) - && backend.present_display_idle(e.pending.crtc_id) - }) - .map(|(&pid, _)| pid) - .collect(); - execute_parked_present_ids(state, backend, &idle_fallback, "idle_fallback"); - - // Blackout flush (spec Lifecycle §"DPMS-off / VT-away blackout"): - // checked unconditionally (not an `else` of the arm/idle-display - // rungs above) so it fires even while the clock is frozen — no flips, - // no sequence samples, `next_wakeup`'s scene deadline gated off, so - // nothing else here would ever unblock these entries. Only - // `source_ready` (msc-parked) entries are force-executed: a - // `source_ready == false` entry is still waiting on its OWN producer - // fence, a condition blackout does nothing to resolve, and forcing - // that copy would read whatever partial content the producer has - // written so far. - if blackout { - let blackout_ids: Vec = state - .present_pending_exec - .iter() - .filter(|(_, e)| e.source_ready) - .map(|(&pid, _)| pid) - .collect(); - execute_parked_present_ids(state, backend, &blackout_ids, "blackout"); - - // Both halves flush together: parked completions deliver too, - // ignoring the due check entirely (a frozen clock would - // otherwise never satisfy it — round-4 F1c). Stamped with the - // COMPLETION clock, not the general clock used for scheduling - // above — stamping/gate-release keeps its existing - // completion-clock provenance (spec "Loop-order and clock - // contract" item 2: scheduling and stamping are different - // concerns). - fire_all_present_completions_now(state, backend); - } -} - -fn accumulate_present_execution_damage( - state: &mut ServerState, - window: u32, - x_off: i16, - y_off: i16, - src_width: u16, - src_height: u16, - update_rects: Option<&[yserver_protocol::x11::xfixes::RegionRect]>, -) { - if let Some(rects) = update_rects { - for rect in rects { - let _dropped = accumulate_damage_to_state( - state, - ResourceId(window), - x_off.saturating_add(rect.x), - y_off.saturating_add(rect.y), - rect.width, - rect.height, - ); - } - } else { - let _dropped = accumulate_damage_to_state( - state, - ResourceId(window), - x_off, - y_off, - src_width, - src_height, - ); - } -} - -fn execute_present_pixmap_copy( - state: &mut ServerState, - backend: &mut dyn Backend, - pending: PendingPresentPixmap, -) -> io::Result<()> { - let PendingPresentPixmap { - origin, - client_id, - request: req, - wake, - masked_options, - src_host_xid, - paint_dst_host_xid, - completion_dst_host_xid, - src_width, - src_height, - update_rects, - present_id, - window_generation, - crtc_id, - crtc_epoch, - msc_offset, - effective_target_msc, - } = pending; - let (serial, pixmap, window, x_off, y_off, valid, update) = match &req { - PendingPresentRequest::Pixmap(req) => ( - req.serial, req.pixmap, req.window, req.x_off, req.y_off, req.valid, req.update, - ), - PendingPresentRequest::PixmapSynced(req) => ( - req.serial, req.pixmap, req.window, req.x_off, req.y_off, req.valid, req.update, - ), - }; - - let candidate = crate::backend::PresentScanoutCandidate { - client_id: client_id.0, - present_id, - crtc_id, - crtc_epoch, - src_pixmap_xid: pixmap, - dst_window_xid: window, - src_host_xid, - paint_dst_host_xid, - completion_dst_host_xid, - src_width, - src_height, - x_off, - y_off, - valid_region_xid: valid, - update_region_xid: update, - update_is_full: update_rects.is_none(), - explicit_sync: matches!(req, PendingPresentRequest::PixmapSynced(_)), - options: masked_options, - }; - let completion = crate::backend::CompletedPresentEvent { - client_id, - serial, - host_xid: pixmap, - dst_host_xid: window, - options: masked_options, - present_id, - window_generation, - crtc_id, - crtc_epoch, - msc_offset, - completion_clock: None, - wake, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }; - - if window_unviewable(state, ResourceId(window)) { - // Xorg: flip check fails on the empty clipList and the Copy clips to nothing, - // but idle and CompleteModeCopy are still delivered (present_execute.c:119-156). - if let Some(eff) = effective_target_msc { - state.present_complete_gate.insert( - present_id, - crate::server::PresentCompleteGate { - crtc_id, - crtc_epoch, - msc_offset, - effective_target_msc: eff, - owner: client_id, - dst_window_xid: window, - }, - ); - } - backend.enqueue_present_completion(completion, completion_dst_host_xid); - return Ok(()); - } - backend.note_present_scanout_candidate(candidate); - - // M2b attempts direct ownership before recording the fallback Copy. The - // completion gate must exist before the backend can own the page flip; - // on decline/error remove the provisional row so the unchanged Copy path - // below retains its historical "install only after successful Copy" - // failure semantics. - if let Some(eff) = effective_target_msc { - state.present_complete_gate.insert( - present_id, - crate::server::PresentCompleteGate { - crtc_id, - crtc_epoch, - msc_offset, - effective_target_msc: eff, - owner: client_id, - dst_window_xid: window, - }, - ); - } - match backend.try_present_direct(candidate, completion.clone()) { - Ok(true) => { - backend.note_present_pixmap(src_host_xid, paint_dst_host_xid); - accumulate_present_execution_damage( - state, - window, - x_off, - y_off, - src_width, - src_height, - update_rects.as_deref(), - ); - return Ok(()); - } - Ok(false) => {} - Err(error) => log::warn!( - "present direct submit failed, retaining Copy fallback (pid={present_id}): {error}" - ), - } - state.present_complete_gate.remove(&present_id); - - // PresentPixmap has no client GC. Clear every piece of draw state that a - // preceding request may have left bound before recording the copy. - let present_gc = crate::backend::DrawState::default(); - backend.apply_clip_state(origin, &present_gc.clip)?; - backend.apply_draw_state(origin, &present_gc)?; - - if let Some(rects) = &update_rects { - for rect in rects { - backend.copy_area( - origin, - src_host_xid, - paint_dst_host_xid, - rect.x, - rect.y, - x_off.saturating_add(rect.x), - y_off.saturating_add(rect.y), - rect.width, - rect.height, - )?; - } - } else { - backend.copy_area( - origin, - src_host_xid, - paint_dst_host_xid, - 0, - 0, - x_off, - y_off, - src_width, - src_height, - )?; - } - - backend.note_present_pixmap(src_host_xid, paint_dst_host_xid); - // Task 13 (spec §"Amendment 2026-08-01" — damage-arm dependency): - // re-keyed off `update_rects.is_none()`, not the raw `update` xid — - // an unresolvable region (`update != 0` but `update_rects == None`) - // must still damage full-extent, not nothing. Per-rect damage is - // translated by `x_off`/`y_off` exactly like the copy arm above - // (`x_off.saturating_add(rect.x)`), matching Xorg's `CT_REGION` clip- - // origin semantics (`present.c:76-92`). - accumulate_present_execution_damage( - state, - window, - x_off, - y_off, - src_width, - src_height, - update_rects.as_deref(), - ); - - // The direct attempt above removed its provisional gate when it declined - // ownership. Reinstall that gate only after the fallback Copy succeeded, - // preserving the historical copy-failure semantics. - if let Some(eff) = effective_target_msc { - state.present_complete_gate.insert( - present_id, - crate::server::PresentCompleteGate { - crtc_id, - crtc_epoch, - msc_offset, - effective_target_msc: eff, - owner: client_id, - dst_window_xid: window, - }, - ); - } - backend.enqueue_present_completion(completion, completion_dst_host_xid); - Ok(()) -} - -/// Task 8 §Supersession copy-failure reroute (round-4 F5). Wrapper -/// around `execute_present_pixmap_copy` used by ALL THREE execute sites -/// (`execute_parked_present_ids`, `arrival_execute_or_park_present_pixmap`'s -/// `ExecuteNow` arm, `drain_ready_present_pixmaps`'s `ExecuteNow` arm) — -/// pin release stays at the call sites, after this call, as today. -/// -/// Today a failing `execute_present_pixmap_copy` can only fail in -/// `apply_clip_state`/`apply_draw_state`/`copy_area` — all BEFORE the -/// completion gate is inserted and `enqueue_present_completion` runs, so -/// a failed copy leaves no gate row and no retained backend wake. Left -/// alone, that strands the client's buffer (never idled) and its -/// completion (never delivered) forever. On failure this wrapper: -/// releases the buffer by XID immediately (fence/syncobj + fence mirror, -/// mirroring scrap), fires `IdleNotify` now, and either parks a `Copy` -/// completion (`emit_idle: false`) in the ordered delivery queue when -/// `effective_target_msc` is `Some` (rides the same per-window hold-back -/// as everything else), or — when `None` (no clock, including -/// nested backends whose sweep never runs because `clock.msc == 0` -/// guards it) — delivers it inline, mirroring `run.rs`'s no-clock arm: a -/// `fire_due_present_completions` flush first (so this inline delivery -/// cannot overtake an already-due sibling), then `complete_present_with_clock` -/// with an Immediate clock sample built like `complete_present_now` does. -/// -/// Returns `true` iff the copy succeeded. -fn execute_present_pixmap_copy_or_reroute( - state: &mut ServerState, - backend: &mut dyn Backend, - pending: PendingPresentPixmap, -) -> bool { - // Captured before the call below consumes `pending`. - let event = completed_event_for_pending(&pending); - let wake = pending.wake.clone(); - let effective_target_msc = pending.effective_target_msc; - let present_id = pending.present_id; - - match execute_present_pixmap_copy(state, backend, pending) { - Ok(()) => true, - Err(e) => { - log::warn!("present copy failed, rerouting completion (pid={present_id}): {e}"); - // Accepted trade (Task 0 item (a) has the same shape for - // Xorg-parity scrap): on a multi-rect `update_rects` copy, a - // failure partway through may leave earlier rects' GPU reads - // of the source already recorded before the failing rect. By- - // XID buffer release below happens immediately regardless, so - // this is a WAR hazard against those already-recorded reads — - // a concurrent client write to the released buffer could race - // GPU work still reading it. Accepted because the alternative - // (holding the buffer/completion open indefinitely, hoping a - // retry never comes) strands the client's buffer and - // completion forever, which is strictly worse. - match wake { - crate::backend::PresentWake::Pixmap { idle_fence_xid } if idle_fence_xid != 0 => { - if let Err(e) = backend.dri3_trigger_fence(idle_fence_xid) { - log::warn!( - "PRESENT copy-failure: trigger idle fence 0x{idle_fence_xid:x} \ - failed: {e}" - ); - } - crate::core_loop::sync_await::fence_triggered(state, idle_fence_xid); - } - crate::backend::PresentWake::PixmapSynced { - release, - release_syncobj, - release_value, - } => { - if let Err(e) = release.signal(release_value) { - log::warn!( - "PRESENT copy-failure: signal release syncobj \ - 0x{release_syncobj:x}@{release_value} failed: {e}" - ); - } - } - _ => {} - } - fire_present_idle_notify_now(state, &event); - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=copy_failed eff={:?}", - pace_instr_ms(), present_id, effective_target_msc - ); - if let Some(target) = effective_target_msc { - state - .present_pending_complete - .push(crate::server::PendingPresentComplete { - event, - effective_target_msc: target, - mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: false, - }); - } else { - // No clock: no due-pass will ever drain a parked - // queue entry for this present, so deliver inline — - // mirroring run.rs's no-clock completion arm. Flush - // due-and-unblocked siblings first so this inline - // delivery cannot overtake an already-due one. - let clock = refresh_present_crtc_completion_clock( - state, - backend, - event.crtc_id, - event.crtc_epoch, - event.completion_clock, - ); - fire_due_present_completions_for_domain( - state, - backend, - event.crtc_id, - event.crtc_epoch, - clock, - ); - let cached = cached_present_crtc_clock(state, event.crtc_id, event.crtc_epoch); - let immediate = crate::backend::PresentClockSample { - msc: cached.msc, - ust: cached.ust, - source: crate::backend::PresentClockSource::Immediate, - }; - complete_present_with_clock( - state, - backend, - &event, - immediate, - yserver_protocol::x11::present::COMPLETE_MODE_COPY, - false, - ); - } - false - } - } -} - -/// Arrival-time msc-due evaluation (spec §msc-due; Task 7 Step 2) for a -/// present whose source is READY at request time — i.e. this runs at the -/// point today's code executed the copy unconditionally. Request drain -/// runs before the run-loop tail, so a lone present on an idle display -/// still executes right here at arrival; it never waits for the next -/// due-pass. `ExecuteNow` keeps today's immediate-copy path. `Park` inserts -/// a `source_ready: true, wait_id: None` entry (taking the entry pin) — -/// the due-pass (`drain_due_present_pending_exec`) picks it up later. -fn arrival_execute_or_park_present_pixmap( - state: &mut ServerState, - backend: &mut dyn Backend, - present_id: u64, - pending: PendingPresentPixmap, -) { - let epoch_current = backend.present_crtc_clock_epoch(pending.crtc_id) == pending.crtc_epoch; - let clock_msc = if epoch_current { - refresh_present_crtc_general_clock(state, backend, pending.crtc_id, pending.crtc_epoch).msc - } else { - cached_present_crtc_clock(state, pending.crtc_id, pending.crtc_epoch).msc - }; - let flip_in_flight = epoch_current && backend.present_flip_in_flight(pending.crtc_id); - let due = if epoch_current { - crate::present_scheduler::classify_msc_due( - pending.effective_target_msc, - clock_msc, - flip_in_flight, - ) - } else { - crate::present_scheduler::MscDue::ExecuteNow - }; - match due { - crate::present_scheduler::MscDue::ExecuteNow => { - let stage = match &pending.request { - PendingPresentRequest::Pixmap(_) => "source_ready", - PendingPresentRequest::PixmapSynced(_) => "acquire_ready", - }; - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage={stage}", - pace_instr_ms(), pending.present_id - ); - execute_present_pixmap_copy_or_reroute(state, backend, pending); - } - crate::present_scheduler::MscDue::Park => { - let reason = if flip_in_flight { - "flip_in_flight" - } else { - "future" - }; - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=parked_msc reason={reason} eff={:?} clock_msc={clock_msc}", - pace_instr_ms(), pending.present_id, pending.effective_target_msc - ); - let pin = backend.pin_present_source(pending.src_host_xid); - state.present_pending_exec.insert( - present_id, - crate::server::PendingPresentEntry { - pending, - source_ready: true, - wait_id: None, - pin, - }, - ); - } - } -} - -pub(crate) fn drain_ready_present_pixmaps(state: &mut ServerState, backend: &mut dyn Backend) { - for wait_id in backend.drain_ready_present_source_waits() { - let present_id = state.present_wait_to_id.remove(&wait_id); - let entry = present_id.and_then(|pid| state.present_pending_exec.remove(&pid)); - let outcome = entry.map(|mut entry| { - let stage = match &entry.pending.request { - PendingPresentRequest::Pixmap(_) => "source_signaled", - PendingPresentRequest::PixmapSynced(_) => "acquire_signaled", - }; - let epoch_current = backend.present_crtc_clock_epoch(entry.pending.crtc_id) - == entry.pending.crtc_epoch; - let clock_msc = if epoch_current { - refresh_present_crtc_general_clock( - state, - backend, - entry.pending.crtc_id, - entry.pending.crtc_epoch, - ) - .msc - } else { - cached_present_crtc_clock( - state, - entry.pending.crtc_id, - entry.pending.crtc_epoch, - ) - .msc - }; - let flip_in_flight = - epoch_current && backend.present_flip_in_flight(entry.pending.crtc_id); - let due = if epoch_current { - crate::present_scheduler::classify_msc_due( - entry.pending.effective_target_msc, - clock_msc, - flip_in_flight, - ) - } else { - crate::present_scheduler::MscDue::ExecuteNow - }; - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage={} wait_id={}", - pace_instr_ms(), entry.pending.present_id, stage, wait_id - ); - match due { - // The entry became source-ready AND is msc-due: execute now - // — releasing the ENTRY pin on both the success and - // failure path so a failing copy never leaks the pinned - // drawable. - crate::present_scheduler::MscDue::ExecuteNow => { - backend.begin_ready_present_destination_write(wait_id); - let ok = - execute_present_pixmap_copy_or_reroute(state, backend, entry.pending); - if let Some(pin) = entry.pin { - backend.release_present_source(pin); - } - Some(ok) - } - // Source-ready but not yet msc-due (Task 7 Step 2 combined - // vector): stays parked, now purely on msc-due — the WAIT - // pin still drops below (unconditional, as always), but - // the ENTRY pin stays held until the due-pass executes it. - crate::present_scheduler::MscDue::Park => { - let reason = if flip_in_flight { "flip_in_flight" } else { "future" }; - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=parked_msc reason={reason} eff={:?} clock_msc={clock_msc}", - pace_instr_ms(), entry.pending.present_id, entry.pending.effective_target_msc - ); - let pid = entry.pending.present_id; - entry.source_ready = true; - entry.wait_id = None; - state.present_pending_exec.insert(pid, entry); - None - } - } - }); - // The WAIT pin is distinct from the entry pin above and is - // released exactly here, as today — unconditionally, whether or - // not the entry was still present (an unknown-id backend report - // is a no-op guard). - backend.finish_present_source_wait(wait_id); - match outcome { - Some(Some(true)) => backend.mark_dirty(), - // Failure already logged + rerouted (by-XID release, IdleNotify, - // parked/inline completion) inside - // `execute_present_pixmap_copy_or_reroute`. - Some(Some(false)) => {} - Some(None) => {} - None => log::warn!("backend reported unknown Present source wait id {wait_id}"), - } - } -} - -/// Full-server shutdown: release every still-parked (pre-copy) entry in -/// the unified pending-present store. Mirrors the window-destroy teardown -/// loop's by-XID release exactly (same wake mechanism, same two distinct -/// pin releases) but with no window filter — every entry is stale once -/// there is no more request/vblank drain left to resolve it. Called once, -/// core-side, before the listening socket is torn down (yserver's -/// `lib.rs`, next to `signal_all_retained_present_wakes` which does the -/// analogous flush for the *post*-copy retained-wake population). -pub fn shutdown_drain_present_pending_exec(state: &mut ServerState, backend: &mut dyn Backend) { - for (_, entry) in std::mem::take(&mut state.present_pending_exec) { - match &entry.pending.wake { - crate::backend::PresentWake::Pixmap { idle_fence_xid } if *idle_fence_xid != 0 => { - if let Err(e) = backend.dri3_trigger_fence(*idle_fence_xid) { - log::warn!( - "PRESENT shutdown: trigger idle fence 0x{idle_fence_xid:x} failed: {e}" - ); - } - } - crate::backend::PresentWake::PixmapSynced { - release, - release_syncobj, - release_value, - } => { - if let Err(e) = release.signal(*release_value) { - log::warn!( - "PRESENT shutdown: signal release syncobj 0x{release_syncobj:x}@\ - {release_value} failed: {e}" - ); - } - } - _ => {} - } - if let Some(wid) = entry.wait_id { - backend.finish_present_source_wait(wid); - } - if let Some(pin) = entry.pin { - backend.release_present_source(pin); - } - } - state.present_wait_to_id.clear(); -} - -#[allow(clippy::too_many_arguments)] -fn present_remainder_invalid(divisor: u64, remainder: u64) -> bool { - (divisor == 0 && remainder != 0) || (divisor != 0 && remainder >= divisor) -} - -fn present_remainder_error_value(remainder: u64) -> u32 { - u32::try_from(remainder & u64::from(u32::MAX)).expect("masked to CARD32") -} - -/// Validate the resource/option/pacing tail shared by PresentPixmap and -/// PresentPixmapSynced, in Xorg `proc_present_pixmap_common` order. Drawable -/// and depth checks precede this helper; PixmapSynced's syncobj/point checks -/// precede the entire common path. `None` fence arguments model Synced's two -/// protocol-level `None` fences, while `Some(0)` is PresentPixmap's explicit -/// `None` XID. -#[allow(clippy::too_many_arguments)] -fn present_pixmap_common_validation_error( - state: &ServerState, - valid_region: u32, - update_region: u32, - target_crtc: u32, - wait_fence: Option, - idle_fence: Option, - options: u32, - divisor: u64, - remainder: u64, -) -> Option<(u8, u32)> { - if valid_region != 0 && !state.xfixes_regions.contains_key(&valid_region) { - return Some((XFIXES_BAD_REGION, valid_region)); - } - if update_region != 0 && !state.xfixes_regions.contains_key(&update_region) { - return Some((XFIXES_BAD_REGION, update_region)); - } - if target_crtc != 0 && !present_crtc_exists(state, target_crtc) { - return Some((RANDR_BAD_CRTC, target_crtc)); - } - if let Some(wait_fence) = wait_fence - && wait_fence != 0 - && !state.sync_fences.contains_key(&wait_fence) - { - return Some((SYNC_BAD_FENCE, wait_fence)); - } - if let Some(idle_fence) = idle_fence - && idle_fence != 0 - && !state.sync_fences.contains_key(&idle_fence) - { - return Some((SYNC_BAD_FENCE, idle_fence)); - } - if options & !PRESENT_ALL_OPTIONS != 0 { - return Some((x11::error::BAD_VALUE, options)); - } - if present_remainder_invalid(divisor, remainder) { - return Some(( - x11::error::BAD_VALUE, - present_remainder_error_value(remainder), - )); - } - None -} - -fn handle_present_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, present as x11present}; - const PRESENT_MAJOR_OPCODE: u8 = 145; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - debug!( - "client {} #{} PRESENT dispatch minor={} body.len()={}", - client_id.0, - sequence.0, - minor, - body.len() - ); - match minor { - x11present::QUERY_VERSION => { - let _ = x11present::parse_query_version(body); - debug!( - "client {} #{} PRESENT::QueryVersion -> {}.{}", - client_id.0, - sequence.0, - x11present::MAJOR_VERSION, - x11present::MINOR_VERSION - ); - let reply = x11present::encode_query_version_reply( - byte_order, - sequence, - x11present::MAJOR_VERSION, - x11present::MINOR_VERSION, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11present::QUERY_CAPABILITIES => { - let target = x11present::parse_query_capabilities(body).unwrap_or(0); - let caps = backend.present_capabilities(target).encode(); - debug!( - "client {} #{} PRESENT::QueryCapabilities target=0x{target:x} -> 0x{caps:x}", - client_id.0, sequence.0 - ); - let reply = x11present::encode_query_capabilities_reply(byte_order, sequence, caps); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - x11present::SELECT_INPUT => { - if let Some(req) = x11present::parse_select_input(body) { - debug!( - "client {} #{} PRESENT::SelectInput eid=0x{:x} window=0x{:x} mask=0x{:x}", - client_id.0, sequence.0, req.eid, req.window, req.event_mask - ); - state.present_event_selections.insert( - req.eid, - crate::server::PresentEventSelection { - owner: client_id, - window: ResourceId(req.window), - event_mask: req.event_mask, - }, - ); - } else { - debug!( - "client {} #{} PRESENT::SelectInput parse failed body_len={}", - client_id.0, - sequence.0, - body.len() - ); - } - } - x11present::PIXMAP => { - let Some(req) = x11present::parse_pixmap(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - }; - // Phase 4.2.3: wait_fence / idle_fence are accepted. The - // dispatcher mirrors the result onto state.sync_fences via - // the XSync resource table for QueryFence / TriggerFence. - let window_exists = state.resources.window(ResourceId(req.window)).is_some(); - let pixmap_exists = state.resources.pixmap(ResourceId(req.pixmap)).is_some(); - let src = state.resources.host_drawable_target(ResourceId(req.pixmap)); - let dst = state.resources.host_drawable_target(ResourceId(req.window)); - let dst_window_host_xid = state - .resources - .window(ResourceId(req.window)) - .and_then(|window| window.host_xid) - .map(|host_xid| host_xid.as_raw()); - if !window_exists { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - if !pixmap_exists { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.pixmap, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - if let ( - Some(crate::resources::HostDrawableTarget::Pixmap { - depth: src_depth, .. - }), - Some(dst), - ) = (&src, &dst) - && *src_depth != dst.depth() - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.pixmap, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - // Keep the full Xorg common validation path read-only. A rejected - // request must neither bind this window's Present domain nor - // allocate a new lifetime generation. - if let Some((error_code, error_value)) = present_pixmap_common_validation_error( - state, - req.valid, - req.update, - req.target_crtc, - Some(req.wait_fence), - Some(req.idle_fence), - req.options, - req.divisor, - req.remainder, - ) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error_code, - error_value, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - let domain = - match select_present_domain(state, backend, req.window, req.target_crtc, false) { - Ok(domain) => domain, - Err(crtc) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - crtc, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - }; - // Per design §4 AsyncMayTear silent-clear: mask the bit - // off here when the cap isn't advertised. Computed up - // front so the deferred-completion enqueue (inside the - // `if let` below) uses the masked options. - let caps = backend.present_capabilities(req.window); - let masked_options = if caps.async_may_tear { - req.options - } else { - const PRESENT_OPTION_ASYNC_MAY_TEAR: u32 = 0x10; - req.options & !PRESENT_OPTION_ASYNC_MAY_TEAR - }; - // INSTRUMENTATION (2026-05-29, wait_fence hypothesis check): on a - // BLANK Firefox run, do content-sized presents even arrive, and is - // the wait_fence un-triggered when we copy? Logs src kind+SIZE, - // wait_fence + our server-side triggered bit (caveat: that bit is - // set by SYNC TriggerFence; Mesa may trigger the xshmfence - // out-of-band, so `wait_triggered` reflects only what the server - // observed, not the true GPU/xshmfence state). Grep "PRESENT-INSTR". - { - let (src_kind, sw, sh) = match &src { - Some(crate::resources::HostDrawableTarget::Pixmap { - width, height, .. - }) => ("pixmap", *width, *height), - Some(_) => ("non-pixmap", 0, 0), - None => ("unresolved", 0, 0), - }; - let wait_triggered = if req.wait_fence == 0 { - "no-fence".to_string() - } else { - match state.sync_fences.get(&req.wait_fence) { - Some(f) => format!("{}", f.triggered), - None => "unknown-fence".to_string(), - } - }; - log::debug!( - "PRESENT-INSTR client {} #{} Pixmap serial={} src={} {}x{} \ - window=0x{:x} wait_fence=0x{:x} wait_triggered={} idle_fence=0x{:x}", - client_id.0, - sequence.0, - req.serial, - src_kind, - sw, - sh, - req.window, - req.wait_fence, - wait_triggered, - req.idle_fence, - ); - } - // Diagnostic: the copy below is gated on the source resolving to - // a usable host pixmap and the window resolving to a host target. - // The pixmap/window resource-existence checks already ran above - // (BadDrawable/BadWindow), so reaching here unresolved means the - // resource exists but has no backend host xid — the classic - // failed-DRI3-dmabuf-import shape (e.g. PixmapFromBuffers rejected - // a multi-plane/modifier buffer). Without this warn the present is - // silently dropped and the window shows stale content. - if !matches!( - src, - Some(crate::resources::HostDrawableTarget::Pixmap { .. }) - ) || dst.is_none() - { - log::warn!( - "client {} #{} Present::Pixmap pixmap=0x{:x} window=0x{:x}: dropping present \ - copy — src_resolved_as_host_pixmap={} dst_resolved={} (window keeps stale \ - content; a preceding DRI3 dmabuf import likely failed)", - client_id.0, - sequence.0, - req.pixmap, - req.window, - matches!( - src, - Some(crate::resources::HostDrawableTarget::Pixmap { .. }) - ), - dst.is_some(), - ); - } - if let ( - Some(crate::resources::HostDrawableTarget::Pixmap { - host_xid, - width, - height, - depth: _src_depth, - .. - }), - Some(dst), - ) = (src, dst) - { - // Keep the destination's window identity for the paint. A - // redirected window's HostDrawableTarget names its backing - // pixmap, which is useful for completion fencing but loses - // ClipByChildren and hierarchy stacking. The backend resolves - // this window xid to that same backing after computing the - // correct window clip. - let paint_dst_host_xid = dst_window_host_xid.unwrap_or_else(|| dst.host_xid()); - // DIAG (2026-07-08, MATE compositor slow-drag smear): log what the - // compositor actually presents into the COW so we can tell whether - // the `update` region is a full frame or thin drag slivers, and - // whether the slivers tile the swept region. Env-gated - // (YSERVER_PRESENT_TRACE=1) so it is zero-cost / no timing - // perturbation when off. Grep "PRESENT-UPDATE". See - // docs/superpowers/findings/2026-07-08-mate-compositor-drag-smear-diagnosis.md - { - use std::sync::OnceLock; - static TRACE: OnceLock = OnceLock::new(); - if *TRACE.get_or_init(|| std::env::var_os("YSERVER_PRESENT_TRACE").is_some()) { - let (nrects, bbox): (isize, Option<(i32, i32, i32, i32)>) = - if req.update == 0 { - (-1, None) // full copy: no update region - } else if let Some(region) = state.xfixes_regions.get(&req.update) { - let bbox = region.rects.iter().fold( - None, - |acc: Option<(i32, i32, i32, i32)>, r| { - let x0 = i32::from(r.x); - let y0 = i32::from(r.y); - let x1 = x0 + i32::from(r.width); - let y1 = y0 + i32::from(r.height); - Some(match acc { - None => (x0, y0, x1, y1), - Some((ax0, ay0, ax1, ay1)) => { - (ax0.min(x0), ay0.min(y0), ax1.max(x1), ay1.max(y1)) - } - }) - }, - ); - (region.rects.len() as isize, bbox) - } else { - (-2, None) // update id set but region not found → full copy - }; - log::info!( - "PRESENT-UPDATE window=0x{:x} x_off={} y_off={} pixmap={}x{} \ - update_id=0x{:x} nrects={} bbox={:?}", - req.window, - req.x_off, - req.y_off, - width, - height, - req.update, - nrects, - bbox, - ); - } - } - // Snapshot the region now: XFixes regions are mutable resources, - // while an imported producer may keep this request parked. - let update_rects = if req.update == 0 { - None - } else { - state - .xfixes_regions - .get(&req.update) - .map(|region| region.rects.clone()) - }; - let present_id = state.next_present_id(); - let window_generation = state.present_window_generation(req.window); - let effective_target_msc = effective_present_target_raw( - domain, - req.target_msc, - req.divisor, - req.remainder, - masked_options, - ); - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} client={} serial={} stage=request kind=pixmap target_msc={} div={} rem={} kernel_msc={} eff={:?}", - pace_instr_ms(), present_id, client_id.0, req.serial, req.target_msc, req.divisor, req.remainder, domain.raw_msc, effective_target_msc - ); - let pending = PendingPresentPixmap { - origin, - client_id, - request: PendingPresentRequest::Pixmap(req.clone()), - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: req.idle_fence, - }, - masked_options, - src_host_xid: host_xid.as_raw(), - paint_dst_host_xid, - completion_dst_host_xid: dst.host_xid(), - src_width: width, - src_height: height, - update_rects, - present_id, - window_generation, - crtc_id: domain.crtc_id, - crtc_epoch: domain.crtc_epoch, - msc_offset: domain.msc_offset, - effective_target_msc, - }; - // Arm before scrap — see - // `arm_present_pixmap_source_then_supersede` doc comment - // for why the order matters (a fallible arm after scrap - // would destroy a frame nothing replaces). - let armed = arm_present_pixmap_source_then_supersede(state, backend, &pending)?; - match armed { - crate::backend::PresentSourceWait::Ready => { - arrival_execute_or_park_present_pixmap(state, backend, present_id, pending); - } - crate::backend::PresentSourceWait::Deferred(wait_id) => { - log::debug!(target: "present_pace", "PACE-INSTR t={} pid={} stage=source_deferred wait_id={}", pace_instr_ms(), pending.present_id, wait_id); - let pin = backend.pin_present_source(pending.src_host_xid); - if state - .present_wait_to_id - .insert(wait_id, present_id) - .is_some() - { - log::warn!("backend reused live Present source wait id {wait_id}"); - } - state.present_pending_exec.insert( - present_id, - crate::server::PendingPresentEntry { - pending, - source_ready: false, - wait_id: Some(wait_id), - pin, - }, - ); - } - } - } - debug!( - "client {} #{} PRESENT::Pixmap serial={} notifies={}", - client_id.0, - sequence.0, - req.serial, - req.notifies.len() - ); - } - x11present::NOTIFY_MSC => { - if let Some(req) = x11present::parse_notify_msc(body) { - if state.resources.window(ResourceId(req.window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - // Xorg resolves the target window first. Invalid residue is - // BadValue only once BadWindow has been ruled out. - if present_remainder_invalid(req.divisor, req.remainder) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - present_remainder_error_value(req.remainder), - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - let domain = select_present_domain(state, backend, req.window, 0, true) - .expect("implicit Present CRTC selection cannot fail"); - let raw_target_msc = req.target_msc.wrapping_add(domain.msc_offset); - // Vblank-paced clock: the current MSC is the real kernel - // value from the last pageflip (mirrored into ServerState). - // If already satisfied (and we have a real flip to time - // against), complete now; otherwise PARK the request and let - // a future pageflip fire it (drain_present_completions). On - // master these were dropped when unsatisfied, which froze a - // compositor's `present` frame clock after one frame. - let current_msc = domain.raw_msc; - let clockless = - domain.crtc_id == 0 || !present_crtc_is_enabled(state, domain.crtc_id); - let satisfied = clockless - || (current_msc > 0 - && notify_msc_satisfied( - current_msc, - raw_target_msc, - req.divisor, - req.remainder, - )); - if satisfied { - fire_present_notify_msc_complete_events( - state, - byte_order, - PRESENT_MAJOR_OPCODE, - req.window, - req.serial, - current_msc.wrapping_sub(domain.msc_offset), - domain.raw_ust, - ); - } else { - state - .present_pending_msc - .push(crate::server::PendingNotifyMsc { - owner: client_id, - window: req.window, - crtc_id: domain.crtc_id, - crtc_epoch: domain.crtc_epoch, - msc_offset: domain.msc_offset, - serial: req.serial, - target_msc: raw_target_msc, - divisor: req.divisor, - remainder: req.remainder, - byte_order, - }); - } - } - debug!("client {} #{} PRESENT::NotifyMSC", client_id.0, sequence.0); - } - x11present::PIXMAP_SYNCED => { - let Some(req) = x11present::parse_pixmap_synced(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - }; - let acquire_known = req.acquire_syncobj != 0 - && backend.dri3_syncobj_owned(client_id, req.acquire_syncobj); - if !acquire_known { - // Mirror Xorg's bad-value choice: VERIFY_DRI3_SYNCOBJ - // (dri3/dri3.h:51-56) sets client->errorValue = when the - // syncobj lookup fails. This is the error ARGUMENT, not the - // error CODE — it is NOT part of the declared divergence - // (which covers the code only). - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.acquire_syncobj, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - let release_handle = if req.release_syncobj != 0 - && backend.dri3_syncobj_owned(client_id, req.release_syncobj) - { - backend.dri3_syncobj_handle(req.release_syncobj) - } else { - None - }; - let Some(release_handle) = release_handle else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.release_syncobj, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - }; - if req.acquire_value == 0 - || req.release_value == 0 - || (req.acquire_syncobj == req.release_syncobj - && req.acquire_value >= req.release_value) - { - // Point/ordering failures in Xorg (present_request.c:299-301) - // leave errorValue at zero. - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - let window_exists = state.resources.window(ResourceId(req.window)).is_some(); - let pixmap_exists = state.resources.pixmap(ResourceId(req.pixmap)).is_some(); - let src = state.resources.host_drawable_target(ResourceId(req.pixmap)); - let dst = state.resources.host_drawable_target(ResourceId(req.window)); - let dst_window_host_xid = state - .resources - .window(ResourceId(req.window)) - .and_then(|window| window.host_xid) - .map(|host_xid| host_xid.as_raw()); - if !window_exists { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - if !pixmap_exists { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.pixmap, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - // Keep domain binding after every fallible drawable validation: - // a rejected request must not change the CRTC that a later - // NotifyMSC remembers for this window. - if let ( - Some(crate::resources::HostDrawableTarget::Pixmap { - depth: src_depth, .. - }), - Some(dst), - ) = (&src, &dst) - && *src_depth != dst.depth() - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.pixmap, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - if let Some((error_code, error_value)) = present_pixmap_common_validation_error( - state, - req.valid, - req.update, - req.target_crtc, - None, - None, - req.options, - req.divisor, - req.remainder, - ) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - error_code, - error_value, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - let caps = backend.present_capabilities(req.window); - let masked_options = if caps.async_may_tear { - req.options - } else { - const PRESENT_OPTION_ASYNC_MAY_TEAR: u32 = 0x10; - req.options & !PRESENT_OPTION_ASYNC_MAY_TEAR - }; - let domain = - match select_present_domain(state, backend, req.window, req.target_crtc, false) { - Ok(domain) => domain, - Err(crtc) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - RANDR_BAD_CRTC, - crtc, - u16::from(header.data), - PRESENT_MAJOR_OPCODE, - ); - } - }; - // INSTRUMENTATION (2026-05-29): synced variant uses acquire_syncobj - // (explicit-sync timeline) as its wait. Log src kind+SIZE + the - // acquire/release syncobj so a blank run shows whether content-sized - // synced presents arrive and what sync points they carry. - // Grep "PRESENT-INSTR". - { - let (src_kind, sw, sh) = match &src { - Some(crate::resources::HostDrawableTarget::Pixmap { - width, height, .. - }) => ("pixmap", *width, *height), - Some(_) => ("non-pixmap", 0, 0), - None => ("unresolved", 0, 0), - }; - log::debug!( - "PRESENT-INSTR client {} #{} PixmapSynced serial={} src={} {}x{} \ - window=0x{:x} acquire_syncobj=0x{:x} acquire_value={} \ - release_syncobj=0x{:x} release_value={}", - client_id.0, - sequence.0, - req.serial, - src_kind, - sw, - sh, - req.window, - req.acquire_syncobj, - req.acquire_value, - req.release_syncobj, - req.release_value, - ); - } - // Same silent-drop diagnostic as the Present::Pixmap path: if the - // source pixmap didn't resolve to a backend host pixmap (failed - // DRI3 dmabuf import) or the window didn't resolve, the copy below - // is skipped and the window keeps stale content. - if !matches!( - src, - Some(crate::resources::HostDrawableTarget::Pixmap { .. }) - ) || dst.is_none() - { - log::warn!( - "client {} #{} Present::PixmapSynced pixmap=0x{:x} window=0x{:x}: dropping \ - present copy — src_resolved_as_host_pixmap={} dst_resolved={} (window keeps \ - stale content; a preceding DRI3 dmabuf import likely failed)", - client_id.0, - sequence.0, - req.pixmap, - req.window, - matches!( - src, - Some(crate::resources::HostDrawableTarget::Pixmap { .. }) - ), - dst.is_some(), - ); - } - let queued_copy = if let ( - Some(crate::resources::HostDrawableTarget::Pixmap { - host_xid, - width, - height, - depth: src_depth, - .. - }), - Some(dst), - ) = (src, dst) - { - let paint_dst_host_xid = dst_window_host_xid.unwrap_or_else(|| dst.host_xid()); - if src_depth != dst.depth() { - false - } else { - let update_rects = if req.update == 0 { - None - } else { - state - .xfixes_regions - .get(&req.update) - .map(|region| region.rects.clone()) - }; - let present_id = state.next_present_id(); - let window_generation = state.present_window_generation(req.window); - let effective_target_msc = effective_present_target_raw( - domain, - req.target_msc, - req.divisor, - req.remainder, - masked_options, - ); - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} client={} serial={} stage=request kind=synced target_msc={} div={} rem={} kernel_msc={} eff={:?} acquire=0x{:x}@{} release=0x{:x}@{}", - pace_instr_ms(), present_id, client_id.0, req.serial, req.target_msc, req.divisor, req.remainder, domain.raw_msc, effective_target_msc, - req.acquire_syncobj, req.acquire_value, req.release_syncobj, req.release_value, - ); - let pending = PendingPresentPixmap { - origin, - client_id, - request: PendingPresentRequest::PixmapSynced(req.clone()), - wake: crate::backend::PresentWake::PixmapSynced { - release: release_handle.clone(), - release_syncobj: req.release_syncobj, - release_value: req.release_value, - }, - masked_options, - src_host_xid: host_xid.as_raw(), - paint_dst_host_xid, - completion_dst_host_xid: dst.host_xid(), - src_width: width, - src_height: height, - update_rects, - present_id, - window_generation, - crtc_id: domain.crtc_id, - crtc_epoch: domain.crtc_epoch, - msc_offset: domain.msc_offset, - effective_target_msc, - }; - // Arm before scrap — see - // `arm_present_pixmap_synced_source_then_supersede` - // doc comment for why the order matters (a fallible - // arm after scrap would destroy a frame nothing - // replaces). - let armed = arm_present_pixmap_synced_source_then_supersede( - state, - backend, - req.acquire_syncobj, - req.acquire_value, - &pending, - )?; - match armed { - crate::backend::PresentSourceWait::Ready => { - arrival_execute_or_park_present_pixmap( - state, backend, present_id, pending, - ); - } - crate::backend::PresentSourceWait::Deferred(wait_id) => { - log::debug!(target: "present_pace", "PACE-INSTR t={} pid={} stage=acquire_deferred wait_id={} syncobj=0x{:x} value={}", pace_instr_ms(), pending.present_id, wait_id, req.acquire_syncobj, req.acquire_value); - let pin = backend.pin_present_source(pending.src_host_xid); - if state - .present_wait_to_id - .insert(wait_id, present_id) - .is_some() - { - log::warn!("backend reused live Present syncobj wait id {wait_id}"); - } - state.present_pending_exec.insert( - present_id, - crate::server::PendingPresentEntry { - pending, - source_ready: false, - wait_id: Some(wait_id), - pin, - }, - ); - } - } - true - } - } else { - false - }; - if !queued_copy { - log::debug!( - "PRESENT::PixmapSynced copy path was not queued \ - (window=0x{:x} pixmap=0x{:x})", - req.window, - req.pixmap - ); - } - debug!( - "client {} #{} PRESENT::PixmapSynced serial={} acquire=0x{:x}@{} release=0x{:x}@{}", - client_id.0, - sequence.0, - req.serial, - req.acquire_syncobj, - req.acquire_value, - req.release_syncobj, - req.release_value - ); - } - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(minor), - header.opcode, - ); - } - } - Ok(RequestOutcome::Handled) -} - -fn notify_msc_satisfied(current_msc: u64, target_msc: u64, divisor: u64, remainder: u64) -> bool { - if crate::present_scheduler::msc_is_after(target_msc, current_msc) { - return false; - } - if divisor == 0 { - return true; - } - current_msc % divisor == remainder -} - -/// Fan out `CompleteNotify { mode: Copy }` and `IdleNotify` to every -/// `present_event_selections` entry that subscribed to the window -/// with the matching event-mask bit. Phase 4.2.3 design §3.3.2. -pub fn fire_present_completion_events( - state: &mut ServerState, - event: &crate::backend::CompletedPresentEvent, -) { - let cached = cached_present_crtc_clock(state, event.crtc_id, event.crtc_epoch); - let raw = event.completion_clock.unwrap_or({ - if cached.completion.msc > 0 { - cached.completion - } else { - crate::backend::PresentClockSample { - msc: cached.msc, - ust: cached.ust, - source: crate::backend::PresentClockSource::Immediate, - } - } - }); - let clock = present_wire_clock(raw, event.msc_offset); - fire_present_completion_events_at( - state, - event, - clock, - yserver_protocol::x11::present::COMPLETE_MODE_COPY, - true, - true, - ); -} - -pub(crate) fn fire_present_completion_events_at( - state: &mut ServerState, - event: &crate::backend::CompletedPresentEvent, - clock: crate::backend::PresentClockSample, - mode: u8, - emit_idle: bool, - emit_complete: bool, -) { - use crate::backend::PresentWake; - use yserver_protocol::x11::present as x11present; - - /// PRESENT major opcode. - const PRESENT_MAJOR_OPCODE: u8 = 145; - /// `PresentEventMaskCompleteNotify` per `presentproto`. - const COMPLETE_NOTIFY_MASK: u32 = 0x2; - /// `PresentEventMaskIdleNotify`. - const IDLE_NOTIFY_MASK: u32 = 0x4; - - let window = ResourceId(event.dst_host_xid); - // Report the provenance-aware display sample selected by the caller. - // Pixmap completion deliberately excludes standalone sequence events - // observed while scanout is active, while NotifyMSC remains driven by - // the general vblank clock. (Was: a per-window software counter + ust=0, - // which picom rejects as "Invalid PresentCompleteNotify event".) - let current_msc = clock.msc; - let pixmap_xid = event.host_xid; - let idle_fence = match &event.wake { - PresentWake::Pixmap { idle_fence_xid } => *idle_fence_xid, - PresentWake::PixmapSynced { - release_syncobj, .. - } => *release_syncobj, - }; - - // Gather the matching (eid, owning client, mask) tuples up front - // so we can iterate state.clients without holding a borrow on - // present_event_selections. - let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); - for (eid, sel) in &state.present_event_selections { - if sel.window == window { - targets.push((*eid, sel.owner, sel.event_mask)); - } - } - debug!( - "PRESENT events: window=0x{:x} serial={} pixmap=0x{:x} targets={:?}", - window.0, - event.serial, - pixmap_xid, - targets - .iter() - .map(|(e, c, m)| format!("eid=0x{e:x}/client={}/mask=0x{m:x}", c.0)) - .collect::>() - ); - - for (eid, owner, mask) in targets { - let Some(client) = state.clients.get_mut(&owner.0) else { - continue; - }; - // byte_order is sourced from the OWNER client (the one - // receiving the event), not the caller. Fixes a latent bug - // where events to owners of different endianness than the - // submitting client were mis-encoded. - let byte_order = client.byte_order; - let seq = SequenceNumber( - client - .last_sequence - .load(std::sync::atomic::Ordering::Relaxed), - ); - // Per Xorg's present_execute_copy: IdleNotify fires *first* - // (the pixmap is idle as soon as the GPU finishes reading, - // which on our synchronous CopyArea path is immediately), - // CompleteNotify fires on vblank afterwards. Mesa's - // loader_dri3 expects this order — flipping it makes - // vkAcquireNextImage hang on the second frame. - if emit_idle && mask & IDLE_NOTIFY_MASK != 0 { - let ev = x11present::encode_idle_notify( - byte_order, - seq, - PRESENT_MAJOR_OPCODE, - eid, - window.0, - event.serial, - pixmap_xid, - idle_fence, - ); - let outcome = write_to_client(client, owner, &ev); - debug!( - "PRESENT IdleNotify -> client {} eid=0x{eid:x} pixmap=0x{:x} fence=0x{idle_fence:x} ({} bytes) outcome={:?} outbound_len={}", - owner.0, - pixmap_xid, - ev.len(), - outcome, - client.outbound.len(), - ); - } - if emit_complete && mask & COMPLETE_NOTIFY_MASK != 0 { - let ev = x11present::encode_complete_notify( - byte_order, - seq, - PRESENT_MAJOR_OPCODE, - eid, - window.0, - event.serial, - x11present::COMPLETE_KIND_PIXMAP, - mode, - clock.ust, - current_msc, - ); - debug!( - "PRESENT CompleteNotify -> client {} eid=0x{eid:x} ({} bytes)", - owner.0, - ev.len() - ); - let _ = write_to_client(client, owner, &ev); - } - } -} - -/// Emit `Present::ConfigureNotify` to every client that selected -/// `EVENT_MASK_CONFIGURE_NOTIFY` on `window`. Triggered from -/// `handle_configure_window` whenever the window's geometry changes -/// (size primarily — Mesa keys buffer reallocation on -/// `pixmap_{width,height}` here). Mirrors the iteration shape of -/// `fire_present_completion_events`. -pub(crate) fn fire_present_configure_notify_for_window( - state: &mut ServerState, - window_id: ResourceId, - geometry: yserver_protocol::x11::Geometry, -) { - use yserver_protocol::x11::present as x11present; - const PRESENT_MAJOR_OPCODE: u8 = 145; - - let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); - for (eid, sel) in &state.present_event_selections { - if sel.window == window_id { - targets.push((*eid, sel.owner, sel.event_mask)); - } - } - for (eid, owner, mask) in targets { - if mask & x11present::EVENT_MASK_CONFIGURE_NOTIFY == 0 { - continue; - } - let Some(client) = state.clients.get_mut(&owner.0) else { - continue; - }; - let byte_order = client.byte_order; - let seq = SequenceNumber( - client - .last_sequence - .load(std::sync::atomic::Ordering::Relaxed), - ); - let ev = x11present::encode_configure_notify( - byte_order, - seq, - PRESENT_MAJOR_OPCODE, - eid, - window_id.0, - geometry.x, - geometry.y, - geometry.width, - geometry.height, - 0, - 0, - geometry.width, - geometry.height, - 0, - ); - let _ = write_to_client(client, owner, &ev); - debug!( - "PRESENT ConfigureNotify -> client {} eid=0x{eid:x} window=0x{:x} \ - geom=({},{} {}x{})", - owner.0, window_id.0, geometry.x, geometry.y, geometry.width, geometry.height, - ); - } -} - -fn fire_present_notify_msc_complete_events( - state: &mut ServerState, - byte_order: yserver_protocol::x11::ClientByteOrder, - extension_major: u8, - window: u32, - serial: u32, - current_msc: u64, - ust: u64, -) { - use yserver_protocol::x11::present as x11present; - const COMPLETE_NOTIFY_MASK: u32 = 0x2; - - let window = ResourceId(window); - let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); - for (eid, sel) in &state.present_event_selections { - if sel.window == window { - targets.push((*eid, sel.owner, sel.event_mask)); - } - } - - for (eid, owner, mask) in targets { - if mask & COMPLETE_NOTIFY_MASK == 0 { - continue; - } - let Some(client) = state.clients.get_mut(&owner.0) else { - continue; - }; - let seq = SequenceNumber( - client - .last_sequence - .load(std::sync::atomic::Ordering::Relaxed), - ); - let ev = x11present::encode_complete_notify( - byte_order, - seq, - extension_major, - eid, - window.0, - serial, - x11present::COMPLETE_KIND_NOTIFY_MSC, - x11present::COMPLETE_MODE_COPY, - ust, - current_msc, - ); - debug!( - "PRESENT NotifyMSC CompleteNotify -> client {} eid=0x{eid:x} msc={current_msc} ust={ust} ({} bytes)", - owner.0, - ev.len() - ); - let _ = write_to_client(client, owner, &ev); - } -} - -/// Fire every parked `NotifyMSC` (NOTIFY_MSC handler) whose target MSC is now -/// satisfied by the real kernel `(msc, ust)` from the latest pageflip. -/// Called from `drain_present_completions` after the backend advances the -/// vblank clock — this is what keeps a compositor's `present` frame clock -/// running at the display refresh rate. -#[cfg(test)] -pub(crate) fn fire_due_present_notify_msc(state: &mut ServerState, msc: u64, ust: u64) { - let mut domains: Vec<(u32, u64)> = state - .present_pending_msc - .iter() - .map(|pending| (pending.crtc_id, pending.crtc_epoch)) - .collect(); - domains.sort_unstable(); - domains.dedup(); - for (crtc_id, crtc_epoch) in domains { - fire_due_present_notify_msc_for_domain(state, crtc_id, crtc_epoch, msc, ust, false); - } -} - -pub(crate) fn fire_due_present_notify_msc_for_domain( - state: &mut ServerState, - crtc_id: u32, - crtc_epoch: u64, - msc: u64, - ust: u64, - force: bool, -) { - if (!force && msc == 0) || state.present_pending_msc.is_empty() { - return; - } - const PRESENT_MAJOR_OPCODE: u8 = 145; - let mut still_pending = Vec::new(); - for p in std::mem::take(&mut state.present_pending_msc) { - if p.crtc_id != crtc_id || p.crtc_epoch != crtc_epoch { - still_pending.push(p); - } else if force || notify_msc_satisfied(msc, p.target_msc, p.divisor, p.remainder) { - fire_present_notify_msc_complete_events( - state, - p.byte_order, - PRESENT_MAJOR_OPCODE, - p.window, - p.serial, - msc.wrapping_sub(p.msc_offset), - ust, - ); - } else { - still_pending.push(p); - } - } - state.present_pending_msc = still_pending; -} - -/// Milliseconds since first call, for correlating per-present pipeline stages -/// under `target: "present_pace"`. -/// -/// Kept deliberately (was introduced as TEMP scaffolding): the -/// `PresentPixmapSynced` acquire-wait work reports its ready/deferred/signalled -/// stages through this target, and the numbers that validated that fix — 473 of -/// 2,221 synced requests arriving before their acquire point, 0.87 ms mean -/// wait — came from it. Emission is `log::debug!(target: "present_pace", ...)`, -/// so it is silent unless that target is explicitly enabled and costs nothing -/// at the default log level. -pub(crate) fn pace_instr_ms() -> u128 { - use std::{sync::OnceLock, time::Instant}; - static EPOCH: OnceLock = OnceLock::new(); - EPOCH.get_or_init(Instant::now).elapsed().as_millis() -} - -/// Signal the client's retained wake (real xshmfence/syncobj) via the -/// backend, update X11 fence bookkeeping, then emit IdleNotify+CompleteNotify -/// (idle-before-complete, per Xorg). Stamps the complete event with the -/// latest cached clock for this request's exact CRTC epoch. Used for ungated -/// completions and teardown; paced completion passes an explicit raw sample. -pub(crate) fn complete_present_now( - state: &mut ServerState, - backend: &mut dyn Backend, - event: &crate::backend::CompletedPresentEvent, -) { - let cached = cached_present_crtc_clock(state, event.crtc_id, event.crtc_epoch); - let clock = event.completion_clock.unwrap_or({ - if cached.completion.msc > 0 { - cached.completion - } else { - crate::backend::PresentClockSample { - msc: cached.msc, - ust: cached.ust, - source: crate::backend::PresentClockSource::Immediate, - } - } - }); - complete_present_with_clock( - state, - backend, - event, - clock, - event.completion_mode, - event.emit_idle, - ); -} - -/// Whether a backend completion still belongs to the live destination window -/// that accepted it. Numeric XIDs may be reused after destruction, so resource -/// existence alone is not sufficient. -pub(crate) fn present_event_window_is_current( - state: &ServerState, - event: &crate::backend::CompletedPresentEvent, -) -> bool { - // Legacy unit fixtures predate window generations and use zero. Real - // accepted Presents always allocate a nonzero generation. - #[cfg(test)] - if event.window_generation == 0 { - return true; - } - state - .resources - .window(ResourceId(event.dst_host_xid)) - .is_some() - && state - .present_window_generations - .get(&event.dst_host_xid) - .is_some_and(|&generation| generation == event.window_generation) -} - -/// Drop a backend completion for a destroyed/reused window without emitting -/// wire events. Copy completions may release once their GPU read retired; -/// direct completions must wait for the distinct retired-idle event because -/// their source can still be scanned out. -pub(crate) fn discard_stale_present_event( - state: &mut ServerState, - backend: &mut dyn Backend, - event: &crate::backend::CompletedPresentEvent, - retired_idle: bool, -) { - let release = retired_idle || event.emit_idle; - if !release { - return; - } - backend.signal_present_wake(event.present_id); - if let crate::backend::PresentWake::Pixmap { idle_fence_xid } = &event.wake - && *idle_fence_xid != 0 - { - crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); - } -} - -/// `mode`/`emit_idle` are the wire mode byte and whether to also release -/// the retained wake / emit IdleNotify (spec §Ordered completion delivery -/// item 1): a parked Skip (Task 8 supersession) already released its idle -/// fence/syncobj and set the `sync_fences` mirror at scrap time, so its -/// delivery here must not touch idle machinery a second time — no -/// `signal_present_wake`, no IdleNotify, no fence-mirror write. -/// `signal_present_wake` is gated too (not just the fence mirror / -/// IdleNotify): both `emit_idle == false` populations — scrap (Task 8 -/// §Supersession) and the copy-failure reroute (Task 8 round-4 F5) — are -/// never-executed: the failing copy precedes `enqueue_present_completion` -/// just as scrap precedes it, so neither ever retains a real backend -/// wake, and the by-XID release (fence/syncobj + mirror + IdleNotify) at -/// scrap/failure time is each entry's sole release path. Gating this -/// signal is therefore a no-op today given how the two populations are -/// built — kept explicit (rather than relying on the backend's -/// unknown-id no-op guard) so a future `emit_idle: false` population -/// that DOES retain a real wake cannot silently double-fire it. -pub(crate) fn complete_present_with_clock( - state: &mut ServerState, - backend: &mut dyn Backend, - event: &crate::backend::CompletedPresentEvent, - clock: crate::backend::PresentClockSample, - mode: u8, - emit_idle: bool, -) { - use crate::backend::PresentWake; - let clock = present_wire_clock(clock, event.msc_offset); - match &event.wake { - PresentWake::Pixmap { idle_fence_xid } => log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=signal_wake msc={} source={:?} idle_fence=0x{:x}", - pace_instr_ms(), event.present_id, clock.msc, clock.source, idle_fence_xid, - ), - PresentWake::PixmapSynced { - release_syncobj, - release_value, - .. - } => log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=signal_wake msc={} source={:?} release=0x{:x}@{}", - pace_instr_ms(), event.present_id, clock.msc, clock.source, - release_syncobj, release_value, - ), - } - if emit_idle { - backend.signal_present_wake(event.present_id); - } - if emit_idle - && let PresentWake::Pixmap { idle_fence_xid } = &event.wake - && *idle_fence_xid != 0 - { - crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); - } - fire_present_completion_events_at(state, event, clock, mode, emit_idle, true); -} - -/// Release a previously completed direct-scanout source after its replacement -/// has retired. This emits IdleNotify only; CompleteNotify was emitted when -/// the source first reached every CRTC. -pub(crate) fn retire_present_idle( - state: &mut ServerState, - backend: &mut dyn Backend, - event: &crate::backend::CompletedPresentEvent, -) { - use crate::backend::PresentWake; - - backend.signal_present_wake(event.present_id); - if let PresentWake::Pixmap { idle_fence_xid } = &event.wake - && *idle_fence_xid != 0 - { - crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); - } - let clock = refresh_present_crtc_completion_clock( - state, - backend, - event.crtc_id, - event.crtc_epoch, - event.completion_clock, - ); - let clock = present_wire_clock(clock, event.msc_offset); - fire_present_completion_events_at(state, event, clock, event.completion_mode, true, false); -} - -/// Fire parked completions whose target MSC has been reached. Called from the -/// MSC-advance drain, alongside `fire_due_present_notify_msc`. -/// -/// Delivery is per-window `present_id` order, not raw queue order (spec -/// §"Ordered completion delivery (per-window `present_id` order)"): -/// `present_id` is allocated monotonically at request time, so it IS -/// per-window `CompleteNotify` serial order, and Mesa's `loader_dri3` -/// regenerates its swap accounting from the latest event's serial — a -/// backward serial is a real client hazard. A Copy enters this queue at -/// GPU-fence-retirement time while a Skip (Task 8 supersession) enters at -/// scrap (request-arrival) time, so raw insertion order is not serial -/// order: a due entry for window `W` must be held back while any SMALLER -/// `present_id` for `W` is still unresolved in any of three places — -/// msc-parked-unexecuted (`present_pending_exec`), executed-but-undrained -/// (`present_complete_gate`, which carries `dst_window_xid`), or -/// parked-not-yet-due (this same queue). The hold-back is per-window so a -/// stalled window's GPU copy cannot head-of-line block another window's -/// completions. -#[cfg(test)] -pub(crate) fn fire_due_present_completions( - state: &mut ServerState, - backend: &mut dyn Backend, - clock: crate::backend::PresentClockSample, -) { - let mut domains: Vec<(u32, u64)> = state - .present_pending_complete - .iter() - .map(|pending| (pending.event.crtc_id, pending.event.crtc_epoch)) - .collect(); - domains.sort_unstable(); - domains.dedup(); - for (crtc_id, crtc_epoch) in domains { - advance_present_crtc_completion_clock(state, crtc_id, crtc_epoch, clock); - } - fire_present_completions_sweep(state, backend, false); -} - -pub(crate) fn fire_due_present_completions_for_domain( - state: &mut ServerState, - backend: &mut dyn Backend, - crtc_id: u32, - crtc_epoch: u64, - clock: crate::backend::PresentClockSample, -) { - advance_present_crtc_completion_clock(state, crtc_id, crtc_epoch, clock); - fire_present_completions_sweep(state, backend, false); -} - -/// Blackout flush (spec Lifecycle §"DPMS-off / VT-away blackout"; Task 7): -/// deliver every parked completion NOW, ignoring the msc-due check — -/// `present_scanout_blackout()` means no flips and no sequence samples -/// will ever arrive, so the clock is frozen and would never otherwise -/// satisfy `fire_due_present_completions`'s due test (round-4 F1c). The -/// per-window hold-back (`blocked`) still applies unmodified: an -/// outstanding GPU fence in `present_complete_gate` is not something a -/// dark display can force to retire early. -/// -/// The msc-parked half of the hold-back is only PARTIALLY cleared by -/// `drain_due_present_pending_exec`'s own blackout branch, which runs -/// first in the same due-pass: that branch force-executes `source_ready` -/// entries only (deliberately — a `source_ready == false` entry is still -/// waiting on its own producer fence, and blackout does nothing to -/// resolve that). So an uncovered `source_ready:false` entry that the -/// successor gate declines to scrap (spec §Supersession) keeps its -/// window's parked completions held back through this flush too, even -/// while blackout is on. DECISION (accepted, do not change): holding the -/// order here is correct — the entry's own producer fence can still -/// signal during blackout (GPU work is display-independent), after which -/// the *next* blackout pass force-executes it and the queue drains. The -/// truly-stuck case (the producer fence never signals) is the same -/// pre-existing exposure that entry always had regardless of blackout, -/// and the purge paths (destroy/disconnect/shutdown) clear it. -pub(crate) fn fire_all_present_completions_now(state: &mut ServerState, backend: &mut dyn Backend) { - fire_present_completions_sweep(state, backend, true); -} - -fn fire_present_completions_sweep(state: &mut ServerState, backend: &mut dyn Backend, force: bool) { - if state.present_pending_complete.is_empty() { - return; - } - - // Smallest still-unresolved present_id per window in the other two - // hold-back states (BTreeMap iteration order doesn't matter here — - // every entry is visited to find the per-window min). - let mut exec_min_by_window: HashMap = HashMap::new(); - for (&pid, entry) in &state.present_pending_exec { - exec_min_by_window - .entry(entry.pending.request.window()) - .and_modify(|m| *m = (*m).min(pid)) - .or_insert(pid); - } - let mut gate_min_by_window: HashMap = HashMap::new(); - for (&pid, gate) in &state.present_complete_gate { - gate_min_by_window - .entry(gate.dst_window_xid) - .and_modify(|m| *m = (*m).min(pid)) - .or_insert(pid); - } - - // BTreeMap (not HashMap): the rebuild below walks this in window-XID - // order, which makes the surviving `still_pending` queue's - // cross-window order deterministic run-to-run. Nothing currently - // depends on that order, but a HashMap here would be a standing - // test-flakiness trap for whatever eventually does. - let mut by_window: std::collections::BTreeMap> = - std::collections::BTreeMap::new(); - for p in std::mem::take(&mut state.present_pending_complete) { - by_window.entry(p.event.dst_host_xid).or_default().push(p); - } - - let mut still_pending = Vec::new(); - for (window, mut entries) in by_window { - // Ascending present_id: the third hold-back state (parked-not-yet- - // due, i.e. an earlier entry in this very group) falls out of - // walking in this order and stopping at the first entry that is - // not both due and externally unblocked — everything after it is - // held back too, by construction. - entries.sort_by_key(|p| p.event.present_id); - let ext_min = match ( - exec_min_by_window.get(&window), - gate_min_by_window.get(&window), - ) { - (Some(&a), Some(&b)) => Some(a.min(b)), - (Some(&a), None) | (None, Some(&a)) => Some(a), - (None, None) => None, - }; - let mut iter = entries.into_iter(); - for p in iter.by_ref() { - let blocked = ext_min.is_some_and(|m| m < p.event.present_id); - let cached = cached_present_crtc_clock(state, p.event.crtc_id, p.event.crtc_epoch); - let due_clock = if cached.completion.msc > 0 { - cached.completion - } else if let Some(exact) = p.event.completion_clock { - exact - } else { - crate::backend::PresentClockSample { - msc: cached.msc, - ust: cached.ust, - source: crate::backend::PresentClockSource::Immediate, - } - }; - // The domain cache decides when a paced event is due. An exact - // grouped-direct reference sample only stamps that event; using an - // older exact retirement as the due clock would park it forever - // after the domain itself advanced past the target. - let stamp_clock = p.event.completion_clock.unwrap_or(due_clock); - let epoch_current = - backend.present_crtc_clock_epoch(p.event.crtc_id) == p.event.crtc_epoch; - // Due when msc has reached/passed the target (wrap-safe): NOT - // (target after msc) — or unconditionally due when `force` - // (blackout flush) bypasses the clock test entirely. An epoch - // mismatch also fails open: its raw target belongs to a counter - // that no longer backs this RANDR XID and must never be compared - // against the replacement epoch. - let due = force - || !epoch_current - || (due_clock.msc > 0 - && !crate::present_scheduler::msc_is_after( - p.effective_target_msc, - due_clock.msc, - )); - if blocked || !due { - still_pending.push(p); - break; - } - log::debug!( - target: "present_pace", - "PACE-INSTR t={} pid={} stage=fired msc={} eff={} source={:?}", - pace_instr_ms(), p.event.present_id, stamp_clock.msc, p.effective_target_msc, - stamp_clock.source - ); - complete_present_with_clock(state, backend, &p.event, stamp_clock, p.mode, p.emit_idle); - } - still_pending.extend(iter); - } - state.present_pending_complete = still_pending; -} - -fn handle_dri3_request( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], - attached_fd: Option, -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, dri3 as x11dri3}; - const DRI3_MAJOR_OPCODE: u8 = 147; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let caps = backend.dri3_capabilities(); - let minor = header.data; - match minor { - x11dri3::QUERY_VERSION => { - let (cmaj, cmin) = x11dri3::parse_query_version(body).unwrap_or((0, 0)); - // Server caps the version per Dri3Caps::version. Without - // syncobj support, version is (1, 3); fence_fd governs - // individual request availability rather than the version - // reply. - let server_major = caps.version.0; - let server_minor = caps.version.1; - let major = cmaj.min(server_major); - let minor = cmin.min(server_minor); - debug!( - "client {} #{} DRI3::QueryVersion client={cmaj}.{cmin} -> {major}.{minor}", - client_id.0, sequence.0 - ); - let reply = x11dri3::encode_query_version_reply(byte_order, sequence, major, minor); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11dri3::OPEN => { - let req = x11dri3::parse_open(body); - let drawable = req.map_or(0, |r| r.drawable); - match backend.dri3_open(drawable) { - Ok(fd) => { - debug!( - "client {} #{} DRI3::Open drawable=0x{drawable:x} -> fd={}", - client_id.0, - sequence.0, - std::os::fd::AsRawFd::as_raw_fd(&fd) - ); - let reply = x11dri3::encode_open_reply(byte_order, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let raw = std::os::fd::AsRawFd::as_raw_fd(&fd); - if let Err(e) = send_reply_with_fd(client, &reply, raw) { - log::warn!("DRI3::Open SCM_RIGHTS dispatch failed: {e}"); - return Ok(RequestOutcome::Disconnect(client_id)); - } - drop(fd); - return Ok(RequestOutcome::Handled); - } - Err(err) => { - debug!( - "client {} #{} DRI3::Open drawable=0x{drawable:x} -> BadAlloc ({err})", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - } - } - x11dri3::PIXMAP_FROM_BUFFER => { - let Some(req) = x11dri3::parse_pixmap_from_buffer(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - let Some(fd) = attached_fd else { - debug!( - "client {} #{} DRI3::PixmapFromBuffer no SCM_RIGHTS fd attached -> BadAlloc", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - match backend.dri3_import_pixmap( - fd, - req.width, - req.height, - u32::from(req.stride), - 0, - // DRI3 1.0 carries no modifier. That means the layout is - // IMPLICIT, to be resolved from the buffer -- not linear. - // This line used to pass `0`, i.e. an explicit - // DRM_FORMAT_MOD_LINEAR, which is #138: Chrome hands us a - // TILED VA-API decode buffer here, we recorded it as - // linear, and `BuffersFromPixmap` then handed that lie - // back so Chrome sampled its own frame wrong. - crate::backend::Dri3ImportModifier::Implicit { size: req.size }, - req.depth, - req.bpp, - ) { - Ok(handle) => { - debug!( - "client {} #{} DRI3::PixmapFromBuffer pixmap=0x{:x} {}x{} stride={} depth={} bpp={} -> imported", - client_id.0, - sequence.0, - req.pixmap, - req.width, - req.height, - req.stride, - req.depth, - req.bpp, - ); - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - pixmap: ResourceId(req.pixmap), - drawable: ResourceId(req.drawable), - width: req.width, - height: req.height, - depth: req.depth, - }, - ); - let _ = state - .resources - .set_pixmap_host_xid(ResourceId(req.pixmap), handle); - } - Err(err) => { - debug!( - "client {} #{} DRI3::PixmapFromBuffer pixmap=0x{:x} {}x{} stride={} depth={} bpp={} -> BadAlloc ({err})", - client_id.0, - sequence.0, - req.pixmap, - req.width, - req.height, - req.stride, - req.depth, - req.bpp, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - } - } - x11dri3::PIXMAP_FROM_BUFFERS => { - let Some(req) = x11dri3::parse_pixmap_from_buffers(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - // Phase 4.2 scope: single-plane RGB only. num_buffers > 1 - // is wire-decoded (so logging is accurate) but rejected. - if req.num_buffers != 1 { - debug!( - "client {} #{} DRI3::PixmapFromBuffers num_buffers={} -> BadAlloc \ - (multi-plane out of scope for Phase 4.2)", - client_id.0, sequence.0, req.num_buffers - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let Some(fd) = attached_fd else { - debug!( - "client {} #{} DRI3::PixmapFromBuffers no SCM_RIGHTS fd attached -> BadAlloc", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - match backend.dri3_import_pixmap( - fd, - req.width, - req.height, - req.strides[0], - req.offsets[0], - crate::backend::Dri3ImportModifier::Explicit(req.modifier), - req.depth, - req.bpp, - ) { - Ok(handle) => { - debug!( - "client {} #{} DRI3::PixmapFromBuffers pixmap=0x{:x} {}x{} stride={} offset={} modifier=0x{:x} depth={} bpp={} -> imported", - client_id.0, - sequence.0, - req.pixmap, - req.width, - req.height, - req.strides[0], - req.offsets[0], - req.modifier, - req.depth, - req.bpp, - ); - // Register the X resource id so subsequent - // CopyArea / PresentPixmap can resolve it. Mirror - // what handle_create_pixmap does. - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - pixmap: ResourceId(req.pixmap), - drawable: ResourceId(req.window), - width: req.width, - height: req.height, - depth: req.depth, - }, - ); - let _ = state - .resources - .set_pixmap_host_xid(ResourceId(req.pixmap), handle); - } - Err(err) => { - debug!( - "client {} #{} DRI3::PixmapFromBuffers pixmap=0x{:x} {}x{} stride={} offset={} modifier=0x{:x} depth={} bpp={} -> BadAlloc ({err})", - client_id.0, - sequence.0, - req.pixmap, - req.width, - req.height, - req.strides[0], - req.offsets[0], - req.modifier, - req.depth, - req.bpp, - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - } - } - x11dri3::BUFFER_FROM_PIXMAP => { - let Some(pixmap) = x11dri3::parse_buffer_from_pixmap(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - let host_xid = match state - .resources - .pixmap(yserver_protocol::x11::ResourceId(pixmap)) - .and_then(|p| p.host_xid.map(|h| h.as_raw())) - { - Some(h) => h, - None => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - }; - match backend.dri3_export_pixmap(host_xid) { - Ok((size, width, height, stride, depth, bpp, fd)) => { - debug!( - "client {} #{} DRI3::BufferFromPixmap pixmap=0x{pixmap:x} size={size} {width}x{height} stride={stride} depth={depth} bpp={bpp}", - client_id.0, sequence.0 - ); - let reply = x11dri3::encode_buffer_from_pixmap_reply( - byte_order, sequence, size, width, height, stride, depth, bpp, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let raw = std::os::fd::AsRawFd::as_raw_fd(&fd); - if let Err(e) = send_reply_with_fd(client, &reply, raw) { - log::warn!("DRI3::BufferFromPixmap SCM_RIGHTS dispatch failed: {e}"); - return Ok(RequestOutcome::Disconnect(client_id)); - } - drop(fd); - return Ok(RequestOutcome::Handled); - } - Err(err) => { - // Xorg dri3/dri3_request.c:277 maps export failure to BadPixmap. - // BadDrawable is reserved for the unresolvable-XID case above. - // Note: Xorg returns BadAlloc when sending the fd fails; yserver - // instead disconnects (see the send_reply_with_fd path above) — - // a broken SCM_RIGHTS socket is unrecoverable for the client. - debug!( - "client {} #{} DRI3::BufferFromPixmap pixmap=0x{pixmap:x} -> BadPixmap ({err})", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - } - } - x11dri3::BUFFERS_FROM_PIXMAP => { - // DRI3 op 8 (BUFFERS_FROM_PIXMAP). mesa's loader_dri3 uses op 8 - // (not op 3) whenever the server advertises DRI3 >= 1.2 — and a - // modifier-tiled backing (the RADV export path) is unusable by the - // client without the modifier op 8 carries. yserver exports a - // single plane, so the reply has nfd=1. - let Some(pixmap) = x11dri3::parse_buffers_from_pixmap(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - let host_xid = match state - .resources - .pixmap(yserver_protocol::x11::ResourceId(pixmap)) - .and_then(|p| p.host_xid.map(|h| h.as_raw())) - { - Some(h) => h, - None => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - }; - match backend.dri3_export_pixmap_buffers(host_xid) { - Ok(export) => { - debug!( - "client {} #{} DRI3::BuffersFromPixmap pixmap=0x{pixmap:x} {}x{} stride={} offset={} modifier=0x{:x} depth={} bpp={}", - client_id.0, - sequence.0, - export.width, - export.height, - export.stride, - export.offset, - export.modifier, - export.depth, - export.bpp, - ); - let reply = x11dri3::encode_buffers_from_pixmap_reply( - byte_order, - sequence, - export.width, - export.height, - export.modifier, - export.depth, - export.bpp, - &[export.stride], - &[export.offset], - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let raw = std::os::fd::AsRawFd::as_raw_fd(&export.fd); - if let Err(e) = send_reply_with_fd(client, &reply, raw) { - log::warn!("DRI3::BuffersFromPixmap SCM_RIGHTS dispatch failed: {e}"); - return Ok(RequestOutcome::Disconnect(client_id)); - } - drop(export.fd); - return Ok(RequestOutcome::Handled); - } - Err(err) => { - debug!( - "client {} #{} DRI3::BuffersFromPixmap pixmap=0x{pixmap:x} -> BadPixmap ({err})", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - pixmap, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - } - } - x11dri3::GET_SUPPORTED_MODIFIERS => { - let req = match x11dri3::parse_get_supported_modifiers(body) { - Some(r) => r, - None => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - }; - let (window_mods, screen_mods) = - backend.dri3_supported_modifiers(req.window, req.depth, req.bpp); - debug!( - "client {} #{} DRI3::GetSupportedModifiers w=0x{:x} d={} bpp={} -> window={:?} screen={:?}", - client_id.0, - sequence.0, - req.window, - req.depth, - req.bpp, - window_mods - .iter() - .map(|m| format!("0x{m:x}")) - .collect::>(), - screen_mods - .iter() - .map(|m| format!("0x{m:x}")) - .collect::>(), - ); - let reply = x11dri3::encode_get_supported_modifiers_reply( - byte_order, - sequence, - &window_mods, - &screen_mods, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11dri3::FENCE_FROM_FD => { - if !caps.fence_fd { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let Some(req) = x11dri3::parse_fence_from_fd(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - let Some(fd) = attached_fd else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.fence, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - // Best-effort import: many clients (Mesa included) send an - // fd that doesn't import cleanly via SYNC_FD on Venus - // passthrough. Per design §3.4 the GPU-side semaphore is - // an optimisation; XSync trigger/await semantics still - // work server-side via the fence resource. Always mirror - // onto state.sync_fences so QueryFence / TriggerFence / - // ResetFence behave correctly. - match backend.dri3_fence_from_fd(req.fence, fd) { - Ok(()) => { - debug!( - "client {} #{} DRI3::FenceFromFD 0x{:x} initially_triggered={} -> imported (semaphore-backed)", - client_id.0, sequence.0, req.fence, req.initially_triggered - ); - } - Err(e) => { - log::warn!( - "DRI3::FenceFromFD 0x{:x}: VkSemaphore import failed ({e}); \ - falling back to server-only fence (XSync trigger/await still works)", - req.fence - ); - } - } - state.sync_fences.insert( - req.fence, - crate::server::SyncFence { - owner: client_id, - triggered: req.initially_triggered, - }, - ); - } - x11dri3::FD_FROM_FENCE => { - if !caps.fence_fd { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let Some(req) = x11dri3::parse_fd_from_fence(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - match backend.dri3_fd_from_fence(req.fence) { - Ok(fd) => { - let reply = x11dri3::encode_fd_from_fence_reply(byte_order, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let raw = std::os::fd::AsRawFd::as_raw_fd(&fd); - if let Err(e) = send_reply_with_fd(client, &reply, raw) { - log::warn!("DRI3::FDFromFence SCM_RIGHTS dispatch failed: {e}"); - return Ok(RequestOutcome::Disconnect(client_id)); - } - drop(fd); - return Ok(RequestOutcome::Handled); - } - Err(e) => { - debug!( - "client {} #{} DRI3::FDFromFence 0x{:x} -> BadAlloc ({e})", - client_id.0, sequence.0, req.fence - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.fence, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - } - } - x11dri3::IMPORT_SYNCOBJ => { - if !caps.syncobj { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let Some(req) = x11dri3::parse_import_syncobj(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - if xid_out_of_client_range(state, client_id, req.syncobj) - || state.xid_occupied(req.syncobj) - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - req.syncobj, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let drawable_exists = state.resources.window(ResourceId(req.drawable)).is_some() - || state.resources.pixmap(ResourceId(req.drawable)).is_some(); - if !drawable_exists { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.drawable, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let Some(fd) = attached_fd else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.syncobj, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - if let Err(e) = backend.dri3_import_syncobj(client_id, req.syncobj, fd) { - debug!( - "client {} #{} DRI3::ImportSyncobj 0x{:x} -> BadAlloc ({e})", - client_id.0, sequence.0, req.syncobj - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ALLOC, - req.syncobj, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - assert!( - state - .resources - .register_dri3_syncobj(ResourceId(req.syncobj), client_id), - "validated DRI3 syncobj XID became occupied before registration" - ); - debug!( - "client {} #{} DRI3::ImportSyncobj 0x{:x} -> imported", - client_id.0, sequence.0, req.syncobj - ); - } - x11dri3::FREE_SYNCOBJ => { - if !caps.syncobj { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_IMPLEMENTATION, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let Some(syncobj) = x11dri3::parse_free_syncobj(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - let Some(owner) = state.resources.dri3_syncobj_owner(ResourceId(syncobj)) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - syncobj, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - }; - if owner != client_id { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - syncobj, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - if let Err(e) = backend.dri3_free_syncobj(client_id, syncobj) { - let code = if e.kind() == std::io::ErrorKind::PermissionDenied { - debug!( - "client {} #{} DRI3::FreeSyncobj 0x{:x} -> BadAccess ({e})", - client_id.0, sequence.0, syncobj - ); - x11::error::BAD_ACCESS - } else { - debug!( - "client {} #{} DRI3::FreeSyncobj 0x{:x} -> BadValue ({e})", - client_id.0, sequence.0, syncobj - ); - x11::error::BAD_VALUE - }; - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - syncobj, - u16::from(header.data), - DRI3_MAJOR_OPCODE, - ); - } - let removed = state.resources.remove_dri3_syncobj(ResourceId(syncobj)); - debug_assert_eq!(removed, Some(client_id)); - // Pairs with the `-> imported` line above. A successful free was - // silent, so an import count could not be matched against a free - // count and "are retired swapchain syncobjs released?" was - // unanswerable from a capture — mpv scrubbing imports 6 per - // swapchain rebuild. - debug!( - "client {} #{} DRI3::FreeSyncobj 0x{:x} -> freed", - client_id.0, sequence.0, syncobj - ); - } - x11dri3::SET_DRM_DEVICE_IN_USE => { - // Acknowledged but ignored — single-GPU only per design §1. - debug!( - "client {} #{} DRI3::SetDRMDeviceInUse (single-GPU; ignored)", - client_id.0, sequence.0 - ); - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - DRI3_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -/// Build the FBConfig list returned by `GetFBConfigs`. We synthesise -/// from each X visual (depth-24 RGB and depth-32 ARGB), double buffered, -/// plus one visual-less, single-buffered pixmap configuration for -/// QtWebEngine's native DMA-BUF import. All share depth=24 stencil=8 (the -/// universal default for OpenGL apps). The two visual-backed configurations -/// advertise GLX_PBUFFER_BIT so Chromium/ANGLE can allocate its offscreen -/// surface. -/// Resolve the attribute list for a `GetDrawableAttributes` reply, -/// mirroring Xorg's `DoGetDrawableAttributes` (glxcmds.c:1863-1914). -/// With no GLX record (a naked X window queried directly, the GLX 1.2 -/// pattern) the `pGlxDraw` block is skipped entirely — `GLX_FBCONFIG_ID`, -/// `GLX_TEXTURE_TARGET_EXT` and `GLX_EVENT_MASK` are absent, not zero. -fn drawable_attributes_for(state: &ServerState, xid: u32) -> Vec<(u32, u32)> { - use yserver_protocol::x11::glx as g; - let drawable = state.glx_drawables.get(&xid); - // Resolve drawable geometry. For a pbuffer the size lives in the - // GlxDrawable record (from CreatePbuffer); otherwise read the real - // geometry of the backing X drawable from the resource store. Mesa's - // loader_dri3 reads GLX_WIDTH/GLX_HEIGHT here to size the buffer; - // without them it gets 0×0 and fails with "failed to create drawable". - // Xorg reports the same from pDraw->width/height (glxcmds.c:1891). - // A 0×0 pbuffer is treated as NOT a pbuffer here (matches the old - // size-keyed behaviour): its geometry falls through to the backing - // pixmap, which CREATE_PBUFFER clamps to max(1), so it reports 1×1. - let is_pbuffer = matches!( - drawable, - Some(d) if d.kind == crate::server::GlxDrawableKind::Pbuffer - && (d.width != 0 || d.height != 0) - ); - // A GLXWindow/GLXPixmap XID is a fresh client-allocated id with no X - // resource behind it — its geometry lives on the *backing* X drawable - // recorded at create time. Looking up the GLX XID itself always missed - // and reported 0×0. Xorg reads pGlxDraw->pDraw->width/height - // (glxcmds.c:1891). - let geometry_xid = match drawable { - Some(d) if !is_pbuffer => d.x_drawable, - _ => xid, - }; - let (width, height) = match drawable { - Some(d) if is_pbuffer => (d.width, d.height), - _ => state - .resources - .window(ResourceId(geometry_xid)) - .map(|w| (u32::from(w.width), u32::from(w.height))) - .or_else(|| { - state - .resources - .pixmap(ResourceId(geometry_xid)) - .map(|p| (u32::from(p.width), u32::from(p.height))) - }) - .unwrap_or((0, 0)), - }; - // Xorg's exact attribute set and order (glxcmds.c:1889-1914). - let mut attribs: Vec<(u32, u32)> = Vec::with_capacity(9); - attribs.push((g::GLX_Y_INVERTED_EXT, 0)); - attribs.push((g::GLX_WIDTH, width)); - attribs.push((g::GLX_HEIGHT, height)); - attribs.push((g::GLX_SCREEN, 0)); - if let Some(d) = drawable { - attribs.push((g::GLX_TEXTURE_TARGET_EXT, d.texture_target)); - attribs.push((g::GLX_EVENT_MASK, d.event_mask)); - attribs.push((g::GLX_FBCONFIG_ID, d.fbconfig)); - if d.kind == crate::server::GlxDrawableKind::Pbuffer { - attribs.push((g::GLX_PRESERVED_CONTENTS, 1)); - } - if d.kind == crate::server::GlxDrawableKind::Window { - attribs.push((g::GLX_STEREO_TREE_EXT, 0)); - } - } - // GLX_EXT_get_drawable_type — always last; Xorg's no-record - // fallthrough is GLX_WINDOW_BIT (glxcmds.c:1908-1910). - let drawable_type = match drawable.map(|d| d.kind) { - Some(crate::server::GlxDrawableKind::Pixmap) => g::GLX_PIXMAP_BIT, - Some(crate::server::GlxDrawableKind::Pbuffer) => g::GLX_PBUFFER_BIT, - Some(crate::server::GlxDrawableKind::Window) | None => g::GLX_WINDOW_BIT, - }; - attribs.push((g::GLX_DRAWABLE_TYPE, drawable_type)); - attribs -} - -/// GLX 1.2 visual configs in the legacy untagged form Mesa parses -/// via `__glXInitializeVisualConfigFromTags(!tagged_only)`. Mirrors -/// the visuals our setup-reply advertises (ROOT_VISUAL depth-24 -/// TrueColor RGB, ARGB_VISUAL depth-32 TrueColor RGBA). -/// -/// An X visual describes one GLX visual configuration. Do not publish the -/// same visual ID once as double-buffered and again as single-buffered: Mesa -/// cannot preserve that ambiguity when a context and window are selected -/// independently. ANGLE selected yserver's single-buffered config for its -/// context/pbuffer but the double-buffered config carrying the same visual for -/// its windows. Mesa then allocated a fake front buffer for every window. Xorg -/// gives those configurations distinct X visuals; until yserver exposes more -/// setup visuals, associate only the double-buffered configuration with each -/// real visual. -fn synthesise_glx_visual_configs() -> Vec { - use yserver_protocol::x11::glx::VisualConfig; - // X11 visual class 4 == TrueColor, matching the class we put in the - // setup-reply visual list. - const TRUE_COLOR: u32 = 4; - let mut out: Vec = Vec::with_capacity(3); - for &(visual_id, alpha_bits, rgb_bits, stencil_bits) in &[ - // Must match the client driver's configs (see synthesise_glx_fb_configs): - // radeonsi advertises alpha-8 / 32-bit-buffer for both depths. - (0x102_u32, 8_u32, 32_u32, 8_u32), // ROOT_VISUAL — TrueColor (GL alpha 8) - (0x103_u32, 8_u32, 32_u32, 8_u32), // ARGB_VISUAL — TrueColor RGBA - (crate::resources::GLMARK_VISUAL.0, 8_u32, 32_u32, 0_u32), - ] { - out.push(VisualConfig { - visual_id, - visual_class: TRUE_COLOR, - rgba: true, - red_bits: 8, - green_bits: 8, - blue_bits: 8, - alpha_bits, - double_buffer: true, - stereo: false, - rgb_bits, - depth_bits: 24, - stencil_bits, - aux_buffers: 0, - level: 0, - }); - } - out -} - -/// Build the GLX extension string. The base extensions are always -/// present; `GLX_EXT_texture_from_pixmap` is appended only when the -/// backend confirmed at init that it can export a BGRA8 dma-buf. -/// `GLX_SGIX_fbconfig` is always appended: `GetFBConfigsSGIX`, -/// `CreateContextWithConfigSGIX` and `CreateGLXPixmapWithConfigSGIX` -/// are fully dispatched (VendorPrivate arms) — advertise-after-implement. -/// -/// **Every chunk is space-terminated, so the string ends with `' '`.** -/// This mirrors Xorg, which writes `' '` then `'\0'` after each enabled -/// extension (`glx/extension_string.c:144-145`). It is not cosmetic: -/// `libGLX_nvidia` loses the final token of an unterminated list — it -/// silently dropped the `GLX_SGIX_fbconfig` we advertise — and also -/// withholds `GLX_ARB_get_proc_address` from the client extension -/// string, which aborts libepoxy and crashes `kwin_x11`. Appending via -/// this closure keeps the invariant true for any extension added later. -fn glx_extension_string(tfp_supported: bool) -> String { - let mut s = String::new(); - let mut push = |chunk: &str| { - s.push_str(chunk); - s.push(' '); - }; - push(yserver_protocol::x11::glx::SERVER_EXTENSIONS); - push(yserver_protocol::x11::glx::SGIX_FBCONFIG_EXTENSION); - if tfp_supported { - push(yserver_protocol::x11::glx::TFP_EXTENSION); - } - s -} - -fn synthesise_glx_fb_configs(tfp_supported: bool) -> Vec> { - use yserver_protocol::x11::glx as g; - let mut out = Vec::with_capacity(4); - let depth = 24; - for &(visual_id, fbconfig_id, alpha_size, total_buffer_size, stencil) in &[ - // (X visual id, FBConfig id, alpha bits, total color buffer bits) - // - // These MUST match the client driver's __DRIconfig attributes - // exactly, or mesa's driConfigEqual rejects them all and GLX dri3 - // screen creation fails with "No matching fbConfigs or visuals - // found" (no direct GLX → no TFP). radeonsi advertises BOTH its - // depth-24 and depth-32 TrueColor configs as 8-bit-alpha, - // 32-bit-buffer (the GL backbuffer is BGRA8 regardless of the X - // visual's opacity), so we mirror that for both. The depth-24 X - // visual stays opaque on screen; the alpha is GL-side only. - (0x102_u32, 0x101_u32, 8_u32, 32_u32, 8_u32), // ROOT_VISUAL — TrueColor - // Preserve the IDs of the two double-buffered configurations while - // dropping the ambiguous single-buffered 0x102 and 0x104 entries. - (0x103_u32, 0x103_u32, 8_u32, 32_u32, 8_u32), // ARGB_VISUAL — TrueColor RGBA - ( - crate::resources::GLMARK_VISUAL.0, - 0x105_u32, - 8_u32, - 32_u32, - 0_u32, - ), - ] { - let mut config = vec![ - (g::GLX_VISUAL_ID, visual_id), - (g::GLX_FBCONFIG_ID, fbconfig_id), - (g::GLX_X_VISUAL_TYPE, g::GLX_TRUE_COLOR), - // PBUFFER_BIT is load-bearing for Chromium/ANGLE: it allocates - // its offscreen GL surface as a pbuffer and filters configs on - // this bit. Without it ANGLE's HW GL init fails and Chromium - // drops to SwiftShader (no WebGL accel → no Maps 3D). Firefox - // uses window surfaces and is unaffected either way. (#96) - ( - g::GLX_DRAWABLE_TYPE, - g::GLX_WINDOW_BIT | g::GLX_PIXMAP_BIT | g::GLX_PBUFFER_BIT, - ), - (g::GLX_RENDER_TYPE, g::GLX_RGBA_BIT), - (g::GLX_X_RENDERABLE, 1), - (g::GLX_BUFFER_SIZE, total_buffer_size), - (g::GLX_LEVEL, 0), - (g::GLX_DOUBLEBUFFER, 1), - (g::GLX_STEREO, 0), - (g::GLX_AUX_BUFFERS, 0), - (g::GLX_RED_SIZE, 8), - (g::GLX_GREEN_SIZE, 8), - (g::GLX_BLUE_SIZE, 8), - (g::GLX_ALPHA_SIZE, alpha_size), - (g::GLX_DEPTH_SIZE, depth), - (g::GLX_STENCIL_SIZE, stencil), - (g::GLX_ACCUM_RED_SIZE, 0), - (g::GLX_ACCUM_GREEN_SIZE, 0), - (g::GLX_ACCUM_BLUE_SIZE, 0), - (g::GLX_ACCUM_ALPHA_SIZE, 0), - (g::GLX_CONFIG_CAVEAT, g::GLX_NONE), - (g::GLX_TRANSPARENT_TYPE, g::GLX_NONE), - (g::GLX_SAMPLE_BUFFERS, 0), - (g::GLX_SAMPLES, 0), - // Pbuffer size caps — required alongside PBUFFER_BIT so ANGLE's - // glXGetFBConfigAttrib(GLX_MAX_PBUFFER_*) validation passes. - // 16384 comfortably exceeds any browser offscreen surface - // (ANGLE's init pbuffer is 1×1). Not compared by driConfigEqual. - (g::GLX_MAX_PBUFFER_WIDTH, 16384), - (g::GLX_MAX_PBUFFER_HEIGHT, 16384), - (g::GLX_MAX_PBUFFER_PIXELS, 16384 * 16384), - ]; - // Append bind-to-texture pairs in Xorg's exact reply order - // (glxcmds.c:1094-1100 / glxdricommon.c:165) when TFP is supported. - // - // These attributes are scalar-compared by mesa's driConfigEqual - // against the client driver's __DRIconfig (attribMap in - // src/glx/dri_common.c), so they MUST match what radeonsi - // advertises or the whole config is rejected and dri3 screen - // creation fails ("No matching fbConfigs or visuals found"). - // HW-verified on bee (radeonsi via Xwayland): every TFP config - // reports BIND_RGB=1, BIND_RGBA=1, and BIND_TARGETS=GLX_DONT_CARE. - // So advertise RGBA=1 for BOTH depths (depth-24 windows are - // opaque; the sample_view forces α=1, so an RGBA bind reads as - // opaque — correct) and DONT_CARE for targets (matches any - // driver target bitmask, as Xwayland itself does). - if tfp_supported { - config.push((g::GLX_BIND_TO_TEXTURE_RGB_EXT, 1)); - config.push((g::GLX_BIND_TO_TEXTURE_RGBA_EXT, 1)); - // MIPMAP: not backed, but pair MUST be present for contract. - config.push((g::GLX_BIND_TO_MIPMAP_TEXTURE_EXT, 0)); - config.push((g::GLX_BIND_TO_TEXTURE_TARGETS_EXT, g::GLX_DONT_CARE)); - // Y_INVERTED in FBConfig = GLX_DONT_CARE (differs from drawable-attributes - // where it is 0/GL_FALSE — do not confuse them; glxcmds.c:1093). - config.push((g::GLX_Y_INVERTED_EXT, g::GLX_DONT_CARE)); - } - out.push(config); - } - // QtWebEngine's GLXHelper chooses a single-buffered RGBA pixmap config - // before importing a native DMA-BUF through DRI3 (#152). Do not attach it - // to either real visual: #96 showed that Mesa can then pair the - // single-buffered config with a double-buffered window of the same visual, - // making it allocate a fake front buffer. A visual-less, pixmap-only - // config is sufficient for GLXPixmap and cannot be selected for windows - // or pbuffers. Keep the property count uniform: GetFBConfigs encodes one - // count for the whole reply. - let mut native_pixmap = out[0].clone(); - for (attribute, value) in &mut native_pixmap { - match *attribute { - g::GLX_VISUAL_ID => *value = 0, - g::GLX_FBCONFIG_ID => *value = 0x104, - g::GLX_X_VISUAL_TYPE => *value = g::GLX_NONE, - g::GLX_DRAWABLE_TYPE => *value = g::GLX_PIXMAP_BIT, - g::GLX_X_RENDERABLE => *value = 0, - g::GLX_DOUBLEBUFFER => *value = 0, - _ => {} - } - } - out.push(native_pixmap); - out -} - -/// X-Resource (`Res`) extension. `QueryClients` returns the real list of -/// connected clients (their XID ranges); `QueryClientResources` returns -/// real per-type resource counts for a client (the two queries `xrestop` -/// leans on). `QueryClientPixmapBytes` computes live padded pixmap storage. -/// `QueryClientIds` reports ClientXID identities (PID identities are omitted -/// because peer credentials are not retained). `QueryResourceBytes` remains -/// empty until yserver keeps recursive resource-size accounting. -fn handle_x_resource_request( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, x_resource as x11xres}; - - /// Peer pid of a client's connection, for X-Resource's LocalClientPID - /// identity. Read from the live socket rather than cached at accept: the - /// credentials are fixed for the socket's lifetime, and `ClientState` is - /// built at 46 sites (mostly tests), so a lazy read avoids threading a - /// field through all of them for a rarely-issued request. - /// - /// `SO_PEERCRED`/`ucred` is Linux-specific. FreeBSD's `getpeereid` and - /// `LOCAL_PEERCRED` expose uid/gid but no pid, so there we report no PID - /// identity — which is a supported outcome, not a gap: Xorg's - /// `GetClientPid` returns -1 whenever the OS cannot supply one and the - /// caller then omits the identity (`Xext/xres.c`). - #[cfg(target_os = "linux")] - fn client_peer_pid(client: &crate::server::ClientState) -> Option { - use std::os::fd::AsRawFd; - if !client.is_local { - return None; - } - let guard = client - .writer - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let mut cred = libc::ucred { - pid: 0, - uid: 0, - gid: 0, - }; - let mut len = u32::try_from(std::mem::size_of::()).ok()?; - // SAFETY: `guard` keeps the socket alive for the call, and `cred`/`len` - // are the exact out-param types SO_PEERCRED documents. - let rc = unsafe { - libc::getsockopt( - guard.as_raw_fd(), - libc::SOL_SOCKET, - libc::SO_PEERCRED, - std::ptr::from_mut(&mut cred).cast(), - &mut len, - ) - }; - drop(guard); - (rc == 0 && cred.pid > 0).then(|| cred.pid.cast_unsigned()) - } - - #[cfg(not(target_os = "linux"))] - fn client_peer_pid(_client: &crate::server::ClientState) -> Option { - None - } - - fn target_client_for_xid(state: &ServerState, xid: u32) -> Option { - state - .clients - .iter() - .find(|(_, client)| (xid & !client.resource_id_mask) == client.resource_id_base) - .map(|(id, _)| ClientId(*id)) - } - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - let reply = match minor { - x11xres::QUERY_VERSION => { - let (cmaj, cmin) = x11xres::parse_query_version(body).unwrap_or((0, 0)); - let major = u16::from(cmaj).min(x11xres::MAJOR_VERSION); - let minor_ver = u16::from(cmin).min(x11xres::MINOR_VERSION); - debug!( - "client {} #{} X-Resource::QueryVersion client={cmaj}.{cmin} -> {major}.{minor_ver}", - client_id.0, sequence.0 - ); - x11xres::encode_query_version_reply(byte_order, sequence, major, minor_ver) - } - x11xres::QUERY_CLIENTS => { - // Every connected client by its XID resource range - // (resource_base, resource_mask), sorted by client id for a - // deterministic reply. This is exactly what xrestop and other - // resource monitors read. - let mut entries: Vec<(u32, u32, u32)> = state - .clients - .iter() - .map(|(id, c)| (*id, c.resource_id_base, c.resource_id_mask)) - .collect(); - entries.sort_by_key(|(id, _, _)| *id); - let clients: Vec<(u32, u32)> = entries - .iter() - .map(|(_, base, mask)| (*base, *mask)) - .collect(); - debug!( - "client {} #{} X-Resource::QueryClients -> {} clients", - client_id.0, - sequence.0, - clients.len() - ); - x11xres::encode_query_clients_reply(byte_order, sequence, &clients) - } - x11xres::QUERY_CLIENT_RESOURCES => { - // body: xid(4). X-Resource identifies the target client by the - // xid's resource range (Xorg CLIENT_ID()), not by it being a - // live resource — xrestop passes the client's resource_base. - let xid = if body.len() >= 4 { - u32::from_le_bytes([body[0], body[1], body[2], body[3]]) - } else { - 0 - }; - let Some(target) = target_client_for_xid(state, xid) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - xid, - u16::from(minor), - header.opcode, - ); - }; - let pairs = state.resources.resource_counts_by_owner(target); - let types: Vec<(u32, u32)> = pairs - .iter() - .map(|(name, count)| (state.atoms.intern(name, false).0, *count)) - .collect(); - debug!( - "client {} #{} X-Resource::QueryClientResources xid=0x{xid:x} -> {} types", - client_id.0, - sequence.0, - types.len() - ); - x11xres::encode_query_client_resources_reply(byte_order, sequence, &types) - } - x11xres::QUERY_CLIENT_PIXMAP_BYTES => { - let xid = body - .get(0..4) - .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) - .unwrap_or(0); - let Some(target) = target_client_for_xid(state, xid) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - xid, - u16::from(minor), - header.opcode, - ); - }; - let bytes = state.resources.pixmap_bytes_by_owner(target); - debug!( - "client {} #{} X-Resource::QueryClientPixmapBytes xid=0x{xid:x} -> {bytes}", - client_id.0, sequence.0, - ); - x11xres::encode_query_client_pixmap_bytes_reply(byte_order, sequence, bytes) - } - x11xres::QUERY_CLIENT_IDS => { - let num_specs = body - .get(0..4) - .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) - .unwrap_or(0); - // Track the requested mask per client: Xorg applies each spec's - // mask to the clients that spec selects (`WillConstructMask`, - // Xext/xres.c), where mask 0 means "every identity". A client - // named by several specs gets the union. - let mut selected: Vec<(u32, u32)> = Vec::new(); - for spec in body - .get(4..) - .unwrap_or_default() - .chunks_exact(8) - .take(usize::try_from(num_specs).unwrap_or(usize::MAX)) - { - let requested = u32::from_le_bytes(spec[0..4].try_into().unwrap()); - let mask = u32::from_le_bytes(spec[4..8].try_into().unwrap()); - const KNOWN: u32 = x11xres::CLIENT_XID_MASK | x11xres::LOCAL_CLIENT_PID_MASK; - if mask != 0 && mask & KNOWN == 0 { - continue; - } - if requested == 0 { - selected.extend(state.clients.keys().map(|id| (*id, mask))); - } else if let Some(target) = target_client_for_xid(state, requested) { - selected.push((target.0, mask)); - } - } - selected.sort_unstable(); - let mut merged: Vec<(u32, u32)> = Vec::with_capacity(selected.len()); - for (id, mask) in selected { - match merged.last_mut() { - Some((prev, acc)) if *prev == id => *acc |= mask, - _ => merged.push((id, mask)), - } - } - - let mut entries = Vec::with_capacity(merged.len()); - for (id, mask) in merged { - let Some(client) = state.clients.get(&id) else { - continue; - }; - let base = client.resource_id_base; - // Xorg emits ClientXID first, then LocalClientPID. - if mask == 0 || mask & x11xres::CLIENT_XID_MASK != 0 { - entries.push(x11xres::ClientIdEntry::xid(base)); - } - if mask == 0 || mask & x11xres::LOCAL_CLIENT_PID_MASK != 0 { - // Omitted when the OS cannot supply a pid, exactly as Xorg - // skips the identity when GetClientPid returns -1. - if let Some(pid) = client_peer_pid(client) { - entries.push(x11xres::ClientIdEntry::pid(base, pid)); - } - } - } - debug!( - "client {} #{} X-Resource::QueryClientIds -> {} identities", - client_id.0, - sequence.0, - entries.len(), - ); - x11xres::encode_query_client_ids_reply(byte_order, sequence, &entries) - } - x11xres::QUERY_RESOURCE_BYTES => { - debug!( - "client {} #{} X-Resource::QueryResourceBytes -> 0 sizes (stub)", - client_id.0, sequence.0 - ); - x11xres::encode_query_resource_bytes_empty_reply(byte_order, sequence) - } - other => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ); - } - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, &reply)) -} - -#[derive(Debug)] -struct CurrentVidModeOutput { - output_id: u32, - crtc_id: u32, - connector: String, - mode: yserver_protocol::x11::xf86vidmode::ModeLine, -} - -fn current_vidmode_output(state: &ServerState) -> Option { - use yserver_protocol::x11::xf86vidmode::ModeLine; - - // Xwayland's VidMode shim uses its fixed output, or otherwise the first - // output. Yserver's configured primary is the closest equivalent; if it - // is off, fall back to the first enabled output. - let output = state - .randr - .outputs - .iter() - .find(|output| output.output_id == state.randr.primary_output && output.mode_id != 0) - .or_else(|| { - state - .randr - .outputs - .iter() - .find(|output| output.mode_id != 0) - })?; - - // Same resolved timing RANDR's ModeInfo reports, so the two extensions - // can never describe the same mode differently. VidMode carries the - // pixel clock in whole kHz rather than RANDR's Hz. - let timing = output.effective_timing(); - // A zero clock would make Mesa derive a zero MSC rate; Xorg's - // VidModeGetCurrentModeline fails the same way and yields BadValue. - if timing.dot_clock_hz == 0 { - return None; - } - Some(CurrentVidModeOutput { - output_id: output.output_id, - crtc_id: output.crtc_id, - connector: output.name.clone(), - mode: ModeLine { - dot_clock: timing.dot_clock_khz(), - hdisplay: output.width, - hsync_start: timing.hsync_start, - hsync_end: timing.hsync_end, - htotal: timing.htotal, - hskew: timing.hskew, - vdisplay: output.height, - vsync_start: timing.vsync_start, - vsync_end: timing.vsync_end, - vtotal: timing.vtotal, - flags: timing.mode_flags, - }, - }) -} - -#[cfg(test)] -fn current_vidmode_mode_line( - state: &ServerState, -) -> Option { - current_vidmode_output(state).map(|output| output.mode) -} - -fn vidmode_timing_order_is_valid(mode: yserver_protocol::x11::xf86vidmode::ModeLine) -> bool { - mode.hdisplay <= mode.hsync_start - && mode.hsync_start <= mode.hsync_end - && mode.hsync_end <= mode.htotal - && mode.vdisplay <= mode.vsync_start - && mode.vsync_start <= mode.vsync_end - && mode.vsync_end <= mode.vtotal -} - -/// Derive VidMode's old monitor strings from the same raw EDID RANDR exposes. -/// A missing/invalid EDID leaves the vendor empty and uses the connector name -/// as the model, which is more useful than inventing an identity. -fn vidmode_monitor_identity(edid: &[u8], connector: &str) -> (Vec, Vec) { - let vendor = edid - .get(8..10) - .and_then(|bytes| { - let code = u16::from_be_bytes(bytes.try_into().ok()?); - let letters = [ - u8::try_from((code >> 10) & 0x1f).ok()?, - u8::try_from((code >> 5) & 0x1f).ok()?, - u8::try_from(code & 0x1f).ok()?, - ]; - letters - .iter() - .all(|letter| (1..=26).contains(letter)) - .then(|| { - letters - .into_iter() - .map(|letter| b'A' + letter - 1) - .collect() - }) - }) - .unwrap_or_default(); - - let model = [54usize, 72, 90, 108] - .into_iter() - .filter_map(|offset| edid.get(offset..offset + 18)) - .find_map(|descriptor| { - if descriptor.get(..5) != Some(&[0, 0, 0, 0xfc, 0]) { - return None; - } - let name = descriptor.get(5..18)?; - let end = name - .iter() - .rposition(|byte| !matches!(byte, 0 | b'\n' | b'\r' | b' ')) - .map_or(0, |index| index + 1); - (end != 0 - && name[..end] - .iter() - .all(|byte| byte.is_ascii_graphic() || *byte == b' ')) - .then(|| name[..end].to_vec()) - }) - .unwrap_or_else(|| connector.as_bytes().to_vec()); - (vendor, model) -} - -fn vidmode_sync_ranges(mode: yserver_protocol::x11::xf86vidmode::ModeLine) -> ([u32; 1], [u32; 1]) { - fn rounded_hundredths(numerator: u64, denominator: u64) -> u16 { - if denominator == 0 { - return 0; - } - let value = numerator.saturating_add(denominator / 2) / denominator; - u16::try_from(value).unwrap_or(u16::MAX) - } - fn singleton_range(value: u16) -> u32 { - u32::from(value) | (u32::from(value) << 16) - } - - // Horizontal range is kHz * 100. Vertical range is Hz * 100. - let hsync = rounded_hundredths( - u64::from(mode.dot_clock).saturating_mul(100), - u64::from(mode.htotal), - ); - let vsync = rounded_hundredths( - u64::from(mode.dot_clock).saturating_mul(100_000), - u64::from(mode.htotal).saturating_mul(u64::from(mode.vtotal)), - ); - ([singleton_range(hsync)], [singleton_range(vsync)]) -} - -/// Validate the `screen(u16) + pad(u16)` body shared by VidMode's -/// read-only requests. `Err` carries `(error code, errorValue)`. -/// -/// Xorg checks `screen >= screenInfo.numScreens => BadValue`; yserver -/// drives exactly one X screen, so anything but 0 is out of range. -fn vidmode_screen_number(screen: u32) -> Result<(), (u8, u32)> { - if screen != 0 { - return Err((x11::error::BAD_VALUE, screen)); - } - Ok(()) -} - -fn vidmode_screen(body: &[u8]) -> Result<(), (u8, u32)> { - let screen = yserver_protocol::x11::xf86vidmode::parse_screen(body) - .ok_or((x11::error::BAD_LENGTH, 0))?; - vidmode_screen_number(u32::from(screen)) -} - -fn write_vidmode_reply( - state: &mut ServerState, - client_id: ClientId, - reply: &[u8], -) -> io::Result { - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, reply)) -} - -fn handle_xf86vidmode_request( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use crate::nested::{XF86VIDMODE_FIRST_ERROR, XF86VIDMODE_MAJOR_OPCODE}; - use yserver_protocol::x11::{ClientByteOrder, xf86vidmode as x11vm}; - - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |client| client.byte_order); - let is_local = state - .clients - .get(&client_id.0) - .is_none_or(|client| client.is_local); - let version_2 = state - .vidmode_client_versions - .get(&client_id) - .is_some_and(|(major, _)| *major >= 2); - - match header.data { - x11vm::QUERY_VERSION => { - if !body.is_empty() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let reply = x11vm::encode_query_version_reply(byte_order, sequence); - return write_vidmode_reply(state, client_id, &reply); - } - x11vm::SET_CLIENT_VERSION => { - let Some(version) = x11vm::parse_client_version(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - state - .vidmode_client_versions - .insert(client_id, (version.major, version.minor)); - debug!( - "client {} #{} XFree86-VidMode::SetClientVersion {}.{}", - client_id.0, sequence.0, version.major, version.minor - ); - } - x11vm::VALIDATE_MODE_LINE => { - let Some(request) = - x11vm::parse_validate_mode_line_request(byte_order, body, version_2) - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - if let Err((code, bad_value)) = vidmode_screen_number(request.screen) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - bad_value, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let Some(current) = current_vidmode_output(state) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - - // Xorg rejects inverted timing order before invoking the monitor - // and driver validators. Yserver exposes only the active mode, so - // that exact advertised line is the only one its read-only - // VidMode surface can truthfully validate. Legacy clients cannot - // carry hskew, matching the legacy GetModeLine reply. - let mut advertised = current.mode; - if !version_2 { - advertised.hskew = 0; - } - let status = - if vidmode_timing_order_is_valid(request.mode) && request.mode == advertised { - x11vm::MODE_OK - } else { - x11vm::MODE_BAD - }; - let reply = x11vm::encode_validate_mode_line_reply(byte_order, sequence, status); - return write_vidmode_reply(state, client_id, &reply); - } - x11vm::GET_GAMMA => { - let Some(screen) = x11vm::parse_gamma_screen(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - if let Err((code, bad_value)) = vidmode_screen_number(u32::from(screen)) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - bad_value, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let reply = x11vm::encode_get_gamma_reply(byte_order, sequence); - return write_vidmode_reply(state, client_id, &reply); - } - x11vm::GET_GAMMA_RAMP => { - let Some(request) = x11vm::parse_gamma_ramp_request(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - if let Err((code, bad_value)) = vidmode_screen_number(u32::from(request.screen)) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - bad_value, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let Some(current) = current_vidmode_output(state) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - let expected = backend.crtc_gamma_size(current.crtc_id); - if request.size != expected { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(request.size), - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let (red, green, blue) = backend.get_crtc_gamma(current.crtc_id); - let expected = usize::from(expected); - if red.len() != expected || green.len() != expected || blue.len() != expected { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let reply = - x11vm::encode_get_gamma_ramp_reply(byte_order, sequence, &red, &green, &blue); - return write_vidmode_reply(state, client_id, &reply); - } - // The ordinary read-only screen-scoped requests all carry - // `screen(u16) + pad(u16)`. - x11vm::GET_MODE_LINE - | x11vm::GET_MONITOR - | x11vm::GET_ALL_MODE_LINES - | x11vm::GET_VIEW_PORT - | x11vm::GET_DOT_CLOCKS - | x11vm::GET_GAMMA_RAMP_SIZE - | x11vm::GET_PERMISSIONS => { - if let Err((code, bad_value)) = vidmode_screen(body) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - bad_value, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - let reply = match header.data { - x11vm::GET_PERMISSIONS => { - x11vm::encode_get_permissions_reply(byte_order, sequence, is_local) - } - x11vm::GET_VIEW_PORT => { - x11vm::encode_get_view_port_reply(byte_order, sequence, 0, 0) - } - x11vm::GET_DOT_CLOCKS => x11vm::encode_get_dot_clocks_reply(byte_order, sequence), - _ => { - let Some(current) = current_vidmode_output(state) else { - // Xorg: VidModeGetCurrentModeline failure => BadValue. - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - }; - match header.data { - x11vm::GET_GAMMA_RAMP_SIZE => x11vm::encode_get_gamma_ramp_size_reply( - byte_order, - sequence, - backend.crtc_gamma_size(current.crtc_id), - ), - x11vm::GET_MONITOR => { - let edid = backend - .output_identity(current.output_id) - .map_or_else(Vec::new, |(edid, _)| edid); - let (vendor, model) = - vidmode_monitor_identity(&edid, ¤t.connector); - let (hsync, vsync) = vidmode_sync_ranges(current.mode); - x11vm::encode_get_monitor_reply( - byte_order, sequence, &vendor, &model, &hsync, &vsync, - ) - } - x11vm::GET_MODE_LINE | x11vm::GET_ALL_MODE_LINES => { - debug!( - "client {} #{} XFree86-VidMode::{} \ - {}x{} clock={}kHz totals={}x{} flags=0x{:x}", - client_id.0, - sequence.0, - if header.data == x11vm::GET_MODE_LINE { - "GetModeLine" - } else { - "GetAllModeLines" - }, - current.mode.hdisplay, - current.mode.vdisplay, - current.mode.dot_clock, - current.mode.htotal, - current.mode.vtotal, - current.mode.flags - ); - if header.data == x11vm::GET_MODE_LINE { - x11vm::encode_get_mode_line_reply( - byte_order, - sequence, - current.mode, - version_2, - ) - } else { - x11vm::encode_get_all_mode_lines_reply( - byte_order, - sequence, - current.mode, - version_2, - ) - } - } - _ => unreachable!("screen-scoped VidMode read"), - } - } - }; - return write_vidmode_reply(state, client_id, &reply); - } - // Yserver is Unix-socket-only, so these clients are physically local. - // We nevertheless expose Xorg's coherent non-local/read-only VidMode - // policy: RANDR owns all writes, permissions omit WRITE, and known - // write minors fail with the matching extension error. - x11vm::MOD_MODE_LINE - | x11vm::SWITCH_MODE - | x11vm::LOCK_MODE_SWITCH - | x11vm::ADD_MODE_LINE - | x11vm::DELETE_MODE_LINE - | x11vm::SWITCH_TO_MODE - | x11vm::SET_VIEW_PORT - | x11vm::SET_GAMMA - | x11vm::SET_GAMMA_RAMP => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XF86VIDMODE_FIRST_ERROR + x11vm::CLIENT_NOT_LOCAL, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - _ => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(header.data), - XF86VIDMODE_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -fn handle_glx_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::{ClientByteOrder, glx as x11glx}; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - match minor { - x11glx::QUERY_VERSION => { - let (cmaj, cmin) = x11glx::parse_query_version(body).unwrap_or((0, 0)); - let major = cmaj.min(x11glx::MAJOR_VERSION); - let minor = cmin.min(x11glx::MINOR_VERSION); - debug!( - "client {} #{} GLX::QueryVersion client={cmaj}.{cmin} -> {major}.{minor}", - client_id.0, sequence.0 - ); - let reply = x11glx::encode_query_version_reply(byte_order, sequence, major, minor); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::QUERY_SERVER_STRING => { - let req = x11glx::parse_query_server_string(body); - let name = req.map_or(0, |r| r.name); - // Build the extension string lazily so we only pay the - // allocation cost when the client actually asks for it. - let ext_string; - let s: &str = match name { - x11glx::STRING_VENDOR => "yserver", - x11glx::STRING_VERSION => "1.4", - x11glx::STRING_EXTENSIONS => { - ext_string = glx_extension_string(state.glx_tfp_supported); - &ext_string - } - // libglvnd vendor-neutral dispatch: tells the client which - // libGLX_.so drives this screen. Resolved once at - // startup from the render driver - // (`BackendCapabilities::from_backend`); every non-NVIDIA - // driver keeps `VENDOR_NAMES` ("mesa"), which is what stops - // libglvnd from falling back to a vendor that resolves to - // nothing on Asahi → NULL glXQueryExtensionsString → cogl - // SIGSEGV. Only queried because we advertise - // GLX_EXT_libglvnd. - x11glx::VENDOR_NAMES_EXT => &state.glx_vendor_names, - _ => "", - }; - debug!( - "client {} #{} GLX::QueryServerString name={name:#x} -> {s:?}", - client_id.0, sequence.0 - ); - let reply = x11glx::encode_string_reply(byte_order, sequence, s); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::QUERY_EXTENSIONS_STRING => { - // Per design §3.5 — list of GLX extensions Mesa probes for. - // Same list as the server string (opcode 19) — see - // `x11glx::SERVER_EXTENSIONS`. - let ext_string = glx_extension_string(state.glx_tfp_supported); - let reply = x11glx::encode_string_reply(byte_order, sequence, &ext_string); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::CLIENT_INFO | x11glx::SET_CLIENT_INFO_ARB | x11glx::SET_CLIENT_INFO_2_ARB => { - // Drop on the floor — Mesa sends one of these on connect - // carrying its GL/GLX/GLES versions; we don't act on them. - debug!( - "client {} #{} GLX::ClientInfo* minor={} body_len={}", - client_id.0, - sequence.0, - minor, - body.len() - ); - } - x11glx::IS_DIRECT => { - // Xorg answers the context's recorded isDirect and - // GLXBadContext for an XID that is not a context - // (glxcmds.c:702-726, glx/vnd_dispatch_stubs.c:509-525). Mesa's - // glXImportContextEXT sends this first and returns NULL for a - // direct context without ever sending QueryContext. - let context = match glx_request_context(state, body) { - Ok(context) => context, - Err((code, value)) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(minor), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - }; - let is_direct = state.glx_contexts[&context].is_direct; - let reply = x11glx::encode_is_direct_reply(byte_order, sequence, is_direct); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::GET_FB_CONFIGS => { - // Synthesise FBConfigs from each X visual × singleBuf / - // doubleBuf. Mesa picks one matching the app's request - // via glXChooseFBConfig. - let configs = synthesise_glx_fb_configs(state.glx_tfp_supported); - let config_refs: Vec<&[(u32, u32)]> = configs.iter().map(|c| c.as_slice()).collect(); - let reply = x11glx::encode_get_fb_configs_reply(byte_order, sequence, &config_refs); - debug!( - "client {} #{} GLX::GetFBConfigs -> {} configs × {} props", - client_id.0, - sequence.0, - config_refs.len(), - config_refs.first().map_or(0, |c| c.len()), - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::GET_VISUAL_CONFIGS => { - // Synthesise GLX visual configs from the X visuals our - // setup-reply advertises. Mesa's `glx_screen_init` calls - // `getVisualConfigs` *before* `getFBConfigs` and bails the - // entire DRI3 screen creation if we hand back zero - // visuals — even though FBConfigs would otherwise carry - // the same info. So we always emit at least one visual. - let visuals = synthesise_glx_visual_configs(); - let reply = x11glx::encode_get_visual_configs_reply(byte_order, sequence, &visuals); - debug!( - "client {} #{} GLX::GetVisualConfigs -> {} visuals", - client_id.0, - sequence.0, - visuals.len(), - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::CREATE_CONTEXT - | x11glx::CREATE_NEW_CONTEXT - | x11glx::CREATE_CONTEXT_ATTRIBS_ARB => { - // Allocate a GlxContext resource keyed by the client-chosen - // XID. We never execute server-side GL; the recorded config, - // share list, render type and isDirect flag are what - // QueryContext / IsDirect report back (Xorg DoCreateContext - // stores the same fields, glxcmds.c:318-325). - let Some(req) = x11glx::parse_create_context(minor, body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - crate::nested::GLX_MAJOR_OPCODE, - ); - }; - let (visual_id, fbconfig) = match req.config { - x11glx::ContextConfigRef::Visual(visual) => { - (visual, glx_visual_fbconfig(visual).unwrap_or(0)) - } - x11glx::ContextConfigRef::FbConfig(fbconfig) => { - (glx_fbconfig_visual(fbconfig), fbconfig) - } - }; - state.glx_contexts.insert( - req.context, - crate::server::GlxContext { - owner: client_id, - screen: req.screen, - visual_id, - fbconfig, - render_type: req.render_type, - share_list: req.share_list, - is_direct: req.is_direct, - }, - ); - debug!( - "client {} #{} GLX::CreateContext minor={minor} xid=0x{:x} fbconfig=0x{:x} \ - visual=0x{visual_id:x} share=0x{:x} direct={}", - client_id.0, sequence.0, req.context, fbconfig, req.share_list, req.is_direct - ); - } - x11glx::DESTROY_CONTEXT => { - let xid = if body.len() >= 4 { - u32::from_le_bytes([body[0], body[1], body[2], body[3]]) - } else { - 0 - }; - state.glx_contexts.remove(&xid); - debug!( - "client {} #{} GLX::DestroyContext xid=0x{:x}", - client_id.0, sequence.0, xid - ); - } - x11glx::MAKE_CURRENT | x11glx::MAKE_CONTEXT_CURRENT => { - // MakeCurrent is a *round-trip* request — Mesa's - // `glXMakeCurrent` blocks on the contextTag in the reply - // and labels every subsequent indirect rendering request - // with it. Direct-rendering clients only use the tag for - // dispatch identification, but the reply is still - // mandatory; without it libxcb stalls. - // - // The new context XID sits at a minor-specific offset - // (glxproto.h:225-233, :471-481), body-relative: - // minor 5 MakeCurrent: drawable, context, oldContextTag - // minor 26 MakeContextCurrent: oldContextTag, drawable, - // readdrawable, context - let context = if minor == x11glx::MAKE_CURRENT { - body.get(4..8) - } else { - body.get(12..16) - } - .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .unwrap_or(0); - // The release form (context == None) returns contextTag = 0 — - // tag 0 is reserved by the protocol to mean "no context - // current" (server.rs documents this; Xorg vndcmds.c:232-234, - // :271-273). A malformed/short body also releases. - let tag = if context == 0 { - 0 - } else { - let tag = state.glx_next_context_tag; - state.glx_next_context_tag = state.glx_next_context_tag.wrapping_add(1).max(1); - tag - }; - let reply = x11glx::encode_make_current_reply(byte_order, sequence, tag); - debug!( - "client {} #{} GLX::MakeCurrent -> contextTag={tag}", - client_id.0, sequence.0 - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::WAIT_GL | x11glx::WAIT_X => { - // No-op for direct contexts. - debug!( - "client {} #{} GLX::Wait{}", - client_id.0, - sequence.0, - if minor == x11glx::WAIT_GL { "GL" } else { "X" } - ); - } - x11glx::CREATE_WINDOW | x11glx::CREATE_PIXMAP => { - let parsed = x11glx::parse_create_glx_window(body); - if let Some(req) = parsed { - // For CREATE_PIXMAP: validate the X pixmap exists. - // CREATE_WINDOW wraps an X window XID, which we don't - // validate here (windows have a different resource type). - if minor == x11glx::CREATE_PIXMAP - && state - .resources - .pixmap(yserver_protocol::x11::ResourceId(req.x_window)) - .is_none() - { - debug!( - "client {} #{} GLX::CreatePixmap glx_xid=0x{:x} \ - x_pixmap=0x{:x} not found -> GLXBadPixmap", - client_id.0, sequence.0, req.glx_window, req.x_window - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR - + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP, - req.x_window, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - - if minor == x11glx::CREATE_PIXMAP { - insert_glx_pixmap_record( - state, - backend, - client_id, - req.glx_window, - req.x_window, - req.fbconfig, - x11glx::GLX_TEXTURE_2D_EXT, - ); - } else { - state.glx_drawables.insert( - req.glx_window, - crate::server::GlxDrawable { - owner: client_id, - kind: crate::server::GlxDrawableKind::Window, - x_drawable: req.x_window, - fbconfig: req.fbconfig, - width: 0, - height: 0, - event_mask: 0, - glx_export_host_xid: None, - texture_target: x11glx::GLX_TEXTURE_2D_EXT, - }, - ); - } - - debug!( - "client {} #{} GLX::CreateDrawable minor={minor} \ - glx_xid=0x{:x} x_drawable=0x{:x} fbconfig=0x{:x}", - client_id.0, sequence.0, req.glx_window, req.x_window, req.fbconfig - ); - } else { - debug!( - "client {} #{} GLX::CreateDrawable minor={minor} (parse failed)", - client_id.0, sequence.0 - ); - } - } - x11glx::CREATE_PBUFFER => { - // Pbuffers have NO parent X drawable and carry their size in - // the request attribs — parse them with the dedicated parser - // (parse_create_glx_window would mis-read the layout). The - // stored width/height are reported back as GLX_WIDTH/GLX_HEIGHT - // from GetDrawableAttributes so Mesa can size the buffer; key - // the record by the pbuffer XID itself (it is its own drawable). - if let Some(req) = x11glx::parse_create_pbuffer(body) { - state.glx_drawables.insert( - req.pbuffer, - crate::server::GlxDrawable { - owner: client_id, - kind: crate::server::GlxDrawableKind::Pbuffer, - x_drawable: req.pbuffer, - fbconfig: req.fbconfig, - width: req.width, - height: req.height, - event_mask: 0, - glx_export_host_xid: None, - texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, - }, - ); - // #96 tier-2: back the pbuffer with a real GPU pixmap under its - // own XID, so DRI3 BuffersFromPixmap can export a dmabuf for it. - // ANGLE (Chromium) renders WebGL into this surface; with no BO - // it gets BadDrawable and WebGL produces nothing → Google Maps - // hides the 3D button. Depth comes from the fbconfig's visual. - let depth = glx_fbconfig_depth(req.fbconfig); - let pw = u16::try_from(req.width).unwrap_or(1).max(1); - let ph = u16::try_from(req.height).unwrap_or(1).max(1); - match backend.create_pixmap(origin, depth, pw, ph) { - Ok(handle) => { - state.resources.create_pixmap( - client_id, - x11::CreatePixmapRequest { - depth, - pixmap: ResourceId(req.pbuffer), - drawable: ROOT_WINDOW, - width: pw, - height: ph, - }, - ); - let updated = state - .resources - .set_pixmap_host_xid(ResourceId(req.pbuffer), handle); - debug_assert!(updated, "pbuffer backing pixmap was just inserted"); - } - Err(err) => log::warn!( - "client {} #{} GLX::CreatePbuffer host pixmap alloc failed: {err}", - client_id.0, - sequence.0 - ), - } - debug!( - "client {} #{} GLX::CreatePbuffer pbuffer=0x{:x} \ - fbconfig=0x{:x} {}x{}", - client_id.0, sequence.0, req.pbuffer, req.fbconfig, req.width, req.height - ); - } else { - debug!( - "client {} #{} GLX::CreatePbuffer (parse failed)", - client_id.0, sequence.0 - ); - } - } - x11glx::CREATE_GLX_PIXMAP => { - // GLX 1.0 glXCreateGLXPixmap: the visual-based counterpart of - // CreatePixmap. Checks run in Xorg's order — GLXVND's - // dispatch_CreateGLXPixmap (size, LEGAL_NEW_RESOURCE, screen → - // BadMatch; glx/vnd_dispatch_stubs.c:143-169), then - // __glXDisp_CreateGLXPixmap (visual → BadValue) and - // DoCreateGLXPixmap (dixLookupDrawable → BadDrawable, a window → - // BadPixmap; glxcmds.c:1198-1220, :1267-1280). Xorg compares - // neither the pixmap depth nor its visual with the config. - let glx_error = |state: &mut ServerState, code: u8, value: u32| { - emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(minor), - crate::nested::GLX_MAJOR_OPCODE, - ) - }; - let Some(req) = x11glx::parse_create_glx_pixmap(body) else { - return glx_error(state, x11::error::BAD_LENGTH, 0); - }; - let owned = state.clients.get(&client_id.0).is_some_and(|c| { - crate::server::IdAllocator::validate_owned( - req.glx_pixmap, - c.resource_id_base, - c.resource_id_mask, - ) - }); - if !owned || state.xid_occupied(req.glx_pixmap) { - return glx_error(state, x11::error::BAD_ID_CHOICE, req.glx_pixmap); - } - // yserver has exactly one screen (screenInfo.numScreens == 1). - if req.screen != 0 { - return glx_error(state, x11::error::BAD_MATCH, req.screen); - } - let Some(fbconfig) = glx_visual_fbconfig(req.visual) else { - return glx_error(state, x11::error::BAD_VALUE, req.visual); - }; - if state.resources.pixmap(ResourceId(req.pixmap)).is_none() { - let code = if state.resources.window(ResourceId(req.pixmap)).is_some() { - x11::error::BAD_PIXMAP - } else { - x11::error::BAD_DRAWABLE - }; - return glx_error(state, code, req.pixmap); - } - // Xorg never runs determineTextureTarget for the GLX 1.0 form, - // so the target stays 0 and GetDrawableAttributes reports - // GLX_TEXTURE_RECTANGLE_EXT (glxcmds.c:1896-1897). - insert_glx_pixmap_record( - state, - backend, - client_id, - req.glx_pixmap, - req.pixmap, - fbconfig, - x11glx::GLX_TEXTURE_RECTANGLE_EXT, - ); - debug!( - "client {} #{} GLX::CreateGLXPixmap glx_xid=0x{:x} x_pixmap=0x{:x} \ - visual=0x{:x} fbconfig=0x{fbconfig:x}", - client_id.0, sequence.0, req.glx_pixmap, req.pixmap, req.visual - ); - } - x11glx::DESTROY_GLX_PIXMAP => { - // GLX 1.0 glXDestroyGLXPixmap. Only a live GLX pixmap — created - // by either CreateGLXPixmap or CreatePixmap, which Xorg keeps as - // the same GLX_DRAWABLE_PIXMAP type — may be destroyed; any other - // XID is GLXBadPixmap (glx/vnd_dispatch_stubs.c:189-205, - // glxcmds.c validGlxDrawable / DoDestroyDrawable). - let Some(xid) = x11glx::parse_single_xid(body) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - crate::nested::GLX_MAJOR_OPCODE, - ); - }; - let is_glx_pixmap = state - .glx_drawables - .get(&xid) - .is_some_and(|d| d.kind == crate::server::GlxDrawableKind::Pixmap); - if !is_glx_pixmap { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR + x11glx::ERROR_GLX_BAD_PIXMAP, - xid, - u16::from(minor), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - // Release the export ref through the host xid stored at create - // time, never by re-resolving the X pixmap: it may already be - // freed (see the DESTROY_PIXMAP arm). - if let Some(record) = state.glx_drawables.remove(&xid) - && let Some(host_xid) = record.glx_export_host_xid - { - backend.release_glx_pixmap_export(host_xid); - } - debug!( - "client {} #{} GLX::DestroyGLXPixmap glx_xid=0x{xid:x}", - client_id.0, sequence.0 - ); - } - x11glx::DELETE_WINDOW | x11glx::DESTROY_PIXMAP | x11glx::DESTROY_PBUFFER => { - let xid = if body.len() >= 4 { - u32::from_le_bytes([body[0], body[1], body[2], body[3]]) - } else { - 0 - }; - // For DESTROY_PIXMAP: release the export-lifetime ref taken at - // CREATE_PIXMAP, using the host_xid resolved+stored at acquire - // time. Do NOT re-resolve via resources.pixmap(x_drawable) — the - // X pixmap may already be freed (FreePixmap-before-destroy), and - // re-resolution would return None and leak the ref forever. - let release_host_xid = if minor == x11glx::DESTROY_PIXMAP { - state - .glx_drawables - .get(&xid) - .and_then(|d| d.glx_export_host_xid) - } else { - None - }; - if let Some(host_xid) = release_host_xid { - backend.release_glx_pixmap_export(host_xid); - } - state.glx_drawables.remove(&xid); - // #96 tier-2: release the GPU pixmap that backed a pbuffer (allocated - // at CreatePbuffer under the pbuffer's own XID). - if minor == x11glx::DESTROY_PBUFFER - && let Some(pixmap) = state.resources.free_pixmap(ResourceId(xid)) - && let Some(host) = pixmap.host_xid - { - backend.free_pixmap(origin, host.as_raw())?; - } - debug!( - "client {} #{} GLX::DestroyDrawable minor={minor} glx_xid=0x{:x}", - client_id.0, sequence.0, xid - ); - } - x11glx::CHANGE_DRAWABLE_ATTRIBUTES => { - // body: [glx_drawable: u32][num_attribs: u32][attribs * (id, value)] - if body.len() >= 8 { - let xid = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - let num_attribs = u32::from_le_bytes([body[4], body[5], body[6], body[7]]) as usize; - if let Some(drawable) = state.glx_drawables.get_mut(&xid) { - // Xorg's ChangeDrawableAttributes is a switch with a - // single case: record GLX_EVENT_MASK, silently ignore - // everything else (glxcmds.c:1494-1503). - let mut p = 8; - for _ in 0..num_attribs { - if p + 8 > body.len() { - break; - } - let id = - u32::from_le_bytes([body[p], body[p + 1], body[p + 2], body[p + 3]]); - let val = u32::from_le_bytes([ - body[p + 4], - body[p + 5], - body[p + 6], - body[p + 7], - ]); - if id == x11glx::GLX_EVENT_MASK { - drawable.event_mask = val; - } - p += 8; - } - } - debug!( - "client {} #{} GLX::ChangeDrawableAttributes glx_xid=0x{:x} n={num_attribs}", - client_id.0, sequence.0, xid - ); - } - } - x11glx::GET_DRAWABLE_ATTRIBUTES => { - // body: [glx_drawable: u32]. Mirrors Xorg's four-way - // behaviour, where GLXVND is the front door: a registered - // GLX drawable gets the full reply; a naked X window (the - // GLX 1.2 pattern — Mesa's `pixmap_from_buffer` + - // `glXMakeCurrent(window, ctx)` queries the X window XID - // directly) gets the reply without the pGlxDraw block; a - // naked X pixmap is forwarded by GLXVND (pixmaps carry - // RC_DRAWABLE) but fails dixLookupWindow → GLXBadDrawable; - // an XID that is not a drawable at all never reaches - // DoGetDrawableAttributes → core BadDrawable - // (glx/vnd_dispatch_stubs.c:456-472, glxcmds.c:1873-1880). - let xid = if body.len() >= 4 { - u32::from_le_bytes([body[0], body[1], body[2], body[3]]) - } else { - 0 - }; - if !state.glx_drawables.contains_key(&xid) - && state.resources.window(ResourceId(xid)).is_none() - { - if state.resources.pixmap(ResourceId(xid)).is_some() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR + x11glx::ERROR_GLX_BAD_DRAWABLE, - xid, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - xid, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - let attribs = drawable_attributes_for(state, xid); - let reply = - x11glx::encode_get_drawable_attributes_reply(byte_order, sequence, &attribs); - debug!( - "client {} #{} GLX::GetDrawableAttributes glx_xid=0x{:x} -> {} attribs", - client_id.0, - sequence.0, - xid, - attribs.len() - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::SWAP_BUFFERS => { - // Direct-rendering clients route swaps through DRI3 + - // Present, never through indirect GLX SwapBuffers. Indirect - // clients hitting this path can't be served (no server-side - // GL), but a no-op (rather than an error) keeps silly - // clients limping along. - debug!( - "client {} #{} GLX::SwapBuffers (no-op)", - client_id.0, sequence.0 - ); - } - x11glx::QUERY_CONTEXT => { - // GLX 1.3 QueryContext, the request behind - // glXImportContextEXT (GLX_EXT_import_context, which, like Xorg - // without +iglx, we do not advertise). Xorg's DoQueryContext reports five - // attributes, in this order, for a live context of ANY client - // (glxcmds.c:1659-1708); an XID that is not a context is - // GLXBadContext (glx/vnd_dispatch_stubs.c:492-508). - let context = match glx_request_context(state, body) { - Ok(context) => context, - Err((code, value)) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(minor), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - }; - let ctx = &state.glx_contexts[&context]; - let attribs = [ - (x11glx::GLX_SHARE_CONTEXT_EXT, ctx.share_list), - (x11glx::GLX_VISUAL_ID, ctx.visual_id), - (x11glx::GLX_SCREEN, ctx.screen), - (x11glx::GLX_FBCONFIG_ID, ctx.fbconfig), - (x11glx::GLX_RENDER_TYPE, ctx.render_type), - ]; - let reply = x11glx::encode_query_context_reply(byte_order, sequence, &attribs); - debug!( - "client {} #{} GLX::QueryContext 0x{context:x} -> {attribs:x?}", - client_id.0, sequence.0 - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::VENDOR_PRIVATE | x11glx::VENDOR_PRIVATE_WITH_REPLY => { - // Dispatch known vendor codes; reject everything else with - // GLXUnsupportedPrivateRequest (modern Mesa direct-rendering - // never reaches this path). - // - // VendorPrivate body layout: - // [0..4] vendor_code (u32 LE) - // [4..8] context_tag (u32 LE, informational) - // [8..12] glx_drawable (u32 LE, GLXPixmap XID) - // [12..16] buffer (u32 LE, e.g. GLX_FRONT_LEFT_EXT) - let vendor_code = if body.len() >= 4 { - u32::from_le_bytes([body[0], body[1], body[2], body[3]]) - } else { - 0 - }; - match vendor_code { - x11glx::VENDOR_CODE_BIND_TEX_IMAGE => { - // glXBindTexImageEXT (indirect path, EXT completeness). - // Direct-context compositors (muffin) ride DRI3 and never - // hit this. For indirect contexts: resolve the GLXPixmap to - // its underlying X pixmap, ensure it is export-promoted - // (so any indirect GL texture sampling reads live content), - // and return success. BindTexImageEXT has no reply. - let glx_drawable = if body.len() >= 12 { - u32::from_le_bytes([body[8], body[9], body[10], body[11]]) - } else { - 0 - }; - debug!( - "client {} #{} GLX::BindTexImageEXT glx_drawable=0x{glx_drawable:x}", - client_id.0, sequence.0 - ); - if let Some(d) = state.glx_drawables.get(&glx_drawable) { - let x_drawable = d.x_drawable; - let stored_host_xid = d.glx_export_host_xid; - let current_host_xid = state - .resources - .pixmap(yserver_protocol::x11::ResourceId(x_drawable)) - .and_then(|p| p.host_xid.map(|h| h.as_raw())); - let host_xid_for_export = current_host_xid.or(stored_host_xid); - if let Some(current_host_xid) = current_host_xid - && stored_host_xid != Some(current_host_xid) - { - retarget_glx_pixmap_export( - state, - backend, - glx_drawable, - current_host_xid, - ); - } - // Ensure the backing is promoted to exportable storage so - // indirect GL texture sampling can read live content. - // - // CRITICAL: use promote_pixmap_exportable, NOT - // acquire_glx_pixmap_export. Bind is decoupled from the - // GLXPixmap LIFETIME refcount (glx_refs): TFP compositors - // rebind every frame / on damage (the spec allows rebind - // without an intervening release), so calling acquire here - // would grow glx_refs unboundedly and the backing would - // never tear down after glXDestroyPixmap. promote is - // idempotent (the engine short-circuits via is_exportable) - // and touches no refcount. The backing is already kept - // alive by glXCreatePixmap's acquire (glx_refs >= 1 until - // glXDestroyPixmap). - // - // TODO(glx-tfp): indirect texture *sampling* (serving - // glTexImage2D-equivalent data from the promoted backing) - // is not yet implemented; the bind succeeds so clients - // do not receive a protocol error, but the texture - // content will not be updated until indirect GL sampling - // is wired up. - if let Some(host_xid) = host_xid_for_export { - let _ = backend.promote_pixmap_exportable(host_xid); - } - // No reply for VENDOR_PRIVATE; for VENDOR_PRIVATE_WITH_REPLY - // send an empty success reply so the client does not block. - if minor == x11glx::VENDOR_PRIVATE_WITH_REPLY { - let reply = x11glx::encode_get_drawable_attributes_reply( - byte_order, - sequence, - &[], - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - } else { - debug!( - "client {} #{} GLX::BindTexImageEXT \ - glx_drawable=0x{glx_drawable:x} not found -> GLXBadPixmap", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR - + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP, - glx_drawable, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - } - x11glx::VENDOR_CODE_GET_FB_CONFIGS_SGIX => { - // glXGetFBConfigsSGIX (VendorPrivateWithReply, vendor - // code 65540). Proxied to synthesise_glx_fb_configs - // and encoded with the GLX 1.3 GetFBConfigsReply wire - // format — glxproto.h defines no separate SGIX reply - // struct; the extension reuses the same layout. - // - // Request body: - // [0..4] vendorCode (already read) - // [4..8] pad1 - // [8..12] screen — intentionally ignored (yserver is - // single-screen; configs are valid for any screen, - // same as the GLX 1.3 GET_FB_CONFIGS handler). - // GetFBConfigsSGIX is a reply-bearing call; if a malformed - // client sends it as plain VENDOR_PRIVATE (no reply expected) - // do NOT write a reply, or we desync its reply stream. - if minor != x11glx::VENDOR_PRIVATE_WITH_REPLY { - return Ok(RequestOutcome::Handled); - } - let configs = synthesise_glx_fb_configs(state.glx_tfp_supported); - let config_refs: Vec<&[(u32, u32)]> = - configs.iter().map(|c| c.as_slice()).collect(); - let reply = x11glx::encode_get_fb_configs_sgix_reply( - byte_order, - sequence, - &config_refs, - ); - debug!( - "client {} #{} GLX::GetFBConfigsSGIX -> {} configs × {} props", - client_id.0, - sequence.0, - config_refs.len(), - config_refs.first().map_or(0, |c| c.len()), - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - x11glx::VENDOR_CODE_CREATE_CONTEXT_WITH_CONFIG_SGIX => { - // glXCreateContextWithConfigSGIX (VendorPrivate, no - // reply, vendor code 65541). Proxied to the existing - // context-creation logic: insert a GlxContext record. - // - // Request body: - // [0..4] vendorCode - // [4..8] pad1 - // [8..12] context XID - // [12..16] fbconfig - // [16..20] screen - // [20..24] renderType - // [24..28] shareList - // [28] isDirect - // [29..32] reserved - if let Some(req) = x11glx::parse_create_context_with_config_sgix(body) { - state.glx_contexts.insert( - req.context, - crate::server::GlxContext { - owner: client_id, - screen: req.screen, - visual_id: glx_fbconfig_visual(req.fbconfig), - fbconfig: req.fbconfig, - render_type: req.render_type, - share_list: req.share_list, - is_direct: req.is_direct, - }, - ); - debug!( - "client {} #{} GLX::CreateContextWithConfigSGIX \ - xid=0x{:x} fbconfig=0x{:x}", - client_id.0, sequence.0, req.context, req.fbconfig - ); - } else { - debug!( - "client {} #{} GLX::CreateContextWithConfigSGIX \ - (body too short, parse failed)", - client_id.0, sequence.0 - ); - } - } - x11glx::VENDOR_CODE_CREATE_GLX_PIXMAP_WITH_CONFIG_SGIX => { - // glXCreateGLXPixmapWithConfigSGIX (VendorPrivate, no - // reply, vendor code 65542). Proxied to the existing - // CREATE_PIXMAP path: validate X pixmap, record the - // GlxDrawable, call acquire_glx_pixmap_export. - // - // Request body: - // [0..4] vendorCode - // [4..8] pad1 - // [8..12] screen - // [12..16] fbconfig - // [16..20] pixmap (X pixmap XID) - // [20..24] glxpixmap (GLXPixmap XID) - if let Some(req) = x11glx::parse_create_glx_pixmap_with_config_sgix(body) { - // Validate that the X pixmap exists. - if state - .resources - .pixmap(yserver_protocol::x11::ResourceId(req.pixmap)) - .is_none() - { - debug!( - "client {} #{} GLX::CreateGLXPixmapWithConfigSGIX \ - glx_xid=0x{:x} x_pixmap=0x{:x} not found -> GLXBadPixmap", - client_id.0, sequence.0, req.glx_pixmap, req.pixmap - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR - + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP, - req.pixmap, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - insert_glx_pixmap_record( - state, - backend, - client_id, - req.glx_pixmap, - req.pixmap, - req.fbconfig, - x11glx::GLX_TEXTURE_2D_EXT, - ); - - debug!( - "client {} #{} GLX::CreateGLXPixmapWithConfigSGIX \ - glx_xid=0x{:x} x_pixmap=0x{:x} fbconfig=0x{:x}", - client_id.0, sequence.0, req.glx_pixmap, req.pixmap, req.fbconfig - ); - } else { - debug!( - "client {} #{} GLX::CreateGLXPixmapWithConfigSGIX \ - (body too short, parse failed)", - client_id.0, sequence.0 - ); - } - } - x11glx::VENDOR_CODE_RELEASE_TEX_IMAGE => { - // glXReleaseTexImageEXT (indirect path, EXT completeness). - // - // CRITICAL: this is a LIFETIME no-op. It must NOT call - // release_glx_pixmap_export — that decrements the - // GLXPixmap's create-time lifetime ref (glx_refs), which - // glXDestroyPixmap owns. A release without a matching bind - // (or more releases than binds) would drive glx_refs to 0 - // and tear down the backing WHILE THE GLXPixmap IS STILL - // ALIVE. Release only ends the texture binding; since bind - // is promote-only (no refcount taken), there is nothing to - // undo here. The promoted storage stays promoted (cheap, - // and a likely-imminent rebind reuses it). Unknown GLXPixmap - // XIDs are silently ignored (no error — matches Xorg - // glx/glxcmds.c behaviour for stale release after destroy). - let glx_drawable = if body.len() >= 12 { - u32::from_le_bytes([body[8], body[9], body[10], body[11]]) - } else { - 0 - }; - debug!( - "client {} #{} GLX::ReleaseTexImageEXT glx_drawable=0x{glx_drawable:x} \ - (lifetime no-op)", - client_id.0, sequence.0 - ); - // No reply for VENDOR_PRIVATE; for VENDOR_PRIVATE_WITH_REPLY - // send an empty success reply. - if minor == x11glx::VENDOR_PRIVATE_WITH_REPLY { - let reply = - x11glx::encode_get_drawable_attributes_reply(byte_order, sequence, &[]); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &reply)); - } - } - _ => { - // All other vendor codes are unsupported. - debug!( - "client {} #{} GLX::VendorPrivate \ - vendor_code={vendor_code} (rejected: GLXUnsupportedPrivateRequest)", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR - + yserver_protocol::x11::glx::ERROR_GLX_UNSUPPORTED_PRIVATE_REQUEST, - 0, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - } - } - other => { - // Indirect-rendering opcodes 1..=198 + anything else we - // don't handle → GLXBadRequest. - debug!( - "client {} #{} GLX unsupported minor={other} -> GLXBadRequest", - client_id.0, sequence.0 - ); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - crate::nested::GLX_FIRST_ERROR - + yserver_protocol::x11::glx::ERROR_GLX_BAD_RENDER_REQUEST, - 0, - u16::from(header.data), - crate::nested::GLX_MAJOR_OPCODE, - ); - } - } - Ok(RequestOutcome::Handled) -} - -// ─── XI 1.x request validation (XTS XI scenario, the "Got Success, -// Expecting " family) ───────────────────────────────────────── -// -// XI extension error codes are offsets from the extension's first_error -// (157): BadDevice=+0, BadEvent=+1, BadMode=+2, DeviceBusy=+3, -// BadClass=+4 (XIproto.h). Error packets carry major=137 + the -// request's minor. -const XI1_ERROR_BAD_DEVICE: u8 = crate::nested::XI2_FIRST_ERROR; -const XI1_ERROR_BAD_MODE: u8 = crate::nested::XI2_FIRST_ERROR + 2; -const XI1_ERROR_BAD_CLASS: u8 = crate::nested::XI2_FIRST_ERROR + 4; - -/// Keycode range + pointer shape advertised by ListInputDevices / -/// XIQueryDevice (yserver-protocol `encode_list_input_devices_reply`: -/// KEY_MIN/KEY_MAX/NUM_BUTTONS/POINTER_AXES). Validation must agree -/// with what enumeration promised the client. -const XI1_KEY_MIN: u8 = 8; -const XI1_KEY_MAX: u8 = 255; -const XI1_NUM_BUTTONS: u8 = 7; -const XI1_POINTER_AXES: u8 = 4; -/// XIproto `UseXKeyboard` — the "default modifier device" sentinel -/// accepted wherever a modifier_device byte is taken. -const XI1_USE_X_KEYBOARD: u16 = 255; - -/// The fixed 4-device registry: 2 = master (core) pointer, 3 = master -/// (core) keyboard, 4 = slave/extension pointer, 5 = slave/extension -/// keyboard. Mirrors `crate::xinput::initial_xi_devices`. -fn xi1_device_valid(id: u16) -> bool { - (2..=5).contains(&id) -} - -/// The virtual core pointer (2) and keyboard (3) are the masters. -fn xi1_device_is_master(id: u16) -> bool { - matches!(id, 2 | 3) -} - -/// `XI2LASTEVENT` for XI 2.4 (`XI_GestureSwipeEnd`, XI2.h). -const XI2_LAST_EVENT: u32 = 32; - -/// Xorg `XICheckInvalidMaskBits` (Xi/xiselectev.c): the lowest set bit -/// above [`XI2_LAST_EVENT`] in an XI2 event mask (a bit array, bit n in -/// byte n/8), if any. -fn xi2_first_invalid_mask_bit(mask: &[u8]) -> Option { - mask.iter().enumerate().find_map(|(i, &byte)| { - let first_bit = u32::try_from(i * 8).ok()?; - (0..8u32) - .map(|b| first_bit + b) - .find(|&bit| bit > XI2_LAST_EVENT && byte & (1 << (bit - first_bit)) != 0) - }) -} - -/// Keyboards (3, 5) carry a KeyClass; pointers don't. -pub(crate) fn xi1_device_has_keys(id: u16) -> bool { - matches!(id, 3 | 5) -} - -/// Pointers (2, 4) carry Button + Valuator classes; keyboards don't. -pub(crate) fn xi1_device_has_buttons(id: u16) -> bool { - matches!(id, 2 | 4) -} - -pub(crate) fn xi1_device_has_valuators(id: u16) -> bool { - matches!(id, 2 | 4) -} - -/// Core grab-modifier validity: any combination of the 8 modifier -/// masks, or AnyModifier (0x8000) alone. -fn xi1_modifiers_valid(modifiers: u16) -> bool { - modifiers == 0x8000 || modifiers & !0x00ff == 0 -} - -/// XI 1.x event classes pack the device id in the upper byte -/// (`deviceid << 8 | event_offset`). -fn xi1_event_class_device(class: u32) -> u16 { - u16::try_from((class >> 8) & 0xff).unwrap_or(u16::MAX) -} - -/// Standard 32-byte all-zero XI1 reply (status/count fields read as -/// Success / empty in every minor's reply layout). -fn xi1_zero_reply( - byte_order: yserver_protocol::x11::ClientByteOrder, - sequence: SequenceNumber, -) -> Vec { - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.extend_from_slice(&[0u8; 24]); - reply -} - -/// Emit an X error for an XI 1.x request: major = 137, minor = the -/// request's minor opcode. -fn xi1_error( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - code: u8, - value: u32, - minor: u8, -) -> io::Result { - emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(minor), - XI2_MAJOR_OPCODE, - ) -} - -fn xi1_window_exists(state: &ServerState, xid: u32) -> bool { - state.resources.window(ResourceId(xid)).is_some() -} - -fn motion_history_range( - state: &ServerState, - start: u32, - stop: u32, -) -> Vec { - let now = state.timestamp_now(); - let start = if start == 0 { now } else { start }; - let stop = if stop == 0 { now } else { stop.min(now) }; - if start > stop || start > now { - return Vec::new(); - } - state - .pointer_motion_history - .iter() - .copied() - .filter(|record| (start..=stop).contains(&record.time)) - .collect() -} - -/// Collect the set of XI1 clients receiving a `SendExtensionEvent` -/// dispatched to `dest_window`. Implements Xorg -/// `Xi/exevents.c::SendEvent` (xserver.git:2952-2965) selection + -/// propagation, with two simplifications from the canonical path: -/// -/// - per-window per-device do-not-propagate-mask is not yet modelled -/// (xts5 SendEvent 11/12 leave it empty), so the walk doesn't -/// trim classes as it ascends; -/// - `propagate` doesn't honour the `effectiveFocus` stop when -/// `dest_window` was resolved via `InputFocus` (the per-test -/// coverage there is XTS purposes 7-10, which all use -/// propagate=False). -/// -/// `mask_is_zero` reflects the `CreateMaskFromList` result: empty -/// when the only class in the list is `noextensioneventclass` -/// (`_noExtensionEvent = 9`). On a zero mask, delivery falls through -/// to the window's creator — Xorg's `DeliverToWindowOwner` short- -/// circuit on `filter == CantBeFiltered`. -fn xi1_send_extension_event_resolve_targets( - state: &ServerState, - dest_window: ResourceId, - request_classes: &[u32], - mask_is_zero: bool, - propagate: bool, -) -> std::collections::HashSet { - let mut current = dest_window; - // The active class set shrinks as the walk crosses windows whose - // do-not-propagate-list bans a class (Xorg - // `wOtherInputMasks(pWin)->dontPropagateMask[d->id]`). When the - // remaining set is empty, propagation stops without delivery — - // xts5 XSendExtensionEvent-8. - let mut active: std::collections::HashSet = request_classes.iter().copied().collect(); - for _ in 0..256 { - let mut targets: std::collections::HashSet = std::collections::HashSet::new(); - if mask_is_zero { - if let Some(owner) = state.resources.window_owner(current) { - targets.insert(owner); - } - } else { - for (cid, c) in &state.clients { - if let Some(set) = c.xi1_window_event_classes.get(¤t) - && active.iter().any(|cl| set.contains(cl)) - { - targets.insert(ClientId(*cid)); - } - } - } - if !targets.is_empty() || !propagate { - return targets; - } - // No selector at `current` — apply this window's - // do-not-propagate list to the active class set before walking - // up, then move to the parent. - if let Some(blocked) = state.xi1_window_dont_propagate.get(¤t) { - active.retain(|c| !blocked.contains(c)); - if active.is_empty() { - return std::collections::HashSet::new(); - } - } - match state.resources.parent_of(current) { - Some(parent) if parent != current => current = parent, - _ => return std::collections::HashSet::new(), - } - } - std::collections::HashSet::new() -} - -/// XIWarpPointer (XI 2.0 minor 41) — Xorg `ProcXIWarpPointer` -/// (Xi/xiwarppointer.c): core WarpPointer for one device, with FP16.16 -/// coordinates. Only a master pointer or a floating slave may be warped; -/// yserver's only candidate is the master pointer (2), whose sprite is the -/// core one, so this runs the core warp path with the XI source-rectangle -/// rule. -fn handle_xi_warp_pointer( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - // Length is gated to exactly 9 units above, so the body is 32 bytes. - let u32_at = |o: usize| u32::from_le_bytes([body[o], body[o + 1], body[o + 2], body[o + 3]]); - let fp1616_pixels = |o: usize| u32_at(o).cast_signed() / 65536; - let u16_at = |o: usize| u16::from_le_bytes([body[o], body[o + 1]]); - let deviceid = u16_at(28); - if deviceid != crate::xinput::DEVICEID_MASTER_POINTER { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(deviceid), - 41, - ); - } - let req = WarpRequest { - src: ResourceId(u32_at(0)), - dst: ResourceId(u32_at(4)), - src_x: fp1616_pixels(8), - src_y: fp1616_pixels(12), - src_w: u16_at(16), - src_h: u16_at(18), - dst_x: fp1616_pixels(20), - dst_y: fp1616_pixels(24), - }; - if let Some(bad) = warp_pointer_bad_window(state, &req) { - return xi1_error(state, client_id, sequence, x11::error::BAD_WINDOW, bad, 41); - } - if warp_pointer_src_allows(state, &req, WarpSrcRule::XInput2) { - apply_pointer_warp(state, backend, origin, &req); - } - debug!( - "client {} #{} XIWarpPointer dst=0x{:x} ({}, {})", - client_id.0, sequence.0, req.dst.0, req.dst_x, req.dst_y - ); - Ok(RequestOutcome::Handled) -} - -/// XISetFocus (XI 2.0 minor 49) — Xorg `ProcXISetFocus` -/// (Xi/xisetdevfocus.c): `SetInputFocus(dev, focus, RevertToParent, -/// time, followOK=TRUE)` on a device with a focus class, i.e. a keyboard. -/// Pointers and unknown ids are BadDevice (Xorg sets no errorValue). -/// -/// The master keyboard's focus is the core focus, so device 3 runs core -/// SetInputFocus. The slave keyboard (5) keeps its own focus -/// (`xi1_device_focus`, shared with XI1 SetDeviceFocus) and may follow -/// the keyboard. FollowKeyboard on the master keyboard itself would make -/// it follow itself: Xorg stores `FollowKeyboardWin` and then crashes -/// dereferencing it (Xvfb 21.1.24 segfaults at address 0x7), so yserver -/// answers BadValue instead. -fn handle_xi_set_focus( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - use crate::core_loop::xi1_focus; - const MINOR: u8 = 49; - // Length is gated to at least 4 units above. - let focus = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - let req_time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let deviceid = u16::from_le_bytes([body[8], body[9]]); - if !xi1_device_has_keys(deviceid) { - return xi1_error(state, client_id, sequence, XI1_ERROR_BAD_DEVICE, 0, MINOR); - } - let revert_to = xi1_focus::REVERT_TO_PARENT; - if deviceid == crate::xinput::DEVICEID_MASTER_KEYBOARD { - if focus == xi1_focus::FOCUS_FOLLOW_KEYBOARD { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - focus, - MINOR, - ); - } - if let Some((code, value)) = core_focus_window_error(state, ResourceId(focus)) { - return xi1_error(state, client_id, sequence, code, value, MINOR); - } - apply_core_input_focus( - state, - client_id, - sequence, - ResourceId(focus), - revert_to, - req_time, - ); - return Ok(RequestOutcome::Handled); - } - if focus != xi1_focus::FOCUS_FOLLOW_KEYBOARD - && let Some((code, value)) = core_focus_window_error(state, ResourceId(focus)) - { - return xi1_error(state, client_id, sequence, code, value, MINOR); - } - // Timestamp gate (dix/events.c:4920-4922), as XI1 SetDeviceFocus. - let now = state.timestamp_now(); - let time = if req_time == 0 { now } else { req_time }; - let prev = xi1_focus::device_focus(state, deviceid); - if xi1_focus::time_after(time, now) || xi1_focus::time_after(prev.time, time) { - debug!( - "client {} #{} XISetFocus device={deviceid} stale time {time} \ - (now={now} last={}) — ignored", - client_id.0, sequence.0, prev.time - ); - return Ok(RequestOutcome::Handled); - } - xi1_focus::set_device_focus(state, deviceid, focus, revert_to, time); - debug!( - "client {} #{} XISetFocus device={deviceid} focus=0x{focus:x}", - client_id.0, sequence.0 - ); - Ok(RequestOutcome::Handled) -} - -/// XIChangeHierarchy (XI 2.0 minor 43) — Xorg `ProcXIChangeHierarchy` -/// (Xi/xichangehierarchy.c) over yserver's fixed device set: masters 2/3 -/// (the virtual core pair) and one fixed slave each (4/5). -/// -/// The change list is walked exactly as Xorg walks it — same length -/// checks, unknown change types skipped, processing stops at the first -/// failing change — and every change gets the answer Xorg gives for the -/// same devices: -/// - RemoveMaster: return_mode must be Float/AttachToMaster (BadValue); -/// the virtual core pair can never be removed (BadDevice), and a slave -/// is not a master (BadDevice, errorValue = id). -/// - AttachSlave / DetachSlave: masters are BadDevice (errorValue = id); -/// yserver's slaves are fixed, which Xorg answers for its own fixed -/// slaves (the XTest devices, ids 4/5 on Xvfb) with BadDevice, -/// errorValue = id. -/// - AddMaster: Xorg creates a new pair; yserver can't add devices, so it -/// gives Xorg's answer when no device can be allocated (BadAlloc). -/// -/// Unknown device ids are BadDevice with errorValue 0 (dixLookupDevice -/// sets none). No change ever succeeds, so no HierarchyChanged event is -/// sent. The change records are opaque to the request swapper and are -/// read in the client's byte order (Xorg swaps only type/length/name_len -/// and reads the device ids unswapped — for a big-endian client on a -/// little-endian server that only changes the errorValue of the same -/// BadDevice error). -fn handle_xi_change_hierarchy( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - byte_order: yserver_protocol::x11::ClientByteOrder, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::ClientByteOrder; - const MINOR: u8 = 43; - const ADD_MASTER: u16 = 1; - const REMOVE_MASTER: u16 = 2; - const ATTACH_SLAVE: u16 = 3; - const DETACH_SLAVE: u16 = 4; - const ATTACH_TO_MASTER: u8 = 1; - const FLOATING: u8 = 2; - let rd16 = |o: usize| { - let b = [body[o], body[o + 1]]; - match byte_order { - ClientByteOrder::LittleEndian => u16::from_le_bytes(b), - ClientByteOrder::BigEndian => u16::from_be_bytes(b), - } - }; - let fail = |state: &mut ServerState, code: u8, value: u32| { - xi1_error(state, client_id, sequence, code, value, MINOR) - }; - // Length is gated to at least 2 units above: num_changes + pad. - let num_changes = body[0]; - let mut pos = 4usize; - for _ in 0..num_changes { - let len = body.len() - pos; - if len < 4 { - return fail(state, x11::error::BAD_LENGTH, 0); - } - let change_type = rd16(pos); - let change_bytes = usize::from(rd16(pos + 2)) * 4; - if len < change_bytes { - return fail(state, x11::error::BAD_LENGTH, 0); - } - // CHANGE_SIZE_MATCH: fixed-size records must state their own size. - let size_matches = |size: usize| len >= size && change_bytes == size; - match change_type { - ADD_MASTER => { - if len < 8 || usize::from(rd16(pos + 4)) > len - 8 { - return fail(state, x11::error::BAD_LENGTH, 0); - } - return fail(state, x11::error::BAD_ALLOC, 0); - } - REMOVE_MASTER => { - if !size_matches(12) { - return fail(state, x11::error::BAD_LENGTH, 0); - } - let return_mode = body[pos + 6]; - if return_mode != ATTACH_TO_MASTER && return_mode != FLOATING { - return fail(state, x11::error::BAD_VALUE, 0); - } - let deviceid = rd16(pos + 4); - // A slave is "not a master" (errorValue = id); the virtual - // core pair can't be removed and unknown ids don't exist - // (Xorg sets no errorValue for either). - let value = if xi1_device_valid(deviceid) && !xi1_device_is_master(deviceid) { - u32::from(deviceid) - } else { - 0 - }; - return fail(state, XI1_ERROR_BAD_DEVICE, value); - } - ATTACH_SLAVE | DETACH_SLAVE => { - if !size_matches(8) { - return fail(state, x11::error::BAD_LENGTH, 0); - } - let deviceid = rd16(pos + 4); - // Masters and the fixed slaves report their id; unknown - // ids report 0. - let value = if xi1_device_valid(deviceid) { - u32::from(deviceid) - } else { - 0 - }; - return fail(state, XI1_ERROR_BAD_DEVICE, value); - } - _ => {} - } - pos += change_bytes; - } - debug!( - "client {} #{} XIChangeHierarchy: {num_changes} change(s), nothing to do", - client_id.0, sequence.0 - ); - Ok(RequestOutcome::Handled) -} - -fn handle_xi2_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::ClientByteOrder; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - // Per-minor length validation mirroring Xorg's `REQUEST_SIZE_MATCH` / - // `REQUEST_AT_LEAST_SIZE` macros invoked at the top of each `ProcX*` - // handler in `xserver/Xi/*.c`. xts5 XIproto probes under-/over-length - // headers for every XI minor and expects core `BadLength` (code 16), - // not the extension-level `BadDevice` the handlers would otherwise - // produce after mis-parsing the truncated/extended body. The XI - // `minor_opcode` is also stamped into the error reply so the test - // harness can attribute the failure. - if !x11::request_lengths::validate_xi_request_length(minor, header.length_units) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - // Content-derived exact-length check for variable-length minors. - // xts5 probes both `length-1` and `length+1`; the AtLeast gate - // catches the under-length case while this gate catches the - // over-length one. - if !x11::request_lengths::validate_xi_exact_request_length(minor, header.length_units, body) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - let mut buf: Vec = Vec::with_capacity(64); - match minor { - 1 => { - // XI GetExtensionVersion, as Xorg's ProcXGetExtensionVersion - // (Xi/getvers.c): the length must match `nbytes`, and the reply - // is the server's XI version (XIVersion, 2.4) with RepType = - // X_GetExtensionVersion. libXi reads this version to decide - // whether XI 2.2 fields (a raw event's sourceid) are valid. - debug!( - "client {} #{} XIGetExtensionVersion", - client_id.0, sequence.0 - ); - let nbytes = body - .get(0..2) - .map_or(0, |b| usize::from(u16::from_le_bytes([b[0], b[1]]))); - if usize::try_from(header.length_units).ok() != Some((8 + nbytes).div_ceil(4)) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - 1, - XI2_MAJOR_OPCODE, - ); - } - let mut reply = x11::fixed_reply(byte_order, sequence, 1, 0); - x11::write_u16(byte_order, &mut reply, XI2_SERVER_MAJOR_VERSION); - x11::write_u16(byte_order, &mut reply, XI2_SERVER_MINOR_VERSION); - reply.push(1); - reply.extend_from_slice(&[0; 19]); - buf.extend_from_slice(&reply); - } - 42 => { - // XIChangeCursor (XI2 opcode 42). Wire body after the - // request header: window(4), cursor(4), deviceid(2), pad(2). - // GTK4 (gnome-text-editor, modern GTK apps) sets per-widget - // cursors via this rather than core `XDefineCursor`, so - // pre-fix the I-beam never reached the backend and text - // areas kept showing the default arrow. Treat it as - // `XDefineCursor` for now — yserver doesn't yet route - // per-device cursors, but a single effective cursor on the - // window matches what XInput2 produces for AllMasterDevices - // and is what GTK relies on in practice. `cursor = None` - // (xid 0) means "clear" — same semantics as the CWA cursor - // path, see Xorg `dix/window.c:1487-1491`. - if body.len() < 8 { - debug!( - "client {} #{} XIChangeCursor (body too short: {})", - client_id.0, - sequence.0, - body.len() - ); - return Ok(RequestOutcome::Handled); - } - let window = ResourceId(u32::from_le_bytes(body[0..4].try_into().expect("4 bytes"))); - let cursor = ResourceId(u32::from_le_bytes(body[4..8].try_into().expect("4 bytes"))); - let host_window_raw = if window == ROOT_WINDOW { - Some(backend.window_id()) - } else { - state - .resources - .window(window) - .and_then(|w| w.host_xid) - .map(|h| h.as_raw()) - }; - let cursor_host_xid = if cursor.0 == 0 { - Some(0u32) - } else { - state.resources.cursor_host_xid(cursor) - }; - debug!( - "client {} #{} XIChangeCursor window=0x{:x} cursor=0x{:x}", - client_id.0, sequence.0, window.0, cursor.0 - ); - if let (Some(hw), Some(ch)) = (host_window_raw, cursor_host_xid) { - let _ = backend.define_cursor(origin, hw, ch); - } - return Ok(RequestOutcome::Handled); - } - 44 => { - debug!("client {} #{} XISetClientPointer", client_id.0, sequence.0); - return Ok(RequestOutcome::Handled); - } - 45 => { - // XIGetClientPointer reply layout (xXIGetClientPointerReply, - // X11/extensions/XI2proto.h): - // response_type(1) | pad0(1) | sequence(2) | length(4) - // | set:BOOL(1) | pad0(1) | deviceid(2) | pad1..5(20) - // Total = 32 bytes. NOTE: deviceid sits at byte 10 — only - // ONE pad byte follows `set`. Writing 3 pad bytes here pushed - // deviceid to byte 12, so clients read 0 (broke nemo's - // desktop rubber-band, which looks up its pointer device via - // this reply). - // - // Must reply `set=True`: libXi's `XIGetClientPointer` - // only writes the caller's `*deviceid` out-parameter - // when `reply.set == True`. With `set=False` it returns - // False and leaves the caller's variable uninitialized, - // which GDK then passes verbatim to `g_hash_table_lookup` - // on its device id_table — looking up garbage returns - // NULL, so GDK assigns `device=NULL` to any synthetic - // core ButtonPress/ButtonRelease/MotionNotify from - // XSendEvent (gdkdevicemanager-xi2.c::translate_event - // calls `get_client_pointer` to attribute the device), - // and the next `proxy_button_event` SEGVs at - // `pointer_info->toplevel_under_pointer`. mate-panel - // dies on every workspace-switch click because wnck-applet - // SendEvents a synthetic ButtonRelease into the panel - // when activating a workspace. - debug!( - "client {} #{} XIGetClientPointer -> set=1 deviceid=2", - client_id.0, sequence.0 - ); - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.push(1); // byte 8: set = True - reply.push(0); // byte 9: pad0 - // bytes 10-11: deviceid = master pointer (2). - x11::write_u16(byte_order, &mut reply, 2); - reply.extend_from_slice(&[0u8; 20]); // bytes 12-31: pad1..5 - debug_assert_eq!(reply.len(), 32); - buf.extend_from_slice(&reply); - } - 46 => { - debug!("client {} #{} XISelectEvents", client_id.0, sequence.0); - let mut send_device_changed_bootstrap = false; - if body.len() >= 8 { - let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let num_masks = u16::from_le_bytes([body[4], body[5]]) as usize; - // Xorg ProcXISelectEvents checks every mask before - // setting any, so a rejected request changes nothing. - let mut masks: Vec<(u16, u64)> = Vec::with_capacity(num_masks); - let mut pos = 8; - for _ in 0..num_masks { - if pos + 4 > body.len() { - break; - } - let deviceid = u16::from_le_bytes([body[pos], body[pos + 1]]); - let mask_len = u16::from_le_bytes([body[pos + 2], body[pos + 3]]) as usize; - pos += 4; - let byte_len = mask_len.saturating_mul(4); - if pos + byte_len > body.len() { - break; - } - let mask_bytes = &body[pos..pos + byte_len]; - // XICheckInvalidMaskBits: a bit past XI2LASTEVENT is - // BadValue with the bit number as errorValue. - if let Some(bit) = xi2_first_invalid_mask_bit(mask_bytes) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - bit, - 46, - header.opcode, - ); - } - // The mask is a bit array (bit n in byte n/8), so the - // bytes are little-endian whatever the client order. - let mut word = [0u8; 8]; - let keep = byte_len.min(8); - word[..keep].copy_from_slice(&mask_bytes[..keep]); - masks.push((deviceid, u64::from_le_bytes(word))); - pos += byte_len; - } - if let Some(client) = state.clients.get_mut(&client_id.0) { - for (deviceid, mask) in masks { - debug!( - "client {} XISelectEvents window=0x{:x} deviceid={} mask=0x{:x}", - client_id.0, window.0, deviceid, mask - ); - if mask == 0 { - client.xi2_masks.remove(&(window, deviceid)); - } else { - client.xi2_masks.insert((window, deviceid), mask); - if window == ROOT_WINDOW - && matches!(deviceid, 0..=2) - && (mask & u64::from(XI2_DEVICE_CHANGED_MASK)) != 0 - { - send_device_changed_bootstrap = true; - } - } - } - } - } - if send_device_changed_bootstrap { - emit_xi2_device_changed_bootstrap( - state, - backend, - origin, - client_id, - sequence, - XI2_MAJOR_OPCODE, - )?; - } - return Ok(RequestOutcome::Handled); - } - 47 => { - debug!("client {} #{} XIQueryVersion", client_id.0, sequence.0); - let requested_major = body - .get(0..2) - .map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]])) - .unwrap_or(0); - let requested_minor = body - .get(2..4) - .map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]])) - .unwrap_or(0); - if requested_major < 2 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(requested_major), - 47, - XI2_MAJOR_OPCODE, - ); - } - let (reply_major, reply_minor) = if (requested_major, requested_minor) - < (XI2_SERVER_MAJOR_VERSION, XI2_SERVER_MINOR_VERSION) - { - (requested_major, requested_minor) - } else { - (XI2_SERVER_MAJOR_VERSION, XI2_SERVER_MINOR_VERSION) - }; - record_xi2_client_version(state, client_id, (reply_major, reply_minor)); - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - x11::write_u16(byte_order, &mut reply, reply_major); - x11::write_u16(byte_order, &mut reply, reply_minor); - reply.extend_from_slice(&[0; 20]); - buf.extend_from_slice(&reply); - } - 48 => { - // XIQueryDevice. Class type ids per XI2: - // 0=Key, 1=Button, 2=Valuator, 3=Scroll. - // ATOM=0 (None) is spec-legal for unlabeled buttons/axes — - // GDK falls back to a default string. Length fields are in - // 4-byte units and include the 8-byte class header (type + - // length + sourceid + a class-specific u16). - debug!("client {} #{} XIQueryDevice", client_id.0, sequence.0); - let le = ClientByteOrder::LittleEndian; - let pointer = ( - i32::from(state.randr.screen_width) / 2, - i32::from(state.randr.screen_height) / 2, - ); - let button_labels = [ - state.atoms.intern("Button Left", false), - state.atoms.intern("Button Middle", false), - state.atoms.intern("Button Right", false), - state.atoms.intern("Button Wheel Up", false), - state.atoms.intern("Button Wheel Down", false), - state.atoms.intern("Button Horiz Wheel Left", false), - state.atoms.intern("Button Horiz Wheel Right", false), - ]; - let axis_labels = [ - state.atoms.intern("Rel X", false), - state.atoms.intern("Rel Y", false), - state.atoms.intern("Rel Vert Scroll", false), - state.atoms.intern("Rel Horiz Scroll", false), - ]; - - // Device names come from the XI2 registry (`state.xi_devices`) - // so a seeded touchpad's real name is reported, and so the XI1 - // `XListInputDevices` reply (which reads the SAME registry) - // can never disagree (the ListInputDevices fatal-CHECK class). - // Snapshot to owned Strings up front: the registry borrow must - // end before `infos`/`classes` are populated below. - let name_master_pointer = crate::xinput::device_name(&state.xi_devices, 2).to_owned(); - let name_master_keyboard = crate::xinput::device_name(&state.xi_devices, 3).to_owned(); - let name_slave_pointer = crate::xinput::device_name(&state.xi_devices, 4).to_owned(); - let name_slave_keyboard = crate::xinput::device_name(&state.xi_devices, 5).to_owned(); - - fn write_button_class(buf: &mut Vec, sourceid: u16, label_atoms: &[AtomId]) { - let le = ClientByteOrder::LittleEndian; - let num_buttons = u16::try_from(label_atoms.len()).unwrap_or(u16::MAX); - let state_words = num_buttons.div_ceil(32) as usize; - let byte_len = 8 + 4 * state_words + 4 * num_buttons as usize; - let units = byte_len / 4; - x11::write_u16(le, buf, 1); // type = Button - x11::write_u16(le, buf, units as u16); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, num_buttons); - buf.extend(std::iter::repeat_n(0u8, 4 * state_words)); - for atom in label_atoms { - x11::write_u32(le, buf, atom.0); - } - } - - fn write_valuator_class( - buf: &mut Vec, - sourceid: u16, - number: u16, - label_atom: AtomId, - min_int: i32, - max_int: i32, - mode: u8, - value: i32, - ) { - let le = ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, 2); // type = Valuator - x11::write_u16(le, buf, 11); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, number); - x11::write_u32(le, buf, label_atom.0); - x11::write_u32(le, buf, min_int as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, max_int as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, value as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, 0); // resolution - buf.push(mode); - buf.extend_from_slice(&[0u8; 3]); // pad - } - - // Scroll class: declares one of the device's valuators as - // a scroll axis. Length is 6 4-byte units (24 bytes). - // `number` references the valuator class; `scroll_type`: - // 1 = Vertical, 2 = Horizontal. Increment is 1.0 (one - // logical click per unit), matching our button-4/5 - // synthesis at v120 boundaries. - fn write_scroll_class(buf: &mut Vec, sourceid: u16, number: u16, scroll_type: u16) { - let le = ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, 3); // type = Scroll - x11::write_u16(le, buf, 6); // length = 6 units = 24 bytes - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, number); - x11::write_u16(le, buf, scroll_type); - x11::write_u16(le, buf, 0); // pad - // Flags: 0 (no NoEmulation, no Preferred). yserver - // emits BOTH the XI_Motion-with-scroll-axis update AND - // the legacy XI_ButtonPress/Release(4..7), with the - // `XIPointerEmulated` flag set on the latter (see - // `pointer_fanout` + `XI_POINTER_EMULATED`). This - // matches Xorg's modesetting/evdev declaration: the - // device class advertises "I emit emulated button - // events too," and clients use the per-event - // PointerEmulated flag to discard them after consuming - // the smooth-scroll Motion. - // - // Setting `NoEmulation` here while still emitting - // XI_ButtonPress(4..7) is a contract violation that - // crashed release Chrome on bee (Chrome's input - // dispatcher trusts the class declaration; receiving - // an event the class says can never come hits an - // internal invariant). Fixed 2026-05-29. - x11::write_u32(le, buf, 0); // flags = 0 - // FP3232 increment = 1.0 → (1, 0) - x11::write_u32(le, buf, 1); - x11::write_u32(le, buf, 0); - } - - fn write_key_class(buf: &mut Vec, sourceid: u16) { - let le = ClientByteOrder::LittleEndian; - // Header(8) + num_keycodes(implicit via pad u16 slot...) — - // actually: header = type+length+sourceid+num_keycodes (8B). - // Body = num_keycodes * CARD32 keycodes. - // X11 keycodes 8..=255 (248 of them) — matches the - // min_keycode/max_keycode advertised in the setup reply. - const NUM_KEYCODES: u16 = 248; - let body_bytes = 4 * NUM_KEYCODES as usize; - let units = (8 + body_bytes) / 4; - x11::write_u16(le, buf, 0); // type = Key - x11::write_u16(le, buf, units as u16); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, NUM_KEYCODES); - for kc in 8u32..=255 { - x11::write_u32(le, buf, kc); - } - } - - fn write_device_info( - buf: &mut Vec, - deviceid: u16, - use_type: u16, - attachment: u16, - name: &str, - classes: &[u8], - num_classes: u16, - ) { - let le = ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, deviceid); - x11::write_u16(le, buf, use_type); - x11::write_u16(le, buf, attachment); - x11::write_u16(le, buf, num_classes); - x11::write_u16(le, buf, name.len() as u16); - buf.push(1); // enabled - buf.push(0); // pad - buf.extend_from_slice(name.as_bytes()); - x11::pad_vec4(buf); - buf.extend_from_slice(classes); - } - - let mut infos = Vec::new(); - - // Master Pointer (deviceid=2): - // Button(7) + Valuator(0 X Absolute) + Valuator(1 Y - // Absolute) + Valuator(2 vscroll Relative) + Valuator(3 - // hscroll Relative) + Scroll(2 Vertical) + Scroll(3 - // Horizontal). - // - // Earlier attempt `20fd361` declared the Scroll classes - // referencing axes 2/3 but only declared valuators 0/1 — - // GDK's `_gdk_x11_device_xi2_add_scroll_valuator` asserts - // `scroll_number < n_axes`, firing Gdk-CRITICAL on every - // GTK startup. That regression was reverted in `e690ca0`. - // This time the scroll valuators ARE declared, so GDK - // registers them as scroll axes and processes wheel input - // through its modern path instead of the legacy - // button-4/5 fallback (which left caja / appearance - // settings ignoring the wheel until a view-switch). - { - let deviceid: u16 = 2; - let name = name_master_pointer.as_str(); - let mut classes = Vec::new(); - write_button_class(&mut classes, deviceid, &button_labels); - write_valuator_class( - &mut classes, - deviceid, - 0, - axis_labels[0], - -1, - -1, - 0, - pointer.0, - ); - write_valuator_class( - &mut classes, - deviceid, - 1, - axis_labels[1], - -1, - -1, - 0, - pointer.1, - ); - write_valuator_class( - &mut classes, - deviceid, - 2, - axis_labels[2], - -1, - 0, - 0, - state.scroll_axis_value[0], - ); - write_valuator_class( - &mut classes, - deviceid, - 3, - axis_labels[3], - -1, - 0, - 0, - state.scroll_axis_value[1], - ); - write_scroll_class(&mut classes, deviceid, 2, 1); // vertical - write_scroll_class(&mut classes, deviceid, 3, 2); // horizontal - write_device_info(&mut infos, deviceid, 1, 3, name, &classes, 7); - } - - // Master Keyboard (deviceid=3): Key with keycodes 8..=255. - { - let deviceid: u16 = 3; - let name = name_master_keyboard.as_str(); - let mut classes = Vec::new(); - write_key_class(&mut classes, deviceid); - write_device_info(&mut infos, deviceid, 2, 2, name, &classes, 1); - } - - // Attached slave devices. GTK/GDK builds its seat/device - // tables from the XI2 master/slave hierarchy and also - // probes the first slave pointer for libinput-ish - // properties. Device 4 therefore needs to look like a - // generic attached pointer, not like XTEST. - { - let deviceid: u16 = 4; - // Name from the XI2 registry: a seeded touchpad reports its - // real libinput name here; the XI1 ListInputDevices encoder - // reads the same source so the two enumerations agree. - let name = name_slave_pointer.as_str(); - // Device 4's class block is built by the SINGLE shared - // builder in `fanout` so this reply and the touchpad - // add/remove XI_DeviceChanged event can never drift - // (asserted byte-identical by - // `query_device_4_matches_device_changed_block`). The - // local `write_*_class` helpers above are still used by - // devices 2/3/5, which have different shapes. - let (classes, num_classes) = - crate::core_loop::fanout::build_slave_pointer_class_block(state); - write_device_info(&mut infos, deviceid, 3, 2, name, &classes, num_classes); - } - - { - let deviceid: u16 = 5; - let name = name_slave_keyboard.as_str(); - let mut classes = Vec::new(); - write_key_class(&mut classes, deviceid); - write_device_info(&mut infos, deviceid, 4, 3, name, &classes, 1); - } - - let mut reply = x11::fixed_reply( - byte_order, - sequence, - 0, - x11::checked_units(infos.len())? as u32, - ); - x11::write_u16(le, &mut reply, 4); // num_devices - reply.extend_from_slice(&[0; 22]); - reply.extend_from_slice(&infos); - buf.extend_from_slice(&reply); - } - 56 => { - // XIListProperties (xXIListPropertiesReq, XI2proto.h:742-749). - // body[0..2] = deviceid, body[2..4] = pad. - if body.len() < 2 { - return Ok(RequestOutcome::Handled); - } - let deviceid = u16::from_le_bytes([body[0], body[1]]); - debug!( - "client {} #{} XIListProperties deviceid={}", - client_id.0, sequence.0, deviceid - ); - let Some(device) = crate::xinput::find_device(&state.xi_devices, deviceid) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 56, - XI2_MAJOR_OPCODE, - ); - }; - buf.extend_from_slice(&crate::xinput::encode_list_properties_reply( - byte_order, sequence, device, - )); - } - 57 => { - // XIChangeProperty (xXIChangePropertyReq, XI2proto.h:769-780). - // Header struct: deviceid(2), mode(1), format(1), property(4), - // type(4), num_items(4); after stripping the 4-byte generic - // header `body` begins at deviceid: - // body[0..2] deviceid, body[2] mode, body[3] format, - // body[4..8] property, body[8..12] type, - // body[12..16] num_items, body[16..] value bytes. - if body.len() < 16 { - return Ok(RequestOutcome::Handled); - } - let deviceid = u16::from_le_bytes([body[0], body[1]]); - let mode = body[2]; - let format = body[3]; - let property = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let type_atom = AtomId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let num_items = u32::from_le_bytes([body[12], body[13], body[14], body[15]]) as usize; - debug!( - "client {} #{} XIChangeProperty deviceid={} mode={} format={} property={} type={} num_items={}", - client_id.0, sequence.0, deviceid, mode, format, property.0, type_atom.0, num_items - ); - // Device lookup FIRST (xserver ProcXIChangeProperty, - // xiproperty.c:1137-1141, does dixLookupDevice before the - // format/mode checks), so an unknown device yields BadDevice - // even when the format is also invalid. - if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 57, - XI2_MAJOR_OPCODE, - ); - } - // Validate mode (xiproperty.c check_change_property:325-329). - if mode != crate::xinput::XI_PROP_MODE_REPLACE - && mode != crate::xinput::XI_PROP_MODE_PREPEND - && mode != crate::xinput::XI_PROP_MODE_APPEND - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - u32::from(mode), - 57, - XI2_MAJOR_OPCODE, - ); - } - // Format must be 8/16/32 before we compute the value length. - if format != 8 && format != 16 && format != 32 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - u32::from(format), - 57, - XI2_MAJOR_OPCODE, - ); - } - let value_len = num_items.saturating_mul(usize::from(format / 8)); - let Some(data) = body.get(16..16 + value_len) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 16, // BadLength - 0, - 57, - XI2_MAJOR_OPCODE, - ); - }; - let data = data.to_vec(); - // T3 spec §D order is implemented by `dispatch_change_property`; - // both write arms (XI2 minor 57 + XI1 minor 37) share the same - // pipeline so T5/T6 only has to wire event emission in one place. - match dispatch_change_property( - state, backend, deviceid, mode, format, property, type_atom, &data, - ) { - Ok(what) => { - let _ = emit_property_change(state, deviceid, property, what); - return Ok(RequestOutcome::Handled); - } - Err(err) => { - return emit_property_dispatch_error(state, client_id, sequence, err, 57); - } - } - } - 58 => { - // XIDeleteProperty (xXIDeletePropertyReq, XI2proto.h:785-793). - // body[0..2] deviceid, body[2..4] pad0, body[4..8] property. - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let deviceid = u16::from_le_bytes([body[0], body[1]]); - let property = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - debug!( - "client {} #{} XIDeleteProperty deviceid={} property={}", - client_id.0, sequence.0, deviceid, property.0 - ); - // T3: BadAtom guard (xserver ProcXIDeleteProperty, - // xiproperty.c). We intentionally do NOT BadAccess on - // attempting to delete a libinput descriptor — the driver - // re-seeds those on every device add, so a delete is a no-op - // race the client recovers from on its own. - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 5, // BadAtom - property.0, - 58, - XI2_MAJOR_OPCODE, - ); - } - let Some(device) = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 58, - XI2_MAJOR_OPCODE, - ); - }; - if let Some(what) = crate::xinput::apply_delete_property(device, property) { - // Notify on a real removal only; a redundant delete of - // an absent property must stay silent — xiproperty.c - // does not call `send_property_event` in that case. - let _ = emit_property_change(state, deviceid, property, what); - } - return Ok(RequestOutcome::Handled); - } - 59 => { - // XIGetProperty (xXIGetPropertyReq, XI2proto.h:798-814). - // Struct: deviceid(2), delete(1), pad0(1), property(4), - // type(4), offset(4), len(4). After the 4-byte generic header - // `body` begins at deviceid: - // body[0..2] deviceid, body[2] delete, body[3] pad0, - // body[4..8] property, body[8..12] type, - // body[12..16] offset, body[16..20] len. - if body.len() < 20 { - return Ok(RequestOutcome::Handled); - } - let deviceid = u16::from_le_bytes([body[0], body[1]]); - let delete_raw = body[2]; - let property = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let req_type = AtomId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let offset = u32::from_le_bytes([body[12], body[13], body[14], body[15]]); - let len = u32::from_le_bytes([body[16], body[17], body[18], body[19]]); - debug!( - "client {} #{} XIGetProperty deviceid={} property={} type={} offset={} len={} delete={}", - client_id.0, sequence.0, deviceid, property.0, req_type.0, offset, len, delete_raw - ); - // T3: BadAtom guard before the device lookup so a bogus atom - // surfaces as BadAtom (xserver ProcXIGetProperty does it the - // same way via ValidAtom() before dixLookupDevice's payload - // path; the relative precedence vs. BadDevice never matters - // because clients always pair a valid atom with the deviceid - // they just learned from XIListProperties). - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 5, // BadAtom - property.0, - 59, - XI2_MAJOR_OPCODE, - ); - } - // Device lookup first (xserver dixLookupDevice precedes - // get_property, so BadDevice outranks the BadValue below). - if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 59, - XI2_MAJOR_OPCODE, - ); - } - // `delete` must be exactly 0 or 1; xserver's get_property - // (xiproperty.c:252-255) rejects anything else with BadValue. - if delete_raw > 1 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - u32::from(delete_raw), - 59, - XI2_MAJOR_OPCODE, - ); - } - let delete = delete_raw != 0; - // Re-acquire mutably now that both validations passed. - let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) - .expect("device existence verified above"); - // Snapshot pre-existence so we can detect an inline delete - // and emit `XI_PropertyEvent(Deleted)` after the reply is - // queued. `encode_get_property_reply` removes the property - // iff `delete && bytes_after == 0` — re-checking - // `contains_key` post-call is the simplest oracle. - let pre_existed = delete && device.properties.contains_key(&property); - match crate::xinput::encode_get_property_reply( - byte_order, sequence, device, property, req_type, offset, len, delete, - ) { - Ok(reply) => buf.extend_from_slice(&reply), - Err(crate::xinput::XiPropError::BadValue) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - offset, - 59, - XI2_MAJOR_OPCODE, - ); - } - Err(_) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, - offset, - 59, - XI2_MAJOR_OPCODE, - ); - } - } - if pre_existed { - let device = crate::xinput::find_device(&state.xi_devices, deviceid) - .expect("device existence verified above"); - if !device.properties.contains_key(&property) { - let _ = emit_property_change( - state, - deviceid, - property, - crate::xinput::PropWhat::Deleted, - ); - } - } - } - 60 => { - debug!("client {} #{} XIGetSelectedEvents", client_id.0, sequence.0); - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - // Xorg ProcXIGetSelectedEvents: one xXIEventMask per device - // in device-id order, each trimmed to the words that hold set - // bits. deviceid/mask_len follow the client byte order; the - // mask itself is a bit array (bit n in byte n/8), written as - // little-endian bytes for every client. - let mut selected: Vec<(u16, u64)> = state - .clients - .get(&client_id.0) - .map(|client| { - client - .xi2_masks - .iter() - .filter(|&(&(win, _), &mask)| win == window && mask != 0) - .map(|(&(_, dev), &mask)| (dev, mask)) - .collect() - }) - .unwrap_or_default(); - selected.sort_unstable_by_key(|&(dev, _)| dev); - let mut masks = Vec::new(); - for &(dev, mask) in &selected { - let mask_len: u16 = if mask >> 32 == 0 { 1 } else { 2 }; - x11::write_u16(byte_order, &mut masks, dev); - x11::write_u16(byte_order, &mut masks, mask_len); - masks.extend_from_slice(&mask.to_le_bytes()[..4 * usize::from(mask_len)]); - } - let num_masks = u16::try_from(selected.len()).unwrap_or(u16::MAX); - let mut reply = x11::fixed_reply( - byte_order, - sequence, - 0, - x11::checked_units(masks.len())? as u32, - ); - x11::write_u16(byte_order, &mut reply, num_masks); - reply.extend_from_slice(&[0; 22]); - reply.extend_from_slice(&masks); - buf.extend_from_slice(&reply); - } - 40 => { - // XIQueryPointer: GDK calls this to fetch the current - // pointer position for gesture-drag anchors (caja-desktop - // marquee, mate-panel applet drags). Previously hardcoded - // every coordinate to 0, so every drag started from (0,0) - // regardless of the actual cursor position — caja then - // rubber-banded from screen origin to the click point on - // any single click. Wire the real cursor position through - // from the backend. - // XIQueryPointer body layout (per xinput.xml): - // bytes [0..4] window (WINDOW) - // bytes [4..6] deviceid (u16) - // bytes [6..8] pad - // Previously this read body[4..8], which is deviceid + pad - // — i.e. always interpreted as some sentinel xid (e.g. - // `0xfd820002`, `0xffff0002`). Then - // `window_absolute_position` couldn't find the bogus xid - // and returned `(0, 0)`, so the win-relative coords came - // out equal to the root-absolute coords. GTK popups in - // file managers (Thunar, Caja) place themselves at - // `(window_origin + win_xy + menu_offset)` — with our - // wrong reply they ended up offset by the window's own - // origin, and rubber-band drags anchored at root (0,0) - // instead of at the click point. - let queried_window = if body.len() >= 4 { - ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])) - } else { - ROOT_WINDOW - }; - let pointer = backend.query_pointer(origin).ok(); - let (root_x_int, root_y_int, mask, same_screen) = - if let Some(p) = pointer.filter(|p| p.same_screen) { - (p.win_x, p.win_y, p.mask, 1u8) - } else { - (0, 0, 0, 0u8) - }; - let (origin_x, origin_y) = state.resources.window_absolute_position(queried_window); - let win_x_int = - i16::try_from(i32::from(root_x_int).saturating_sub(origin_x)).unwrap_or(i16::MAX); - let win_y_int = - i16::try_from(i32::from(root_y_int).saturating_sub(origin_y)).unwrap_or(i16::MAX); - let child = state - .direct_child_at(queried_window, win_x_int, win_y_int) - .unwrap_or(ResourceId(0)); - debug!( - "client {} #{} XIQueryPointer window=0x{:x} -> root=({},{}) win=({},{}) child=0x{:x} mask=0x{:x}", - client_id.0, - sequence.0, - queried_window.0, - root_x_int, - root_y_int, - win_x_int, - win_y_int, - child.0, - mask, - ); - // Reply layout (length = 6 units = 24 bytes after the - // 8-byte header — total 32 + 24 = 56). FP1616 coords are - // (i32::from(coord) << 16) as u32. Per xinput.xml the - // BOOL `same_screen` is at offset 32 (NOT in the `pad0` - // slot at offset 1 — confirmed via x11trace 2026-05-15). - // GTK uses `same_screen` to pick popup-placement code - // paths; encoding it as pad0 left every client reading - // `same_screen=false` and routing through the "different - // screen" branch, which made Thunar's right-click popup - // appear at root+window_origin instead of near the click. - // XI2 button state: fold the KeyButMask button bits into the - // XI2 button bitmask (button N -> bit N). muffin's - // `_NET_WM_MOVERESIZE` move grab queries the pointer to learn - // whether the initiating button is still held — an empty mask - // makes it abort the move and the window never budges. - let mut button_mask: u32 = 0; - for (keybut_bit, button) in [ - (0x0100u16, 1u32), - (0x0200, 2), - (0x0400, 3), - (0x0800, 4), - (0x1000, 5), - ] { - if mask & keybut_bit != 0 { - button_mask |= 1 << button; - } - } - // length 7 units: 6 coord words + the same_screen/buttons_len/ - // ModifierInfo/GroupInfo block + a 1-unit button bitmask. - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 7); - x11::write_u32(byte_order, &mut reply, ROOT_WINDOW.0); - x11::write_u32(byte_order, &mut reply, child.0); - x11::write_u32(byte_order, &mut reply, (i32::from(root_x_int) << 16) as u32); - x11::write_u32(byte_order, &mut reply, (i32::from(root_y_int) << 16) as u32); - x11::write_u32(byte_order, &mut reply, (i32::from(win_x_int) << 16) as u32); - x11::write_u32(byte_order, &mut reply, (i32::from(win_y_int) << 16) as u32); - reply.push(same_screen); // byte 32: same_screen (BOOL) - reply.push(0); // byte 33: pad - x11::write_u16(byte_order, &mut reply, 1); // bytes 34-35: buttons_len (1 unit) - // ModifierInfo: 4× CARD32 = base / latched / locked / - // effective. `mask` carries the X11 KeyButMask snapshot - // from the backend: MODIFIERS in the low byte (Shift=0x1 … - // Mod5=0x80), buttons at 0x100+. Xorg fills `rep.mods` - // from the paired MASTER_KEYBOARD's XKB state - // (Xi/xiquerypointer.c:120,139) — base_mods must carry the - // modifier bits WITHOUT the button bits. Pre-fix base was - // hardcoded 0: cinnamon's alt-tab switcher polls - // `global.get_pointer()` (GDK → XIQueryPointer) right - // after pushModal to check Alt is still held; reading 0 it - // took the modifier-already-released branch - // (_activateSelected + destroy) and the switcher popup - // never appeared. `effective` keeps the full KeyButMask - // (mods + button bits) — GDK reads effective and the - // button bits are harmlessly idempotent with the XI2 - // buttons array below. - let mod_bits = u32::from(mask & 0x00ff); - x11::write_u32(byte_order, &mut reply, mod_bits); // base_mods - x11::write_u32(byte_order, &mut reply, 0); // latched_mods - x11::write_u32(byte_order, &mut reply, 0); // locked_mods - x11::write_u32(byte_order, &mut reply, u32::from(mask)); // effective_mods - reply.extend_from_slice(&[0u8; 4]); // group info - // XI2 button mask is a raw byte array indexed by - // `XIMaskIsSet(ptr, btn) = ptr[btn>>3] & (1 << (btn & 7))` - // (X11/extensions/XI2.h) — byte[0] holds buttons 0-7. It is - // NOT byte-swapped per client order (Xorg leaves the trailing - // mask bytes untouched in its reply swap), so emit - // little-endian unconditionally. - reply.extend_from_slice(&button_mask.to_le_bytes()); - buf.extend_from_slice(&reply); - } - // XI2 grab opcodes (51-55). yserver wires these into the - // existing core X11 grab state (`state.active_pointer_grab`, - // `state.button_grabs`, - // `state.active_keyboard_grab`, `state.key_grabs`) which the - // pointer/key fanout already honours. The XI2 mask + per- - // device routing isn't fully implemented — every grab is - // mapped to a core X11 grab on either the master pointer - // (deviceid != 3) or master keyboard (deviceid == 3). That - // matches what GTK relies on in practice (its uses of - // XIGrabDevice are equivalent to XGrabPointer/XGrabKeyboard). - // - // Pre-fix all five handlers were no-ops that just sent - // Success replies — GTK then thought it owned the device but - // events still went to the normal pointer-window, so popups - // dismissed on the first stray motion event and `gtk_window_ - // present` looped re-mapping the popup at ~50 Hz (visible as - // brisk-menu's MapWindow remap storm pre-`MapWindow` - // no-op fix, and as subtle popup misbehavior elsewhere). - // - // Match Xorg `Xi/exevents.c::DeviceGrabDevice` / - // `ProcXIPassiveGrabDevice` for state-update intent. The - // status byte at reply offset 8 is always Success(0); a - // strict implementation would return AlreadyGrabbed(1) / - // NotViewable(3) / etc., but Xorg's permissive behaviour - // (set the grab and let later events sort it out) keeps GTK - // happy across pause/resume sleeps. - 51 => { - // XIGrabDevice reply: 32 bytes (header + status at offset - // 8 + 23 pad). Wire body: window(4) + time(4) + cursor(4) - // + deviceid(2) + mode(1) + paired_device_mode(1) + - // owner_events(1) + pad(1) + mask_len(2) + ... - // XIGrabDevice body: window(4) time(4) cursor(4) - // deviceid(2) mode(1) paired(1) owner_events(1) pad(1) - // mask_len(2) mask... - let (grab_window, time, cursor, deviceid, owner_events) = if body.len() >= 17 { - ( - u32::from_le_bytes([body[0], body[1], body[2], body[3]]), - u32::from_le_bytes([body[4], body[5], body[6], body[7]]), - u32::from_le_bytes([body[8], body[9], body[10], body[11]]), - u16::from_le_bytes([body[12], body[13]]), - body[16] != 0, - ) - } else { - (0, 0, 0, 0, false) - }; - // First word of the grab's event mask (mask_len at body[18..20], - // mask words from body[20]) — event types 0..=31. - let grab_xi2_mask = match body.get(18..24) { - Some(b) if u16::from_le_bytes([b[0], b[1]]) > 0 => { - u32::from_le_bytes([b[2], b[3], b[4], b[5]]) - } - _ => 0, - }; - // Xorg `dix/events.c:5240` (GrabDevice): a device already - // grabbed by ANOTHER client → AlreadyGrabbed(1); do NOT - // overwrite the grab. Same-client re-grab still replaces - // (Xorg SameClient path, unchanged below). #94 Cinnamon - // click-swallow: muffin `XIGrabDevice`-stole the master - // pointer from Steam mid-click (both device=2), so the - // ButtonRelease was delivered to muffin and Steam's click - // never completed (cinnamon.xtrace conn 026 vs 105). The - // pointer slot covers implicit / passive-activated / explicit - // grabs alike — exactly Xorg's single `deviceGrab.grab`. - let grab_status: u8 = if deviceid == 3 { - u8::from( - state - .active_keyboard_grab - .is_some_and(|g| g.owner != client_id), - ) - } else { - // Xorg GrabDevice returns AlreadyGrabbed for any foreign - // active grab, including passive-activated and implicit grabs. - // SameClient replacement continues through the success path. - u8::from( - state - .active_pointer_grab - .is_some_and(|grab| grab.owner != client_id), - ) - }; - if grab_status == 0 { - // Capture the previous grab window (if any, this client's) - // BEFORE we overwrite. Synthesised crossings need to send - // Leave on the previous grab window when transitioning to - // a different one. GTK3 popups grab the input-shadow - // window first, then re-grab the visible popup — without - // the Leave on the shadow window GTK3's menu-tracking - // never engages on the visible popup. - let prev_pointer_grab_window: Option = if deviceid == 3 { - None - } else { - state - .active_pointer_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window) - }; - let prev_keyboard_grab_window: Option = if deviceid == 3 { - state - .active_keyboard_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window) - } else { - None - }; - if deviceid == 3 { - state.active_keyboard_grab = Some(crate::server::ActiveKeyboardGrab { - owner: client_id, - grab_window: ResourceId(grab_window), - source: crate::server::ActiveKeyboardGrabSource::Explicit, - owner_events, - via_xi2: true, - xi2_mask: grab_xi2_mask, - }); - } else { - state.set_pointer_grab(crate::server::ActivePointerGrab { - owner: client_id, - grab_window: ResourceId(grab_window), - event_mask: 0xFFFF, // permissive — XI2 mask not parsed - cursor: ResourceId(cursor), - time, - owner_events, - via_xi2: true, - implicit: false, - passive: false, - xi2_mask: u64::MAX, - }); - } - // Core↔XI bridge — Xorg `ActivateKeyboardGrab` / - // `ActivatePointerGrab` end with `CheckGrabForSyncs` - // (dix/events.c:1424): a SYNCHRONOUS grab freezes this - // device, an ASYNCHRONOUS grab THAWS it — including a - // freeze left behind by a sync passive-grab activation — - // and `ComputeFreezes` replays the withheld queues. The - // core GrabKeyboard/GrabPointer handlers already do this; - // pre-fix the XI2 path skipped it, so muffin's alt-tab - // (sync passive keybinding grab → ASYNC XIGrabDevice - // pushModal → XIUngrabDevice) left the keyboard - // FrozenNoEvent forever: one alt-tab killed all key input - // (the XIAllowEvents muffin sends after the ungrab is - // correctly a no-op — its grab is already gone). - // Wire: body[14]=grab_mode, body[15]=paired_device_mode; - // XI2 GrabModeSync=0 / GrabModeAsync=1. - let grab_mode = body.get(14).copied().unwrap_or(1); - let paired_mode = body.get(15).copied().unwrap_or(1); - let sync_dev = if deviceid == 3 { - crate::xinput::DEVICEID_SLAVE_KEYBOARD - } else { - crate::xinput::DEVICEID_SLAVE_POINTER - }; - crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( - state, - sync_dev, - client_id, - grab_mode == 0, - paired_mode == 0, - ); - if grab_mode != 0 { - // The withheld sync-passive replay candidate was already - // delivered to the grab owner; an async grab forecloses - // Replay (Xorg drops the stored event on thaw). - if deviceid == 3 { - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .or_default() - .stored = None; - } else { - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default() - .stored = None; - } - } - debug!( - "client {} #{} XIGrabDevice window=0x{:x} deviceid={} cursor=0x{:x} -> Success", - client_id.0, sequence.0, grab_window, deviceid, cursor - ); - // Synthesised XI2 crossings on grab activation. Matches - // Xorg `Xi/exevents.c::ActivateKeyboardGrab` / - // `ActivatePointerGrab` (which call `DoEnterLeaveEvents` - // with `NotifyGrab`). Without these GTK3 popup state - // machines never engage their hover/click tracking — the - // menu is visible but items don't highlight or activate - // on click. Captured in `mate-xorg.xtrace` as the pair - // `XI_Leave(mode=Grab, detail=Nonlinear)` on the previous - // grab window followed by `XI_Enter(mode=Grab, - // detail=Nonlinear)` on the new grab window; keyboard - // grabs additionally get `XI_FocusIn(mode=Grab, - // detail=Nonlinear)`. NotifyGrab = 1, NotifyNonlinear = 3. - let pointer_xy = backend - .query_pointer(origin) - .ok() - .map(|p| (p.win_x, p.win_y)) - .unwrap_or((0, 0)); - let (root_x, root_y) = pointer_xy; - let server_time = state.timestamp_now(); - // Emit one XI2 crossing (Enter/Leave/FocusIn/FocusOut) on a - // single window with an explicit detail code, mode - // NotifyGrab. The keyboard-focus path drives this directly; - // the pointer path drives it from a crossing chain so the - // detail codes — and the `from == to` no-op — match Xorg's - // `DoEnterLeaveEvents`. - let emit_xi_crossing = |state: &mut ServerState, - evtype: u16, - target_window: ResourceId, - detail: u8| { - let (origin_x, origin_y) = - state.resources.window_absolute_position(target_window); - let event_x = i16::try_from(i32::from(root_x).saturating_sub(origin_x)) - .unwrap_or(i16::MAX); - let event_y = i16::try_from(i32::from(root_y).saturating_sub(origin_y)) - .unwrap_or(i16::MAX); - let _dropped = - fanout_event_to_clients(state, &[client_id], |out, seq, order| { - x11::encode_xi2_crossing_event( - out, - order, - seq, - XI2_MAJOR_OPCODE, - evtype, - deviceid, - server_time, - ROOT_WINDOW, - target_window, - root_x, - root_y, - event_x, - event_y, - 0, - 1, // mode = NotifyGrab - detail, - deviceid, - ); - }); - }; - if deviceid == 3 { - // Keyboard grab → focus transitions (Xorg - // `ActivateKeyboardGrab` → `DoFocusEvents`). Unchanged. - if let Some(prev) = prev_keyboard_grab_window - && prev != ResourceId(grab_window) - { - emit_xi_crossing(state, 10, prev, 3); // XI_FocusOut - } - emit_xi_crossing(state, 9, ResourceId(grab_window), 3); // XI_FocusIn - } else { - // Pointer grab → Xorg `ActivatePointerGrab` → - // `DoEnterLeaveEvents(from, grab_window, NotifyGrab)` - // (dix/events.c). `from` is the previous grab window - // when replacing an active grab, else the window the - // pointer currently sits in (the sprite, resolved from - // the live position). `compute_crossing_chain` - // early-returns when `from == grab_window`, so grabbing - // the window already under the pointer emits nothing — - // matching Xorg. The pre-fix code emitted an - // unconditional `XI_Enter(NotifyGrab)` on the grab - // window, which desynced cinnamon's XEmbed-systray - // click-forward whenever muffin grabbed its own - // full-screen stage (pamac tray unclickable, 2026-06-22). - let from = prev_pointer_grab_window.unwrap_or_else(|| { - state - .root_pointer_target_at(root_x, root_y) - .map_or(ResourceId(grab_window), |h| h.0) - }); - let chain = crate::crossings::implicit_grab_crossings( - state, - from, - ResourceId(grab_window), - ); - for e in chain { - let evtype: u16 = match e.kind { - crate::crossings::CrossingKind::Enter => 7, - crate::crossings::CrossingKind::Leave => 8, - }; - emit_xi_crossing(state, evtype, e.window, e.detail); - } - } - } // end: mutate grab state + emit crossings only when granted - // XIGrabDevice reply carries the grab status at offset 8 - // (0 = Success, 1 = AlreadyGrabbed — Xorg dix/events.c:5240). - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - let mut grab_reply_body = [0u8; 24]; - grab_reply_body[0] = grab_status; - reply.extend_from_slice(&grab_reply_body); - buf.extend_from_slice(&reply); - } - 52 => { - // XIUngrabDevice body: time(4) + deviceid(2) + pad(2). - let deviceid = if body.len() >= 6 { - u16::from_le_bytes([body[4], body[5]]) - } else { - 0 - }; - // Capture grab_window BEFORE clearing — we synthesize the - // matching XI2 crossing with `NotifyUngrab` on the way out - // so the client's grab state machine pairs cleanly with - // its earlier NotifyGrab. Matches Xorg - // `Xi/exevents.c::DeactivateKeyboardGrab` / - // `DeactivatePointerGrab`. - let grab_window_for_event: Option = if deviceid == 3 { - state - .active_keyboard_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window) - } else { - state - .active_pointer_grab - .filter(|grab| grab.owner == client_id) - .map(|grab| grab.grab_window) - }; - if deviceid == 3 { - if state - .active_keyboard_grab - .is_some_and(|g| g.owner == client_id) - { - state.active_keyboard_grab = None; - // Xorg DeactivateKeyboardGrab freeze epilogue - // (mirrors `deactivate_core_keyboard_grab`): drop - // the replay candidate and release any XI1-side - // hold (sync.state → THAWED + ComputeFreezes). - // Pre-fix the freeze survived the ungrab and every - // later key event was withheld. - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .or_default() - .stored = None; - crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( - state, - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - client_id, - ); - } - } else if state - .active_pointer_grab - .is_some_and(|grab| grab.owner == client_id) - { - state.clear_pointer_grab(); - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default() - .stored = None; - // Clear any grab-cursor sprite override, as - // `deactivate_core_pointer_grab` does — a core - // XGrabPointer(cursor) torn down via XIUngrabDevice - // must not strand the grab cursor on the sprite. - let _ = backend.set_grab_cursor(None, None); - // Same freeze epilogue for the pointer (mirrors - // `deactivate_core_pointer_grab`). - crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( - state, - crate::xinput::DEVICEID_SLAVE_POINTER, - client_id, - ); - } - if let Some(grab_window) = grab_window_for_event { - let pointer_xy = backend - .query_pointer(origin) - .ok() - .map(|p| (p.win_x, p.win_y)) - .unwrap_or((0, 0)); - let (root_x, root_y) = pointer_xy; - let server_time = state.timestamp_now(); - let emit_xi_crossing = |state: &mut ServerState, - evtype: u16, - target_window: ResourceId, - detail: u8| { - let (origin_x, origin_y) = - state.resources.window_absolute_position(target_window); - let event_x = i16::try_from(i32::from(root_x).saturating_sub(origin_x)) - .unwrap_or(i16::MAX); - let event_y = i16::try_from(i32::from(root_y).saturating_sub(origin_y)) - .unwrap_or(i16::MAX); - let _dropped = - fanout_event_to_clients(state, &[client_id], |out, seq, order| { - x11::encode_xi2_crossing_event( - out, - order, - seq, - XI2_MAJOR_OPCODE, - evtype, - deviceid, - server_time, - ROOT_WINDOW, - target_window, - root_x, - root_y, - event_x, - event_y, - 0, - 2, // mode = NotifyUngrab - detail, - deviceid, - ); - }); - }; - if deviceid == 3 { - // Keyboard ungrab → focus restore. Unchanged. - emit_xi_crossing(state, 10, grab_window, 3); // XI_FocusOut - } else { - // Pointer ungrab → Xorg `DeactivatePointerGrab` → - // `DoEnterLeaveEvents(grab_window, sprite, NotifyUngrab)` - // (dix/events.c). Symmetric with the activation - // chain: `from == to` (sprite still inside the grab - // window) emits nothing. - let to = state - .root_pointer_target_at(root_x, root_y) - .map_or(grab_window, |h| h.0); - let chain = crate::crossings::implicit_grab_crossings(state, grab_window, to); - for e in chain { - let evtype: u16 = match e.kind { - crate::crossings::CrossingKind::Enter => 7, - crate::crossings::CrossingKind::Leave => 8, - }; - emit_xi_crossing(state, evtype, e.window, e.detail); - } - } - } - debug!( - "client {} #{} XIUngrabDevice deviceid={}", - client_id.0, sequence.0, deviceid - ); - return Ok(RequestOutcome::Handled); - } - 53 => { - // XIAllowEvents body (per X11/extensions/XI2proto.h - // `xXIAllowEventsReq`): time(4) + deviceid(2) + mode(1) + - // pad(1). XI 2.2 extends with touchid(4) + grab_window(4) - // for touch grabs; we don't implement touch, so the - // extension fields are ignored. - // - // mutter/muffin/cinnamon install click-to-focus passive - // button grabs (sync) and keybinding key grabs (sync); on each - // press they examine it then call XIAllowEvents to thaw/replay. - // The mode (XIAsyncDevice/XISyncDevice/XIReplayDevice/…) + - // deviceid map onto a core AllowSome mode — see - // `xi2_allow_mode_to_core` — and run through the shared - // `apply_allow_events` below. - let (deviceid, mode) = if body.len() >= 8 { - (u16::from_le_bytes([body[4], body[5]]), body[6]) - } else { - (0, 0) - }; - debug!( - "client {} #{} XIAllowEvents deviceid={} mode={}", - client_id.0, sequence.0, deviceid, mode - ); - let time = if body.len() >= 4 { - u32::from_le_bytes([body[0], body[1], body[2], body[3]]) - } else { - 0 - }; - // Map the XI2 mode + target deviceid onto the equivalent core - // AllowSome mode and run the SHARED `apply_allow_events`. This - // used to be a partial reimplementation that diverged from the - // core path and caused recurring freezes (desktop rubber-band = - // Async/Replay thaw gap; Cinnamon input freeze = XISyncDevice - // treated as a no-op). Touch modes (XIAcceptTouch/XIRejectTouch) - // are unsupported → no-op. - if let Some(core_mode) = xi2_allow_mode_to_core(mode, deviceid) { - return apply_allow_events(state, backend, client_id, sequence, core_mode, time); - } - return Ok(RequestOutcome::Handled); - } - 54 => { - // XIPassiveGrabDevice body (per X11/extensions/XI2proto.h - // `xXIPassiveGrabDeviceReq`): time(4) + grab_window(4) + - // cursor(4) + detail(4) + deviceid(2) + num_modifiers(2) - // + mask_len(2) + grab_type(1) + grab_mode(1) + - // paired_device_mode(1) + owner_events(1) + pad1(2) + - // mask(mask_len*4) + modifiers(num_modifiers*4). - // - // GrabType: Button=0, Keycode=1, Enter=2, FocusIn=3, - // TouchBegin=4. Button and Keycode map onto core X11 - // PassiveButtonGrab / KeyGrab; the other three are no-ops - // for now (yserver doesn't synthesise core X11 Enter/ - // FocusIn passive grabs). - let ( - grab_window, - detail, - deviceid, - num_modifiers, - mask_len, - grab_type, - grab_mode, - paired_device_mode, - owner_events, - ) = if body.len() >= 25 { - ( - u32::from_le_bytes([body[4], body[5], body[6], body[7]]), - u32::from_le_bytes([body[12], body[13], body[14], body[15]]), - u16::from_le_bytes([body[16], body[17]]), - u16::from_le_bytes([body[18], body[19]]), - u16::from_le_bytes([body[20], body[21]]) as usize, - body[22], - body[23], - body[24], - body.get(25).copied().unwrap_or(0) != 0, - ) - } else { - (0, 0, 0, 0, 0, 0xff, 1, 1, false) - }; - // Modifiers tail starts after the header (28) and the mask - // (mask_len * 4 bytes). - let mods_start = 28 + mask_len * 4; - // First mask word: event types 0..=31. - let grab_xi2_mask = if mask_len > 0 { - body.get(28..32) - .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - } else { - 0 - }; - let mut modifier_masks: Vec = Vec::with_capacity(num_modifiers.max(1).into()); - if num_modifiers == 0 { - // "no modifiers" — single grab with modifier-mask 0. - modifier_masks.push(0); - } else { - for i in 0..usize::from(num_modifiers) { - let off = mods_start + i * 4; - if let Some(slice) = body.get(off..off + 4) { - let raw = u32::from_le_bytes(slice.try_into().unwrap()); - // XI2 `Any` = bit 31; map to core X11 AnyModifier (0x8000). - #[allow(clippy::cast_possible_truncation)] - let m = if raw & 0x8000_0000 != 0 { - 0x8000u16 - } else { - (raw & 0xFFFF) as u16 - }; - modifier_masks.push(m); - } - } - } - match grab_type { - 0 => { - // Button. detail = button number (0 == AnyButton). - let button = u8::try_from(detail).unwrap_or(0); - for modifiers in &modifier_masks { - state.button_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window.0 == grab_window - && g.button == button - && g.modifiers == *modifiers) - }); - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: client_id, - grab_window: ResourceId(grab_window), - button, - modifiers: *modifiers, - owner_events, - event_mask: 0xFFFF_FFFF, - pointer_mode: grab_mode, - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: true, - }); - } - } - 1 => { - // Keycode. detail = keycode (0 == AnyKey). - let keycode = u8::try_from(detail).unwrap_or(0); - for modifiers in &modifier_masks { - state.key_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window.0 == grab_window - && g.keycode == keycode - && g.modifiers == *modifiers) - }); - state.key_grabs.push(crate::server::KeyGrab { - owner: client_id, - grab_window: ResourceId(grab_window), - keycode, - modifiers: *modifiers, - owner_events: false, - pointer_mode: paired_device_mode, - keyboard_mode: grab_mode, - via_xi2: true, - xi2_mask: grab_xi2_mask, - }); - } - } - _ => { - // Enter/FocusIn/TouchBegin — yserver has no - // matching machinery yet; record the request in - // the debug log so a real repro shows up. - debug!( - "client {} #{} XIPassiveGrabDevice unsupported grab_type={} \ - (Enter/FocusIn/TouchBegin)", - client_id.0, sequence.0, grab_type - ); - } - } - debug!( - "client {} #{} XIPassiveGrabDevice window=0x{:x} detail=0x{:x} deviceid={} \ - grab_type={} num_modifiers={} -> Success", - client_id.0, sequence.0, grab_window, detail, deviceid, grab_type, num_modifiers, - ); - // Reply: num_modifiers(2) + pad(22). With 0 failed - // modifiers the client treats every requested combination - // as grabbed. - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.extend_from_slice(&[0u8; 24]); - buf.extend_from_slice(&reply); - } - 55 => { - // XIPassiveUngrabDevice body: grab_window(4) + detail(4) - // + deviceid(2) + num_modifiers(2) + grab_type(1) + - // pad(3) + modifiers. - let (grab_window, detail, num_modifiers, grab_type) = if body.len() >= 13 { - ( - u32::from_le_bytes([body[0], body[1], body[2], body[3]]), - u32::from_le_bytes([body[4], body[5], body[6], body[7]]), - u16::from_le_bytes([body[10], body[11]]), - body[12], - ) - } else { - (0, 0, 0, 0xff) - }; - let mods_start = 16; - let mut modifier_masks: Vec = Vec::with_capacity(num_modifiers.max(1).into()); - if num_modifiers == 0 { - modifier_masks.push(0); - } else { - for i in 0..usize::from(num_modifiers) { - let off = mods_start + i * 4; - if let Some(slice) = body.get(off..off + 4) { - let raw = u32::from_le_bytes(slice.try_into().unwrap()); - #[allow(clippy::cast_possible_truncation)] - let m = if raw & 0x8000_0000 != 0 { - 0x8000u16 - } else { - (raw & 0xFFFF) as u16 - }; - modifier_masks.push(m); - } - } - } - match grab_type { - 0 => { - let button = u8::try_from(detail).unwrap_or(0); - state.button_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window.0 == grab_window - && (g.button == button || button == 0) - && modifier_masks - .iter() - .any(|m| g.modifiers == *m || *m == 0x8000)) - }); - } - 1 => { - let keycode = u8::try_from(detail).unwrap_or(0); - state.key_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window.0 == grab_window - && (g.keycode == keycode || keycode == 0) - && modifier_masks - .iter() - .any(|m| g.modifiers == *m || *m == 0x8000)) - }); - } - _ => {} - } - debug!( - "client {} #{} XIPassiveUngrabDevice window=0x{:x} detail=0x{:x} grab_type={}", - client_id.0, sequence.0, grab_window, detail, grab_type - ); - return Ok(RequestOutcome::Handled); - } - // XI 1.x ListInputDevices (minor 2). Returns the real 4-device - // model (mirrors XIQueryDevice). A previous empty-list stub - // crashed Chromium/Electron: Ozone-X11 cross-checks XI1's - // ListInputDevices against XI2's XIQueryDevice and fatal-CHECKs - // when XI2 has a master pointer but XI1 reports zero devices. - 2 => { - debug!("client {} #{} XListInputDevices", client_id.0, sequence.0); - // Names come from the SAME source as XIQueryDevice (the - // `xi_devices` registry, ids 2/3/4/5) so the XI1 and XI2 - // enumerations report identical device names — clients - // cross-check and fatal-CHECK on a mismatch. - let names = [ - crate::xinput::device_name(&state.xi_devices, 2), - crate::xinput::device_name(&state.xi_devices, 3), - crate::xinput::device_name(&state.xi_devices, 4), - crate::xinput::device_name(&state.xi_devices, 5), - ]; - // Device-type atoms (MOUSE / KEYBOARD / TOUCHPAD) were - // interned at ServerState construction, so these lookups are - // infallible (only_if_exists=true still finds them). - let mouse_atom = state.atoms.intern(crate::xinput::XI_ATOM_MOUSE, true).0; - let kbd_atom = state.atoms.intern(crate::xinput::XI_ATOM_KEYBOARD, true).0; - let touchpad_atom = state.atoms.intern(crate::xinput::XI_ATOM_TOUCHPAD, true).0; - // id 4 (slave pointer) is TOUCHPAD when active, otherwise MOUSE. - let slave_ptr_type = if crate::xinput::device_is_touchpad(&state.xi_devices, 4) { - touchpad_atom - } else { - mouse_atom - }; - let types = [mouse_atom, kbd_atom, slave_ptr_type, kbd_atom]; - buf.extend_from_slice(&x11::encode_list_input_devices_reply( - byte_order, sequence, names, types, - )); - } - // XI 1.x SelectExtensionEvent (minor 6; xSelectExtensionEventReq, - // XIproto.h). Body after the 4-byte generic header: - // body[0..4] window (Window = CARD32), - // body[4..6] count (CARD16, number of XEventClass values), - // body[6..8] pad00 (CARD16), - // body[8..] count × XEventClass (CARD32). - // - // An XEventClass packs `(deviceid << 8) | event_code`. We only - // implement XI1 `DevicePropertyNotify` (event code 16 within - // the XInput block, i.e. low byte = `XI_FIRST_EVENT + 16` = 82 - // — yserver assigns XInput the contiguous block 66..=82), so - // classes for other XI1 events (motion / button / key / etc.) - // are accepted but ignored. We do NOT error on unknown classes: - // a single SelectExtensionEvent often selects multiple classes - // and Xorg silently drops the ones it can't service. - // - // Selection state is canonical per window, as in Xorg. Events such - // as DevicePropertyNotify carry no event-window field, so a separate - // aggregate is derived from the per-window state for delivery. - // - // Replace semantics: for every deviceid mentioned in the - // supplied class list, this client's prior selections for that - // deviceid on this window are dropped before the new set is - // installed. A client - // unsubscribes a given deviceid by passing at least one class - // for it whose low byte is not `DevicePropertyNotify` — the - // deviceid lands in `touched_devices` and its prior entries - // are cleared; the unsupported class itself is silently - // dropped. `count == 0` is a no-op (the existing selection - // survives unchanged), matching Xorg's behaviour. - 6 => { - if body.len() < 8 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 16, // BadLength - 0, - 6, - XI2_MAJOR_OPCODE, - ); - } - let count = usize::from(u16::from_le_bytes([body[4], body[5]])); - let expected_len = 8usize.saturating_add(count.saturating_mul(4)); - if body.len() < expected_len { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 16, // BadLength - 0, - 6, - XI2_MAJOR_OPCODE, - ); - } - // Xorg Xi/selectev.c validates the window first (BadWindow), - // then rejects classes whose embedded deviceid names no - // device (BadClass) — XTS XSelectExtensionEvent-11/-13. - let sel_window = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if state.resources.window(ResourceId(sel_window)).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - sel_window, - u16::from(minor), - XI2_MAJOR_OPCODE, - ); - } - for i in 0..count { - let off = 8 + i * 4; - let class = - u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); - if !xi1_device_valid(xi1_event_class_device(class)) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI1_ERROR_BAD_CLASS, - class, - u16::from(minor), - XI2_MAJOR_OPCODE, - ); - } - } - // Decode the requested class list and collect the set of - // deviceids that appear (so we can drop the client's stale - // entries for *those* devices — Xorg's "replace per device" - // semantics, see Xi/selectev.c::ProcXSelectExtensionEvent). - let mut accepted_classes: Vec = Vec::with_capacity(count); - let mut touched_devices: HashSet = HashSet::new(); - for i in 0..count { - let off = 8 + i * 4; - let class = - u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); - #[allow(clippy::cast_possible_truncation)] - let class_low = class as u8; // event code in the XInput block - #[allow(clippy::cast_possible_truncation)] - let dev_byte = (class >> 8) as u8; - touched_devices.insert(dev_byte); - // DevicePropertyNotify classes are device-scoped; the - // input-event classes (DeviceKeyPress..DeviceMotionNotify), - // the focus classes (DeviceFocusIn/Out, consumed by - // `xi1_focus::emit_device_focus`) and DeviceStateNotify - // (consumed by `xi1_state_notify::deliver_state_notify`) - // select per window like core input events and are - // recorded in `xi1_window_event_classes` below. Other - // classes are silently discarded, matching Xorg: it walks - // `xi_all_events` and skips entries it cannot service. - if crate::server::xi1_class_is_global_notification(class) { - // DevicePropertyNotify / DeviceMappingNotify / - // ChangeDeviceNotify are server-wide per-device - // events: Xorg `Xi/exevents.c::SendMappingNotify` / - // `SendDeviceNotify` fan them out by walking the - // global client list, NOT a per-window event-mask. - accepted_classes.push(class); - } else if (XI_FIRST_EVENT + XI_DEVICE_KEY_PRESS_OFFSET - ..=XI_FIRST_EVENT + crate::xinput::XI_DEVICE_FOCUS_OUT_OFFSET) - .contains(&class_low) - || class_low == XI_FIRST_EVENT + crate::xinput::XI_DEVICE_STATE_NOTIFY_OFFSET - { - accepted_classes.push(class); - } - } - debug!( - "client {} #{} XSelectExtensionEvent window=0x{:x} count={} accepted={} window_input={}", - client_id.0, - sequence.0, - sel_window, - count, - accepted_classes - .iter() - .filter(|class| crate::server::xi1_class_is_global_notification(**class)) - .count(), - accepted_classes - .iter() - .filter(|class| !crate::server::xi1_class_is_global_notification(**class)) - .count(), - ); - if let Some(client) = state.clients.get_mut(&client_id.0) { - // Selection state belongs to the request window. Drop stale - // entries for the named devices on that window only (Xorg - // replacement semantics), then install the accepted list. - if !touched_devices.is_empty() - && let Some(set) = client - .xi1_window_event_classes - .get_mut(&ResourceId(sel_window)) - { - set.retain(|c| { - #[allow(clippy::cast_possible_truncation)] - let dev_byte = (c >> 8) as u8; - !touched_devices.contains(&dev_byte) - }); - } - if !accepted_classes.is_empty() { - let set = client - .xi1_window_event_classes - .entry(ResourceId(sel_window)) - .or_default(); - for class in accepted_classes { - set.insert(class); - } - } - - // Keep the delivery-oriented aggregate in sync. Global XI1 - // notifications have no event-window field, but selecting - // them is still per-window protocol state. - client.rebuild_xi1_global_event_classes(); - } - return Ok(RequestOutcome::Handled); - } - // XI 1.x ListDeviceProperties (minor 36; xListDevicePropertiesReq, - // XIproto.h:1433-1440). Body after the 4-byte generic header: - // body[0] deviceid (CARD8), body[1] pad0, body[2..4] pad1. - // MATE's settings daemon enumerates a touchpad's libinput - // properties through this XI1 path (not the XI2 XIListProperties), - // so a real reply backed by `xi_devices` is required. - 36 => { - if body.is_empty() { - return Ok(RequestOutcome::Handled); - } - let deviceid = u16::from(body[0]); - debug!( - "client {} #{} XListDeviceProperties deviceid={}", - client_id.0, sequence.0, deviceid - ); - let Some(device) = crate::xinput::find_device(&state.xi_devices, deviceid) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 36, - XI2_MAJOR_OPCODE, - ); - }; - buf.extend_from_slice(&crate::xinput::encode_xi1_list_properties_reply( - byte_order, sequence, device, - )); - } - // XI 1.x ChangeDeviceProperty (minor 37; xChangeDevicePropertyReq, - // XIproto.h:1462-1473). Body after the 4-byte generic header: - // body[0..4] property (Atom), body[4..8] type (Atom), - // body[8] deviceid (CARD8), body[9] format, body[10] mode, - // body[11] pad, body[12..16] nUnits (CARD32), body[16..] value. - 37 => { - if body.len() < 16 { - return Ok(RequestOutcome::Handled); - } - let property = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let type_atom = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let deviceid = u16::from(body[8]); - let format = body[9]; - let mode = body[10]; - let num_items = u32::from_le_bytes([body[12], body[13], body[14], body[15]]) as usize; - debug!( - "client {} #{} XChangeDeviceProperty deviceid={} mode={} format={} property={} type={} num_items={}", - client_id.0, sequence.0, deviceid, mode, format, property.0, type_atom.0, num_items - ); - // Device lookup first, mirroring the XI2 path (xserver does - // dixLookupDevice before the mode/format checks). - if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 37, - XI2_MAJOR_OPCODE, - ); - } - if mode != crate::xinput::XI_PROP_MODE_REPLACE - && mode != crate::xinput::XI_PROP_MODE_PREPEND - && mode != crate::xinput::XI_PROP_MODE_APPEND - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - u32::from(mode), - 37, - XI2_MAJOR_OPCODE, - ); - } - if format != 8 && format != 16 && format != 32 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - u32::from(format), - 37, - XI2_MAJOR_OPCODE, - ); - } - let value_len = num_items.saturating_mul(usize::from(format / 8)); - let Some(data) = body.get(16..16 + value_len) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 16, // BadLength - 0, - 37, - XI2_MAJOR_OPCODE, - ); - }; - let data = data.to_vec(); - // The T3 spec §D pipeline is shared with the XI2 arm - // (minor 57) via `dispatch_change_property`; the same - // `emit_property_change` helper fans out - // `XI_PropertyEvent` here too — xserver's - // `send_property_event` fires from both XI1 and XI2 paths. - match dispatch_change_property( - state, backend, deviceid, mode, format, property, type_atom, &data, - ) { - Ok(what) => { - let _ = emit_property_change(state, deviceid, property, what); - return Ok(RequestOutcome::Handled); - } - Err(err) => { - return emit_property_dispatch_error(state, client_id, sequence, err, 37); - } - } - } - // XI 1.x DeleteDeviceProperty (minor 38; xDeleteDevicePropertyReq, - // XIproto.h:1481-1489). Body after the 4-byte generic header: - // body[0..4] property (Atom), body[4] deviceid (CARD8), - // body[5] pad0, body[6..8] pad1. - 38 => { - if body.len() < 5 { - return Ok(RequestOutcome::Handled); - } - let property = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let deviceid = u16::from(body[4]); - debug!( - "client {} #{} XDeleteDeviceProperty deviceid={} property={}", - client_id.0, sequence.0, deviceid, property.0 - ); - // T3: BadAtom guard (mirror of XI2 minor 58). Same policy: - // libinput descriptor deletes are tolerated as no-ops; the - // driver re-seeds on the next device add. - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 5, // BadAtom - property.0, - 38, - XI2_MAJOR_OPCODE, - ); - } - let Some(device) = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) - else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 38, - XI2_MAJOR_OPCODE, - ); - }; - if let Some(what) = crate::xinput::apply_delete_property(device, property) { - // Same XI2 fan-out the minor-58 arm runs. - let _ = emit_property_change(state, deviceid, property, what); - } - return Ok(RequestOutcome::Handled); - } - // XI 1.x GetDeviceProperty (minor 39; xGetDevicePropertyReq, - // XIproto.h:1497-1512). Body after the 4-byte generic header: - // body[0..4] property (Atom), body[4..8] type (Atom), - // body[8..12] longOffset (CARD32), body[12..16] longLength - // (CARD32), body[16] deviceid (CARD8), body[17] delete (BOOL), - // body[18..20] pad. - // This is the request MATE's settings daemon uses to read - // "libinput Tapping Enabled" etc. The reply echoes the requested - // deviceid (byte 21), unlike the XI2 reply (Task brief: the old - // zero-stub returned device=0 and MATE rejected the touchpad). - 39 => { - if body.len() < 18 { - return Ok(RequestOutcome::Handled); - } - let property = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let req_type = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let offset = u32::from_le_bytes([body[8], body[9], body[10], body[11]]); - let len = u32::from_le_bytes([body[12], body[13], body[14], body[15]]); - let deviceid = u16::from(body[16]); - let delete_raw = body[17]; - debug!( - "client {} #{} XGetDeviceProperty deviceid={} property={} type={} offset={} len={} delete={}", - client_id.0, sequence.0, deviceid, property.0, req_type.0, offset, len, delete_raw - ); - // T3: BadAtom guard (mirror of XI2 minor 59). - if !state.atoms.exists(property) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 5, // BadAtom - property.0, - 39, - XI2_MAJOR_OPCODE, - ); - } - if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI2_FIRST_ERROR, // XI_BadDevice - u32::from(deviceid), - 39, - XI2_MAJOR_OPCODE, - ); - } - if delete_raw > 1 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - u32::from(delete_raw), - 39, - XI2_MAJOR_OPCODE, - ); - } - let delete = delete_raw != 0; - let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) - .expect("device existence verified above"); - // Same delete-detection oracle as the XI2 minor-59 arm: - // snapshot pre-existence and emit when the encoder removed it. - let pre_existed = delete && device.properties.contains_key(&property); - match crate::xinput::encode_xi1_get_property_reply( - byte_order, sequence, device, property, req_type, offset, len, delete, - ) { - Ok(reply) => buf.extend_from_slice(&reply), - Err(_) => { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - 2, // BadValue - offset, - 39, - XI2_MAJOR_OPCODE, - ); - } - } - if pre_existed { - let device = crate::xinput::find_device(&state.xi_devices, deviceid) - .expect("device existence verified above"); - if !device.properties.contains_key(&property) { - let _ = emit_property_change( - state, - deviceid, - property, - crate::xinput::PropWhat::Deleted, - ); - } - } - } - // XI1 OpenDevice (minor 3). Xlib's `DevicePropertyNotify(dev, type, - // _class)` macro walks `XDevice->classes` (populated from this - // reply) for an `OtherClass(6)` entry, then computes - // type = entry.event_type_base + _propertyNotify(=6) - // _class = (deviceid << 8) | type - // and passes _class to `XSelectExtensionEvent`. An empty class - // list (our pre-fix stub) leaves _class = 0, and `xinput - // watch-props` silently subscribes to nothing. - // - // Verified against `mate-asahi-xorg.xtrace`: Xorg returns four - // entries — Button(1)/Valuator(2)/Feedback(3)/Other(6) with - // `event_type_base = 0x4c = 76` — and xinput's subsequent - // `SelectExtensionEvent` carries class `(deviceid<<8)|82`. - // We return the minimum compatible reply (one OtherClass entry) - // so watch-props gets DevicePropertyNotify events; the other - // three classes carry trailing per-class data (button count, - // valuator axes, feedback) we don't emit yet, so they stay out - // until a client is found to need them. - 3 => { - // Xorg Xi/opendev.c: an unknown device id AND the core - // (master) pointer/keyboard both yield BadDevice — XOpenDevice - // only opens extension devices (XTS XOpenDevice-3/-4). - { - let deviceid = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(deviceid) - || deviceid == crate::xinput::DEVICEID_MASTER_POINTER - || deviceid == crate::xinput::DEVICEID_MASTER_KEYBOARD - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(deviceid), - u16::from(minor), - XI2_MAJOR_OPCODE, - ); - } - } - // Mirror Xorg's OpenDevice reply layout (verified in - // mate-asahi-xorg.xtrace line 142667): four XInputClassInfo - // entries in the order Button(1), Valuator(2), Feedback(3), - // Other(6) with `event_type_base` values that line up the - // XI1 wire event codes against `XI_FIRST_EVENT`. - // - // The Other entry is the load-bearing one for property - // notification: xinput's Xlib `DevicePropertyNotify(dev, - // type, _class)` macro walks `XDevice->classes`, finds the - // OtherClass entry, and computes - // type = entry.event_type_base + _propertyNotify(=6) - // _class = (deviceid << 8) | type - // and passes _class to `XSelectExtensionEvent`. An empty - // class list (our pre-fix stub) leaves _class = 0 and - // `xinput watch-props` silently subscribes to nothing. - // - // The Button/Valuator/Feedback entries carry only their - // (class, event_type_base) tags here — the OpenDevice - // reply itself never includes per-class trailing data - // (buttons / axes / feedback descriptors live in separate - // requests). Including them empty-shaped matches Xorg's - // wire byte-for-byte, which Xlib appears to need for the - // `XDevice` to register as fully usable even though only - // the OtherClass entry is consumed for property events. - // Class tags (XI.h) + event_type_base offsets relative to - // `XI_FIRST_EVENT` (= 66; Xorg `Xi/extinit.c::FixExtensionEvents`): - // Key(0) base + 1 = 0x43 Button(1) base + 3 = 0x45 - // Valuator(2) base + 5 = 0x47 Feedback(3) base 0 (no event) - // Focus(5) base + 6 = 0x48 Other(6) base + 10 = 0x4c - const KEY_CLASS: u8 = 0; - const BUTTON_CLASS: u8 = 1; - const VALUATOR_CLASS: u8 = 2; - const FEEDBACK_CLASS: u8 = 3; - const FOCUS_CLASS: u8 = 5; - const OTHER_CLASS: u8 = 6; - // The class set MUST match the device's use: a pointer reports - // Button/Valuator/Feedback/Other; a keyboard reports - // Key/Feedback/Focus/Other (verified against mate-xorg.xtrace - // OpenDevice replies). Returning pointer classes for a keyboard - // contradicts ListInputDevices and trips clients' device model. - let deviceid = u16::from(*body.first().unwrap_or(&0)); - let is_keyboard = deviceid == crate::xinput::DEVICEID_MASTER_KEYBOARD - || deviceid == crate::xinput::DEVICEID_SLAVE_KEYBOARD; - let entries: [u8; 8] = if is_keyboard { - [ - KEY_CLASS, - XI_FIRST_EVENT + 1, - FEEDBACK_CLASS, - 0, - FOCUS_CLASS, - XI_FIRST_EVENT + 6, - OTHER_CLASS, - XI_FIRST_EVENT + 10, - ] - } else { - [ - BUTTON_CLASS, - XI_FIRST_EVENT + 3, - VALUATOR_CLASS, - XI_FIRST_EVENT + 5, - FEEDBACK_CLASS, - 0, - OTHER_CLASS, - XI_FIRST_EVENT + 10, - ] - }; - // CRITICAL: `num_classes` lives at byte 8 of xOpenDeviceReply - // (the first field after the 8-byte header), NOT the detail - // byte. Clients (Xlib XOpenDevice, Chromium's XI device init) - // read it there; the old code passed it as `fixed_reply`'s - // detail byte, leaving byte 8 = 0, so num_classes read as 0 on - // the wire and the class array below was invisible. That made - // OpenDevice contradict ListInputDevices' per-device class - // count → Chromium fatal CHECK / SIGTRAP on startup. - // length=2 = two extra 4-byte units (8 bytes of class entries). - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 2); - reply.push(4); // byte 8: num_classes - reply.extend_from_slice(&[0u8; 23]); // bytes 9..=31: header pad - reply.extend_from_slice(&entries); - debug!( - "client {} #{} XI1 OpenDevice device={deviceid} -> {} classes", - client_id.0, sequence.0, 4 - ); - buf.extend_from_slice(&reply); - } - // ── XI 1.x minors with request validation ────────────────── - // - // Spec-error checks first (the XTS XI scenario's "Got Success, - // Expecting " family — BadDevice/BadValue/BadMatch/ - // BadWindow/BadMode/BadClass per the XInput 1.x protocol spec, - // cross-checked against Xorg Xi/*.c). Success behavior is described - // per request below; capability boundaries such as absent motion - // history and device-resolution ranges are explicit rather than a - // blanket zero-reply fallback. - - // CloseDevice (void): xCloseDeviceReq { deviceid }. - 4 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - debug!( - "client {} #{} XI1 CloseDevice device={dev}", - client_id.0, sequence.0 - ); - } - // SetDeviceMode: { deviceid, mode }. Mode changes only make - // sense for devices with valuators (Xorg Xi/setmode.c). - 5 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_valuators(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // Store the mode (Relative=0 / Absolute=1) — - // DeviceStateNotify reports it in the `classes_reported` - // bits above ModeBitsShift. Xorg - // `Xi/setmode.c::ProcXSetDeviceMode` returns - // `AlreadyGrabbed` (reply byte 8) when another client - // holds the device's active grab; in that case the mode - // is NOT updated. xts5 XSetDeviceMode-2. - const ALREADY_GRABBED: u8 = 1; - let grabbed_elsewhere = state - .xi1_active_grabs - .get(&dev) - .is_some_and(|g| g.owner != client_id); - let status = if grabbed_elsewhere { - ALREADY_GRABBED - } else { - let mode = *body.get(1).unwrap_or(&0); - if mode <= 1 { - state - .xi1_device_input_state - .entry(dev) - .or_default() - .valuator_mode = mode; - } - 0 - }; - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.push(status); - reply.extend_from_slice(&[0u8; 23]); - buf.extend_from_slice(&reply); - } - // GetSelectedExtensionEvents: { window }. The trailing payload is - // this client's classes followed by all clients' classes for the - // requested window (Xorg Xi/getselev.c). - 7 => { - let win = u32::from_le_bytes([ - *body.first().unwrap_or(&0), - *body.get(1).unwrap_or(&0), - *body.get(2).unwrap_or(&0), - *body.get(3).unwrap_or(&0), - ]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let window = ResourceId(win); - let mut this_client: Vec = state - .clients - .get(&client_id.0) - .and_then(|client| client.xi1_window_event_classes.get(&window)) - .map(|classes| classes.iter().copied().collect()) - .unwrap_or_default(); - this_client.sort_unstable(); - - let mut all_clients: Vec = state - .clients - .values() - .filter_map(|client| client.xi1_window_event_classes.get(&window)) - .flat_map(|classes| classes.iter().copied()) - .collect(); - all_clients.sort_unstable(); - - let total_classes = this_client.len().saturating_add(all_clients.len()); - let length_words = u32::try_from(total_classes).unwrap_or(u32::MAX); - let this_count = u16::try_from(this_client.len()).unwrap_or(u16::MAX); - let all_count = u16::try_from(all_clients.len()).unwrap_or(u16::MAX); - let mut reply = x11::fixed_reply(byte_order, sequence, minor, length_words); - x11::write_u16(byte_order, &mut reply, this_count); - x11::write_u16(byte_order, &mut reply, all_count); - reply.extend_from_slice(&[0u8; 20]); - for class in this_client.into_iter().chain(all_clients) { - x11::write_u32(byte_order, &mut reply, class); - } - buf.extend_from_slice(&reply); - } - // ChangeDeviceDontPropagateList (void): { window, count, mode }, - // classes follow. mode ∈ {AddToList=0, DeleteFromList=1}. - 8 => { - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let mode = body[6]; - if mode > 1 { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_MODE, - u32::from(mode), - minor, - ); - } - let count = usize::from(u16::from_le_bytes([body[4], body[5]])); - let mut classes: Vec = Vec::with_capacity(count); - for i in 0..count { - let off = 8 + i * 4; - if off + 4 > body.len() { - break; - } - let class = - u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); - if !xi1_device_valid(xi1_event_class_device(class)) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_CLASS, - class, - minor, - ); - } - classes.push(class); - } - // mode 0 = AddToList, 1 = DeleteFromList. Xorg - // `Xi/chgdprop.c::ChangeDeviceDontPropagateList` applies the - // change to `OtherInputMasks.dontPropagateMask[deviceid]`; - // the deviceid is encoded in the high byte of each class so - // the per-device split is implicit in the class set. - let entry = state - .xi1_window_dont_propagate - .entry(ResourceId(win)) - .or_default(); - if mode == 0 { - for c in &classes { - entry.insert(*c); - } - } else { - for c in &classes { - entry.remove(c); - } - if entry.is_empty() { - state.xi1_window_dont_propagate.remove(&ResourceId(win)); - } - } - debug!( - "client {} #{} XI1 ChangeDeviceDontPropagateList win=0x{win:x} mode={mode} count={count}", - client_id.0, sequence.0 - ); - } - // GetDeviceDontPropagateList: { window }. Reply layout - // (XIproto.h:`xGetDeviceDontPropagateListReply`): - // bytes 0..1 = reply opcode (1) + pad - // bytes 2..4 = sequence - // bytes 4..8 = length (32-bit units of trailing class array) - // bytes 8..10 = count (CARD16) - // bytes 10..32 = pad - // trailing `count` × XEventClass (CARD32) at byte 32 - 9 => { - let win = u32::from_le_bytes([ - *body.first().unwrap_or(&0), - *body.get(1).unwrap_or(&0), - *body.get(2).unwrap_or(&0), - *body.get(3).unwrap_or(&0), - ]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let classes: Vec = state - .xi1_window_dont_propagate - .get(&ResourceId(win)) - .map(|set| set.iter().copied().collect()) - .unwrap_or_default(); - #[allow(clippy::cast_possible_truncation)] - let count = classes.len() as u16; - let length_words = u32::try_from(classes.len()).unwrap_or(u32::MAX); - let mut reply = x11::fixed_reply(byte_order, sequence, 0, length_words); - x11::write_u16(byte_order, &mut reply, count); // bytes 8..10 - reply.extend_from_slice(&[0u8; 22]); // pad to 32 - for c in &classes { - x11::write_u32(byte_order, &mut reply, *c); - } - buf.extend_from_slice(&reply); - } - // GetDeviceMotionEvents: { start, stop, deviceid }. Motion - // history needs valuators (Xorg Xi/getmev.c). - 10 => { - let dev = u16::from(*body.get(8).unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_valuators(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - let start = u32::from_le_bytes(body[0..4].try_into().expect("four bytes")); - let stop = u32::from_le_bytes(body[4..8].try_into().expect("four bytes")); - let history = motion_history_range(state, start, stop); - const XI_ABSOLUTE: u8 = 1; - let words_per_event = 1 + u32::from(XI1_POINTER_AXES); - let length_words = u32::try_from(history.len()) - .unwrap_or(u32::MAX) - .saturating_mul(words_per_event); - let mut reply = x11::fixed_reply(byte_order, sequence, minor, length_words); - x11::write_u32( - byte_order, - &mut reply, - u32::try_from(history.len()).unwrap_or(u32::MAX), - ); - reply.push(XI1_POINTER_AXES); - reply.push(XI_ABSOLUTE); - reply.extend_from_slice(&[0u8; 18]); - for record in history { - x11::write_u32(byte_order, &mut reply, record.time); - x11::write_u32( - byte_order, - &mut reply, - i32::from(record.root_x).cast_unsigned(), - ); - x11::write_u32( - byte_order, - &mut reply, - i32::from(record.root_y).cast_unsigned(), - ); - x11::write_u32(byte_order, &mut reply, 0); - x11::write_u32(byte_order, &mut reply, 0); - } - buf.extend_from_slice(&reply); - } - // ChangeKeyboardDevice: { deviceid }. Needs a device with keys - // (Xorg Xi/chgkbd.c). xts5 expects: - // 1. ChangeDeviceNotify (request=1 = NewKeyboard) - // 2. core MappingNotify (request=1 = MappingKeyboard) - // 3. reply - // — in that order on the wire. - 11 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_keys(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // 1. ChangeDeviceNotify for originator (if selected) + fanout. - if crate::core_loop::xi1_focus::xi1_client_wants_change_device_notify( - state, client_id, dev, - ) { - let time = state.timestamp_now(); - #[allow(clippy::cast_possible_truncation)] - let device_byte = dev as u8; - crate::xinput::encode_xi1_change_device_notify( - &mut buf, - byte_order, - crate::server::XI_FIRST_EVENT + crate::xinput::XI_CHANGE_DEVICE_NOTIFY_OFFSET, - device_byte, - sequence, - time, - 1, // NewKeyboard - ); - } - crate::core_loop::xi1_focus::emit_change_device_notify(state, client_id, dev, 1); - // 2. core MappingNotify (request=1 = MappingKeyboard) to all - // clients, including originator inline so the wire order is - // ChangeDeviceNotify → MappingNotify → reply. - let _ = x11::write_mapping_notify_event(&mut buf, byte_order, sequence, 1, 0, 0); - let others: Vec = state - .clients - .keys() - .filter(|id| **id != client_id.0) - .map(|id| ClientId(*id)) - .collect(); - let _dropped = - crate::core_loop::fanout::fanout_event_to_clients(state, &others, |b, s, o| { - let _ = x11::write_mapping_notify_event(b, o, s, 1, 0, 0); - }); - // 3. reply. - buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); - } - // ChangePointerDevice: { xaxis, yaxis, deviceid }. Needs - // valuators, and the named axes must exist (Xorg Xi/chgptr.c). - // Same event chain as ChangeKeyboardDevice but with request=0 - // (NewPointer) and core MappingNotify request=2 (MappingPointer). - 12 => { - let xaxis = *body.first().unwrap_or(&0); - let yaxis = *body.get(1).unwrap_or(&0); - let dev = u16::from(*body.get(2).unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_valuators(dev) - || xaxis >= XI1_POINTER_AXES - || yaxis >= XI1_POINTER_AXES - { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - if crate::core_loop::xi1_focus::xi1_client_wants_change_device_notify( - state, client_id, dev, - ) { - let time = state.timestamp_now(); - #[allow(clippy::cast_possible_truncation)] - let device_byte = dev as u8; - crate::xinput::encode_xi1_change_device_notify( - &mut buf, - byte_order, - crate::server::XI_FIRST_EVENT + crate::xinput::XI_CHANGE_DEVICE_NOTIFY_OFFSET, - device_byte, - sequence, - time, - 0, // NewPointer - ); - } - crate::core_loop::xi1_focus::emit_change_device_notify(state, client_id, dev, 0); - let _ = x11::write_mapping_notify_event(&mut buf, byte_order, sequence, 2, 0, 0); - let others: Vec = state - .clients - .keys() - .filter(|id| **id != client_id.0) - .map(|id| ClientId(*id)) - .collect(); - let _dropped = - crate::core_loop::fanout::fanout_event_to_clients(state, &others, |b, s, o| { - let _ = x11::write_mapping_notify_event(b, o, s, 2, 0, 0); - }); - buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); - } - // GrabDevice: { grabWindow, time, event_count, this_device_mode, - // other_devices_mode, ownerEvents, deviceid } + classes. Classes - // must name the grabbed device (XTS XGrabDevice-4/-13). - 13 => { - if body.len() < 16 { - return Ok(RequestOutcome::Handled); - } - let dev = u16::from(body[13]); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let this_mode = body[10]; - let other_mode = body[11]; - let owner_events = body[12]; - if this_mode > 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(this_mode), - minor, - ); - } - if other_mode > 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(other_mode), - minor, - ); - } - if owner_events > 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(owner_events), - minor, - ); - } - let count = usize::from(u16::from_le_bytes([body[8], body[9]])); - for i in 0..count { - let off = 16 + i * 4; - if off + 4 > body.len() { - break; - } - let class = - u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); - let class_dev = xi1_event_class_device(class); - if !xi1_device_valid(class_dev) || class_dev != dev { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_CLASS, - class, - minor, - ); - } - } - // Establish the active device grab. Status values per X.h: - // GrabSuccess 0, AlreadyGrabbed 1, GrabInvalidTime 2, - // GrabNotViewable 3. - let time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.xi1_last_grab_time); - let viewable = state - .resources - .window(ResourceId(win)) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - let status: u8 = if state - .xi1_active_grabs - .get(&dev) - .is_some_and(|g| g.owner != client_id) - { - 1 // AlreadyGrabbed - } else if !viewable { - 3 // GrabNotViewable - } else if time != 0 && (time < state.xi1_last_grab_time || time > now) { - 2 // GrabInvalidTime - } else { - state.xi1_active_grabs.insert( - dev, - crate::server::Xi1ActiveGrab { - owner: client_id, - deviceid: dev, - grab_window: ResourceId(win), - owner_events: owner_events != 0, - this_mode, - other_mode, - passive_detail: None, - }, - ); - state.xi1_last_grab_time = if time == 0 { now } else { time }; - // CheckGrabForSyncs: a sync this_mode freezes the - // device ONCE (FrozenNoEvent — no stored event, so - // Replay is a no-op on it); a sync other_mode holds - // the paired device on this grab's behalf. - crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( - state, - dev, - client_id, - this_mode == 0, - other_mode == 0, - ); - 0 // GrabSuccess - }; - debug!( - "client {} #{} XI1 GrabDevice device={dev} window=0x{win:x} status={status}", - client_id.0, sequence.0 - ); - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.push(status); - reply.extend_from_slice(&[0u8; 23]); - buf.extend_from_slice(&reply); - } - // UngrabDevice (void): { time, deviceid }. Body: time at - // bytes 0..4, deviceid at byte 4 — `xUngrabDeviceReq`. - 14 => { - let time = u32::from_le_bytes([ - *body.first().unwrap_or(&0), - *body.get(1).unwrap_or(&0), - *body.get(2).unwrap_or(&0), - *body.get(3).unwrap_or(&0), - ]); - let dev = u16::from(*body.get(4).unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - // Xorg `Xi/ungrdev.c::ProcXUngrabDevice` requires the - // request's time to be in `[grabTime, currentTime]` - // (CurrentTime = 0 passes both checks). Out-of-range - // timestamps silently skip the release — xts5 - // XUngrabDevice-2 asserts this. - let now = state.timestamp_now(); - let time_ok = time == 0 || (time >= state.xi1_last_grab_time && time <= now); - if time_ok - && state - .xi1_active_grabs - .get(&dev) - .is_some_and(|g| g.owner == client_id) - { - crate::core_loop::pointer_fanout::xi1_deactivate_device_grab(state, dev); - } - debug!( - "client {} #{} XI1 UngrabDevice device={dev}", - client_id.0, sequence.0 - ); - } - // GrabDeviceKey (void): { grabWindow, event_count, modifiers, - // modifier_device, grabbed_device, key, this_device_mode, - // other_devices_mode, ownerEvents } + classes. (The XTS prose - // for XGrabDeviceKey-19/-20/-21 says "BadValue", but the test - // error traps accept only the XI extension BadDevice/BadClass - // codes — verified empirically; Xorg's dixLookupDevice agrees.) - 15 => { - if body.len() < 16 { - return Ok(RequestOutcome::Handled); - } - let mods = u16::from_le_bytes([body[6], body[7]]); - let mod_dev = u16::from(body[8]); - let dev = u16::from(body[9]); - let key = body[10]; - let this_mode = body[11]; - let other_mode = body[12]; - let owner_events = body[13]; - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(mod_dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(mod_dev), - minor, - ); - } - if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(mod_dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // key: AnyKey (0) or within the advertised keycode range. - if key != 0 && key < XI1_KEY_MIN { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(key), - minor, - ); - } - if !xi1_modifiers_valid(mods) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mods), - minor, - ); - } - if this_mode > 1 || other_mode > 1 || owner_events > 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(this_mode.max(other_mode).max(owner_events)), - minor, - ); - } - let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let count = usize::from(u16::from_le_bytes([body[4], body[5]])); - for i in 0..count { - let off = 16 + i * 4; - if off + 4 > body.len() { - break; - } - let class = - u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); - if !xi1_device_valid(xi1_event_class_device(class)) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_CLASS, - class, - minor, - ); - } - } - // Conflicting grab by another client → BadAccess (XTS - // XGrabDeviceKey-16). - if state.xi1_passive_grabs.iter().any(|g| { - g.is_key - && g.owner != client_id - && g.deviceid == dev - && g.grab_window == ResourceId(win) - && (g.detail == key || g.detail == 0 || key == 0) - && (g.modifiers == mods || g.modifiers == 0x8000 || mods == 0x8000) - }) { - return xi1_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, minor); - } - state.xi1_passive_grabs.retain(|g| { - !(g.is_key - && g.owner == client_id - && g.deviceid == dev - && g.grab_window == ResourceId(win) - && g.detail == key - && g.modifiers == mods) - }); - state.xi1_passive_grabs.push(crate::server::Xi1PassiveGrab { - owner: client_id, - deviceid: dev, - grab_window: ResourceId(win), - detail: key, - modifiers: mods, - owner_events: owner_events != 0, - this_mode, - other_mode, - is_key: true, - }); - debug!( - "client {} #{} XI1 GrabDeviceKey device={dev}", - client_id.0, sequence.0 - ); - } - // UngrabDeviceKey (void): { grabWindow, modifiers, - // modifier_device, key, grabbed_device }. - 16 => { - if body.len() < 9 { - return Ok(RequestOutcome::Handled); - } - let mods = u16::from_le_bytes([body[4], body[5]]); - let mod_dev = u16::from(body[6]); - let key = body[7]; - let dev = u16::from(body[8]); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(mod_dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(mod_dev), - minor, - ); - } - if !xi1_device_has_keys(dev) - || (mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(mod_dev)) - { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - if key != 0 && key < XI1_KEY_MIN { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(key), - minor, - ); - } - if !xi1_modifiers_valid(mods) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mods), - minor, - ); - } - let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - state.xi1_passive_grabs.retain(|g| { - !(g.is_key - && g.owner == client_id - && g.deviceid == dev - && g.grab_window == ResourceId(win) - && (key == 0 || g.detail == key) - && (mods == 0x8000 || g.modifiers == mods)) - }); - debug!( - "client {} #{} XI1 UngrabDeviceKey device={dev}", - client_id.0, sequence.0 - ); - } - // GrabDeviceButton (void): { grabWindow, grabbed_device, - // modifier_device, event_count, modifiers, this_device_mode, - // other_devices_mode, button, ownerEvents } + classes. - 17 => { - if body.len() < 16 { - return Ok(RequestOutcome::Handled); - } - let dev = u16::from(body[4]); - let mod_dev = u16::from(body[5]); - let mods = u16::from_le_bytes([body[8], body[9]]); - let this_mode = body[10]; - let other_mode = body[11]; - let owner_events = body[13]; - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(mod_dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(mod_dev), - minor, - ); - } - if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(mod_dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - if !xi1_modifiers_valid(mods) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mods), - minor, - ); - } - if this_mode > 1 || other_mode > 1 || owner_events > 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(this_mode.max(other_mode).max(owner_events)), - minor, - ); - } - let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let button = body[12]; - // Validate the trailing XEventClass array (Xorg - // `Xi/grabdevb.c::ProcXGrabDeviceButton` → - // `CreateMaskFromList` → `BadClass`). Each class's high - // byte names a device id; any unknown deviceid is - // BadClass, including the `0xFFFFFFFF` sentinel xts5 - // GrabDeviceButton-21 builds. event_count lives at - // body[6..8] per `xGrabDeviceButtonReq`. - let event_count = usize::from(u16::from_le_bytes([body[6], body[7]])); - for i in 0..event_count { - let off = 16 + i * 4; - let Some(slice) = body.get(off..off + 4) else { - break; - }; - let class = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]); - if !xi1_device_valid(xi1_event_class_device(class)) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_CLASS, - class, - minor, - ); - } - } - if state.xi1_passive_grabs.iter().any(|g| { - !g.is_key - && g.owner != client_id - && g.deviceid == dev - && g.grab_window == ResourceId(win) - && (g.detail == button || g.detail == 0 || button == 0) - && (g.modifiers == mods || g.modifiers == 0x8000 || mods == 0x8000) - }) { - return xi1_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, minor); - } - state.xi1_passive_grabs.retain(|g| { - !(!g.is_key - && g.owner == client_id - && g.deviceid == dev - && g.grab_window == ResourceId(win) - && g.detail == button - && g.modifiers == mods) - }); - state.xi1_passive_grabs.push(crate::server::Xi1PassiveGrab { - owner: client_id, - deviceid: dev, - grab_window: ResourceId(win), - detail: button, - modifiers: mods, - owner_events: owner_events != 0, - this_mode, - other_mode, - is_key: false, - }); - debug!( - "client {} #{} XI1 GrabDeviceButton device={dev}", - client_id.0, sequence.0 - ); - } - // UngrabDeviceButton (void): { grabWindow, modifiers, - // modifier_device, button, grabbed_device }. - 18 => { - if body.len() < 9 { - return Ok(RequestOutcome::Handled); - } - let mods = u16::from_le_bytes([body[4], body[5]]); - let mod_dev = u16::from(body[6]); - let dev = u16::from(body[8]); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(mod_dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(mod_dev), - minor, - ); - } - if !xi1_device_has_buttons(dev) - || (mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(mod_dev)) - { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - if !xi1_modifiers_valid(mods) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mods), - minor, - ); - } - let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - if !xi1_window_exists(state, win) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - win, - minor, - ); - } - let button = body[7]; - state.xi1_passive_grabs.retain(|g| { - !(!g.is_key - && g.owner == client_id - && g.deviceid == dev - && g.grab_window == ResourceId(win) - && (button == 0 || g.detail == button) - && (mods == 0x8000 || g.modifiers == mods)) - }); - debug!( - "client {} #{} XI1 UngrabDeviceButton device={dev}", - client_id.0, sequence.0 - ); - } - // AllowDeviceEvents (void): { time, mode, deviceid }. Modes: - // AsyncThisDevice(0)..SyncAll(5). - 19 => { - let mode = *body.get(4).unwrap_or(&0); - let dev = u16::from(*body.get(5).unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if mode > 5 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mode), - minor, - ); - } - // Port of Xorg `AllowSome` (dix/events.c:1823-1936) over - // the two-device model. Mode → newState mapping per - // Xi/allowev.c: AsyncThisDevice(0)→THAWED, - // SyncThisDevice(1)→FREEZE_NEXT_EVENT, - // ReplayThisDevice(2)→NOT_GRABBED, - // AsyncOtherDevices(3)→THAW_OTHERS, - // AsyncAll(4)→THAWED_BOTH, SyncAll(5)→FREEZE_BOTH_NEXT_EVENT. - use crate::{ - core_loop::pointer_fanout::{ - xi1_compute_freezes, xi1_deactivate_device_grab, xi1_device_grab_owner, - xi1_other_input_device, xi1_route_device_event, - }, - server::Xi1SyncState, - }; - let time = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - let other_dev = xi1_other_input_device(dev); - let sync_state = |state: &ServerState, d: u16| { - state - .xi1_frozen - .get(&d) - .map_or(Xi1SyncState::Thawed, |f| f.state) - }; - let sync_other = - |state: &ServerState, d: u16| state.xi1_frozen.get(&d).and_then(|f| f.other); - // thisGrabbed / otherGrabbed / thisSynced / othersFrozen - // (dix/events.c:1830-1851). `sync.other` stores the owning - // client, and deactivation clears it, so `== client` means - // "held on behalf of a live grab of this client". - let this_grabbed = xi1_device_grab_owner(state, dev) == Some(client_id); - let other_grabbed = xi1_device_grab_owner(state, other_dev) == Some(client_id); - let this_synced = sync_other(state, dev) == Some(client_id) && other_grabbed; - let others_frozen = - other_grabbed && sync_state(state, other_dev) >= Xi1SyncState::FrozenNoEvent; - let this_frozen_by_grab = - this_grabbed && sync_state(state, dev) >= Xi1SyncState::FrozenNoEvent; - debug!( - "client {} #{} XI1 AllowDeviceEvents device={dev} mode={mode} \ - this_grabbed={this_grabbed} this_synced={this_synced} \ - others_frozen={others_frozen}", - client_id.0, sequence.0, - ); - // Gate 1: only act when this device is frozen by the - // client (directly or on another grab's behalf). - if !(this_frozen_by_grab || this_synced) { - return Ok(RequestOutcome::Handled); - } - // Gate 2: time validation — later than now or earlier than - // the client's last grab time → no effect. - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.xi1_last_grab_time); - if time != 0 - && (crate::core_loop::xi1_focus::time_after(time, now) - || crate::core_loop::xi1_focus::time_after(state.xi1_last_grab_time, time)) - { - return Ok(RequestOutcome::Handled); - } - match mode { - // AsyncThisDevice → THAWED. - 0 => { - if this_grabbed && let Some(f) = state.xi1_frozen.get_mut(&dev) { - f.state = Xi1SyncState::Thawed; - } - if this_synced && let Some(f) = state.xi1_frozen.get_mut(&dev) { - f.other = None; - } - let xid_map = backend.xid_map().clone(); - xi1_compute_freezes(state, backend, &xid_map); - } - // SyncThisDevice → FREEZE_NEXT_EVENT. - 1 => { - if this_grabbed { - state.xi1_frozen.entry(dev).or_default().state = - Xi1SyncState::FreezeNextEvent; - if this_synced && let Some(f) = state.xi1_frozen.get_mut(&dev) { - f.other = None; - } - let xid_map = backend.xid_map().clone(); - xi1_compute_freezes(state, backend, &xid_map); - } - } - // ReplayThisDevice → NOT_GRABBED: only for a grab - // frozen WITH a stored event; release the grab and - // reprocess that event as if the grab never took it - // (passive grabs get a fresh look at it). - 2 => { - if this_grabbed && sync_state(state, dev) == Xi1SyncState::FrozenWithEvent { - if this_synced && let Some(f) = state.xi1_frozen.get_mut(&dev) { - f.other = None; - } - let stored = state.xi1_frozen.get_mut(&dev).and_then(|f| f.stored.take()); - // Reprocessing masks out passive grabs at or - // above the released grab's window (Xorg - // syncEvents.replayWin → CheckDeviceGrabs). - let replay_floor = state.xi1_active_grabs.get(&dev).map(|g| g.grab_window); - if state.xi1_active_grabs.contains_key(&dev) { - xi1_deactivate_device_grab(state, dev); - } else if state.active_pointer_grab.is_some_and(|grab| grab.passive) { - // Xorg NOT_GRABBED → DeactivateGrab before the - // replay, passive flavor (mirrors - // apply_allow_events' passive NOT_GRABBED - // deactivation). - deactivate_passive_pointer_grab_crossings(state); - } else if state - .active_pointer_grab - .is_some_and(|g| g.owner == client_id) - { - // Explicit (or implicit) core grab: full - // deactivation (mirrors apply_allow_events' - // deactivate_core_pointer_grab call). - deactivate_core_pointer_grab(state, backend, client_id); - } - // Thaw dev after any deactivation. Arm A already - // thaws internally; re-thawing an already-thawed - // device is a no-op, and the no-core-grab case - // (previous behavior) simply thaws here. - if let Some(f) = state.xi1_frozen.get_mut(&dev) { - f.state = Xi1SyncState::Thawed; - } - if let Some(stored) = stored { - match stored { - crate::server::QueuedInputEvent::Xi1Routed(mut q) => { - q.replay_floor = replay_floor; - let _ = xi1_route_device_event(state, q, true); - } - crate::server::QueuedInputEvent::HostPointer(event) => { - let xid_map = backend.xid_map().clone(); - let _ = replay_frozen_pointer_event_to_state( - state, backend, &xid_map, event, - ); - } - crate::server::QueuedInputEvent::HostKey(event) => { - let _ = replay_frozen_key_to_focus(state, event); - } - // Only a device event activates a grab, so - // the stored slot never holds a raw event; - // processing one is plain master delivery. - crate::server::QueuedInputEvent::RawKey(event) => { - let _ = crate::core_loop::key_fanout::deliver_raw_key_master( - state, event, - ); - } - } - } - let xid_map = backend.xid_map().clone(); - xi1_compute_freezes(state, backend, &xid_map); - } - } - // AsyncOtherDevices → THAW_OTHERS: thaw every OTHER - // device held by this client (this device untouched). - 3 => { - if others_frozen { - if xi1_device_grab_owner(state, other_dev) == Some(client_id) - && let Some(f) = state.xi1_frozen.get_mut(&other_dev) - { - f.state = Xi1SyncState::Thawed; - } - if sync_other(state, other_dev) == Some(client_id) - && let Some(f) = state.xi1_frozen.get_mut(&other_dev) - { - f.other = None; - } - let xid_map = backend.xid_map().clone(); - xi1_compute_freezes(state, backend, &xid_map); - } - } - // AsyncAll → THAWED_BOTH / SyncAll → FREEZE_BOTH_NEXT_EVENT: - // both REQUIRE the other devices to be frozen by the - // client (XTS XAllowDeviceEvents-16/-18); they act on - // every device the client grabbed or held. - 4 | 5 => { - if others_frozen { - let new_state = if mode == 4 { - Xi1SyncState::Thawed - } else { - Xi1SyncState::FreezeBothNextEvent - }; - for d in [dev, other_dev] { - if xi1_device_grab_owner(state, d) == Some(client_id) { - state.xi1_frozen.entry(d).or_default().state = new_state; - } - if sync_other(state, d) == Some(client_id) - && let Some(f) = state.xi1_frozen.get_mut(&d) - { - f.other = None; - } - } - let xid_map = backend.xid_map().clone(); - xi1_compute_freezes(state, backend, &xid_map); - } - } - _ => unreachable!("mode validated above"), - } - } - // GetDeviceFocus: { deviceid }. Reply layout - // (xGetDeviceFocusReply, XIproto.h:709-721): focus CARD32 @8, - // time CARD32 @12, revertTo CARD8 @16, pad to 32. The focus - // field carries the raw stored value — None(0)/PointerRoot(1)/ - // FollowKeyboard(3) sentinels included (Xorg Xi/getfocus.c - // maps focus->win back to the sentinel, never resolving it). - 20 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - // NOTE: Xorg's `if (!dev->focus) return BadDevice` is NOT - // mirrored as a keyboard-only gate: real servers initialise - // a focus class on extension pointers too (XTS - // Miscellaneous-3..6 call SetDeviceFocus on Devs.Button / - // Devs.DvMod and expect Success). - let f = crate::core_loop::xi1_focus::device_focus(state, dev); - // Byte 1 = RepType = X_GetDeviceFocus (Xi/getfocus.c). - let mut reply = x11::fixed_reply(byte_order, sequence, minor, 0); - x11::write_u32(byte_order, &mut reply, f.focus); // bytes 8-11 - x11::write_u32(byte_order, &mut reply, f.time); // bytes 12-15 - reply.push(f.revert_to); // byte 16 - reply.extend_from_slice(&[0u8; 15]); // bytes 17-31: pad - debug!( - "client {} #{} XI1 GetDeviceFocus device={dev} -> focus=0x{:x} revert={}", - client_id.0, sequence.0, f.focus, f.revert_to - ); - buf.extend_from_slice(&reply); - } - // SetDeviceFocus (void): { focus, time, revertTo, device }. - // focus: None(0) / PointerRoot(1) / FollowKeyboard(3) / a valid - // viewable window. revertTo: RevertToNone(0)..FollowKeyboard(3). - // Mirrors Xorg Xi/setfocus.c → dix SetInputFocus - // (dix/events.c:4879): validate, then silently ignore stale / - // future timestamps, then store + emit DeviceFocusIn/Out. - 21 => { - if body.len() < 10 { - return Ok(RequestOutcome::Handled); - } - let focus = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - let req_time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let revert_to = body[8]; - let dev = u16::from(body[9]); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if revert_to > 3 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(revert_to), - minor, - ); - } - if !matches!(focus, 0 | 1 | 3) { - let Some(window) = state.resources.window(ResourceId(focus)) else { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - focus, - minor, - ); - }; - if window.map_state != crate::resources::MapState::Viewable { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - } - // Timestamp gate (dix/events.c:4920-4922): CurrentTime(0) - // maps to the server clock; a time later than "now" or - // earlier than the last-focus-change time is a silent no-op. - let now = state.timestamp_now(); - let time = if req_time == 0 { now } else { req_time }; - let prev = crate::core_loop::xi1_focus::device_focus(state, dev); - if crate::core_loop::xi1_focus::time_after(time, now) - || crate::core_loop::xi1_focus::time_after(prev.time, time) - { - debug!( - "client {} #{} XI1 SetDeviceFocus device={dev} stale time {time} \ - (now={now} last={}) — ignored", - client_id.0, sequence.0, prev.time - ); - return Ok(RequestOutcome::Handled); - } - crate::core_loop::xi1_focus::set_device_focus(state, dev, focus, revert_to, time); - debug!( - "client {} #{} XI1 SetDeviceFocus device={dev} focus=0x{focus:x} \ - revert={revert_to} time={time}", - client_id.0, sequence.0 - ); - } - // GetFeedbackControl: { deviceid }. yserver models one keyboard - // control + one pointer control (the same state core - // GetKeyboardControl/GetPointerControl expose). Report the device - // class's single default feedback (id 0): a KbdFeedbackState for - // key devices, a PtrFeedbackState for pointer devices — mirroring - // Xorg Xi/getfctl.c, where the KbdFeedback ctrl *is* the keyboard - // control. - 22 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - let feedbacks = if xi1_device_has_keys(dev) { - let kc = &state.keyboard_control; - x11::encode_kbd_feedback_state( - byte_order, - 0, - kc.bell_pitch, - kc.bell_duration, - kc.led_mask, - kc.global_auto_repeat, - kc.key_click_percent, - kc.bell_percent, - &kc.auto_repeats, - ) - } else { - let pc = &state.pointer_control; - x11::encode_ptr_feedback_state( - byte_order, - 0, - pc.accel_numerator, - pc.accel_denominator, - pc.threshold, - ) - }; - x11::write_get_feedback_control_reply(&mut buf, byte_order, sequence, 1, &feedbacks)?; - } - // ChangeFeedbackControl (void): { mask, deviceid, feedbackclass } - // followed by the class-specific control. Yserver advertises one - // KbdFeedback (class 0/id 0) on key devices and one PtrFeedback - // (class 1/id 0) on pointer devices. Both alias the shared core - // keyboard/pointer control, just like Xorg. - 23 => { - let dev = u16::from(*body.get(4).unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - let mask = u32::from_le_bytes([ - *body.first().unwrap_or(&0), - *body.get(1).unwrap_or(&0), - *body.get(2).unwrap_or(&0), - *body.get(3).unwrap_or(&0), - ]); - let feedback_class = *body.get(5).unwrap_or(&u8::MAX); - match feedback_class { - 0 => { - if body.len() != 28 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - minor, - ); - } - if !xi1_device_has_keys(dev) || body[9] != 0 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - minor, - ); - } - let mut control = state.keyboard_control.clone(); - let mut bad_value = |value: i32| { - xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - value.cast_unsigned(), - minor, - ) - }; - if mask & (1 << 0) != 0 { - let value = body[14] as i8; - control.key_click_percent = match value { - -1 => crate::server::KeyboardControlState::new().key_click_percent, - 0..=100 => value.cast_unsigned(), - _ => return bad_value(i32::from(value)), - }; - } - if mask & (1 << 1) != 0 { - let value = body[15] as i8; - control.bell_percent = match value { - -1 => crate::server::KeyboardControlState::new().bell_percent, - 0..=100 => value.cast_unsigned(), - _ => return bad_value(i32::from(value)), - }; - } - if mask & (1 << 2) != 0 { - let value = i16::from_le_bytes([body[16], body[17]]); - control.bell_pitch = match value { - -1 => crate::server::KeyboardControlState::new().bell_pitch, - 0.. => value.cast_unsigned(), - _ => return bad_value(i32::from(value)), - }; - } - if mask & (1 << 3) != 0 { - let value = i16::from_le_bytes([body[18], body[19]]); - control.bell_duration = match value { - -1 => crate::server::KeyboardControlState::new().bell_duration, - 0.. => value.cast_unsigned(), - _ => return bad_value(i32::from(value)), - }; - } - if mask & (1 << 4) != 0 { - let led_mask = - u32::from_le_bytes(body[20..24].try_into().expect("four bytes")); - let led_values = - u32::from_le_bytes(body[24..28].try_into().expect("four bytes")); - control.led_mask = (control.led_mask & !led_mask) | (led_values & led_mask); - } - let key = body[12]; - if mask & (1 << 6) != 0 { - if !(XI1_KEY_MIN..=XI1_KEY_MAX).contains(&key) { - return bad_value(i32::from(key)); - } - if mask & (1 << 7) == 0 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - minor, - ); - } - } - if mask & (1 << 7) != 0 { - let mode = body[13]; - if mask & (1 << 6) == 0 { - control.global_auto_repeat = match mode { - 0 => false, - 1 => true, - 2 => crate::server::KeyboardControlState::new().global_auto_repeat, - _ => return bad_value(i32::from(mode)), - }; - } else { - let index = usize::from(key >> 3); - let bit = 1 << (key & 7); - match mode { - 0 => control.auto_repeats[index] &= !bit, - 1 => control.auto_repeats[index] |= bit, - 2 => { - control.auto_repeats[index] = (control.auto_repeats[index] - & !bit) - | (crate::server::DEFAULT_AUTO_REPEATS[index] & bit); - } - _ => return bad_value(i32::from(mode)), - } - } - } - state.keyboard_control = control; - } - 1 => { - if body.len() != 20 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - minor, - ); - } - if !xi1_device_has_valuators(dev) || body[9] != 0 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - minor, - ); - } - let mut control = state.pointer_control.clone(); - let defaults = crate::server::PointerControlState::new(); - for (bit, offset, target, default, denominator) in [ - ( - 0, - 14, - &mut control.accel_numerator, - defaults.accel_numerator, - false, - ), - ( - 1, - 16, - &mut control.accel_denominator, - defaults.accel_denominator, - true, - ), - (2, 18, &mut control.threshold, defaults.threshold, false), - ] { - if mask & (1 << bit) == 0 { - continue; - } - let value = i16::from_le_bytes([body[offset], body[offset + 1]]); - if value == -1 { - *target = default; - } else if value < 0 || (denominator && value == 0) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - i32::from(value).cast_unsigned(), - minor, - ); - } else { - *target = value.cast_unsigned(); - } - } - state.pointer_control = control; - } - _ => { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - } - debug!( - "client {} #{} XI1 ChangeFeedbackControl device={dev} class={feedback_class} mask=0x{mask:x}", - client_id.0, sequence.0, - ); - } - // GetDeviceKeyMapping: { deviceid, firstKeyCode, count }. Range - // checks against the advertised 8..=255 keycode space. - 24 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - let first = *body.get(1).unwrap_or(&0); - let count = *body.get(2).unwrap_or(&0); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_keys(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - if first < XI1_KEY_MIN { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(first), - minor, - ); - } - if u16::from(first) + u16::from(count) > 256 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(count), - minor, - ); - } - // The XI1 keyboard devices (3 master, 5 slave) share the - // server's single physical keymap — Xorg's XkbGetCoreMap is - // per-device, but yserver models one keyboard. Reuse the core - // GetKeyboardMapping path so the device map matches what the - // client sees via opcode 101. - let (kpc, keysyms) = fetch_merged_keymap(state, backend, origin, first, count); - x11::write_get_device_key_mapping_reply(&mut buf, byte_order, sequence, kpc, &keysyms)?; - } - // ChangeDeviceKeyMapping (void): { deviceid, firstKeyCode, - // keySymsPerKeyCode, keyCodes }. - 25 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - let first = *body.get(1).unwrap_or(&0); - let count = *body.get(3).unwrap_or(&0); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if first < XI1_KEY_MIN || u16::from(first) + u16::from(count) > 256 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(first), - minor, - ); - } - // Write the keysym rows into the shared override store the - // read paths (minor 24 / core opcode 101) merge over the - // backend keymap. Body: deviceid(1) firstKeyCode(1) - // keySymsPerKeyCode(1) keyCodes(1) then keyCodes×kpk CARD32s. - // Without this the round-trip silently dropped the change - // (XTS XChangeDeviceKeyMapping-3). - let kpk = *body.get(2).unwrap_or(&0); - // Xorg XkbApplyMappingChange changes and notifies nothing for - // zero keys. - let xkb_change = if count == 0 { - None - } else { - apply_keymap_change( - state, - backend, - first, - kpk, - count, - &body[4.min(body.len())..], - ) - }; - // Same XKB notifications as the core request (Xorg: both reach - // XkbApplyMappingChange): MapNotify first, ControlsNotify last. - let xkb_event_base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - if let Some(change) = &xkb_change { - crate::core_loop::xkb_layout::send_xkb_map_notify( - state, - xkb_event_base, - change.map_notify, - ); - } - // The core MappingNotify only when the master keyboard changed - // (Xorg XkbSendLegacyMapNotify → XIShouldNotify), as for - // SetDeviceModifierMapping. - if count != 0 && dev == crate::xinput::DEVICEID_MASTER_KEYBOARD { - legacy_keyboard_mapping_notify(state, xkb_change.as_ref(), first, count); - } - // ChangeDeviceKeyMapping is void (no reply), so the event - // ordering question is moot: send to originator + others. - // request_kind=1 = MappingKeyboard. - if crate::core_loop::xi1_focus::xi1_client_wants_device_mapping_notify( - state, client_id, dev, - ) { - let time = state.timestamp_now(); - #[allow(clippy::cast_possible_truncation)] - let device_byte = dev as u8; - crate::xinput::encode_xi1_device_mapping_notify( - &mut buf, - byte_order, - crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MAPPING_NOTIFY_OFFSET, - device_byte, - sequence, - time, - 1, - first, - count, - ); - } - crate::core_loop::xi1_focus::emit_device_mapping_notify( - state, - Some(client_id), - dev, - 1, - first, - count, - ); - if let Some(change) = &xkb_change { - crate::core_loop::xkb_layout::send_keyboard_mapping_followups( - state, - xkb_event_base, - change, - (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), - ); - } - debug!( - "client {} #{} XI1 ChangeDeviceKeyMapping device={dev}", - client_id.0, sequence.0 - ); - } - // GetDeviceModifierMapping: { deviceid }. Keyboard devices - // share the core keymap, so the reply is the same - // modifier→keycode table the core GetModifierMapping handler - // serves (Xorg Xi/getmmap.c reads the per-device key class — - // ours all alias the core keyboard). - // - // This MUST be real data, not a zero stub: XTS's - // Setup_Extension_DeviceInfo only treats a device as - // modifier-capable when `max_keypermod > 0`, and a zero reply - // silently knocked out every ModMask-gated test (GrabDeviceButton, - // SetDeviceModifierMapping, UngrabDeviceKey-2, ... → UNTESTED). - // - // Wire layout (xGetDeviceModifierMappingReply, XIproto.h:1031): - // numKeyPerModifier lives at byte 8 — NOT the core reply's - // byte-1 data slot — followed by 8*numKeyPerModifier keycodes. - 26 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_keys(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // Prefer the per-device override stored by - // `XSetDeviceModifierMapping`; fall back to the backend's - // shared core map. xts5 SetDeviceModifierMapping-1 sets - // the map and immediately reads it back. - let (kpm, keycodes) = state - .xi1_modifier_map - .get(&dev) - .cloned() - .unwrap_or_else(|| { - backend - .get_modifier_mapping(origin) - .unwrap_or((0, Vec::new())) - }); - debug_assert_eq!(keycodes.len(), 8 * usize::from(kpm)); - let length_words = u32::from(kpm) * 2; // 8*kpm bytes / 4 - // Byte 1 = RepType = X_GetDeviceModifierMapping (Xi/getmmap.c). - let mut reply = x11::fixed_reply(byte_order, sequence, minor, length_words); - reply.push(kpm); // byte 8: numKeyPerModifier - reply.extend_from_slice(&[0u8; 23]); // bytes 9..=31: pad - reply.extend_from_slice(&keycodes); - debug!( - "client {} #{} XI1 GetDeviceModifierMapping device={dev} kpm={kpm}", - client_id.0, sequence.0 - ); - buf.extend_from_slice(&reply); - } - // SetDeviceModifierMapping: { deviceid, numKeyPerModifier, - // pad1, 8 × numKeyPerModifier keycodes }. - 27 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - let kpm = *body.get(1).unwrap_or(&0); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_keys(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - let need = 8usize * usize::from(kpm); - let keycodes: Vec = (0..need).filter_map(|i| body.get(4 + i).copied()).collect(); - if keycodes.len() != need { - return xi1_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, minor); - } - // Xorg ProcXSetDeviceModifierMapping → change_modmap, the core - // request's path: a keycode outside the keycode range (xts5 - // SetDeviceModifierMapping-8 probes MinKeyCode-1) or listed - // twice is BadValue; a held modifier key is MappingBusy. - // Busy changed nothing and notifies nothing (Xi/setmmap.c). On - // success the DeviceMappingNotify goes out before the XKB and - // core notifications: to the requester (xts5 does - // `Expect_Event` then `Expect_Reply`, so ahead of the reply too) - // and to every other client that selected it. - // request_kind=0 = MappingModifier. - let notify_device = |state: &mut ServerState| { - if crate::core_loop::xi1_focus::xi1_client_wants_device_mapping_notify( - state, client_id, dev, - ) { - let time = state.timestamp_now(); - #[allow(clippy::cast_possible_truncation)] - let device_byte = dev as u8; - let _dropped = - fanout_event_to_clients(state, &[client_id], |buf, seq, order| { - crate::xinput::encode_xi1_device_mapping_notify( - buf, - order, - crate::server::XI_FIRST_EVENT - + crate::xinput::XI_DEVICE_MAPPING_NOTIFY_OFFSET, - device_byte, - seq, - time, - 0, - 0, - 0, - ); - }); - } - crate::core_loop::xi1_focus::emit_device_mapping_notify( - state, - Some(client_id), - dev, - 0, - 0, - 0, - ); - }; - let status = match change_modifier_mapping( - state, - backend, - origin, - kpm, - &keycodes, - Some(dev), - notify_device, - ) { - ModmapChangeOutcome::Success => 0, - ModmapChangeOutcome::Busy => 1, - ModmapChangeOutcome::BadValue(value) => { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - value, - minor, - ); - } - }; - // xSetDeviceModifierMappingReply: RepType @1, success @8. - let mut reply = x11::fixed_reply(byte_order, sequence, minor, 0); - reply.push(status); - reply.extend_from_slice(&[0u8; 23]); - buf.extend_from_slice(&reply); - } - // GetDeviceButtonMapping: { deviceid }. Real reply: the 7-button - // identity map the device advertises in ListInputDevices — the - // old nElts=0 zero-stub contradicted the ButtonInfo class there, - // and SetDeviceButtonMapping's BadValue check (below) keys off - // this length. - 28 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_buttons(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // nElts lives at byte 8 (first byte after the reply header); - // map bytes follow the 32-byte header, padded to 4 bytes. - // Use the device's stored map if set (xts5 - // SetDeviceButtonMapping-1 verifies that a custom map - // round-trips); otherwise identity. - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 2); - reply.push(XI1_NUM_BUTTONS); - reply.extend_from_slice(&[0u8; 23]); - let stored = state.xi1_button_map.get(&dev).cloned(); - for i in 0..XI1_NUM_BUTTONS { - let mapped = stored - .as_ref() - .and_then(|m| m.get(usize::from(i)).copied()) - .unwrap_or(i + 1); - reply.push(mapped); - } - reply.push(0); // pad 7 -> 8 - buf.extend_from_slice(&reply); - } - // SetDeviceButtonMapping: { deviceid, map_length }. map_length - // must equal the device's button count (XTS - // XSetDeviceButtonMapping-6). - 29 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - let map_length = *body.get(1).unwrap_or(&0); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_buttons(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // Xorg's `setbmap.c::ProcXSetDeviceButtonMapping` does NOT - // reject mismatched `map_length` with BadValue. It calls - // `ApplyPointerMapping(dev, map, map_length, client)` which - // returns `MappingSuccess` whenever the map is a valid - // permutation of [0..N]. We approximate by accepting any - // `map_length <= XI1_NUM_BUTTONS` (the spec ceiling for our - // synthetic device) and emitting `MappingSuccess` as the - // reply status. Over-long maps remain BadValue so absurd - // requests don't silently succeed. - if map_length > XI1_NUM_BUTTONS { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(map_length), - minor, - ); - } - // Read the map bytes from the body (after the 4-byte - // header that holds deviceid/map_length/pad). xts5 - // SetDeviceButtonMapping-7 sets map[0] = map[1] (a - // non-zero duplicate) and expects a BadValue X error; - // Xorg `BadDeviceMap` (dix/devices.c) rejects any - // duplicate non-zero value. Zero (disabled button) may - // repeat. - let map_bytes: Vec = (0..usize::from(map_length)) - .filter_map(|i| body.get(4 + i).copied()) - .collect(); - let mut seen = std::collections::HashSet::new(); - for &b in &map_bytes { - if b != 0 && !seen.insert(b) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(b), - minor, - ); - } - } - // Persist the map so xts5 SetDeviceButtonMapping-1 sees - // it round-trip through GetDeviceButtonMapping. - state.xi1_button_map.insert(dev, map_bytes); - // Reply first, then DeviceMappingNotify event in the same - // outbound write. request_kind=2 = MappingPointer. - buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); - if crate::core_loop::xi1_focus::xi1_client_wants_device_mapping_notify( - state, client_id, dev, - ) { - let time = state.timestamp_now(); - #[allow(clippy::cast_possible_truncation)] - let device_byte = dev as u8; - crate::xinput::encode_xi1_device_mapping_notify( - &mut buf, - byte_order, - crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MAPPING_NOTIFY_OFFSET, - device_byte, - sequence, - time, - 2, - 0, - 0, - ); - } - crate::core_loop::xi1_focus::emit_device_mapping_notify( - state, - Some(client_id), - dev, - 2, - 0, - 0, - ); - } - // QueryDeviceState: { deviceid }. Snapshot of the device's - // key / button / valuator state (Xorg Xi/queryst.c) — the same - // source data DeviceStateNotify reports, in the request-reply - // envelope: num_classes at reply byte 8, then xKeyState / - // xButtonState (36 bytes each: class, length, count, pad, - // 32-byte down-bitmask) and xValuatorState (4 bytes + one - // INT32 per axis). `xinput query-state` consumes this. - // - // num_keys here is max_key_code - min_key_code + 1 (248) — - // ONE MORE than the deviceStateNotify event's max-min (247); - // Xorg is inconsistent between the two and clients are built - // against that, so mirror it. - 30 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - let dev_state = state - .xi1_device_input_state - .get(&dev) - .copied() - .unwrap_or_default(); - let mut data: Vec = Vec::new(); - let mut num_classes = 0u8; - if xi1_device_has_keys(dev) { - // xKeyState: keycodes 8..=255 → num_keys = 248. - data.push(0); // class = KeyClass - data.push(36); // length - data.push(248); // num_keys (max - min + 1) - data.push(0); // pad - data.extend_from_slice(&dev_state.keys_down); - num_classes += 1; - } - if xi1_device_has_buttons(dev) { - data.push(1); // class = ButtonClass - data.push(36); // length - data.push(7); // num_buttons - data.push(0); // pad - data.extend_from_slice(&dev_state.buttons_down); - num_classes += 1; - } - if xi1_device_has_valuators(dev) { - // 4 axes: X / Y are the sprite position, the two - // scroll axes carry no accumulated state. - data.push(2); // class = ValuatorClass - data.push(4 + 4 * 4); // length = header + 4 axes - data.push(4); // num_valuators - data.push(dev_state.valuator_mode); // mode (in-proximity) - // Stored axis values (Xorg axisVal): axes 0/1 track - // the sprite under real motion; fakes write their - // explicit payload. - for v in dev_state.valuators { - x11::write_u32(byte_order, &mut data, v.cast_unsigned()); - } - num_classes += 1; - } - debug_assert_eq!(data.len() % 4, 0); - let length_words = u32::try_from(data.len() / 4).unwrap_or(u32::MAX); - let mut reply = x11::fixed_reply(byte_order, sequence, 0, length_words); - reply.push(num_classes); // byte 8 - reply.extend_from_slice(&[0u8; 23]); // bytes 9..=31: pad - reply.extend_from_slice(&data); - debug!( - "client {} #{} XI1 QueryDeviceState device={dev} classes={num_classes}", - client_id.0, sequence.0 - ); - buf.extend_from_slice(&reply); - } - // SendExtensionEvent (void): { destination, deviceid, propagate, - // count, num_events } + events (32 bytes each) + classes. - 31 => { - if body.len() < 12 { - return Ok(RequestOutcome::Handled); - } - let dest = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - let dev = u16::from(body[4]); - let class_count = usize::from(u16::from_le_bytes([body[6], body[7]])); - let num_events = usize::from(body[8]); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - // Xorg Xi/sendexev.c order: device, then the class list - // (CreateMaskFromList → BadClass), and only then the - // destination window inside SendEvent — XTS - // XSendExtensionEvent-20 sends a stale window + bogus class - // and expects the BadClass. - let classes_off = 12 + num_events * 32; - // The XI swap table for minor 31 marks everything past the - // header as `OpaqueTail` because the per-event payload - // (the sender's byte order, like core SendEvent's xEvent - // template) must NOT be swapped. That leaves the trailing - // XEventClass[] in the client's native order; read each - // class with `byte_order` awareness rather than blind LE. - let read_class = |off: usize| -> Option { - let bytes = body.get(off..off + 4)?; - let arr = [bytes[0], bytes[1], bytes[2], bytes[3]]; - Some(match byte_order { - yserver_protocol::x11::ClientByteOrder::LittleEndian => u32::from_le_bytes(arr), - yserver_protocol::x11::ClientByteOrder::BigEndian => u32::from_be_bytes(arr), - }) - }; - for i in 0..class_count { - let off = classes_off + i * 4; - let Some(class) = read_class(off) else { - break; - }; - if !xi1_device_valid(xi1_event_class_device(class)) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_CLASS, - class, - minor, - ); - } - } - // Like core SendEvent, destination accepts the specials - // PointerWindow (0) and InputFocus (1). - if !matches!(dest, 0 | 1) && !xi1_window_exists(state, dest) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - dest, - minor, - ); - } - // Per Xorg `Xi/sendexev.c::ProcXSendExtensionEvent` → - // `Xi/exevents.c::SendEvent`: resolve the destination, - // then deliver each supplied event to (a) clients whose - // XI1 selection on the destination window intersects the - // request's class list, and (b) the window's CREATOR when - // the per-device mask is empty (the `noextensioneventclass` - // case — Xorg `DeliverToWindowOwner` short-circuits on - // `filter == CantBeFiltered` = `NoEventMask` = 0). The - // class-intersection rule preserves XI1 event chains - // (DeviceKeyPress + DeviceValuator continuation), which - // the client selects via the head class only. - // Propagate semantics are not yet honoured — direct-window - // match only, like core SendEvent with propagate=False. - // - // Specials (xserver.git Xi/exevents.c:2915-2944): - // - PointerWindow → sprite window (deepest mapped window - // under the pointer); - // - InputFocus → device's focus window, with PointerRoot - // falling back to the sprite and FollowKeyboard chasing - // the core focus inside `resolve_focus`. - let dest_window: Option = match dest { - 0 => Some(crate::core_loop::key_fanout::deepest_window_at_pointer( - state, - )), - 1 => { - let focus = crate::core_loop::xi1_focus::device_focus(state, dev).focus; - match crate::core_loop::xi1_focus::resolve_focus(state, focus) { - crate::core_loop::xi1_focus::Xi1FocusTarget::None => None, - crate::core_loop::xi1_focus::Xi1FocusTarget::PointerRoot => Some( - crate::core_loop::key_fanout::deepest_window_at_pointer(state), - ), - crate::core_loop::xi1_focus::Xi1FocusTarget::Window(f) => { - // Xorg `effectiveFocus` rule (xserver.git - // Xi/exevents.c:2936-2941): if the focus is - // an ancestor of (or equal to) the sprite, - // deliver to the sprite — the focus - // bounds propagation but the deepest - // pointer window is the actual target. - // Otherwise the sprite is outside the focus - // subtree and delivery goes to the focus - // directly. xts5 XSendExtensionEvent-3 - // probes the inferior-of-focus case. - let sprite = - crate::core_loop::key_fanout::deepest_window_at_pointer(state); - if f == sprite - || crate::core_loop::xi1_focus::is_ancestor(state, f, sprite) - { - Some(sprite) - } else { - Some(f) - } - } - } - } - w => Some(ResourceId(w)), - }; - if let Some(dest_window) = dest_window { - // Collect the request's class list (already - // validated above for `xi1_device_valid`). Same - // byte-order reasoning as the BadClass loop above — - // classes are in the sender's native order because the - // XI swap table can't carve them out of the variable - // event payload that precedes them. - let mut request_classes: Vec = Vec::with_capacity(class_count); - for i in 0..class_count { - let off = classes_off + i * 4; - let Some(class) = read_class(off) else { - break; - }; - request_classes.push(class); - } - // Xorg `Xi/grabdev.c::CreateMaskFromList` walks the - // class list and OR's per-class mask bits into the - // per-device mask. `noextensioneventclass` (low byte - // `_noExtensionEvent = 9` per XI.h:260) has no - // associated mask bit, so it contributes nothing — - // a request whose only classes are noextensioneventclass - // entries (or an empty list) ends up with an - // all-zero mask, which `DeliverToWindowOwner` treats - // as `CantBeFiltered` and delivers to the window - // creator unconditionally. Without this fall-through - // xts5 XSendExtensionEvent 1–4 (which always pass - // `noextensioneventclass`) fail because the test - // process never calls XSelectExtensionEvent first. - const XI1_NO_EXTENSION_EVENT_OFFSET: u8 = 9; - #[allow(clippy::cast_possible_truncation)] - let mask_is_zero = request_classes.is_empty() - || request_classes - .iter() - .all(|c| (c & 0xff) as u8 == XI1_NO_EXTENSION_EVENT_OFFSET); - let propagate = matches!(body.get(5), Some(&p) if p != 0); - let targets = xi1_send_extension_event_resolve_targets( - state, - dest_window, - &request_classes, - mask_is_zero, - propagate, - ); - if !targets.is_empty() { - // Pre-snapshot all event bytes so the fanout - // closure can borrow them per-recipient. - let mut events_bytes: Vec<[u8; 32]> = Vec::with_capacity(num_events); - for i in 0..num_events { - let off = 12 + i * 32; - let Some(ev) = body.get(off..off + 32) else { - break; - }; - events_bytes.push(ev.try_into().expect("32-byte slice")); - } - let targets_vec: Vec = targets.into_iter().collect(); - let _dropped = - fanout_event_to_clients(state, &targets_vec, |buf, seq, order| { - for ev_bytes in &events_bytes { - let mut out = *ev_bytes; - out[0] |= 0x80; // send_event - let seq_bytes = match order { - yserver_protocol::x11::ClientByteOrder::LittleEndian => { - seq.0.to_le_bytes() - } - yserver_protocol::x11::ClientByteOrder::BigEndian => { - seq.0.to_be_bytes() - } - }; - out[2] = seq_bytes[0]; - out[3] = seq_bytes[1]; - buf.extend_from_slice(&out); - } - }); - } - } - debug!( - "client {} #{} XI1 SendExtensionEvent device={dev}", - client_id.0, sequence.0 - ); - } - // DeviceBell (void): { deviceid, feedbackid, feedbackclass, - // percent }. Yserver exposes KbdFeedback id 0 on key devices but has - // no bell procedure, and exposes no BellFeedback. Xorg - // `Xi/devbell.c::ProcXDeviceBell` returns BadValue for both cases; - // unlike core Bell, this is not a successful bell-less no-op. - 32 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - let feedback_id = *body.get(1).unwrap_or(&0); - let feedback_class = *body.get(2).unwrap_or(&0); - #[allow(clippy::cast_possible_wrap)] - let percent = *body.get(3).unwrap_or(&0) as i8; - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - // Xorg validates percent before looking up the feedback. - if !(-100..=100).contains(&percent) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(*body.get(3).unwrap_or(&0)), - minor, - ); - } - if !matches!(feedback_class, 0 | 5) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(feedback_class), - minor, - ); - } - let feedback_exists = - feedback_class == 0 && feedback_id == 0 && xi1_device_has_keys(dev); - if !feedback_exists { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(feedback_id), - minor, - ); - } - // The feedback exists, but its BellProc is absent. - return xi1_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, minor); - } - // SetDeviceValuators: { deviceid, first_valuator, num_valuators, - // pad1, INT32 values[num_valuators] }. Body layout follows - // `xSetDeviceValuatorsReq` (XIproto.h:1144-1153). - 33 => { - let dev = u16::from(*body.first().unwrap_or(&0)); - let first = *body.get(1).unwrap_or(&0); - let num = *body.get(2).unwrap_or(&0); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if !xi1_device_has_valuators(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - if u16::from(first) + u16::from(num) > u16::from(XI1_POINTER_AXES) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(num), - minor, - ); - } - // Xorg `Xi/setdval.c::ProcXSetDeviceValuators` returns - // `AlreadyGrabbed` when another client holds an active - // grab on the device. `xSetDeviceValuatorsReply.status` - // sits at byte 8 (right after the 8-byte standard reply - // header) — XIproto.h:1249-1261. - const ALREADY_GRABBED: u8 = 1; - let grabbed_elsewhere = state - .xi1_active_grabs - .get(&dev) - .is_some_and(|g| g.owner != client_id); - if grabbed_elsewhere { - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.push(ALREADY_GRABBED); // byte 8: status - reply.extend_from_slice(&[0u8; 23]); // bytes 9-31: pad - buf.extend_from_slice(&reply); - } else { - // Persist the new axis values into - // `xi1_device_input_state` so the next - // DeviceStateNotify / QueryDeviceState reports them. - // xts5 XSetDeviceValuators 1 / 2 read each axis back - // immediately after the set and expect the supplied - // value verbatim. - let entry = state.xi1_device_input_state.entry(dev).or_default(); - for i in 0..usize::from(num) { - let off = 4 + i * 4; - let Some(slice) = body.get(off..off + 4) else { - break; - }; - let value = i32::from_le_bytes(slice.try_into().expect("4-byte slice")); - let idx = usize::from(first) + i; - if let Some(slot) = entry.valuators.get_mut(idx) { - *slot = value; - } - } - buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); - } - } - // GetDeviceControl: { control, deviceid }. DEVICE_RESOLUTION(1) - // is the only control defined for XI 1.x core; it needs - // valuators. Reply layout (`xGetDeviceControlReply` + - // `xDeviceResolutionState`, XIproto.h): - // bytes 0..32 standard reply header (length in 32-bit - // units of the trailing buf) - // bytes 32..40 xDeviceResolutionState header: - // control(2)=1, length(2)=trailing-bytes, - // num_valuators(4) - // bytes 40.. 3 × num_valuators × CARD32 — resolutions, - // min_resolutions, max_resolutions. - // xts5 ChangeDeviceControl-1/-2 set + read back via - // GetDeviceControl; without a real reply the test SEGFAULTs. - 34 => { - let control = - u16::from_le_bytes([*body.first().unwrap_or(&0), *body.get(1).unwrap_or(&0)]); - let dev = u16::from(*body.get(2).unwrap_or(&0)); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if control != 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(control), - minor, - ); - } - if !xi1_device_has_valuators(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - let num_axes = usize::from(XI1_POINTER_AXES); - let stored = state.xi1_resolution.get(&dev).cloned(); - let resolutions: Vec<[i32; 3]> = (0..num_axes) - .map(|i| { - stored - .as_ref() - .and_then(|v| v.get(i).copied()) - .unwrap_or([0, 0, 0]) - }) - .collect(); - // 8 bytes xDeviceResolutionState header + 3 × num_axes × 4 - let trailing_bytes = 8 + 3 * num_axes * 4; - let length_units = u32::try_from(trailing_bytes / 4).unwrap_or(u32::MAX); - let mut reply = x11::fixed_reply(byte_order, sequence, 0, length_units); - // Pad bytes 8..32 of the standard reply header. - reply.extend_from_slice(&[0u8; 24]); - // xDeviceResolutionState header - x11::write_u16(byte_order, &mut reply, 1); // control = DEVICE_RESOLUTION - #[allow(clippy::cast_possible_truncation)] - let ctl_len = trailing_bytes as u16; - x11::write_u16(byte_order, &mut reply, ctl_len); - x11::write_u32(byte_order, &mut reply, u32::try_from(num_axes).unwrap_or(0)); - // Three runs over axes: resolution, min_resolution, max_resolution. - for r in &resolutions { - x11::write_u32(byte_order, &mut reply, r[0].cast_unsigned()); - } - for r in &resolutions { - x11::write_u32(byte_order, &mut reply, r[1].cast_unsigned()); - } - for r in &resolutions { - x11::write_u32(byte_order, &mut reply, r[2].cast_unsigned()); - } - buf.extend_from_slice(&reply); - } - // ChangeDeviceControl: { control, deviceid } + xDeviceCtl - // { control, length, first_valuator, num_valuators, pad2, - // resolutions[] }. - 35 => { - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let control = u16::from_le_bytes([body[0], body[1]]); - let dev = u16::from(body[2]); - if !xi1_device_valid(dev) { - return xi1_error( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(dev), - minor, - ); - } - if control != 1 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(control), - minor, - ); - } - // Embedded xDeviceCtl follows at body[4..]; its control id - // must agree with the request's (Xorg Xi/chgdctl.c → - // BadMatch on mismatch). - if body.len() >= 6 { - let ctl_control = u16::from_le_bytes([body[4], body[5]]); - if ctl_control != control { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - } - if !xi1_device_has_valuators(dev) { - return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); - } - // Xorg initializes relative axes without physical resolution - // metadata as resolution/min_resolution/max_resolution = 0/0/0 - // (`dix/devices.c::InitValuatorClassDeviceStruct`). Yserver's - // synthetic relative axes do the same, so zero is the sole valid - // value and round-trips through GetDeviceControl; nonzero values - // are correctly outside the advertised range. - let mut staged: Vec<(usize, i32)> = Vec::new(); - if body.len() >= 10 { - let first = body[8]; - let num = body[9]; - if u16::from(first) + u16::from(num) > u16::from(XI1_POINTER_AXES) { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(num), - minor, - ); - } - for i in 0..usize::from(num) { - let off = 12 + i * 4; - if off + 4 > body.len() { - break; - } - let res = i32::from_le_bytes([ - body[off], - body[off + 1], - body[off + 2], - body[off + 3], - ]); - if res != 0 { - return xi1_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - res.cast_unsigned(), - minor, - ); - } - staged.push((usize::from(first) + i, res)); - } - } - // Xorg `Xi/chgdctl.c::ProcXChangeDeviceControl` returns - // `AlreadyGrabbed` (status byte 8) when another client - // holds an active grab on the device — xts5 - // ChangeDeviceControl-10. - const ALREADY_GRABBED: u8 = 1; - let grabbed_elsewhere = state - .xi1_active_grabs - .get(&dev) - .is_some_and(|g| g.owner != client_id); - let status = if grabbed_elsewhere { - ALREADY_GRABBED - } else { - // Persist the validated resolutions so the matching - // `XGetDeviceControl` reports them. - if !staged.is_empty() { - let entry = state - .xi1_resolution - .entry(dev) - .or_insert_with(|| vec![[0, 0, 0]; usize::from(XI1_POINTER_AXES)]); - for (axis, value) in &staged { - if let Some(row) = entry.get_mut(*axis) { - row[0] = *value; - } - } - } - 0 - }; - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - reply.push(status); - reply.extend_from_slice(&[0u8; 23]); - buf.extend_from_slice(&reply); - } - 50 => { - // XIGetFocus { deviceid:CARD16 } -> xXIGetFocusReply - // { focus:WINDOW @8, 20 bytes pad }. Xorg ProcXIGetFocus - // (Xi/xisetdevfocus.c) reports the device's raw focus (None=0 / - // PointerRoot=1 / FollowKeyboard=3 / window) without resolving - // the sentinels. Only keyboards have a focus class; pointers - // and unknown ids are BadDevice with no errorValue. The master - // keyboard's focus is the core focus; the slave keyboard's is - // its own (shared with XI1 GetDeviceFocus). - let dev = if body.len() >= 2 { - u16::from_le_bytes([body[0], body[1]]) - } else { - 0 - }; - if !xi1_device_has_keys(dev) { - return xi1_error(state, client_id, sequence, XI1_ERROR_BAD_DEVICE, 0, minor); - } - let focus = if dev == crate::xinput::DEVICEID_MASTER_KEYBOARD { - state.core_focus.raw - } else { - crate::core_loop::xi1_focus::device_focus(state, dev).focus - }; - let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); - x11::write_u32(byte_order, &mut reply, focus); // bytes 8-11 - reply.extend_from_slice(&[0u8; 20]); // bytes 12-31 pad - debug!( - "client {} #{} XIGetFocus device={dev} -> focus=0x{focus:x}", - client_id.0, sequence.0 - ); - buf.extend_from_slice(&reply); - } - 61 => { - if let Some(entries) = x11::parse_xi_barrier_release(body) { - for (deviceid, barrier_id, event_id) in entries { - if !(deviceid == 0 || deviceid == 1 || deviceid == 2) { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - XI1_ERROR_BAD_DEVICE, - u32::from(deviceid), - 61, - XI2_MAJOR_OPCODE, - ); - } - let Some(barrier) = state.pointer_barriers.get_mut(&barrier_id) else { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - barrier_id, - 61, - XI2_MAJOR_OPCODE, - ); - }; - if barrier.owner != client_id { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - barrier_id, - 61, - XI2_MAJOR_OPCODE, - ); - } - if barrier.event_id == event_id { - barrier.release_event_id = event_id; - } - } - } - } - 41 => { - return handle_xi_warp_pointer(state, backend, origin, client_id, sequence, body); - } - 43 => { - return handle_xi_change_hierarchy(state, client_id, sequence, byte_order, body); - } - 49 => return handle_xi_set_focus(state, client_id, sequence, body), - // Every minor in 1..=XINPUT_LAST_REQUEST has an arm above; like - // Xorg's ProcIDispatch, anything else is BadRequest. - _ => { - debug_assert!(minor == 0 || minor > XINPUT_LAST_REQUEST); - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(minor), - header.opcode, - ); - } - } - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - Ok(write_to_client(client, client_id, &buf)) -} - -#[allow(clippy::too_many_arguments)] -fn handle_xkb_request( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let minor = header.data; - if minor > XKB_LAST_REQUEST { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(minor), - header.opcode, - ); - } - debug!( - "client {} #{} XkbProxy minor={}", - client_id.0, sequence.0, minor - ); - // Xorg's per-request order: the request size (REQUEST_AT_LEAST_SIZE, - // for the handlers ported so far), then BadAccess for a client that - // hasn't called XkbUseExtension (every XKB request but UseExtension). - let min_body = match minor { - X_KB_SELECT_EVENTS => 12, - X_KB_SET_MAP => 32, - X_KB_SET_COMPAT_MAP => 12, - X_KB_SET_INDICATOR_MAP => 8, - X_KB_SET_NAMES | X_KB_SET_GEOMETRY => 24, - _ => 0, - }; - if body.len() < min_body { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - if minor != X_KB_USE_EXTENSION - && !crate::core_loop::xkb_select::xkb_initialized(state, client_id) - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_ACCESS, - 0, - u16::from(minor), - header.opcode, - ); - } - let byte_order = state - .clients - .get(&client_id.0) - .map_or(x11::ClientByteOrder::LittleEndian, |c| c.byte_order); - if minor == X_KB_USE_EXTENSION { - // Whether the client is supported is the core loop's decision (it - // tracks the client's XKB state), and so is the reply, which must - // be in the client's byte order. The backend still sees the request: - // a nested backend initialises XKB on its host connection with it. - let supported = crate::core_loop::xkb_select::use_extension(state, client_id, body); - let _backend_reply = { - let atoms = &mut state.atoms; - let mut intern = |name: &str| atoms.intern(name, false).0; - backend.xkb_proxy(origin, minor, body, &mut intern) - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let mut buf = Vec::with_capacity(32); - x11::write_xkb_use_extension_reply(&mut buf, byte_order, sequence, supported)?; - return Ok(write_to_client(client, client_id, &buf)); - } - // SelectEvents is applied here; on success the request still reaches - // the backend (a nested backend forwards it to its host). - if minor == X_KB_SELECT_EVENTS - && let Err((code, value)) = - crate::core_loop::xkb_select::select_events(state, client_id, body) - { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(minor), - header.opcode, - ); - } - // The Set* requests the backend's keyboard description implements (a - // port of Xorg's handler): its events, then its error. - let ancient = crate::core_loop::xkb_select::xkb_ancient(state, client_id); - let set_outcome = { - let atoms = &state.atoms; - let atom_name = |atom: u32| atoms.name(x11::AtomId(atom)).map(str::to_owned); - backend.xkb_set(minor, body, ancient, &atom_name) - }; - if let Some(outcome) = set_outcome { - send_xkb_set_events(state, &*backend, header.opcode, minor, &outcome.events); - if let Some((code, value)) = outcome.error { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - value, - u16::from(minor), - header.opcode, - ); - } - return Ok(RequestOutcome::Handled); - } - // XkbLatchLockState (minor 5): a group lock switches the authoritative - // keyboard group and broadcasts XkbStateNotify to subscribed clients. - // LatchLockState is a void request (no reply), so this runs in the - // pre-proxy region; the backend's xkb_proxy minor-5 returns None. - if minor == 5 - && let Some(requested_group) = crate::core_loop::xkb_layout::parse_latch_lock_group(body) - { - let old_group = backend.current_group(); - backend.set_locked_group(requested_group); - let group = backend.current_group(); - if group == old_group { - return Ok(RequestOutcome::Handled); - } - let base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - let (eff_mods, base_mods, latched_mods, locked_mods) = backend.current_xkb_mods(); - let subs = crate::core_loop::xkb_layout::subscribers(state, 0x0004); - let notify = x11::XkbStateNotify { - device_id: 1, - mods: eff_mods, - base_mods, - latched_mods, - locked_mods, - group, - locked_group: group, - changed: 0x0090, // XkbGroupStateMask | XkbGroupLockMask - keycode: 0, - event_type: 0, // caused by an XKB request, not a key - request_major: 136, - request_minor: 5, - }; - let _dropped = fanout_event_to_clients(state, &subs, |buf, seq, order| { - let _ = x11::write_xkb_state_notify(buf, order, seq, base, notify); - }); - state.last_xkb_mods = eff_mods; - // Dedup anchor: record the group we just announced so the - // compiled-`grp:`-key-action path in `key_event_fanout_to_state` - // (Driver 2) doesn't re-emit a redundant StateNotify on the - // next key. (Driver 2 sets the same field after its own emit.) - state.last_xkb_group = group; - } - // XkbGetKbdByName (minor 23): a real keymap load + reply, NOT the - // minimal stub. The backend owns the keymap/rmlvo/atom-resolution, so it - // parses the body, loads the requested multi-group keymap, and assembles - // the nested-block reply; on a successful load it hands back the - // XkbNewKeyboardInfo this core loop broadcasts as XkbNewKeyboardNotify to - // ALL clients (Xorg ProcXkbGetKbdByName: XkbSendNewKeyboardNotify after - // the reply). The fanout lives here because the client tables do. - if minor == 23 { - let kbn = { - let atoms = &mut state.atoms; - let mut intern = |name: &str| atoms.intern(name, false).0; - backend.xkb_get_kbd_by_name(body, &mut intern) - }; - if let Some((mut bytes, notify)) = kbn { - stamp_reply_sequence(&mut bytes, byte_order, sequence); - // Broadcast NewKeyboardNotify on a successful load, BEFORE writing - // the reply (Xorg order is reply-then-notify, but the notify fans - // out to a different client set; ordering across clients is - // independent, and emitting first keeps the reply write last so an - // early return can't drop it). - if let Some(info) = notify { - let base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - let all: Vec = state.clients.keys().map(|id| ClientId(*id)).collect(); - // A full XkbGetKeyboardByName load replaces the whole - // key-symbol table in Xorg, so stale ChangeKeyboardMapping - // overrides must not keep shadowing it (see the identical - // fix + rationale in `apply_rules_names_change`). - state.keymap_overrides.clear(); - // Legacy core MappingNotify(Keyboard) + MappingNotify(Modifier) - // to ALL clients, mirroring Xorg's XkbSendLegacyMapNotify - // companion to XkbSendNewKeyboardNotify. XKB-unaware clients - // (any plain-X11 WM that never calls XkbSelectEvents — e.g. - // one that resolves keybinds via XKeysymToKeycode once at - // startup) never see XkbNewKeyboardNotify, so without this - // they keep grabbing the pre-switch keycodes forever: typing - // reflects the new layout (translation is per-keystroke) but - // WM keyboard shortcuts stay stuck on the old one, because - // nothing ever told the WM to re-resolve keysym→keycode and - // re-`GrabKey`. This is the same pair `apply_rules_names_change` - // sends for the `_XKB_RULES_NAMES`-ChangeProperty path; real - // `setxkbmap` goes through *this* XkbGetKbdByName path instead, - // so it needs the same legacy fanout here. - let count = info - .max_keycode - .saturating_sub(info.min_keycode) - .saturating_add(1); - let _dropped = fanout_event_to_clients(state, &all, |buf, seq, order| { - let _ = x11::write_mapping_notify_event( - buf, - order, - seq, - 1, - info.min_keycode, - count, - ); - }); - let _dropped = fanout_event_to_clients(state, &all, |buf, seq, order| { - let _ = x11::write_mapping_notify_event(buf, order, seq, 0, 0, 0); - }); - let _dropped = fanout_event_to_clients(state, &all, |buf, seq, order| { - let _ = x11::write_xkb_new_keyboard_notify( - buf, - order, - seq, - base, - 1, - info.min_keycode, - info.max_keycode, - info.old_min_keycode, - info.old_max_keycode, - 136, // requestMajor = XkbReqCode - 23, // requestMinor = X_kbGetKbdByName - info.changed, - ); - }); - // Refresh `_XKB_RULES_NAMES` on the root so it reflects the - // newly-loaded layout — Xorg keeps this property current on - // every keymap change (e.g. Cinnamon's runtime layout-add). - // `notify` is Some only when the keymap actually changed. - crate::core_loop::xkb_layout::publish_xkb_rules_names(state, &*backend); - } - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &bytes)); - } - // Backend declined (no real keymap, e.g. test/v1 fixtures): fall - // through to the proxy's minimal-reply path below. - } - // Thread an atom interner so the backend can populate - // VirtualModNames in the GetNames reply (atoms live in the core - // loop's table; `backend` is a disjoint borrow from `state.atoms`). - let reply = { - let atoms = &mut state.atoms; - let mut intern = |name: &str| atoms.intern(name, false).0; - backend - .xkb_proxy(origin, minor, body, &mut intern) - .ok() - .flatten() - }; - if let Some(mut bytes) = reply { - stamp_reply_sequence(&mut bytes, byte_order, sequence); - // GetControls: the per-key repeat is the core keyboard feedback's - // (Xorg keeps XKB `per_key_repeat` and `autoRepeats` in sync), which - // lives here, not in the backend. - if minor == 6 && bytes.len() >= 92 { - bytes[60..92].copy_from_slice(&state.keyboard_control.auto_repeats); - } - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - return Ok(write_to_client(client, client_id, &bytes)); - } - Ok(RequestOutcome::Handled) -} - -/// Write `sequence` into bytes 2..4 of a reply a backend built, in the -/// client's byte order. -fn stamp_reply_sequence( - bytes: &mut [u8], - byte_order: x11::ClientByteOrder, - sequence: SequenceNumber, -) { - if let Some(field) = bytes.get_mut(2..4) { - field.copy_from_slice(&match byte_order { - x11::ClientByteOrder::LittleEndian => sequence.0.to_le_bytes(), - x11::ClientByteOrder::BigEndian => sequence.0.to_be_bytes(), - }); - } -} - -/// Send what an XKB Set* request did, in Xorg's order: each -/// `XkbSendNewKeyboardNotify` / `XkbSendNotification` with its legacy core -/// MappingNotify, the per-key repeat re-derivation copied to the core -/// keyboard feedback, `_XkbSetCompatMap`'s CompatMapNotify and -/// `XkbApplyLedMapChanges`' indicator notifications. `major`/`minor` are the -/// request's (the events' cause). -fn send_xkb_set_events( - state: &mut ServerState, - backend: &dyn Backend, - major: u8, - minor: u8, - events: &[crate::backend::XkbSetEvent], -) { - use crate::{ - backend::XkbSetEvent, - core_loop::xkb_select::{self, LegacyCause}, - }; - let base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - for event in events { - match event { - XkbSetEvent::NewKeyboard(info) => { - let recipients = xkb_select::new_keyboard_recipients(state, info.changed); - let _dropped = fanout_event_to_clients(state, &recipients, |buf, seq, order| { - let _ = x11::write_xkb_new_keyboard_notify( - buf, - order, - seq, - base, - 1, - info.min_keycode, - info.max_keycode, - info.old_min_keycode, - info.old_max_keycode, - major, - minor, - info.changed, - ); - }); - let num = info - .max_keycode - .wrapping_sub(info.min_keycode) - .wrapping_add(1); - xkb_select::send_legacy_map_notify( - state, - LegacyCause::NewKeyboardNotify, - info.changed, - info.min_keycode, - num, - ); - } - XkbSetEvent::Notification(change) => { - let m = change.map_notify; - if m.changed != 0 { - crate::core_loop::xkb_layout::send_xkb_map_notify(state, base, m); - xkb_select::send_legacy_map_notify( - state, - LegacyCause::MapNotify, - m.changed, - m.first_key_sym, - m.n_key_syms, - ); - } - crate::core_loop::xkb_layout::send_keyboard_mapping_followups( - state, - base, - change, - (major, minor), - ); - } - XkbSetEvent::Repeats(repeats) => { - let _ = crate::core_loop::xkb_layout::apply_repeats_to_core(state, repeats); - } - XkbSetEvent::CompatMap(notify) => { - crate::core_loop::xkb_layout::send_xkb_compat_map_notify(state, base, *notify); - } - XkbSetEvent::IndicatorMaps(change) => { - crate::core_loop::xkb_layout::send_indicator_maps_change(state, base, change); - } - XkbSetEvent::Names(notify) => { - crate::core_loop::xkb_layout::send_xkb_names_notify(state, base, *notify); - } - XkbSetEvent::IndicatorNames { - leds_defined, - state: lit, - } => { - crate::core_loop::xkb_layout::send_indicator_names_change( - state, - base, - *leds_defined, - *lit, - ); - } - } - } -} - -fn handle_reparent_window( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(request) = x11::reparent_window_request(body) else { - return Ok(RequestOutcome::Handled); - }; - let result = match state.resources.reparent_window(request) { - Ok(result) => result, - Err(crate::resources::ReparentWindowError::BadWindow) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - request.window.0, - 7, - ); - } - Err(crate::resources::ReparentWindowError::BadMatch) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - request.window.0, - 7, - ); - } - }; - let on_window = subscribers_by_id(state, result.window, 0x0002_0000); - let on_old_parent = subscribers_by_id(state, result.old_parent, 0x0008_0000); - let on_new_parent = if result.old_parent == result.new_parent { - Vec::new() - } else { - subscribers_by_id(state, result.new_parent, 0x0008_0000) - }; - debug!( - "client {} #{} ReparentWindow 0x{:x}: 0x{:x}->0x{:x} pos=({},{}) host_xid={:?} map_state={:?}->{:?} viewable+{} viewable-{}", - client_id.0, - sequence.0, - result.window.0, - result.old_parent.0, - result.new_parent.0, - result.x, - result.y, - result.host_xid, - result.old_map_state, - result.new_map_state, - result.delta.became_viewable.len(), - result.delta.became_unviewable.len(), - ); - if let Some(xid) = result.host_xid { - let new_host_parent = if result.new_parent == ROOT_WINDOW { - Some(backend.window_id()) - } else { - state - .resources - .window(result.new_parent) - .and_then(|w| w.host_xid) - .map(|h| h.as_raw()) - }; - if let Some(host_parent) = new_host_parent { - let child = xid.as_raw(); - if let Err(e) = - backend.reparent_subwindow(origin, child, host_parent, result.x, result.y) - { - panic!( - "reparent_subwindow failed after protocol validation: child=0x{child:x} \ - parent=0x{host_parent:x}: {e}" - ); - } - } - if result.old_parent == ROOT_WINDOW && result.new_parent != ROOT_WINDOW { - let _ = backend.update_host_event_mask( - origin, - xid.as_raw(), - crate::host_x11::POINTER_EVENT_MASK, - false, - ); - if let Err(err) = backend.register_subwindow(origin, result.window, xid.as_raw()) { - log::warn!( - "client {} register_subwindow for 0x{:x} on reparent failed: {err}", - client_id.0, - result.window.0 - ); - } - } - if result.old_parent != ROOT_WINDOW && result.new_parent == ROOT_WINDOW { - let _ = backend.update_host_event_mask( - origin, - xid.as_raw(), - crate::host_x11::SUBWINDOW_EVENT_MASK, - false, - ); - if let Err(err) = backend.register_top_level(origin, result.window, xid.as_raw()) { - log::warn!( - "client {} register_top_level for 0x{:x} on reparent failed: {err}", - client_id.0, - result.window.0 - ); - } else { - backend.on_window_became_top_level(state, xid.as_raw()); - } - } - // Step 2 (DRIFT 2): a reparent across the root boundary changes - // root's child set; reproject the backend top-level order from core. - if result.old_parent == ROOT_WINDOW || result.new_parent == ROOT_WINDOW { - backend.sync_top_level_order(state); - } - } - // Before the reconcile below, so a GRANT backing finds the leaf that carries its route. - realize_storage_for_delta(state, backend, origin, &result.delta); - let window = result.window; - let new_parent = result.new_parent; - let old_parent = result.old_parent; - let rx = result.x; - let ry = result.y; - let override_redirect = result.override_redirect; - // Phase 2: Xorg-style redirect reconciliation on reparent. - // Mirrors compUnredirectOneSubwindow + compRedirectOneSubwindow - // at /home/jos/Projects/xserver/composite/compwindow.c:453-454. - // The window's redirect state under RedirectSubwindows is - // inherited from its parent — when the parent changes, the - // inheritance changes too. RedirectWindow(W) is per-window - // and not affected. - // - // Without this, a window created under - // RedirectSubwindows(root, Manual) and reparented into a - // non-redirected ancestor (e.g. an XEMBED tray client like - // nm-applet reparenting into mate-panel's notification - // socket) keeps a stale backing. Paints land in that stale - // backing; the compositor reads the new ancestor's pixmap - // (which never received them) when building COW. - // - // Gated on `supports_redirect_activation()` for the same - // reason as `activate_redirect_backing_for` at - // process_request.rs:3289 — backends that don't opt in - // (v1, host-X11, and RecordingBackend in its default - // configuration) don't manage redirect state, so the - // redirect helpers would panic / silently misbehave there. - // Phase 2 tests opt in via - // `RecordingBackend::with_redirect_activation()` (see - // Task 6) and `KmsBackend::for_tests()` (which already - // returns `true`). - if backend.supports_redirect_activation() { - let old_parent_redirects_subwindows = - state.composite_redirects.contains_key(&(old_parent, true)); - let new_parent_redirects_subwindows = - state.composite_redirects.contains_key(&(new_parent, true)); - let directly_redirected = state.composite_redirects.contains_key(&(window, false)); - let had_backing = state - .resources - .window(window) - .is_some_and(|w| w.redirected_backing.is_some()); - - log::debug!( - "reparent reconcile: window=0x{:x} old_parent=0x{:x} new_parent=0x{:x} \ - old_redirects_sub={old_parent_redirects_subwindows} \ - new_redirects_sub={new_parent_redirects_subwindows} \ - directly_redirected={directly_redirected} had_backing={had_backing}", - window.0, - old_parent.0, - new_parent.0, - ); - if !directly_redirected { - if old_parent_redirects_subwindows && !new_parent_redirects_subwindows { - log::debug!( - "reparent reconcile: REVOKE window=0x{:x} (left redirected subtree)", - window.0, - ); - crate::core_loop::process_disconnect::teardown_redirect_for_window( - state, backend, origin, window, - ); - } else if !old_parent_redirects_subwindows - && new_parent_redirects_subwindows - && !had_backing - { - let new_mode = state - .composite_redirects - .get(&(new_parent, true)) - .expect("just checked contains_key") - .mode; - log::debug!( - "reparent reconcile: GRANT window=0x{:x} new_mode={new_mode:?} \ - (entered redirected subtree)", - window.0, - ); - activate_redirect_backing_for(state, backend, origin, window, new_mode); - } else if old_parent_redirects_subwindows && new_parent_redirects_subwindows { - let old_mode = state - .composite_redirects - .get(&(old_parent, true)) - .map(|r| r.mode); - let new_mode = state - .composite_redirects - .get(&(new_parent, true)) - .map(|r| r.mode); - if old_mode != new_mode - && let Some(new_mode) = new_mode - { - log::debug!( - "reparent reconcile: FLIP window=0x{:x} old_mode={old_mode:?} \ - new_mode={new_mode:?}", - window.0, - ); - flip_redirect_target_mode(state, backend, origin, window, new_mode); - } else { - log::debug!( - "reparent reconcile: no-op (both redirected, mode unchanged) \ - window=0x{:x} mode={old_mode:?}", - window.0, - ); - } - } else { - log::debug!( - "reparent reconcile: no-op (state already consistent) window=0x{:x}", - window.0, - ); - } - } else { - log::debug!( - "reparent reconcile: skipped window=0x{:x} has direct RedirectWindow", - window.0, - ); - } - } - // After the reconcile, so a revoke still sees the backing it tears down. - apply_viewability_delta_to_redirects(state, backend, origin, &result.delta); - release_storage_for_delta(state, backend, origin, &result.delta); - let _dropped = fanout_event_to_clients(state, &on_window, |buf, seq, order| { - x11::encode_reparent_notify_event( - buf, - seq, - order, - window, - window, - new_parent, - rx, - ry, - override_redirect, - ); - }); - let _dropped = fanout_event_to_clients(state, &on_old_parent, |buf, seq, order| { - x11::encode_reparent_notify_event( - buf, - seq, - order, - old_parent, - window, - new_parent, - rx, - ry, - override_redirect, - ); - }); - let _dropped = fanout_event_to_clients(state, &on_new_parent, |buf, seq, order| { - x11::encode_reparent_notify_event( - buf, - seq, - order, - new_parent, - window, - new_parent, - rx, - ry, - override_redirect, - ); - }); - Ok(RequestOutcome::Handled) -} - -fn handle_create_window( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let Some(request) = x11::create_window_request(header.data, body) else { - return Ok(RequestOutcome::Handled); - }; - debug!( - "client {} create window 0x{:x} parent=0x{:x} pos=({},{}) size={}x{} mask=0x{:x}", - client_id.0, - request.window.0, - request.parent.0, - request.x, - request.y, - request.width, - request.height, - request.event_mask.unwrap_or(0) - ); - let new_id = request.window.0; - let mask = request.event_mask.unwrap_or(0); - let window_id = request.window; - let parent = request.parent; - let geometry = (request.x, request.y, request.width, request.height); - // Xorg `dix/dispatch.c::ProcCreateWindow` calls dixLookupWindow on - // the parent first; BadWindow if the parent xid is stale. xts5 - // Xlib4 probes XCreateWindow / XCreateSimpleWindow with - // parent=badwin() and expects the protocol error. - if state.resources.window(parent).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - parent.0, - 1, - ); - } - // Xorg `dix/window.c::CreateWindow:769-786` resolves - // `class == CopyFromParent` against the parent, then enforces: - // - class must be InputOutput or InputOnly → BadValue. - // - parent class InputOnly + child class != InputOnly → BadMatch. - // - class InputOnly + (border_width != 0 || depth != 0) → BadMatch. - // xts5 Xlib4: XCreateSimpleWindow-10 (parent InputOnly path), - // XCreateWindow-31 (InputOnly+border_width), XCreateWindow-43 - // (parent InputOnly + InputOutput child), XCreateWindow-44 - // (InputOnly + non-zero depth). - let parent_class = state - .resources - .window(parent) - .map(|w| w.class) - .expect("parent existence verified above"); - let parent_class_value = parent_class.protocol_value(); - let effective_class = match request.class { - 0 => parent_class_value, // CopyFromParent → parent's class - v => v, - }; - if effective_class != 1 && effective_class != 2 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(request.class), - 1, - ); - } - if matches!(parent_class, crate::resources::WindowClass::InputOnly) && effective_class != 2 { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); - } - if effective_class == 2 && (request.border_width != 0 || request.depth != 0) { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); - } - // InputOnly value-mask check, same legal-mask as - // ChangeWindowAttributes — xts5 Xlib4 XCreateWindow-24 cycles - // every illegal bit through value_mask and expects BadMatch. - if effective_class == 2 { - const INPUTONLY_LEGAL_MASK: u32 = 0x0020 // CWWinGravity - | 0x0200 // CWOverrideRedirect - | 0x0800 // CWEventMask - | 0x1000 // CWDontPropagate - | 0x4000; // CWCursor - if (request.value_mask & !INPUTONLY_LEGAL_MASK) != 0 { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); - } - } - // BadIdChoice / BadMatch validation. - let validation_failed = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - let owned = crate::server::IdAllocator::validate_owned( - new_id, - handle.resource_id_base, - handle.resource_id_mask, - ); - let in_use = state.xid_occupied(request.window.0); - !owned || in_use - }; - if validation_failed { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - new_id, - 1, - ); - } - let visual_known = request.visual.0 == 0 || state.resources.is_known_visual(request.visual); - if !visual_known { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - request.visual.0, - 1, - ); - } - // Attribute value-id validation, matching Xorg's - // `dix/window.c::CreateWindow`. CWBackPixmap values 0/1 are - // reserved (None / ParentRelative); CWColormap value 0 in the - // typed enum is CopyFromParent. - if let Some(bg_pixmap) = request.background_pixmap - && bg_pixmap.0 > 1 - && state.resources.pixmap(bg_pixmap).is_none() - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - bg_pixmap.0, - 1, - ); - } - if let Some(Some(colormap)) = request.colormap - && state.resources.colormap(colormap).is_none() - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - colormap.0, - 1, - ); - } - // Border validation. The effective depth resolves CopyFromParent - // (depth 0) against the parent, matching - // `ResourceTable::create_window`. - let parent_depth = state - .resources - .window(parent) - .map(|w| w.depth) - .expect("parent existence verified above"); - let effective_depth = if request.depth == 0 { - parent_depth - } else { - request.depth - }; - // Xorg `dix/window.c:818`: a window whose depth differs from its - // parent's MUST supply a border attribute, because the inherited - // border (`:879`) would otherwise carry the parent's depth. InputOnly - // has no border at all and is exempt. - const CW_BORDER_PIXMAP: u32 = 0x0004; - const CW_BORDER_PIXEL: u32 = 0x0008; - if (request.value_mask & (CW_BORDER_PIXMAP | CW_BORDER_PIXEL)) == 0 - && effective_class != 2 - && effective_depth != parent_depth - { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); - } - // `dix/window.c:1251` CWBorderPixmap. CWBorderPixel overrides it and - // clears the bit before the pixmap is ever resolved (`:1298`), so a - // request carrying both is not validated against the pixmap. - if request.border_pixel.is_none() - && let Some(border_pixmap) = request.border_pixmap - { - if border_pixmap.0 == 0 { - // CopyFromParent: BadMatch unless the depths match. (The - // no-parent case cannot arise here — the parent xid was - // validated above.) - if effective_depth != parent_depth { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); - } - } else { - match state.resources.pixmap(border_pixmap) { - None => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - border_pixmap.0, - 1, - ); - } - Some(pixmap) if pixmap.depth != effective_depth => { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); - } - Some(_) => {} - } - } - } - state.resources.create_window(client_id, request); - if mask != 0 { - state - .clients - .get_mut(&client_id.0) - .expect("client registered") - .event_masks - .insert(window_id, mask); - } - let needs_host_xid = state - .resources - .window(window_id) - .is_some_and(|w| w.class != crate::resources::WindowClass::InputOnly); - if needs_host_xid { - let host_visual = resolve_host_subwindow_visual_to_state(state, window_id); - let host_parent: Option = if parent == ROOT_WINDOW { - crate::backend::WindowHandle::from_raw(backend.window_id()) - } else { - state.resources.window(parent).and_then(|w| w.host_xid) - }; - let local = state.resources.window(window_id); - let resolved_bg = state.resources.window_resolved_background(window_id); - // `window_resolved_background` returning None is MEANINGFUL: it - // says this window has no background, so the server paints - // nothing (X11 §CreateWindow — background-pixmap defaults to - // None). It returns None in exactly four cases, and a stored - // pixel is the wrong answer in all of them: a ParentRelative - // cycle; the window absent from the map (then `local` is None - // too); a ParentRelative chain that resolved to no background; - // and `background_none` itself. - // - // So DO NOT fall back to `w.background_pixel` here. For a - // background-None window that field holds the 0x00ffffff - // PLACEHOLDER `create_window` stores when the request carries no - // background attribute, and passing it on painted every such - // window's fresh storage WHITE — the storage half of - // `window_storage_init_covers_the_whole_allocation`, and the - // reason `default_window_init_color`'s None branch was dead for - // client windows. None reaches that safe default instead. - let host_bg_pixel = resolved_bg.map(|bg| bg.background_pixel); - let host_bg_pixmap = resolved_bg - .and_then(|bg| bg.background_pixmap_host_xid) - .map(|h| h.as_raw()) - .or_else(|| { - local - .and_then(|w| w.background_pixmap_host_xid) - .map(|h| h.as_raw()) - }); - let allocated = host_parent.and_then(|host_parent| { - match backend.create_subwindow( - origin, - host_parent, - geometry.0, - geometry.1, - geometry.2, - geometry.3, - request.border_width, - host_visual, - host_bg_pixel, - host_bg_pixmap, - ) { - Ok(handle) => Some(handle), - Err(err) => { - log::warn!( - "client {} create_subwindow for 0x{:x} failed: {err}", - client_id.0, - new_id - ); - None - } - } - }); - if let Some(host_handle) = allocated { - if let Some(w) = state.resources.window_mut(window_id) { - w.host_xid = Some(host_handle); - } - let host_xid = host_handle.as_raw(); - // #133 step 2 (P3): `create_subwindow` carries `border_width` - // on the wire but not the border SOURCE, so forward it now - // through the generic attribute route. Without this a window - // created with a border pixel that is never changed again - // would leave the backend mirror with no source at all — - // and CreateWindow inherits the parent's border - // (`dix/window.c:879`), so even a client that supplies no - // border attribute can start out with a non-default one. - if let Some(border) = state.resources.window(window_id).map(|w| w.border) { - let (value_mask, values) = border_source_cwa_values(border); - let _ = backend.change_subwindow_attributes(origin, host_xid, value_mask, &values); - } - let result = if parent == ROOT_WINDOW { - backend.register_top_level(origin, window_id, host_xid) - } else { - backend.register_subwindow(origin, window_id, host_xid) - }; - if let Err(err) = result { - log::warn!( - "client {} register host window for 0x{:x} failed: {err}", - client_id.0, - new_id - ); - } else if parent == ROOT_WINDOW { - backend.on_window_became_top_level(state, host_xid); - // Step 2 (DRIFT 2): a new root child changes the top-level - // set; reproject the backend order from core so the new - // window lands where core put it (e.g. below the COW). - backend.sync_top_level_order(state); - } - // L2 plan B.6b future-child hook: under spec, a freshly - // created child of a REDIRECT_SUBWINDOWS parent inherits - // the redirect. NameWindowPixmap's check at the top of - // NAME_WINDOW_PIXMAP already consults `composite_redirects` - // for the parent, so no per-child bookkeeping is needed - // until the backing-pixmap path lands. - } - } - // CreateNotify on parent (SubstructureNotify subscribers). - let create_notify_targets = subscribers_by_id(state, parent, 0x0008_0000); - if !create_notify_targets.is_empty() { - let geometry_opt = state.resources.window(window_id).map(window_geometry); - if let Some(geometry) = geometry_opt { - let override_redir = request.override_redirect.unwrap_or(false); - let _dropped = - fanout_event_to_clients(state, &create_notify_targets, |buf, seq, order| { - x11::encode_create_notify_event( - buf, - seq, - order, - parent, - window_id, - geometry, - override_redir, - ); - }); - } - } - debug!("client {} #{} CreateWindow", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_change_window_attributes( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(request) = x11::change_window_attributes_request(body) else { - return Ok(RequestOutcome::Handled); - }; - if state.resources.window(request.window).is_none() { - // Xorg `dix/dispatch.c::ProcChangeWindowAttributes` returns - // BadWindow via dixLookupWindow before applying any attribute - // changes. xts5 Xlib4 probes XChangeWindowAttributes and its - // wrappers (XSetWindowBackground / *BorderPixmap / *Colormap / - // XDefineCursor / XUndefineCursor / …) on badwin() and expects - // the protocol error. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - request.window.0, - 2, - ); - } - // Xorg `dix/window.c::ChangeWindowAttributes:1174`: an InputOnly - // window may only carry the `INPUTONLY_LEGAL_MASK` bits - // (CWWinGravity, CWEventMask, CWDontPropagate, CWOverrideRedirect, - // CWCursor); any other bit → BadMatch. xts5 Xlib4 - // XChangeWindowAttributes-26 cycles every illegal bit through the - // value_mask and expects BadMatch from each. - const INPUTONLY_LEGAL_MASK: u32 = 0x0020 // CWWinGravity - | 0x0200 // CWOverrideRedirect - | 0x0800 // CWEventMask - | 0x1000 // CWDontPropagate - | 0x4000; // CWCursor - let target_class = state - .resources - .window(request.window) - .map(|w| w.class) - .expect("window existence verified above"); - if matches!(target_class, crate::resources::WindowClass::InputOnly) - && (request.value_mask & !INPUTONLY_LEGAL_MASK) != 0 - { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 2); - } - // Resource-id validation of attribute values, mirroring Xorg's - // `dix/window.c::ChangeWindowAttributes` per-attribute - // `dixLookupResource`. Values 0 and 1 on CWBackPixmap are reserved - // (None / ParentRelative); colormap value 0 in the typed enum - // means CopyFromParent and is resolved against the parent. - if let Some(bg_pixmap) = request.background_pixmap - && bg_pixmap.0 > 1 - && state.resources.pixmap(bg_pixmap).is_none() - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - bg_pixmap.0, - 2, - ); - } - if let Some(Some(colormap)) = request.colormap - && state.resources.colormap(colormap).is_none() - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - colormap.0, - 2, - ); - } - if let Some(cursor) = request.cursor - && cursor.0 != 0 - && !state.resources.cursor_exists(cursor) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - 2, - ); - } - // `dix/window.c:1251` CWBorderPixmap. CWBorderPixel overrides it and - // clears the bit before the pixmap is resolved (`:1298`), so a - // request carrying both is never validated against the pixmap. - if request.border_pixel.is_none() - && let Some(border_pixmap) = request.border_pixmap - { - let (own_depth, parent_depth) = { - let window = state - .resources - .window(request.window) - .expect("window existence verified above"); - let parent_depth = if request.window == ROOT_WINDOW { - None - } else { - state.resources.window(window.parent).map(|p| p.depth) - }; - (window.depth, parent_depth) - }; - if border_pixmap.0 == 0 { - // CopyFromParent: BadMatch with no parent, or when the - // depths differ — the parent's border would carry the wrong - // depth for this window. - if parent_depth != Some(own_depth) { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 2); - } - } else { - match state.resources.pixmap(border_pixmap) { - None => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - border_pixmap.0, - 2, - ); - } - Some(pixmap) if pixmap.depth != own_depth => { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 2); - } - Some(_) => {} - } - } - } - if let Some(bg_pixmap) = request.background_pixmap { - debug!( - "client {} CWA bg_pixmap: window 0x{:x} ← 0x{:x} ({})", - client_id.0, - request.window.0, - bg_pixmap.0, - match bg_pixmap.0 { - 0 => "None", - 1 => "ParentRelative", - _ => "pixmap", - }, - ); - } - if let Some(event_mask) = request.event_mask { - debug!( - "client {} attrs window 0x{:x} mask=0x{:x}", - client_id.0, request.window.0, event_mask - ); - let entry = state - .clients - .get_mut(&client_id.0) - .expect("client registered"); - if event_mask == 0 { - entry.event_masks.remove(&request.window); - } else { - entry.event_masks.insert(request.window, event_mask); - } - } - let target_window = request.window; - let cursor_id = request.cursor; - let released = state.resources.change_window_attributes(request); - // Release a replaced bg / border pixmap on the host ONLY if it is - // fully orphaned: no other window background OR border references it - // AND the client no longer owns it (FreePixmap already happened — at - // which point handle_free_pixmap skipped the host free because the - // attribute reference was still live). Freeing while the client still - // owns the pixmap destroyed it server-side: e16 menu items blanked on - // hover because the bg swap to the hilite pixmap host-freed the kept - // "normal" pixmap the un-hover restore then pointed back at. - // - // Both reference checks gate BOTH releases: one host handle can be a - // background on one window and a border on another (nothing stops a - // client naming the same pixmap for both), so testing only the - // matching attribute would free storage the other kind still samples. - // - // DEDUPLICATED: one request can replace both attributes at once, and if - // both named the same tile then `background` and `border` hand back the - // SAME handle. Freeing it twice happens to be inert on KMS (the store - // entry is gone by the second call) but it is still a broken backend - // contract, and a recording or host-X11 backend sees the duplicate. - let mut released_hosts = [released.background, released.border] - .into_iter() - .flatten() - .collect::>(); - released_hosts.dedup_by_key(|h| h.as_raw()); - for old_host_xid in released_hosts { - if !state.resources.host_xid_still_referenced(old_host_xid) { - let _ = backend.free_pixmap(origin, old_host_xid.as_raw()); - state.resources.host_pixmap_freed(old_host_xid.as_raw()); - } - } - - if target_window == ROOT_WINDOW { - let root_bg = state.resources.window_resolved_background(ROOT_WINDOW); - let root_bg_host_xid = root_bg.and_then(|bg| bg.background_pixmap_host_xid); - debug!( - "client {} CWA(root) bg_pixmap={:?} bg_pixel={:?} root_bg_host_xid={:?}", - client_id.0, request.background_pixmap, request.background_pixel, root_bg_host_xid, - ); - if request.background_pixmap.is_some() { - if let Some(host_bg) = root_bg_host_xid { - let _ = backend.set_container_background_pixmap(origin, host_bg.as_raw()); - } else if let Some(bg_pixel) = root_bg.map(|bg| bg.background_pixel) { - let _ = backend.set_container_background_pixel(origin, bg_pixel); - } - } else if let Some(pixel) = request.background_pixel { - let _ = backend.set_container_background_pixel(origin, pixel); - } - } - - // Only a CWA that (re)selects input may promote focus — i.e. a - // window "advertising input later" by adding key events to its event - // mask. A CWA changing an unrelated attribute (cursor, background, - // ...) must never move the input focus; in X11 focus changes only - // via SetInputFocus / grabs. Without this gate, muffin setting the - // "fleur" move cursor on its guard window during a - // `_NET_WM_MOVERESIZE` drag stole focus to that window, which then - // turned the dragged app's own child-focus move into a - // `FocusOut(Nonlinear)` (GTK4 backdrop) and broke the drag. - - if target_window != ROOT_WINDOW - && (request.background_pixel.is_some() || request.background_pixmap.is_some()) - { - let host_xid = state - .resources - .window(target_window) - .and_then(|w| w.host_xid); - let resolved_bg = state.resources.window_resolved_background(target_window); - if let Some(host_xid) = host_xid { - let mut value_mask: u32 = 0; - let mut values: Vec = Vec::with_capacity(1); - if request.background_pixmap.is_some() { - if let Some(bg_pixmap_host_xid) = - resolved_bg.and_then(|bg| bg.background_pixmap_host_xid) - { - value_mask |= 1 << 0; - values.push(bg_pixmap_host_xid.as_raw()); - } else { - value_mask |= 1 << 1; - values.push(resolved_bg.map(|bg| bg.background_pixel).unwrap_or(0)); - } - } else if request.background_pixel.is_some() { - value_mask |= 1 << 1; - values.push(resolved_bg.map(|bg| bg.background_pixel).unwrap_or(0)); - } - let _ = - backend.change_subwindow_attributes(origin, host_xid.as_raw(), value_mask, &values); - } - } - - // #133 step 2 (P3): the border source needs its OWN forward. The - // background block above fires only on a background change, so - // before this a `CWBorderPixel` / `CWBorderPixmap` reached the - // backend by no route at all — awesome's focus recolour (its only - // border request shape) was dropped on the floor. Read the window's - // CURRENT `border` rather than the request fields: the resource - // layer has already applied CopyFromParent resolution and - // pixel-overrides-pixmap, so this sends the state that actually - // took effect. Unhosted / InputOnly windows have no host xid and - // are silently skipped, same as the background path. - if target_window != ROOT_WINDOW - && (request.border_pixel.is_some() || request.border_pixmap.is_some()) - { - let host_xid = state - .resources - .window(target_window) - .and_then(|w| w.host_xid); - let border = state.resources.window(target_window).map(|w| w.border); - if let (Some(host_xid), Some(border)) = (host_xid, border) { - let (value_mask, values) = border_source_cwa_values(border); - let _ = - backend.change_subwindow_attributes(origin, host_xid.as_raw(), value_mask, &values); - } - // #143 — report protocol DAMAGE for the ring the forward above - // just repainted. Xorg does exactly this, in - // `ChangeWindowAttributes` itself and on the same condition - // (`(vmaskCopy & (CWBorderPixel | CWBorderPixmap)) && pWin->viewable - // && HasBorder(pWin)`, `dix/window.c:1581-1589`): it subtracts - // `winSize` from `borderClip` and `PaintWindow(..., PW_BORDER)`s the - // difference, which lands as a `PolyFillRect` on the window's - // (composite backing) pixmap and so goes through `damagePolyFillRect` - // (`miext/damage/damage.c:1194`). Xorg does NOT compare old-vs-new - // border source, and neither does our backend forward - // (`backend.rs:20110` repaints on any `value_mask & 0x0c`), so the - // damage has to fire on exactly the same trigger or the reported - // region and the painted region drift apart. - // - // Without this, awesome's focus recolour repainted our backing - // correctly but told no compositor: picom, on `EXT_buffer_age` - // partial repaint, kept one ring colour per back buffer and - // alternated between them at frame rate (#143's border flicker). - // - // No-op for unbordered windows, for the root and for a - // non-viewable window. - let _dropped = accumulate_damage_border_to_state(state, target_window); - } - - if let Some(cid) = cursor_id { - let host_window_raw = if target_window == ROOT_WINDOW { - Some(backend.window_id()) - } else { - state - .resources - .window(target_window) - .and_then(|w| w.host_xid) - .map(|w| w.as_raw()) - }; - // X11 `cursor = None` (xid 0) means "clear the per-window - // cursor so the effective cursor inherits from the parent - // chain." Match Xorg `dix/window.c:1487-1491`, which sets - // `pCursor = (CursorPtr) None` in that case. Pre-fix, we - // silently dropped CWA cursor=0 because `cursor_host_xid(0)` - // returns None and the (Some, Some) match below failed — - // marco's resize-frame XDefineCursor(frame, None) reset never - // propagated to the backend, so the resize cursor sprite - // stayed visible after the pointer moved off the edge into - // the frame interior. - let cursor_host_xid = if cid.0 == 0 { - Some(0u32) - } else { - state.resources.cursor_host_xid(cid) - }; - if let (Some(hw), Some(ch)) = (host_window_raw, cursor_host_xid) { - let _ = backend.define_cursor(origin, hw, ch); - } - } - debug!( - "client {} #{} ChangeWindowAttributes", - client_id.0, sequence.0 - ); - Ok(RequestOutcome::Handled) -} - -/// #133 step 2 (P3): flatten a window's border source into the -/// `(value_mask, values)` pair `Backend::change_subwindow_attributes` -/// takes. The mask uses real X11 CW bit numbering — `0x04` -/// CWBorderPixmap, `0x08` CWBorderPixel — because the host-X11 backend -/// forwards mask and values verbatim to a real X server -/// (`host_x11/request.rs:1046`), so the correct bits make the nested -/// path work with no translation. -/// -/// A border is an either/or in Xorg (`PixUnion border` + -/// `borderIsPixel`, `include/windowstr.h:146`), so exactly one bit is -/// ever set. `Window::border` already has CopyFromParent resolved -/// eagerly (`dix/window.c:1251`), so this is a plain read with no -/// ParentRelative-style walk — unlike a background, a border has no -/// inherit-at-paint-time sentinel. -/// -/// A tile pixmap with no host storage degrades to the pixel bit with -/// value 0, mirroring the background block's "no host pixmap → send a -/// pixel" shape: a backend that cannot sample the tile is better off -/// with a defined solid colour than with a dangling xid. -fn border_source_cwa_values(border: BorderSource) -> (u32, Vec) { - match border { - BorderSource::Pixmap { - host_xid: Some(host), - .. - } => (0x04, vec![host.as_raw()]), - BorderSource::Pixmap { host_xid: None, .. } => (0x08, vec![0]), - BorderSource::Pixel(pixel) => (0x08, vec![pixel]), - } -} - -fn window_host_xid(state: &ServerState, window: ResourceId) -> u32 { - state - .resources - .window(window) - .and_then(|w| w.host_xid) - .map(|h| h.as_raw()) - .unwrap_or(window.0) -} - -fn reset_damage_notify_cycle_for_drawable(state: &mut ServerState, drawable: ResourceId) { - let mut drawables = vec![drawable]; - if let Some(window) = state.resources.window(drawable) { - drawables.extend( - window - .composite_named_pixmaps - .iter() - .map(|p| p.client_pixmap), - ); - } - for damage in state.damage_objects.values_mut() { - if drawables.contains(&damage.drawable) { - damage.pending_notify_fired = false; - } - } -} - -fn handle_configure_window( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(request) = x11::configure_window_request(body) else { - return Ok(RequestOutcome::Handled); - }; - log::trace!( - target: "yserver::input::restack", - "CONFIGURE-REQ client={} win={} stack_mode={:?} sibling={}", - state.debug_client_label(client_id), - state.debug_window_label(request.window), - request.stack_mode, - request - .sibling - .map_or_else(|| "None".to_string(), |s| state.debug_window_label(s)), - ); - // X11 spec / Xorg `dix/window.c::ConfigureWindow`: ConfigureWindow - // on the root window is accepted (no error) but has no visible - // effect — root geometry is owned by the screen/RandR, not by the - // client. Without this short-circuit we apply the client's - // width/height to `state.resources.window(ROOT_WINDOW)` and every - // subsequent on-screen check (e.g. GetImage's BadMatch validation) - // breaks because root reports the client's tiny dimensions instead - // of the KMS scanout dims. xts5 produced a 70x61 root resize that - // cascaded into ~1000 UNRES. - if request.window == ROOT_WINDOW { - debug!( - "client {} #{} ConfigureWindow on root — dropped (matches Xorg semantics)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - if state.resources.window(request.window).is_none() { - // Xorg `dix/dispatch.c::ProcConfigureWindow` returns BadWindow - // via dixLookupWindow before applying any geometry change. - // xts5 Xlib4 probes XConfigureWindow and its Xlib wrappers - // (XMoveWindow / XResizeWindow / XMoveResizeWindow / - // XRaiseWindow / XLowerWindow / XMapRaised — Xlib9 XRestack / - // XSetWindowBorderWidth) on badwin() and expects the protocol - // error. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - request.window.0, - 12, - ); - } - // Xorg `dix/window.c::ConfigureWindow` checks (in order, before - // any geometry change or SubstructureRedirect dispatch): - // 1. InputOnly + CWBorderWidth → BadMatch (xts5 Xlib4 - // XConfigureWindow-33 / XSetWindowBorderWidth-6). - // 2. CWSibling without CWStackMode → BadMatch (XConfigureWindow-30). - // 3. CWStackMode value > 4 → BadValue. - // 4. CWSibling: sibling xid unknown → BadWindow; sibling not - // actually a sibling of `window` or sibling==window → BadMatch - // (XConfigureWindow-31). - // 5. CWWidth=0 or CWHeight=0 → BadValue (XConfigureWindow-32). - const CW_BORDER_WIDTH: u16 = 0x0010; - const CW_SIBLING: u16 = 0x0020; - const CW_STACK_MODE: u16 = 0x0040; - let window_class = state - .resources - .window(request.window) - .map(|w| w.class) - .expect("window existence verified above"); - let window_parent = state - .resources - .window(request.window) - .map(|w| w.parent) - .expect("window existence verified above"); - if matches!(window_class, crate::resources::WindowClass::InputOnly) - && (request.value_mask & CW_BORDER_WIDTH) != 0 - { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 12); - } - if (request.value_mask & CW_SIBLING) != 0 && (request.value_mask & CW_STACK_MODE) == 0 { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 12); - } - if let Some(mode) = request.stack_mode - && mode > 4 - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mode), - 12, - ); - } - if let Some(sibling) = request.sibling { - let sibling_window = state.resources.window(sibling); - if sibling_window.is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - sibling.0, - 12, - ); - } - let sibling_parent = sibling_window.map(|w| w.parent); - if sibling_parent != Some(window_parent) || sibling == request.window { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 12); - } - } - if request.width == Some(0) || request.height == Some(0) { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 12); - } - let pre = state - .resources - .window(request.window) - .map(|w| (w.parent, w.override_redirect)); - let redirect_targets: Vec = if let Some((parent, false)) = pre { - let requester_has = state - .clients - .get(&client_id.0) - .and_then(|c| c.event_masks.get(&parent).copied()) - .is_some_and(|m| m & 0x0010_0000 != 0); - if requester_has { - Vec::new() - } else { - subscribers_by_id(state, parent, 0x0010_0000) - } - } else { - Vec::new() - }; - if !redirect_targets.is_empty() { - let parent = pre.map(|(p, _)| p).unwrap_or(ROOT_WINDOW); - let _dropped = fanout_event_to_clients(state, &redirect_targets, |buf, seq, order| { - x11::encode_configure_request_event(buf, seq, order, parent, request.window, &request); - }); - return Ok(RequestOutcome::Handled); - } - let old_size = state - .resources - .window(request.window) - .map(|w| (w.width, w.height)); - // X11 dix/window.c::ConfigureWindow: a ConfigureNotify is emitted - // only when the window is *actually* reconfigured. Snapshot the - // fields the event reports (geometry + above-sibling) before the - // change so we can suppress the notify for a no-op (e.g. a - // stacking-only request that doesn't reorder, or a same-value - // geometry). Emitting on a no-op restack makes Enlightenment - // re-restack forever (~8000 req/s). - let before_geom = state - .resources - .window(request.window) - .map(|w| (w.x, w.y, w.width, w.height, w.border_width)); - let before_above = state - .resources - .configure_notify_above_sibling(request.window); - let sibling_host_xid = request - .sibling - .and_then(|sibling| state.resources.window(sibling)) - .and_then(|w| w.host_xid) - .map(|h| h.as_raw()); - let configure = state - .resources - .configure_window(request) - .map(|w| (w.id, window_geometry(w), w.override_redirect)); - let host_xid = configure - .as_ref() - .and_then(|(id, _, _)| state.resources.window(*id).and_then(|w| w.host_xid)); - let parent = configure - .as_ref() - .and_then(|(id, _, _)| state.resources.window(*id).map(|w| w.parent)); - debug!( - "client {} #{} ConfigureWindow 0x{:x} mask=0x{:x} x={:?} y={:?} w={:?} h={:?} host_xid={:?}", - client_id.0, - sequence.0, - request.window.0, - request.value_mask, - request.x, - request.y, - request.width, - request.height, - host_xid, - ); - if let Some(xid) = host_xid { - let _ = backend.configure_subwindow( - origin, - xid.as_raw(), - crate::host_x11::HostSubwindowConfig { - x: request.x, - y: request.y, - width: request.width, - height: request.height, - border_width: request.border_width, - sibling: sibling_host_xid, - stack_mode: request.stack_mode, - }, - ); - } - // Step 2 (DRIFT 2): a stack_mode restack changed root's child order in - // the core tree (with full occlusion + COW cap). Reproject the - // backend's top-level z-order from core so the two cannot drift. - if request.stack_mode.is_some() { - backend.sync_top_level_order(state); - } - if let Some((window_id, geometry, override_redirect)) = configure { - let above_sibling = state.resources.configure_notify_above_sibling(window_id); - // Only emit ConfigureNotify when the window was actually - // reconfigured (geometry or stacking changed), per Xorg - // dix/window.c::ConfigureWindow. A stacking-only request that - // doesn't reorder, or a configure to identical geometry, is a - // no-op and must stay silent — otherwise a WM that re-applies its - // stacking policy on every ConfigureNotify (Enlightenment) spins - // forever. - let after_geom = state - .resources - .window(window_id) - .map(|w| (w.x, w.y, w.width, w.height, w.border_width)); - let configure_changed = before_geom != after_geom || before_above != above_sibling; - if configure_changed { - // Xorg calls the screen's ConfigNotify hook before it delivers - // the core ConfigureNotify (dix/window.c::ConfigureWindow). - // Present wraps that hook, so a client selecting both events - // observes Present::ConfigureNotify first. Keep this wire order: - // Mesa/CEF consume both streams for the same DRI3 window, and - // reversing them briefly left Steam's popup surface with its - // parent-relative coordinates while the native root child had - // already moved. - fire_present_configure_notify_for_window(state, window_id, geometry); - let _dropped = - emit_window_event_to_state(state, window_id, 0x0002_0000, |buf, seq, order| { - x11::encode_configure_notify_event( - buf, - seq, - order, - window_id, - window_id, - above_sibling, - geometry, - override_redirect, - ); - }); - if let Some(parent) = parent { - let _dropped = - emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { - x11::encode_configure_notify_event( - buf, - seq, - order, - parent, - window_id, - above_sibling, - geometry, - override_redirect, - ); - }); - } - } - // X11 window gravity: resizing a window repositions its children - // per each child's `win_gravity` (Xorg dix ResizeChildrenWinSize). - // Reposition in the host mirror and send GravityNotify. fvwm's - // window-shade relies on this — it parks a South-gravity client - // above the fold and reveals it by growing the client's holder; - // without gravity the client stays parked and renders as a black - // rectangle over the frame (air/silence HW 2026-07-02). - if let Some((ow, oh)) = old_size { - let moved = state.resources.apply_win_gravity( - window_id, - ow, - oh, - geometry.width, - geometry.height, - ); - for (child, nx, ny) in moved { - if let Some(h) = state.resources.window(child).and_then(|w| w.host_xid) { - let _ = backend.configure_subwindow( - origin, - h.as_raw(), - crate::host_x11::HostSubwindowConfig { - x: Some(nx), - y: Some(ny), - width: None, - height: None, - border_width: None, - sibling: None, - stack_mode: None, - }, - ); - } - // GravityNotify → child (StructureNotify) and its parent - // (SubstructureNotify), mirroring ConfigureNotify delivery. - let _dropped = - emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { - x11::encode_gravity_notify_event(buf, seq, order, child, child, nx, ny); - }); - let _dropped = - emit_window_event_to_state(state, window_id, 0x0008_0000, |buf, seq, order| { - x11::encode_gravity_notify_event(buf, seq, order, window_id, child, nx, ny); - }); - } - } - let resized = - old_size.is_some_and(|(ow, oh)| geometry.width != ow || geometry.height != oh); - let old_border_width = before_geom.map_or(geometry.border_width, |g| g.4); - if resized || old_border_width != geometry.border_width { - rotate_redirected_backing_on_resize( - state, - backend, - origin, - window_id, - geometry.width, - geometry.height, - false, - old_border_width, - ); - } - // NOTE (Issue 2 — 2026-07-01): a pure move MUST NOT rotate the - // redirected backing. picom glx holds a one-time `NameWindowPixmap` - // alias to the original backing (its GLX texture never re-binds - // on move), so any swap breaks the alias: the live client content - // starts landing in a new backing picom never samples, and the - // frame visually freezes ("btop stops animating when dragged"). - // The WIP `else if moved { rotate(..., true) }` that briefly lived - // here in commit bb3cc70d was this regression — reverted. - // X11 Composite + DAMAGE interaction: configuring a redirected - // window (move / resize / border / stack-order) changes its - // screen-space presentation. The pixel content of the - // redirected backing doesn't change, but the compositor MUST - // recomposite the moved-from + moved-to regions. Xorg - // signals this by emitting a `DamageNotify` on the window - // for the full window-local extent at the new geometry - // (xserver/composite/compwindow.c). Measured divergence on a - // mate-with-compositing drag: Xephyr emitted 776 DamageNotify - // events to marco over the run; yserver emitted 0. Without - // these events marco's compositor never marked the moved - // window dirty, its SetPictureClipRectangles excluded the - // window's region, and composites against the redirected - // backing no-op'd — producing the "CC disappears on drag / - // muddy bands on caja-redraw" symptom. - // - // Apply to the window itself. `accumulate_damage_full_to_state` - // walks the ancestor chain so any compositor subscribed - // higher in the tree also gets a translated rect. Only fires - // when a damage object exists on the drawable (the helper - // filters on `damage_object.drawable == this`), so cost is - // zero for unredirected/uncomposited windows. - // Xorg's Composite wakeup on ConfigureWindow is about visible - // geometry changes of redirected windows. Pure restacks - // (CWSibling/CWStackMode only) do affect stacking order, but - // they are not modeled as "whole window damaged" events. Doing - // that here seeds bogus fullscreen damage on marco's desktop - // window (0x01300005), which then collapses the compositor's - // update region before later dialog composites run. - const CONFIGURE_DAMAGE_GEOMETRY_MASK: u16 = 0x001f; // x|y|w|h|border - let geometry_changed = (request.value_mask & CONFIGURE_DAMAGE_GEOMETRY_MASK) != 0; - // Gate on Viewable, mirroring the Expose path below. Xorg - // damages a redirected window on configure only when it is - // realized/viewable (compWindowUpdateAutomatic runs on realized - // windows). i3's floating-drag creates a "floatingcon" root - // child, sizes/moves it during the drag, but never maps it — - // under an inherited RedirectSubwindows this path would emit - // full-window DamageNotify for that unmapped window, and the - // compositor (fastcompmgr) NameWindowPixmaps it and composites - // its stale backing at the drag position (the smear trail). - let viewable = state - .resources - .window(window_id) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - if geometry_changed - && viewable - && let Some(mode) = effective_redirect_mode_for_window(state, window_id) - { - log::trace!( - target: "yserver_core::core_loop::damage_fanout", - "configure_damage_emit: window=0x{:x} geom=({},{} {}x{}) old_size={:?} resized={} mode={:?} mask=0x{:x}", - window_id.0, - geometry.x, - geometry.y, - geometry.width, - geometry.height, - old_size, - resized, - mode, - request.value_mask, - ); - let _dropped = accumulate_damage_full_to_state(state, window_id); - } else { - log::trace!( - target: "yserver_core::core_loop::damage_fanout", - "configure_damage_skip: window=0x{:x} geom=({},{} {}x{}) old_size={:?} resized={} geometry_changed={} mask=0x{:x}", - window_id.0, - geometry.x, - geometry.y, - geometry.width, - geometry.height, - old_size, - resized, - geometry_changed, - request.value_mask, - ); - } - // A resize exposes the window in EITHER direction. Xorg draws no - // grow/shrink distinction: `miResizeWindow` copies the whole NEW - // clip list into the exposed region — "the entire window is - // trashed unless bitGravity recovers portions of it", - // `RegionCopy(&pWin->valdata->after.exposed, &pWin->clipList)` - // (`mi/miwindow.c:466-472`) — and only the bits a non-Forget - // `bitGravity` actually moved are subtracted from it afterwards - // (`mi/miwindow.c:596-599`). Under the default ForgetGravity - // `oldWinClip` stays NULL (`mi/miwindow.c:403-406`), nothing is - // subtracted, and the full window is reported for a shrink just - // as for a grow. The background state does not gate the event - // either: `miWindowExposures` paints first and sends second, and - // the `case None: return;` early-out lives in the PAINT - // (`mi/miexpose.c:387-389` and `:438-440`), so a background-None - // window keeps its pixels AND still receives the Expose. - // - // We used to emit this for a grow only, and that is #143's - // "already open windows get broken rendering": awesome retiles an - // xterm smaller, `configure_subwindow` re-tiles the leaf from the - // window's background (black on a dark terminal), and with no - // Expose nothing ever asks xterm to repaint. The prompt line came - // back because xterm redraws it anyway; the static rows of the - // shell banner stayed black for good. - // - // The region is the whole window for every gravity, not only - // ForgetGravity. Xorg would report just the newly-added strip - // under e.g. NorthWestGravity, because it really moved the old - // bits; this server has no bit-gravity path at all (the attribute - // reaches the render backend by no route — see `LeafContent` and - // `configure_subwindow`), so the pixels are gone whatever the - // attribute says and a narrower Expose would leave the window - // black. That narrowing is a separate, tracked divergence. - if resized { - // Per X11 spec, Expose fires only for visible regions. A - // resize-configure on an unmapped (or Unviewable) window has no - // visible region, so suppress the Expose until the window - // becomes Viewable (MapWindow's own viewable-gated Expose path - // covers that case). Without this gate, marco-style - // reparenting WMs make Firefox react to a phantom Expose ~50 - // requests before MapNotify lands: FF paints its - // transparent-black background into the redirected backing, - // marks the window clean, and the actual content never reaches - // the compositor — visible as "empty shadow / blank profile - // chooser." Xorg only emits Expose post-Map. - let viewable = state - .resources - .window(window_id) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - if viewable { - let _dropped = - emit_window_event_to_state(state, window_id, 0x0000_8000, |buf, seq, order| { - x11::encode_expose_event( - buf, - seq, - order, - window_id, - 0, - 0, - geometry.width, - geometry.height, - 0, - ); - }); - let _dropped = emit_expose_subtree_to_state(state, window_id); - } - } - } - // A confined pointer follows its confine window — re-clamp after - // any geometry change (Xorg ConfineCursorToWindow on configure; - // XGrabButton-25 moves confine_to and expects the pointer pulled - // along). - if state.pointer_confine_to.0 != 0 { - confine_pointer_now(state, backend); - } - Ok(RequestOutcome::Handled) -} - -fn handle_destroy_window( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(window) = x11::free_resource_id(body) { - // Xorg `dix/dispatch.c::ProcDestroyWindow` returns BadWindow - // via dixLookupWindow before tearing the subtree down. xts5 - // Xlib4 probes XDestroyWindow on badwin() and expects the - // protocol error. - if state.resources.window(window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 4, - ); - } - destroy_window_subtree(state, backend, origin, window); - } - debug!("client {} #{} DestroyWindow", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_destroy_subwindows( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 4 { - let parent = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - // Xorg `dix/dispatch.c::ProcDestroySubwindows` returns - // BadWindow for an unknown parent xid. - if state.resources.window(parent).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - parent.0, - 5, - ); - } - let kids: Vec = state.resources.children(parent).to_vec(); - for k in kids { - destroy_window_subtree(state, backend, origin, k); - } - } - debug!("client {} #{} DestroySubwindows", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// Returns `(major_opcode, first_event, first_error)` for an extension -/// the client just queried, or `None` if it isn't available. Mirrors -/// `nested::extension_query_reply` but operates on a live -/// `&mut dyn Backend` instead of `Option<&Arc>>`. -fn extension_query_reply(name: &str, backend: &mut dyn Backend) -> Option<(u8, u8, u8)> { - use crate::nested::{EXTENSIONS, ExtensionAvailability}; - let ext = EXTENSIONS.iter().find(|ext| ext.name == name)?; - let available = match ext.availability { - ExtensionAvailability::Always => true, - ExtensionAvailability::HostRender => backend.render_opcode().is_some(), - ExtensionAvailability::HostXkb => backend.xkb_opcode().is_some(), - ExtensionAvailability::Dri3 => backend.dri3_capabilities().version != (0, 0), - }; - if !available { - return None; - } - if ext.availability == ExtensionAvailability::HostXkb { - let (_, first_event, first_error) = backend.xkb_info()?; - return Some((ext.major_opcode, first_event, first_error)); - } - Some((ext.major_opcode, ext.first_event, ext.first_error)) -} - -fn advertised_extension_names(backend: &mut dyn Backend) -> Vec<&'static str> { - use crate::nested::{EXTENSIONS, ExtensionAvailability}; - let render_available = backend.render_opcode().is_some(); - let xkb_available = backend.xkb_opcode().is_some(); - let dri3_available = backend.dri3_capabilities().version != (0, 0); - EXTENSIONS - .iter() - .filter(|ext| match ext.availability { - ExtensionAvailability::Always => true, - ExtensionAvailability::HostRender => render_available, - ExtensionAvailability::HostXkb => xkb_available, - ExtensionAvailability::Dri3 => dri3_available, - }) - .map(|ext| ext.name) - .collect() -} - -fn clear_extent(requested: u16, offset: i16, window_extent: u16) -> u16 { - if requested != 0 { - return requested; - } - if offset <= 0 { - window_extent - } else { - window_extent.saturating_sub(offset as u16) - } -} - -fn rewrite_reply_sequence(reply: &mut [u8], sequence: SequenceNumber) { - if reply.len() >= 4 { - let bytes = sequence.0.to_le_bytes(); - reply[2] = bytes[0]; - reply[3] = bytes[1]; - } -} - -fn supported_pixmap_depth(depth: u8) -> bool { - matches!(depth, 1 | 4 | 8 | 24 | 32) -} - -/// Resolve a `Drawable` resource id to its kind + depth for error -/// validation. Mirrors Xorg's `dixLookupDrawable` shape: the four -/// outcomes the spec distinguishes. -enum DrawableLookup { - InputOutputWindow { depth: u8 }, - InputOnlyWindow, - Pixmap { depth: u8 }, - Missing, -} - -fn drawable_lookup(state: &ServerState, id: ResourceId) -> DrawableLookup { - if let Some(w) = state.resources.window(id) { - return match w.class { - crate::resources::WindowClass::InputOnly => DrawableLookup::InputOnlyWindow, - // `CopyFromParent` / `Other` only show up pre-CreateWindow - // resolution and shouldn't be reachable for a registered window; - // treat them the same as the regular InputOutput case. - crate::resources::WindowClass::InputOutput - | crate::resources::WindowClass::CopyFromParent - | crate::resources::WindowClass::Other(_) => { - DrawableLookup::InputOutputWindow { depth: w.depth } - } - }; - } - if let Some(p) = state.resources.pixmap(id) { - return DrawableLookup::Pixmap { depth: p.depth }; - } - DrawableLookup::Missing -} - -/// Result of validating (drawable, gc) for a paint request. The -/// shape mirrors Xorg's `VALIDATE_DRAWABLE_AND_GC` macro: emit -/// BadDrawable, BadMatch (inputonly), BadGC, or BadMatch -/// (gc-drawable-depth) in that priority order. -/// -/// `gc-drawable-screen` is not modelled — yserver has one screen -/// so the BadMatch-screen case is structurally unreachable, and -/// XTS marks the corresponding TPs UNSUPPORTED on a single-screen -/// server already. -fn validate_drawable_and_gc( - state: &ServerState, - drawable: ResourceId, - gc: ResourceId, -) -> Result<(), (u8, u32)> { - let target_depth = match drawable_lookup(state, drawable) { - DrawableLookup::InputOutputWindow { depth } | DrawableLookup::Pixmap { depth } => depth, - DrawableLookup::InputOnlyWindow => return Err((x11::error::BAD_MATCH, 0)), - DrawableLookup::Missing => return Err((x11::error::BAD_DRAWABLE, drawable.0)), - }; - let Some(gc_entry) = state.resources.gc(gc) else { - return Err((x11::error::BAD_GC, gc.0)); - }; - // GC depth is fixed at CreateGC to the depth of the origin drawable - // (X11 spec). Stored on the GC entry directly so it survives the - // origin drawable being freed. `depth == 0` means "GC was created - // before the depth field was tracked" — skip the check rather than - // emit a spurious BadMatch. - if gc_entry.depth != 0 && gc_entry.depth != target_depth { - return Err((x11::error::BAD_MATCH, 0)); - } - Ok(()) -} - -/// Sibling of [`validate_drawable_and_gc`] for paint ops that consume -/// a drawable WITHOUT a GC depth-match constraint — the `src` side of -/// `CopyPlane`, for instance, where any depth is acceptable because -/// the plane mask extracts a single bit from whatever the source is. -/// Still emits BadDrawable for missing and BadMatch for `InputOnly` -/// windows. -fn validate_drawable_only(state: &ServerState, drawable: ResourceId) -> Result<(), (u8, u32)> { - match drawable_lookup(state, drawable) { - DrawableLookup::InputOutputWindow { .. } | DrawableLookup::Pixmap { .. } => Ok(()), - DrawableLookup::InputOnlyWindow => Err((x11::error::BAD_MATCH, 0)), - DrawableLookup::Missing => Err((x11::error::BAD_DRAWABLE, drawable.0)), - } -} - -/// Sibling for ChangeGC / SetDashes / SetClipRectangles: BadGC on -/// missing id, no drawable involvement. Mirrors Xorg's `dixLookupGC` -/// gate (`dix/dispatch.c:1589,1639,1664`). -fn validate_gc_only(state: &ServerState, gc: ResourceId) -> Result<(), (u8, u32)> { - if state.resources.gc(gc).is_some() { - Ok(()) - } else { - Err((x11::error::BAD_GC, gc.0)) - } -} - -/// Encode an X11 protocol error and ship it to the client through -/// `client_io::write_or_buffer`. Mirrors `nested::emit_x11_error` but -/// operates on the new `&mut ClientState` plumbing. -fn emit_x11_error( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - code: u8, - bad_value: u32, - major_opcode: u8, -) -> io::Result { - emit_x11_error_with_minor(state, client_id, sequence, code, bad_value, 0, major_opcode) -} - -/// True if the picture exists and was created from a SolidFill / -/// LinearGradient / RadialGradient / ConicalGradient — i.e. has no -/// underlying drawable, so cannot be a Composite/Trapezoids/Triangles/ -/// FillRectangles/CompositeGlyphs destination. Unknown picture ids -/// return false (caller falls through to existing missing-id handling). -fn dst_picture_is_sourceless(state: &ServerState, dst: ResourceId) -> bool { - state - .resources - .picture(dst) - .is_some_and(|p| matches!(p.kind, crate::resources::PictureKind::Sourceless)) -} - -fn render_picture_damage_drawable(state: &ServerState, drawable: ResourceId) -> ResourceId { - state - .resources - .composite_named_pixmap_owner_window(drawable) - .unwrap_or(drawable) -} - -/// Why the shared property-change dispatch helper rejected a request. -/// -/// Each variant maps 1:1 to a wire X error: the caller turns it into an -/// `emit_x11_error_with_minor` call with the variant-specific code and -/// error_value. Kept inside `process_request.rs` so the field types -/// don't leak ServerState into `xinput::libinput_props`. Variants -/// share the `Bad` prefix on purpose — they mirror the X11 error code -/// constants (BadAtom = 5, BadAccess = 10, BadValue = 2, BadMatch = 8). -#[derive(Debug)] -#[allow(clippy::enum_variant_names)] -enum PropertyDispatchError { - /// Atom is not interned → X error code 5 (BadAtom). Echoes the atom. - BadAtom { atom: u32 }, - /// Write targets a ReadOnly descriptor → X error code 10 (BadAccess). - /// Echoes the atom. - BadAccess { atom: u32 }, - /// Value failed `validate_value` / `decode_change` / backend - /// rejected it as `Invalid` → X error code 2 (BadValue). Echoes the - /// wire `format` for spec parity with the other BadValue sites in - /// the property arms. - BadValue { error_value: u32 }, - /// Backend rejected the setting as `Unsupported` → X error code 8 - /// (BadMatch). error_value is always 0 here (matches xserver). - BadMatch, -} - -/// Run the T3 spec §D validate-before-commit pipeline shared by XI2 -/// XIChangeProperty (minor 57) and XI1 XChangeDeviceProperty (minor 37). -/// -/// Order: BadAtom → descriptor lookup → ReadOnly→BadAccess → -/// format/type vs descriptor→BadMatch → merge by mode (Append/Prepend -/// against the existing stored value, absent → Replace) → -/// validate_value→BadValue → normalize_value → decode_change→BadValue → -/// `backend.apply_device_config`→Unsupported/Invalid → commit the -/// normalised merged value via `apply_change_property` (Replace mode, -/// since the merge already happened; atoms with no descriptor row skip -/// straight to committing the request's raw `mode`/`data` unchanged). -/// -/// Preconditions (already enforced by both arms before calling): -/// * `find_device(deviceid)` returned Some. -/// * `mode` is one of REPLACE/PREPEND/APPEND. -/// * `format` is one of 8/16/32. -/// * `data.len() == num_items * (format / 8)`. -/// -/// On `Ok`, the per-device property registry has been mutated. The -/// returned [`PropWhat`] is either `Created` (the property did not -/// exist before this write) or `Modified` (it did) — the caller feeds -/// it straight into the `XI_PropertyEvent` / `DevicePropertyNotify` -/// `what` byte. -fn dispatch_change_property( - state: &mut ServerState, - backend: &mut dyn Backend, - deviceid: u16, - mode: u8, - format: u8, - property: AtomId, - type_atom: AtomId, - data: &[u8], -) -> Result { - // 1. BadAtom. - if !state.atoms.exists(property) { - return Err(PropertyDispatchError::BadAtom { atom: property.0 }); - } - // 2. Descriptor lookup. Borrow the name as `&str` from the atom - // table, copy it out before any `find_device_mut` reborrow. - let dev_node = - crate::xinput::find_device(&state.xi_devices, deviceid).and_then(|d| d.device_node.clone()); - let prop_name = state.atoms.name(property).map(str::to_owned); - - // Hoisted above the `if let` (review round S5): `validate_value` / - // `decode_change` live inside the descriptor branch below, but the - // final commit at the bottom of this function is outside it and - // must commit the SAME bytes those two just validated/decoded — a - // naive in-block `normalize_value` compiles but decodes normalised - // bytes while committing raw ones. `merged_replace` tracks whether - // the descriptor branch already computed the final value (merge + - // normalise), in which case the commit below must use Replace - // rather than the request's original `mode` (the merge already - // performed the Append/Prepend). - let mut value: std::borrow::Cow<[u8]> = std::borrow::Cow::Borrowed(data); - let mut merged_replace = false; - - if let Some(name) = prop_name.as_deref() - && let Some(desc) = crate::xinput::libinput_props::descriptor_by_name(name) - { - // 3. ReadOnly → BadAccess. - if desc.access == crate::xinput::libinput_props::Access::ReadOnly { - return Err(PropertyDispatchError::BadAccess { atom: property.0 }); - } - // 3b. format/type vs descriptor → BadMatch (review round B1 — - // server crash). `validate_value`'s `Scalar` arm derives its - // expected byte count from the wire `format`, not `desc.format`; - // without this gate a request lying about `format` (e.g. - // `format=8` against a Scalar/Float descriptor whose real - // format is 32) passes validation with too few bytes and then - // panics on out-of-bounds indexing in `decode_change`'s - // fixed-width decoders (`float32`, `card32`). Matches - // `xf86-input-libinput`, which answers BadMatch for a - // format/size/type mismatch. - let expected_type = crate::xinput::type_atom_for(desc.val, state.float_atom); - if format != desc.format || type_atom != expected_type { - return Err(PropertyDispatchError::BadMatch); - } - // 3c. Merge by mode BEFORE validating (review round B2). Task - // 1's `len <= n` relaxation makes a short *fragment* pass - // `validate_value` on its own, so an Append/Prepend must - // validate/decode the bytes that will actually be stored, not - // just the incoming fragment — otherwise `Append [1]` onto - // `Accel Profile Enabled` would decode as `AccelProfile(Some(0))` - // and silently reprogram libinput. An absent property has - // nothing to merge against, so it degrades to Replace, matching - // `apply_change_property`'s own "new property is always a - // Replace" rule (xiproperty.c:700-706). - let existing = crate::xinput::find_device(&state.xi_devices, deviceid) - .and_then(|d| d.properties.get(&property)) - .map(|p| p.data.clone()); - let merged: Vec = match (mode, existing) { - (m, Some(existing)) if m == crate::xinput::XI_PROP_MODE_APPEND => { - let mut v = existing; - v.extend_from_slice(data); - v - } - (m, Some(existing)) if m == crate::xinput::XI_PROP_MODE_PREPEND => { - let mut v = data.to_vec(); - v.extend_from_slice(&existing); - v - } - _ => data.to_vec(), - }; - // 4. validate_value → BadValue. - if crate::xinput::libinput_props::validate_value(desc.kind, format, &merged).is_err() { - return Err(PropertyDispatchError::BadValue { - error_value: u32::from(format), - }); - } - // Normalise (zero-pad a short multi-slot write to the - // descriptor's declared width) so the decoder below and the - // stored property agree on exactly `n` bytes. - let normalized = - crate::xinput::libinput_props::normalize_value(desc.kind, &merged).into_owned(); - // 5. decode_change → BadValue (covers AccelProfile-custom). - if let Some(binding) = desc.binding { - let change = crate::xinput::libinput_props::decode_change(binding, &normalized) - .map_err(|_| PropertyDispatchError::BadValue { - error_value: u32::from(format), - })?; - // 6. Backend apply → Unsupported/Invalid. - if let Some(node) = dev_node.as_deref() { - match backend.apply_device_config(node, change) { - Ok(()) => {} - Err(crate::xinput::libinput_props::DeviceConfigError::Unsupported) => { - return Err(PropertyDispatchError::BadMatch); - } - Err(crate::xinput::libinput_props::DeviceConfigError::Invalid) => { - return Err(PropertyDispatchError::BadValue { - error_value: u32::from(format), - }); - } - } - } - } - value = std::borrow::Cow::Owned(normalized); - merged_replace = true; - } - // 7. Commit. `apply_change_property` itself reports whether the - // property pre-existed (Modified vs Created), so the dispatch - // layer can fan-out the matching `XI_PropertyEvent.what` byte - // without re-querying the registry. Descriptor rows always - // commit as Replace (the merge above already folded in - // Append/Prepend against the existing value); atoms with no - // descriptor row keep the request's original `mode` and raw - // `data`, unchanged from before this pipeline existed. - let commit_mode = if merged_replace { - crate::xinput::XI_PROP_MODE_REPLACE - } else { - mode - }; - let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) - .expect("caller verified device exists"); - match crate::xinput::apply_change_property( - device, - commit_mode, - format, - property, - type_atom, - &value, - ) { - Ok(what) => Ok(what), - Err(crate::xinput::XiPropError::BadValue) => Err(PropertyDispatchError::BadValue { - error_value: u32::from(format), - }), - Err(crate::xinput::XiPropError::BadMatch) => Err(PropertyDispatchError::BadMatch), - // `apply_change_property` only returns BadValue / BadMatch; - // BadDevice is handled by the caller's lookup, so no BadDevice - // arm is reachable here. - Err(crate::xinput::XiPropError::BadDevice) => { - unreachable!("apply_change_property never returns BadDevice; lookup handled above") - } - } -} - -/// Map a [`PropertyDispatchError`] onto the XI minor-opcode error-emit -/// path. Pure plumbing — the variant carries the error code + value. -fn emit_property_dispatch_error( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - err: PropertyDispatchError, - minor_opcode: u16, -) -> io::Result { - let (code, bad_value) = match err { - PropertyDispatchError::BadAtom { atom } => (5u8, atom), - PropertyDispatchError::BadAccess { atom } => (10u8, atom), - PropertyDispatchError::BadValue { error_value } => (2u8, error_value), - PropertyDispatchError::BadMatch => (8u8, 0u32), - }; - emit_x11_error_with_minor( - state, - client_id, - sequence, - code, - bad_value, - minor_opcode, - XI2_MAJOR_OPCODE, - ) -} - -/// Emit the property-change notification(s) to every client that -/// selected for them on this device. Single fan-out for both XI2 -/// (`XI_PropertyEvent`, evtype 12) and XI1 (`DevicePropertyNotify`, -/// XI1 event code 16 within the XInput event block, delivered as wire -/// type `XI_FIRST_EVENT + 16 = 82`), keyed by the same -/// `(deviceid, property, what)` tuple so the two notifications can -/// never diverge. -/// -/// Delivery follows xserver's `send_property_event` -/// (`Xi/xiproperty.c:189-208`) via `SendEventToAllWindows`: every -/// client that has selected `XI_PropertyEventMask` (XI2) or a matching -/// `XEventClass` via `SelectExtensionEvent` (XI1) for the affected -/// device on **any** window receives one copy of the event. Because -/// neither `xXIPropertyEvent` nor `devicePropertyNotify` carries an -/// event-window field, per-window distinctions only affect *which -/// clients* receive — the wire bytes are identical for every -/// recipient. Deduplication by client id is handled inside -/// `fanout_event_to_clients`. -/// -/// `deviceid` is the literal device id the change applied to (e.g. 4 -/// for the slave pointer). The XISelectEvents storage keys masks by -/// the deviceid the client *requested*, which may be `XIAllDevices(0)` -/// (a client that wants events from every device) or -/// `XIAllMasterDevices(1)` (every master). xserver's delivery walks -/// `dix/events.c::EventMaskForClient` and OR's the masks stored under -/// the specific id AND the wildcard ids — we must mirror that here, or -/// a client that called `xinput watch-props` (which selects with -/// `deviceid=0`) silently receives nothing. The XI2 and XI1 emits are -/// independent: a client may have selected via either (or both) paths -/// and receives one copy per path. -fn emit_property_change( - state: &mut ServerState, - deviceid: u16, - property: AtomId, - what: crate::xinput::PropWhat, -) -> Vec { - // XI2 emit: clients select XI_PropertyEvent via - // `xi2_masks[(window, deviceid)]` keyed by the deviceid they asked - // for. A client targeting `XIAllDevices(0)` or — when the event - // device is a master — `XIAllMasterDevices(1)` selects with that - // wildcard id, so a property event on slave id 4 reaches both - // `dev == 4` selectors AND `dev == 0` selectors. xinput's - // `watch-props` uses `dev == 0`; without the wildcard match it - // sees nothing. - // XI device-id wildcards from `XI2.h`: XIAllDevices=0 selects any - // device; XIAllMasterDevices=1 selects any master. Property events - // are sourced from a slave (id 4 for the touchpad), so the slave - // never matches the master-only wildcard — but a future emit from - // a master device would. The OR keeps both well-defined. - const XI_ALL_DEVICES: u16 = 0; - let xi2_targets: Vec = state - .clients - .iter() - .filter_map(|(id, client)| { - let selected = client.xi2_masks.iter().any(|(&(_, dev), &mask)| { - let device_matches = dev == deviceid || dev == XI_ALL_DEVICES; - device_matches && (mask & u64::from(XI2_PROPERTY_EVENT_MASK)) != 0 - }); - selected.then_some(ClientId(*id)) - }) - .collect(); - let time = state.timestamp_now(); - let mut dropped = Vec::new(); - if !xi2_targets.is_empty() { - dropped.extend(fanout_event_to_clients( - state, - &xi2_targets, - |buf, seq, order| { - let event = crate::xinput::encode_xi2_property_event( - order, - seq, - XI2_MAJOR_OPCODE, - deviceid, - time, - property, - what, - ); - buf.extend_from_slice(&event); - }, - )); - } - // XI1 `DevicePropertyNotify` fan-out, keyed off - // `ClientState::xi1_event_classes`. A client selects via - // `SelectExtensionEvent` (minor 6) and the recorded class is - // `(deviceid << 8) | (XI_FIRST_EVENT + 16)` — a property delivery - // matches only when the client has that exact class. The XI2 and - // XI1 emits are independent: a client may have selected via either - // (or both) paths and receives one copy per path. - // - // XI1 deviceids are CARD8 on the wire, so the high byte of - // `xi1_class` is always zero — `as u8` truncations in the - // SelectExtensionEvent handler (minor 6) rely on this invariant. - debug_assert!(deviceid <= 0xFF, "XI1 deviceid must fit in CARD8"); - let xi1_class = - (u32::from(deviceid) << 8) | u32::from(XI_FIRST_EVENT + XI_DEVICE_PROPERTY_NOTIFY_OFFSET); - let xi1_targets: Vec = state - .clients - .iter() - .filter_map(|(id, client)| { - client - .xi1_event_classes - .contains(&xi1_class) - .then_some(ClientId(*id)) - }) - .collect(); - if !xi1_targets.is_empty() { - let deleted = matches!(what, crate::xinput::PropWhat::Deleted); - dropped.extend(fanout_event_to_clients( - state, - &xi1_targets, - |buf, seq, order| { - let event = crate::xinput::encode_xi1_device_property_notify( - order, - seq, - XI_FIRST_EVENT, - deviceid, - time, - property, - deleted, - ); - buf.extend_from_slice(&event); - }, - )); - } - dropped -} - -fn emit_x11_error_with_minor( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - code: u8, - bad_value: u32, - minor_opcode: u16, - major_opcode: u8, -) -> io::Result { - debug!( - "emit_x11_error: client={} seq={} code={} bad_value=0x{:x} minor={} major_opcode={}", - client_id.0, sequence.0, code, bad_value, minor_opcode, major_opcode - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_error( - &mut buf, - byte_order, - sequence, - code, - bad_value, - minor_opcode, - major_opcode, - )?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn log_void( - client_id: ClientId, - sequence: SequenceNumber, - name: &str, -) -> io::Result { - debug!("client {} #{} {name}", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_grab_server( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - // Requests from another client are held by the core loop and therefore - // never reach this handler while a grab is active. Re-grabbing by the - // owner is idempotent, as in Xorg's ProcGrabServer. - if state.server_grab_owner.is_none() || state.server_grab_owner == Some(client_id) { - state.server_grab_owner = Some(client_id); - } - debug!("client {} #{} GrabServer", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_ungrab_server( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - // A non-owner cannot normally reach this handler: its request is parked - // behind the active grab. Keeping the ownership check makes direct unit - // calls and future dispatch changes fail closed. - if state.server_grab_owner == Some(client_id) { - state.server_grab_owner = None; - } - debug!("client {} #{} UngrabServer", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_recolor_cursor( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let cursor = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - if !state.resources.cursor_exists(cursor) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - 96, - ); - } - let fore = ( - u16::from_le_bytes([body[4], body[5]]), - u16::from_le_bytes([body[6], body[7]]), - u16::from_le_bytes([body[8], body[9]]), - ); - let back = ( - u16::from_le_bytes([body[10], body[11]]), - u16::from_le_bytes([body[12], body[13]]), - u16::from_le_bytes([body[14], body[15]]), - ); - if let Some(host_xid) = state.resources.cursor_host_xid(cursor) { - backend.recolor_cursor(origin, host_xid, fore, back)?; - } - debug!( - "client {} #{} RecolorCursor 0x{:x}", - client_id.0, sequence.0, cursor.0 - ); - Ok(RequestOutcome::Handled) -} - -fn handle_get_input_focus( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetInputFocus", client_id.0, sequence.0); - let focus = state.core_focus; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_get_input_focus_reply( - &mut buf, - byte_order, - sequence, - ResourceId(focus.raw), - focus.revert_to, - )?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_query_keymap( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} QueryKeymap", client_id.0, sequence.0); - let keys_down = state.keys_down; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf = x11::fixed_reply(byte_order, sequence, 0, 2); - buf.extend_from_slice(&keys_down); - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_list_hosts( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} ListHosts", client_id.0, sequence.0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_list_hosts_reply(&mut buf, byte_order, sequence)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_get_pointer_mapping( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetPointerMapping", client_id.0, sequence.0); - let map: Vec = state - .pointer_mapping_override - .clone() - .unwrap_or_else(|| (1..=XI1_NUM_BUTTONS).collect()); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - #[allow(clippy::cast_possible_truncation)] - let mut buf = x11::fixed_reply( - byte_order, - sequence, - map.len() as u8, - map.len().div_ceil(4) as u32, - ); - buf.extend_from_slice(&[0u8; 24]); - buf.extend_from_slice(&map); - while !buf.len().is_multiple_of(4) { - buf.push(0); - } - Ok(write_to_client(client, client_id, &buf)) -} - -/// Build a generic 32-byte stub reply: header + length(0) + zeros. -/// Caller fills `data` byte (offset 1) and any non-zero typed field. -fn stub_reply_32(byte_order: x11::ClientByteOrder, sequence: SequenceNumber, data: u8) -> Vec { - let mut buf = x11::fixed_reply(byte_order, sequence, data, 0); - buf.resize(32, 0); - buf -} - -/// StoreColors (89): always BadAccess on TrueColor (read-only) colormaps. -fn handle_store_colors( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} StoreColors", client_id.0, sequence.0); - emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 89) -} - -/// StoreNamedColor (90): same — TrueColor → BadAccess. -fn handle_store_named_color( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} StoreNamedColor", client_id.0, sequence.0); - emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 90) -} - -/// SetCloseDownMode (112): mode is in header.data. Valid values are -/// 0 (Destroy), 1 (RetainPermanent), 2 (RetainTemporary). Any other -/// value is BadValue. The stored mode is consulted by `process_disconnect` -/// to decide whether to free the client's resources or keep them -/// (with the original `owner: ClientId` intact) and record the client -/// as a zombie in `ServerState.zombie_clients`. -fn handle_set_close_down_mode( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, -) -> io::Result { - debug!( - "client {} #{} SetCloseDownMode mode={}", - client_id.0, sequence.0, header.data - ); - if header.data > 2 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 112, - ); - } - if header.data == 0 { - state.close_down_modes.remove(&client_id.0); - } else { - state.close_down_modes.insert(client_id.0, header.data); - } - Ok(RequestOutcome::Handled) -} - -/// KillClient (113): resource ID lives in the first 4 bytes of `body`. -/// `resource == 0` is the spec-defined `AllTemporary` magic — destroy -/// every zombie client whose stored close-down mode is `RetainTemporary`. -/// Otherwise look up the resource's owner: if it's a live client, -/// force-disconnect them (their close-down mode still applies); if it's -/// a zombie, destroy that zombie's resources; if it's `SERVER_OWNER`, -/// noop; if the resource doesn't exist, BadValue. -fn handle_kill_client( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let resource = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - debug!( - "client {} #{} KillClient resource=0x{:x}", - client_id.0, sequence.0, resource - ); - if resource == 0 { - let temp_zombies: Vec = state - .zombie_clients - .iter() - .filter_map(|(&id, &mode)| (mode == 2).then_some(id)) - .collect(); - for zid in temp_zombies { - super::process_disconnect::destroy_zombie_resources(state, backend, ClientId(zid)); - state.zombie_clients.remove(&zid); - } - return Ok(RequestOutcome::Handled); - } - let Some(owner) = state.resources.resource_owner(ResourceId(resource)) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - resource, - 113, - ); - }; - if owner == crate::resources::SERVER_OWNER { - // Server-reserved resource (root window, overlay, etc.). Noop. - return Ok(RequestOutcome::Handled); - } - if state.zombie_clients.contains_key(&owner.0) { - super::process_disconnect::destroy_zombie_resources(state, backend, owner); - state.zombie_clients.remove(&owner.0); - return Ok(RequestOutcome::Handled); - } - if owner == client_id { - // X11 spec: KillClient targeting any of your own resources - // forces your own connection closed. Your stored close-down - // mode still applies — process_disconnect consults it. - return Ok(RequestOutcome::Disconnect(client_id)); - } - if state.clients.contains_key(&owner.0) { - // Force-disconnect the other client. Their close-down mode is - // honored: if they set RetainPermanent / RetainTemporary, - // their resources survive (they become a zombie) instead of - // being freed. - super::process_disconnect::process_disconnect(state, backend, owner); - } - Ok(RequestOutcome::Handled) -} - -/// AllocColorCells (86): always BadAlloc on TrueColor visuals. -/// X11 spec: cells/planes can only be allocated from -/// DirectColor/PseudoColor/GrayScale colormaps. Our default -/// colormaps are TrueColor → always BadAlloc. -fn handle_alloc_color_cells( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - _body: &[u8], -) -> io::Result { - debug!("client {} #{} AllocColorCells", client_id.0, sequence.0); - emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 86) -} - -/// AllocColorPlanes (87): same — TrueColor → BadAlloc. -fn handle_alloc_color_planes( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - _body: &[u8], -) -> io::Result { - debug!("client {} #{} AllocColorPlanes", client_id.0, sequence.0); - emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 87) -} - -/// CreateColormap (78): allocate colormap, BadIDChoice on duplicate. -/// `BadIDChoice` fires when a CreateXxx request's resource ID is -/// either already allocated OR outside the client's resource-id range -/// declared in the setup reply. -/// `LEGAL_NEW_RESOURCE` equivalent for XFIXES `CreateRegion*`: the -/// candidate region xid must NOT already name a resource (in the -/// core `resources` table OR in the dedicated `xfixes_regions` -/// map). Xorg's `xfixes/region.c:78,114,157,213` all guard their -/// CreateRegion variants with `LEGAL_NEW_RESOURCE(stuff->region, -/// client)` before doing any work — duplicates surface as -/// BadIDChoice (X error code 14). Returns true if the xid clashes -/// (the caller should emit BadIDChoice). -fn xfixes_region_xid_already_taken(state: &ServerState, rid: u32) -> bool { - state.xfixes_regions.contains_key(&rid) || state.resources.xid_in_use(ResourceId(rid)) -} - -fn xid_out_of_client_range(state: &ServerState, client_id: ClientId, xid: u32) -> bool { - let Some(client) = state.clients.get(&client_id.0) else { - return false; - }; - let base = client.resource_id_base; - let mask = client.resource_id_mask; - (xid & !mask) != base -} - -fn handle_create_colormap( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 12 { - return Ok(RequestOutcome::Handled); - } - let mid = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - if state.resources.xid_in_use(mid) || xid_out_of_client_range(state, client_id, mid.0) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - mid.0, - 78, - ); - } - let visual = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - state.resources.create_colormap(client_id, mid, visual); - debug!( - "client {} #{} CreateColormap 0x{:x}", - client_id.0, sequence.0, mid.0 - ); - Ok(RequestOutcome::Handled) -} - -/// CopyColormapAndFree (80): allocate new colormap, BadIDChoice on duplicate. -fn handle_copy_colormap_and_free( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let mid = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - if state.resources.xid_in_use(mid) || xid_out_of_client_range(state, client_id, mid.0) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - mid.0, - 80, - ); - } - // Source colormap's visual; default to ROOT_VISUAL if unknown. - let src_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let visual = state - .resources - .colormap(src_id) - .map(|c| c.visual) - .unwrap_or(crate::resources::ROOT_VISUAL); - state.resources.create_colormap(client_id, mid, visual); - debug!( - "client {} #{} CopyColormapAndFree 0x{:x}", - client_id.0, sequence.0, mid.0 - ); - Ok(RequestOutcome::Handled) -} - -/// GetMotionEvents (39): return bounded pointer history translated into the -/// requested window, filtering samples outside its border-inclusive bounds. -fn handle_get_motion_events( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let Some(win) = state.resources.window(window) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 39, - ); - }; - let (width, height, border) = (win.width, win.height, win.border_width); - let (origin_x, origin_y) = state.resources.window_absolute_position(window); - let start = u32::from_le_bytes(body[4..8].try_into().expect("four bytes")); - let stop = u32::from_le_bytes(body[8..12].try_into().expect("four bytes")); - let border = i32::from(border); - let xmin = origin_x - border; - let ymin = origin_y - border; - let xmax = origin_x + i32::from(width) + border; - let ymax = origin_y + i32::from(height) + border; - let history: Vec<_> = motion_history_range(state, start, stop) - .into_iter() - .filter(|record| { - let x = i32::from(record.root_x); - let y = i32::from(record.root_y); - (xmin..xmax).contains(&x) && (ymin..ymax).contains(&y) - }) - .collect(); - debug!("client {} #{} GetMotionEvents", client_id.0, sequence.0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let length_words = u32::try_from(history.len()) - .unwrap_or(u32::MAX) - .saturating_mul(2); - let mut buf = x11::fixed_reply(client.byte_order, sequence, 0, length_words); - x11::write_u32( - client.byte_order, - &mut buf, - u32::try_from(history.len()).unwrap_or(u32::MAX), - ); - buf.extend_from_slice(&[0u8; 20]); - for record in history { - x11::write_u32(client.byte_order, &mut buf, record.time); - x11::write_i16( - client.byte_order, - &mut buf, - i16::try_from(i32::from(record.root_x) - origin_x).unwrap_or(i16::MAX), - ); - x11::write_i16( - client.byte_order, - &mut buf, - i16::try_from(i32::from(record.root_y) - origin_y).unwrap_or(i16::MAX), - ); - } - Ok(write_to_client(client, client_id, &buf)) -} - -/// GetFontPath (52): reply with 0 paths. -fn handle_get_font_path( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetFontPath", client_id.0, sequence.0); - let paths = backend.font_path(); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - // Layout: reply(1) pad(1) seq(2) length(4) npaths u16(2) pad(22) - // then LISTofSTR (1 length byte + bytes each), padded to 4. - let mut buf = x11::fixed_reply(byte_order, sequence, 0, 0); - let mut tmp = Vec::with_capacity(2); - x11::write_u16( - byte_order, - &mut tmp, - u16::try_from(paths.len()).unwrap_or(0), - ); - buf.extend_from_slice(&tmp); - buf.resize(32, 0); - for p in &paths { - let bytes = p.as_bytes(); - let len = bytes.len().min(255); - buf.push(u8::try_from(len).unwrap_or(255)); - buf.extend_from_slice(&bytes[..len]); - } - while !buf.len().is_multiple_of(4) { - buf.push(0); - } - let units = u32::try_from((buf.len() - 32) / 4).unwrap_or(0); - let len_bytes = match byte_order { - yserver_protocol::x11::ClientByteOrder::LittleEndian => units.to_le_bytes(), - yserver_protocol::x11::ClientByteOrder::BigEndian => units.to_be_bytes(), - }; - buf[4..8].copy_from_slice(&len_bytes); - Ok(write_to_client(client, client_id, &buf)) -} - -/// SetFontPath (51): parse the STR list, hand it to the backend for -/// validation + install. Invalid element → BadValue (old path kept, -/// errorValue = offending element index, matching Xorg's -/// SetFontPathElements bad-element counter). -fn handle_set_font_path( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if body.len() < 4 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - } - let npaths = u16::from_le_bytes([body[0], body[1]]); - let mut paths: Vec = Vec::with_capacity(usize::from(npaths)); - let mut off = 4usize; - for _ in 0..npaths { - let Some(&len) = body.get(off) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - }; - off += 1; - let end = off + usize::from(len); - let Some(bytes) = body.get(off..end) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - }; - paths.push(String::from_utf8_lossy(bytes).into_owned()); - off = end; - } - debug!( - "client {} #{} SetFontPath {:?}", - client_id.0, sequence.0, paths - ); - match backend.set_font_path(origin, &paths) { - Ok(()) => Ok(RequestOutcome::Handled), - Err(bad_index) => emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::try_from(bad_index).unwrap_or(0), - header.opcode, - ), - } -} - -/// ListInstalledColormaps (83): reply with 0 colormaps. -/// Emit `ColormapNotify(window, cmap, new=false, installed=…)` to every -/// window whose `attributes.colormap == cmap`, for clients subscribed -/// with the ColormapChange event mask bit (`1 << 23`). -fn emit_colormap_notify_for(state: &mut ServerState, cmap: ResourceId, installed: bool) { - let windows = state.resources.windows_with_colormap(cmap); - for w in windows { - let _dropped = crate::core_loop::fanout::emit_window_event_to_state( - state, - w, - 0x0080_0000, - |buf, seq, order| { - x11::encode_colormap_notify_event(buf, seq, order, w, cmap, false, installed); - }, - ); - } -} - -/// Restore the default colormap to the installed list if a prior -/// uninstall / free emptied it. X11 spec: "Initially, the default -/// colormap for a screen is installed" plus the server may implicitly -/// install required colormaps; ROOT_COLORMAP is the lone required -/// entry on our TrueColor setup. -fn ensure_default_colormap_installed(state: &mut ServerState) { - if !state.installed_colormaps.is_empty() { - return; - } - let root = crate::resources::ROOT_COLORMAP; - state.installed_colormaps.push(root); - emit_colormap_notify_for(state, root, true); -} - -/// InstallColormap (81): mark a colormap as installed and emit -/// `ColormapNotify(Installed)` on every window that uses it. On a -/// TrueColor server this is bookkeeping only — the hardware colormap -/// never actually changes — but clients (and xts) still observe the -/// notify chain. -fn handle_install_colormap( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let cmap = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - debug!( - "client {} #{} InstallColormap 0x{:x}", - client_id.0, sequence.0, cmap.0 - ); - if state.resources.colormap(cmap).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - cmap.0, - 81, - ); - } - if state.installed_colormaps.contains(&cmap) { - return Ok(RequestOutcome::Handled); - } - // Capacity = `max_installed_maps = 1` (matches the SETUP advertise). - // Evict oldest to make room — its own `ColormapNotify(Uninstalled)` - // fans out before the new install's notify. - if !state.installed_colormaps.is_empty() { - let evicted = state.installed_colormaps.remove(0); - emit_colormap_notify_for(state, evicted, false); - } - state.installed_colormaps.push(cmap); - emit_colormap_notify_for(state, cmap, true); - Ok(RequestOutcome::Handled) -} - -/// SetDashes (58): replace the GC's dash pattern with the multi-byte -/// list supplied. Distinct from the single-byte `CPDashList` form in -/// `CreateGC` / `ChangeGC` (which can only set a uniform [n, n]). -/// -/// Wire: `gc u32, dash_offset u16, n u16, dashes u8[n]`. `n == 0` or -/// any `dashes[i] == 0` is `BadValue` per spec. -fn handle_set_dashes( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 8 { - return Ok(RequestOutcome::Handled); - } - let gc = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let dash_offset = u16::from_le_bytes([body[4], body[5]]); - let n = u16::from_le_bytes([body[6], body[7]]) as usize; - debug!( - "client {} #{} SetDashes gc=0x{:x} offset={} n={}", - client_id.0, sequence.0, gc.0, dash_offset, n - ); - if n == 0 { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 58); - } - let end = 8usize.saturating_add(n); - if body.len() < end { - return Ok(RequestOutcome::Handled); - } - let dashes = &body[8..end]; - // BadGC takes priority over BadValue when the GC id itself is - // bogus. Use the client-range check rather than `gc().is_some()` - // because other GC mutators (`set_clip_rectangles`, etc.) - // auto-vivify entries via `entry().or_insert_with`, so an - // invalid id can be present in the map from an earlier request. - if xid_out_of_client_range(state, client_id, gc.0) || state.resources.gc(gc).is_none() { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_GC, gc.0, 58); - } - if dashes.contains(&0) { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 58); - } - state - .resources - .set_dashes(client_id, gc, dash_offset, dashes); - Ok(RequestOutcome::Handled) -} - -/// FreeColormap (79): destroy the colormap resource. Uninstalls it -/// first if installed (emitting `ColormapNotify(Uninstalled)`). The -/// default colormap is not freeable — BadColor per spec. -fn handle_free_colormap( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let cmap = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - debug!( - "client {} #{} FreeColormap 0x{:x}", - client_id.0, sequence.0, cmap.0 - ); - if cmap == crate::resources::ROOT_COLORMAP || state.resources.colormap(cmap).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - cmap.0, - 79, - ); - } - let was_installed = state.installed_colormaps.contains(&cmap); - state.installed_colormaps.retain(|c| *c != cmap); - if was_installed { - emit_colormap_notify_for(state, cmap, false); - } - state.resources.free_colormap(cmap); - ensure_default_colormap_installed(state); - Ok(RequestOutcome::Handled) -} - -/// UninstallColormap (82): symmetric to `InstallColormap`. Uninstalling -/// the default colormap is allowed but the server implicitly re-installs -/// it later when focus changes; we model the bookkeeping faithfully. -fn handle_uninstall_colormap( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 4 { - return Ok(RequestOutcome::Handled); - } - let cmap = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - debug!( - "client {} #{} UninstallColormap 0x{:x}", - client_id.0, sequence.0, cmap.0 - ); - if state.resources.colormap(cmap).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - cmap.0, - 82, - ); - } - let before = state.installed_colormaps.len(); - state.installed_colormaps.retain(|c| *c != cmap); - if state.installed_colormaps.len() == before { - return Ok(RequestOutcome::Handled); - } - emit_colormap_notify_for(state, cmap, false); - ensure_default_colormap_installed(state); - Ok(RequestOutcome::Handled) -} - -fn handle_list_installed_colormaps( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - // Body's window xid scopes the reply to the window's screen. - // yserver has a single screen so the list is server-global, but - // we still validate the xid — xts probes BadWindow on a freed xid. - let window = if body.len() >= 4 { - ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])) - } else { - ResourceId(0) - }; - debug!( - "client {} #{} ListInstalledColormaps 0x{:x}", - client_id.0, sequence.0, window.0 - ); - if state.resources.window(window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 83, - ); - } - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let installed = state.installed_colormaps.clone(); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - // Layout: reply(1) pad(1) seq(2) length=N(4) nColormaps u16(2) - // pad(22) colormaps u32[N] - // Length field counts u32 units past the 32-byte fixed header. - let length_units = u32::try_from(installed.len()).unwrap_or(0); - let mut buf = x11::fixed_reply(byte_order, sequence, 0, length_units); - let mut tmp = Vec::with_capacity(2); - x11::write_u16( - byte_order, - &mut tmp, - u16::try_from(installed.len()).unwrap_or(0), - ); - buf.extend_from_slice(&tmp); - buf.resize(32, 0); - for cmap in &installed { - let mut entry = Vec::with_capacity(4); - x11::write_u32(byte_order, &mut entry, cmap.0); - buf.extend_from_slice(&entry); - } - Ok(write_to_client(client, client_id, &buf)) -} - -/// GetKeyboardControl (103): 52-byte reply (length=5). Reflects -/// `ServerState::keyboard_control` (mirrors Xorg -/// `ProcGetKeyboardControl`, `dix/devices.c:2257`). -fn handle_get_keyboard_control( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetKeyboardControl", client_id.0, sequence.0); - let kc = state.keyboard_control.clone(); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - // Layout: reply(1) global_auto_repeat(1) seq(2) length=5(4) - // led_mask u32(4) key_click_pct u8(1) bell_pct u8(1) - // bell_pitch u16(2) bell_duration u16(2) pad(2) - // auto_repeats u8[32] = 32 + 20 = 52 bytes - let mut buf = x11::fixed_reply(byte_order, sequence, u8::from(kc.global_auto_repeat), 5); - let mut tmp = Vec::with_capacity(4); - x11::write_u32(byte_order, &mut tmp, kc.led_mask); - buf.extend_from_slice(&tmp); - buf.push(kc.key_click_percent); - buf.push(kc.bell_percent); - tmp.clear(); - x11::write_u16(byte_order, &mut tmp, kc.bell_pitch); - buf.extend_from_slice(&tmp); - tmp.clear(); - x11::write_u16(byte_order, &mut tmp, kc.bell_duration); - buf.extend_from_slice(&tmp); - buf.extend_from_slice(&[0, 0]); // pad - buf.extend_from_slice(&kc.auto_repeats); - debug_assert_eq!(buf.len(), 52); - Ok(write_to_client(client, client_id, &buf)) -} - -/// ChangeKeyboardControl (102): value-mask driven update of -/// `ServerState::keyboard_control`. Mirrors Xorg -/// `DoChangeKeyboardControl` (`dix/devices.c:2050`): validate and -/// stage into a copy, commit only on full success. -fn handle_change_keyboard_control( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - const KB_KEY_CLICK_PERCENT: u32 = 0x01; - const KB_BELL_PERCENT: u32 = 0x02; - const KB_BELL_PITCH: u32 = 0x04; - const KB_BELL_DURATION: u32 = 0x08; - const KB_LED: u32 = 0x10; - const KB_LED_MODE: u32 = 0x20; - const KB_KEY: u32 = 0x40; - const KB_AUTO_REPEAT_MODE: u32 = 0x80; - debug!( - "client {} #{} ChangeKeyboardControl", - client_id.0, sequence.0 - ); - if body.len() < 4 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - } - let mask = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - // Xorg BadLength: req_len must be exactly 2 + Ones(vmask) units. - if body.len() != 4 + 4 * mask.count_ones() as usize { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - } - let bad_value = |state: &mut ServerState, value: u32| { - emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - value, - header.opcode, - ) - }; - let mut ctrl = state.keyboard_control.clone(); - // Sentinel: "no KBLed/KBKey given" → led-mode / auto-repeat-mode - // apply to all leds / the global flag (Xorg DO_ALL). - let mut led: Option = None; - let mut key: Option = None; - let mut values = body[4..].chunks_exact(4); - let mut bit = 1u32; - while bit != 0 { - let item = bit & mask; - bit <<= 1; - if item == 0 { - continue; - } - let Some(raw) = values - .next() - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - else { - break; // unreachable: length validated above - }; - match item { - KB_KEY_CLICK_PERCENT => { - let t = raw as i8; - if t == -1 { - ctrl.key_click_percent = 0; // DEFAULT_KEYBOARD_CLICK - } else if !(0..=100).contains(&t) { - return bad_value(state, i32::from(t) as u32); - } else { - ctrl.key_click_percent = t as u8; - } - } - KB_BELL_PERCENT => { - let t = raw as i8; - if t == -1 { - ctrl.bell_percent = 50; // DEFAULT_BELL - } else if !(0..=100).contains(&t) { - return bad_value(state, i32::from(t) as u32); - } else { - ctrl.bell_percent = t as u8; - } - } - KB_BELL_PITCH => { - let t = raw as i16; - if t == -1 { - ctrl.bell_pitch = 400; // DEFAULT_BELL_PITCH - } else if t < 0 { - return bad_value(state, i32::from(t) as u32); - } else { - ctrl.bell_pitch = t as u16; - } - } - KB_BELL_DURATION => { - let t = raw as i16; - if t == -1 { - ctrl.bell_duration = 100; // DEFAULT_BELL_DURATION - } else if t < 0 { - return bad_value(state, i32::from(t) as u32); - } else { - ctrl.bell_duration = t as u16; - } - } - KB_LED => { - let l = raw as u8; - if !(1..=32).contains(&l) { - return bad_value(state, u32::from(l)); - } - if mask & KB_LED_MODE == 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - header.opcode, - ); - } - led = Some(l); - } - KB_LED_MODE => { - let t = raw as u8; - match (t, led) { - (0, None) => ctrl.led_mask = 0, - (0, Some(l)) => ctrl.led_mask &= !(1u32 << (l - 1)), - (1, None) => ctrl.led_mask = !0, - (1, Some(l)) => ctrl.led_mask |= 1u32 << (l - 1), - _ => return bad_value(state, u32::from(t)), - } - } - KB_KEY => { - let k = raw as u8; - // min_keycode advertised in the setup reply is 8; - // max is 255 so no upper check is reachable for a u8. - if k < 8 { - return bad_value(state, u32::from(k)); - } - if mask & KB_AUTO_REPEAT_MODE == 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - 0, - header.opcode, - ); - } - key = Some(k); - } - KB_AUTO_REPEAT_MODE => { - let t = raw as u8; - match (t, key) { - (0, None) => ctrl.global_auto_repeat = false, - (1, None) => ctrl.global_auto_repeat = true, - (2, None) => ctrl.global_auto_repeat = true, // DEFAULT_AUTOREPEAT - (0..=2, Some(k)) => { - let i = usize::from(k >> 3); - let m = 1 << (k & 7); - match t { - 0 => ctrl.auto_repeats[i] &= !m, - 1 => ctrl.auto_repeats[i] |= m, - _ => { - ctrl.auto_repeats[i] = (ctrl.auto_repeats[i] & !m) - | (crate::server::DEFAULT_AUTO_REPEATS[i] & m); - } - } - // Xorg XkbDisableComputedAutoRepeats: a mapping - // change no longer re-derives this key's repeat. - ctrl.auto_repeats_explicit[i] |= m; - } - _ => return bad_value(state, u32::from(t)), - } - } - _ => { - // Unknown mask bit: Xorg's default case → BadValue. - return bad_value(state, mask); - } - } - } - state.keyboard_control = ctrl; - Ok(RequestOutcome::Handled) -} - -/// Bell (104): validate percent (header data byte, INT8 −100..=100, -/// Xorg `ProcBell` `dix/devices.c:2288`). yserver has no audible -/// bell output; the request succeeds without side effects, like -/// Xorg on a bell-less device. -fn handle_bell( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, -) -> io::Result { - let percent = header.data as i8; - debug!( - "client {} #{} Bell percent={}", - client_id.0, sequence.0, percent - ); - if !(-100..=100).contains(&percent) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - i32::from(percent) as u32, - header.opcode, - ); - } - Ok(RequestOutcome::Handled) -} - -/// ChangePointerControl (105): update `ServerState::pointer_control`. -/// Mirrors Xorg `ProcChangePointerControl` (`dix/devices.c:2326`): -/// stage into a copy, commit only on full success. -fn handle_change_pointer_control( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - debug!( - "client {} #{} ChangePointerControl", - client_id.0, sequence.0 - ); - // Body: accel_num i16, accel_denom i16, threshold i16, - // do_accel u8, do_thresh u8 = 8 bytes. - if body.len() < 8 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - } - let accel_num = i16::from_le_bytes([body[0], body[1]]); - let accel_denom = i16::from_le_bytes([body[2], body[3]]); - let threshold = i16::from_le_bytes([body[4], body[5]]); - let do_accel = body[6]; - let do_thresh = body[7]; - let bad_value = |state: &mut ServerState, value: u32| { - emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - value, - header.opcode, - ) - }; - if do_accel > 1 { - return bad_value(state, u32::from(do_accel)); - } - if do_thresh > 1 { - return bad_value(state, u32::from(do_thresh)); - } - let mut ctrl = state.pointer_control.clone(); - if do_accel == 1 { - match accel_num { - -1 => ctrl.accel_numerator = 2, // DEFAULT_PTR_NUMERATOR - n if n < 0 => return bad_value(state, i32::from(n) as u32), - n => ctrl.accel_numerator = n as u16, - } - match accel_denom { - -1 => ctrl.accel_denominator = 1, // DEFAULT_PTR_DENOMINATOR - n if n <= 0 => return bad_value(state, i32::from(n) as u32), - n => ctrl.accel_denominator = n as u16, - } - } - if do_thresh == 1 { - match threshold { - -1 => ctrl.threshold = 4, // DEFAULT_PTR_THRESHOLD - n if n < 0 => return bad_value(state, i32::from(n) as u32), - n => ctrl.threshold = n as u16, - } - } - state.pointer_control = ctrl; - Ok(RequestOutcome::Handled) -} - -/// GetPointerControl (106): 32-byte reply reflecting -/// `ServerState::pointer_control` (Xorg `ProcGetPointerControl`, -/// `dix/devices.c:2405`). -fn handle_get_pointer_control( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetPointerControl", client_id.0, sequence.0); - let pc = state.pointer_control.clone(); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf = x11::fixed_reply(byte_order, sequence, 0, 0); - let mut tmp = Vec::with_capacity(2); - x11::write_u16(byte_order, &mut tmp, pc.accel_numerator); - buf.extend_from_slice(&tmp); - tmp.clear(); - x11::write_u16(byte_order, &mut tmp, pc.accel_denominator); - buf.extend_from_slice(&tmp); - tmp.clear(); - x11::write_u16(byte_order, &mut tmp, pc.threshold); - buf.extend_from_slice(&tmp); - buf.resize(32, 0); - Ok(write_to_client(client, client_id, &buf)) -} - -/// GetScreenSaver (108): reflects ScreenSaverState back to the client. -fn handle_get_screen_saver( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetScreenSaver", client_id.0, sequence.0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf = x11::fixed_reply(byte_order, sequence, 0, 0); - #[allow(clippy::cast_possible_truncation)] - let timeout = (state.screensaver.timeout_ms / 1000) as u16; - #[allow(clippy::cast_possible_truncation)] - let interval = (state.screensaver.interval_ms / 1000) as u16; - x11::write_u16(byte_order, &mut buf, timeout); - x11::write_u16(byte_order, &mut buf, interval); - buf.push(u8::from(state.screensaver.prefer_blanking)); - buf.push(u8::from(state.screensaver.allow_exposures)); - buf.resize(32, 0); - Ok(write_to_client(client, client_id, &buf)) -} - -/// SetScreenSaver (107): body is `timeout:i16 interval:i16 -/// prefer_blanking:u8 allow_exposures:u8 pad:u16` (8 bytes). -/// -/// Sentinel resolution matches Xorg `dix/globals.c:96-99`: -/// -1 (timeout/interval) → restore 600s default -/// 2 (prefer_blanking/allow_expo) → restore the default value -fn handle_set_screen_saver( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - // Body layout: timeout:i16 interval:i16 prefer_blanking:u8 - // allow_exposures:u8 pad:u16 = 8 bytes. - if body.len() < 8 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - header.opcode, - ); - } - let timeout = i16::from_le_bytes([body[0], body[1]]); - let interval = i16::from_le_bytes([body[2], body[3]]); - let prefer_blanking = body[4]; - let allow_exposures = body[5]; - - if !(-1..=0x7fff).contains(&i32::from(timeout)) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(timeout as u16), - header.opcode, - ); - } - if !(-1..=0x7fff).contains(&i32::from(interval)) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(interval as u16), - header.opcode, - ); - } - if prefer_blanking > 2 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(prefer_blanking), - header.opcode, - ); - } - if allow_exposures > 2 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(allow_exposures), - header.opcode, - ); - } - - state.screensaver.timeout_ms = match timeout { - -1 => 600_000, - n => u32::from(n as u16) * 1000, // n is already ≥ 0 (validated above) - }; - state.screensaver.interval_ms = match interval { - -1 => 600_000, - n => u32::from(n as u16) * 1000, // n is already ≥ 0 (validated above) - }; - state.screensaver.prefer_blanking = match prefer_blanking { - 0 => false, - 1 => true, - _ => true, // 2 = Default; Xorg defaultScreenSaverBlanking = PreferBlanking - }; - state.screensaver.allow_exposures = match allow_exposures { - 0 => false, - 1 => true, - _ => true, // 2 = Default; Xorg defaultScreenSaverAllowExposures = AllowExposures - }; - - // No last_activity reset — Xorg's ProcSetScreenSaver only calls - // SetScreenSaverTimer(), which recomputes the deadline from the - // unchanged LastEventTime. yserver computes the deadline lazily - // at every poll iteration; the next iteration sees the new - // timeout_ms against the unchanged last_activity. - - Ok(RequestOutcome::Handled) -} - -/// ForceScreenSaver (115): `mode` lives in the request header's -/// `data` byte (Fixed(1) in the core length table — no body bytes). -/// mode=0 (Reset) → force Off + bump last_activity. -/// mode=1 (Activate) → force On. -fn handle_force_screen_saver( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, -) -> io::Result { - let mode = header.data; // u8 stashed in the request header's data byte - if mode > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mode), - header.opcode, - ); - } - if mode == 0 { - apply_screen_saver_transition( - state, - backend, - ScreenSaverActive::Off, - /*forced=*/ true, - ); - state.dpms.last_activity = std::time::Instant::now(); - } else { - apply_screen_saver_transition(state, backend, ScreenSaverActive::On, /*forced=*/ true); - } - Ok(RequestOutcome::Handled) -} - -/// SetPointerMapping (116): reply with status=0 + MappingNotify fanout. -fn handle_set_pointer_mapping( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - debug!("client {} #{} SetPointerMapping", client_id.0, sequence.0); - let n = usize::from(header.data); - let Some(map) = body.get(..n) else { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 116); - }; - // Xorg ProcSetPointerMapping: the map length must equal the - // device's button count, and nonzero entries must be unique. - let current_len = state - .pointer_mapping_override - .as_ref() - .map_or(usize::from(XI1_NUM_BUTTONS), Vec::len); - if n != current_len { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 116, - ); - } - let mut seen = [false; 256]; - for &b in map { - if b != 0 { - if seen[usize::from(b)] { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(b), - 116, - ); - } - seen[usize::from(b)] = true; - } - } - state.pointer_mapping_override = Some(map.to_vec()); - // MappingNotify (request=2 = Pointer) to every connected client. - let targets: Vec = state.clients.keys().map(|id| ClientId(*id)).collect(); - let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { - let _ = x11::write_mapping_notify_event(buf, order, seq, 2, 0, 0); - }); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let buf = stub_reply_32(client.byte_order, sequence, 0); // status=Success - Ok(write_to_client(client, client_id, &buf)) -} - -/// SetModifierMapping (118): MappingNotify fanout, then reply. -fn handle_set_modifier_mapping( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - debug!("client {} #{} SetModifierMapping", client_id.0, sequence.0); - let kpm = header.data; - let need = usize::from(kpm) * 8; - let Some(keycodes) = body.get(..need) else { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 118); - }; - // Xorg ProcSetModifierMapping: BadValue for a refused map, else the - // change_modmap status in the reply. - let status = match change_modifier_mapping(state, backend, origin, kpm, keycodes, None, |_| {}) - { - ModmapChangeOutcome::Success => 0, - ModmapChangeOutcome::Busy => 1, - ModmapChangeOutcome::BadValue(value) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - value, - 118, - ); - } - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let buf = stub_reply_32(client.byte_order, sequence, status); - Ok(write_to_client(client, client_id, &buf)) -} - -/// Result of [`change_modifier_mapping`] (Xorg `change_modmap`'s return). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ModmapChangeOutcome { - /// Applied (`MappingSuccess`). - Success, - /// A key that is or would be a modifier is down: nothing applied - /// (`MappingBusy`). - Busy, - /// Refused; the error value (Xorg `client->errorValue`). - BadValue(u32), -} - -/// Xorg's `change_modmap` (dix/inpututils.c) for SetModifierMapping and XI -/// SetDeviceModifierMapping (`xi_device`: the XI device; `None` = core). -/// -/// - `build_modmap_from_modkeymap`: row `i / kpm` of the request is modifier -/// `i / kpm`; a keycode listed twice is BadValue with value 0. -/// - `check_modmap_change`: a keycode outside the keycode range is BadValue -/// (value: the lowest such keycode); MappingBusy if a new modifier key is -/// down, or an old one is, where Xorg's loop over the old ones stops short -/// of the last keycode (255). -/// -/// Then the backend edits its XKB keymap's modmap and the events go out in -/// Xorg's order (`XkbApplyMappingChange` → `XkbSendNotification`): -/// XkbMapNotify, core MappingNotify(Modifier), XkbControlsNotify for per-key -/// repeat changes, XkbIndicatorMapNotify. A backend without an XKB keymap -/// gets the map stored for readback instead. An identical map still applies -/// and notifies, as on Xorg. Keyboard devices share the one keymap, so the XI -/// request changes it for every device (Xorg: the device, its master or -/// slaves). -/// -/// `on_applied` runs once the change took effect and before any notification -/// goes out: the XI request sends its DeviceMappingNotify there, so its -/// clients see it ahead of the XKB and core notifications, as on Xorg. -fn change_modifier_mapping( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - kpm: u8, - keycodes: &[u8], - xi_device: Option, - on_applied: impl FnOnce(&mut ServerState), -) -> ModmapChangeOutcome { - const MIN_KEYCODE: usize = 8; - const MAX_KEYCODE: usize = 255; - let mut modmap = [0u8; 256]; - for (i, &kc) in keycodes.iter().enumerate() { - if kc == 0 { - continue; - } - if modmap[usize::from(kc)] != 0 { - return ModmapChangeOutcome::BadValue(0); - } - modmap[usize::from(kc)] = 1 << (i / usize::from(kpm.max(1))); - } - let down = |kc: usize| state.keys_down[kc >> 3] & (1 << (kc & 7)) != 0; - for (kc, _) in modmap.iter().enumerate().filter(|(_, m)| **m != 0) { - if !(MIN_KEYCODE..=MAX_KEYCODE).contains(&kc) { - return ModmapChangeOutcome::BadValue(u32::try_from(kc).unwrap_or(0)); - } - if down(kc) { - return ModmapChangeOutcome::Busy; - } - } - let current = xi_device - .and_then(|dev| state.xi1_modifier_map.get(&dev).cloned()) - .or_else(|| state.modifier_mapping_override.clone()) - .or_else(|| backend.get_modifier_mapping(origin).ok()); - if let Some((cur_kpm, cur_keys)) = current - && cur_keys.iter().take(8 * usize::from(cur_kpm)).any(|&kc| { - (MIN_KEYCODE..MAX_KEYCODE).contains(&usize::from(kc)) && down(usize::from(kc)) - }) - { - return ModmapChangeOutcome::Busy; - } - - // Xorg XkbSendLegacyMapNotify → XIShouldNotify: the core MappingNotify - // is for clients whose master keyboard changed. An XI request on a slave - // reaches the master only as its lastSlave, which the device an XI client - // remaps isn't on Xorg (XTEST drives a slave of its own there). - let core_notify = xi_device.is_none_or(|dev| dev == crate::xinput::DEVICEID_MASTER_KEYBOARD); - let Some(change) = backend.set_modifier_mapping(&modmap) else { - match xi_device { - Some(dev) => { - state.xi1_modifier_map.insert(dev, (kpm, keycodes.to_vec())); - } - None => state.modifier_mapping_override = Some((kpm, keycodes.to_vec())), - } - on_applied(state); - if core_notify { - let targets: Vec = state.clients.keys().map(|id| ClientId(*id)).collect(); - let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { - let _ = x11::write_mapping_notify_event(buf, order, seq, 0, 0, 0); - }); - } - return ModmapChangeOutcome::Success; - }; - // The keymap is the one modifier map now: drop any stored readback. - state.modifier_mapping_override = None; - state.xi1_modifier_map.clear(); - on_applied(state); - let xkb_event_base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - crate::core_loop::xkb_layout::send_xkb_map_notify(state, xkb_event_base, change.map_notify); - if core_notify { - // Xorg XkbSendLegacyMapNotify: MapNotify's changes decide who gets - // the core MappingNotify(Modifier). - crate::core_loop::xkb_select::send_legacy_core_map_notify( - state, - crate::core_loop::xkb_select::LegacyCause::MapNotify, - change.map_notify.changed, - change.map_notify.first_key_sym, - change.map_notify.n_key_syms, - ); - } - crate::core_loop::xkb_layout::send_keyboard_mapping_followups( - state, - xkb_event_base, - &change, - (crate::core_loop::xkb_layout::X_SET_MODIFIER_MAPPING, 0), - ); - ModmapChangeOutcome::Success -} - -fn handle_get_geometry( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let drawable = x11::drawable_request_id(body).unwrap_or(ROOT_WINDOW); - let geometry = state - .resources - .window(drawable) - .map(window_geometry) - .or_else(|| state.resources.pixmap(drawable).map(pixmap_geometry)) - // #96: a GLX pbuffer is a drawable but lives only in glx_drawables, - // not the core resource store. Mesa's loader_dri3 calls GetGeometry on - // the pbuffer XID to size its DRI3 backing; without this it gets - // BadDrawable → "failed to create drawable" → ANGLE (Chromium) can't - // create its init pbuffer → GPU process dies. - .or_else(|| glx_pbuffer_geometry(state, drawable)); - let Some(geometry) = geometry else { - // Spec: BadDrawable on unknown drawable. xts probes - // destroyed/stale IDs and expects the protocol error. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - drawable.0, - 14, - ); - }; - debug!( - "client {} #{} GetGeometry 0x{:x} -> root=0x{:x} pos=({},{}) size=({}x{}) border={} depth={}", - client_id.0, - sequence.0, - drawable.0, - geometry.root.0, - geometry.x, - geometry.y, - geometry.width, - geometry.height, - geometry.border_width, - geometry.depth, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_get_geometry_reply(&mut buf, byte_order, sequence, geometry)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_query_tree( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let window = x11::drawable_request_id(body).unwrap_or(ROOT_WINDOW); - debug!( - "client {} #{} QueryTree 0x{:x}", - client_id.0, sequence.0, window.0 - ); - let Some(window_state) = state.resources.window(window) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 15, - ); - }; - // X11 spec: the root window's parent is None. Internally we store - // root.parent = root (self) and other code relies on that invariant, so - // translate the self-parent to None only here on the QueryTree wire reply. - // Reporting the root as its own parent makes Chromium/Ozone's GeometryCache - // recurse forever (infinite QueryTree(root)+GetGeometry(root)), so Electron - // apps (VS Code) spin and never map their window. - let parent = if window_state.parent == window { - ResourceId(0) - } else { - window_state.parent - }; - let children = window_state.children.clone(); - debug!( - "client {} #{} QueryTree reply 0x{:x}: parent=0x{:x} children={}", - client_id.0, - sequence.0, - window.0, - parent.0, - children.len(), - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(64); - x11::write_query_tree_reply( - &mut buf, - byte_order, - sequence, - ROOT_WINDOW, - parent, - &children, - )?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_intern_atom( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let name = x11::intern_atom_name(body); - let atom = state.atoms.intern(&name, header.data != 0); - debug!( - "client {} #{} InternAtom {:?} -> {}", - client_id.0, sequence.0, name, atom.0 - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_intern_atom_reply(&mut buf, byte_order, sequence, atom)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_list_properties( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - debug!("client {} #{} ListProperties", client_id.0, sequence.0); - let atoms: Vec = if body.len() >= 4 { - let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - state - .resources - .window(window) - .map(|w| w.properties.keys().copied().collect()) - .unwrap_or_default() - } else { - Vec::new() - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32 + atoms.len() * 4); - x11::write_list_properties_reply(&mut buf, byte_order, sequence, &atoms)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_put_image( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let Some(request) = x11::put_image_request(header.data, body) else { - return Ok(RequestOutcome::Handled); - }; - if request.width == 0 || request.height == 0 { - return Ok(RequestOutcome::Handled); - } - debug!( - "client {} #{} PutImage drawable=0x{:x} {}x{} dst=({},{}) depth={} fmt={:?}", - client_id.0, - sequence.0, - request.drawable.0, - request.width, - request.height, - request.dst_x, - request.dst_y, - request.depth, - request.format, - ); - if let Err((code, bad_value)) = validate_drawable_and_gc(state, request.drawable, request.gc) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 72); - } - let draw_state = state.resources.resolve_draw_state(request.gc); - let target = state.resources.host_drawable_target(request.drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - let (image_bytes, upload_depth) = match request.format { - x11::ImageFormat::ZPixmap => { - if request.left_pad != 0 || request.depth != target.depth() { - return Ok(RequestOutcome::Handled); - } - let Some(expected_len) = - zpixmap_expected_len(request.width, request.height, request.depth) - else { - return Ok(RequestOutcome::Handled); - }; - if request.data.len() < expected_len { - return Ok(RequestOutcome::Handled); - } - (request.data[..expected_len].to_vec(), request.depth) - } - x11::ImageFormat::XyBitmap => { - // XYBitmap is a single depth-1 source plane interpreted through - // the GC foreground/background pixels. This is the path used by - // XCreateBitmapFromData() and XCreatePixmapFromBitmapData(). - if request.depth != 1 { - return Ok(RequestOutcome::Handled); - } - let Some(expected_len) = - xybitmap_expected_len(request.width, request.height, request.left_pad) - else { - return Ok(RequestOutcome::Handled); - }; - if request.data.len() < expected_len { - return Ok(RequestOutcome::Handled); - } - let Some(bytes) = xybitmap_to_target_zpixmap( - &request.data[..expected_len], - request.width, - request.height, - request.left_pad, - target.depth(), - st.foreground, - st.background, - ) else { - return Ok(RequestOutcome::Handled); - }; - (bytes, target.depth()) - } - x11::ImageFormat::XyPixmap => { - // Depth-1 XYPixmap is a single bitmap plane and can be - // normalized through the same repack as XYBitmap. Higher - // depths need multi-plane composition and remain unsupported - // here for now. - if request.depth != 1 || target.depth() != 1 { - return Ok(RequestOutcome::Handled); - } - let Some(expected_len) = - xybitmap_expected_len(request.width, request.height, request.left_pad) - else { - return Ok(RequestOutcome::Handled); - }; - if request.data.len() < expected_len { - return Ok(RequestOutcome::Handled); - } - let Some(bytes) = xybitmap_to_zpixmap( - &request.data[..expected_len], - request.width, - request.height, - request.left_pad, - ) else { - return Ok(RequestOutcome::Handled); - }; - (bytes, request.depth) - } - x11::ImageFormat::Unknown(_) => { - return Ok(RequestOutcome::Handled); - } - }; - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - backend.put_image( - origin, - target.host_xid(), - upload_depth, - request.width, - request.height, - request.dst_x, - request.dst_y, - &image_bytes, - )?; - let _dropped = accumulate_damage_to_state( - state, - request.drawable, - request.dst_x, - request.dst_y, - request.width, - request.height, - ); - } - Ok(RequestOutcome::Handled) -} - -/// Compute the expected ZPixmap data length for `width × height` at -/// `depth`, returning `None` for unsupported depths or arithmetic -/// overflow. Mirrors `nested::zpixmap_expected_len`. -fn zpixmap_expected_len(width: u16, height: u16, depth: u8) -> Option { - let stride_bytes = zpixmap_row_stride(width, depth)?; - stride_bytes.checked_mul(usize::from(height)) -} - -/// Bytes per scanline for X11 ZPixmap of `width` pixels at `depth`, -/// padded to the server's bitmap_scanline_pad of 32 bits. -fn zpixmap_row_stride(width: u16, depth: u8) -> Option { - match depth { - 24 | 32 => usize::from(width).checked_mul(4), - 8 => usize::from(width).div_ceil(4).checked_mul(4), - 4 => usize::from(width).div_ceil(8).checked_mul(4), - 1 => usize::from(width).div_ceil(32).checked_mul(4), - _ => None, - } -} - -fn xybitmap_expected_len(width: u16, height: u16, left_pad: u8) -> Option { - let bits_per_row = usize::from(width).checked_add(usize::from(left_pad))?; - let stride_bytes = bits_per_row.div_ceil(32).checked_mul(4)?; - stride_bytes.checked_mul(usize::from(height)) -} - -fn xybitmap_to_zpixmap(data: &[u8], width: u16, height: u16, left_pad: u8) -> Option> { - let bits_per_row = usize::from(width).checked_add(usize::from(left_pad))?; - let src_row_stride = bits_per_row.div_ceil(32).checked_mul(4)?; - if data.len() < src_row_stride.checked_mul(usize::from(height))? { - return None; - } - let dst_row_stride = zpixmap_row_stride(width, 1)?; - let mut out = vec![0u8; dst_row_stride.checked_mul(usize::from(height))?]; - let left_pad = usize::from(left_pad); - let width = usize::from(width); - for row in 0..usize::from(height) { - let src_row = &data[row * src_row_stride..(row + 1) * src_row_stride]; - let dst_row = &mut out[row * dst_row_stride..(row + 1) * dst_row_stride]; - for x in 0..width { - let src_bit = left_pad + x; - let src_byte = src_row[src_bit / 8]; - if (src_byte >> (src_bit % 8)) & 1 != 0 { - dst_row[x / 8] |= 1 << (x % 8); - } - } - } - Some(out) -} - -fn depth_plane_mask(depth: u8) -> u32 { - if depth >= 32 { - u32::MAX - } else { - (1u32 << depth) - 1 - } -} - -fn write_zpixmap_pixel(bytes: &mut [u8], width: usize, depth: u8, x: usize, y: usize, value: u32) { - let stride = zpixmap_row_stride(width as u16, depth).expect("validated target depth"); - match depth { - 1 => { - let byte = &mut bytes[y * stride + x / 8]; - let bit = 1u8 << (x % 8); - if value & 1 != 0 { - *byte |= bit; - } else { - *byte &= !bit; - } - } - 4 => { - let byte = &mut bytes[y * stride + x / 2]; - let nibble = (value & 0x0f) as u8; - if x.is_multiple_of(2) { - *byte = (*byte & 0xf0) | nibble; - } else { - *byte = (*byte & 0x0f) | (nibble << 4); - } - } - 8 => bytes[y * stride + x] = value as u8, - 24 | 32 => { - let off = y * stride + x * 4; - bytes[off..off + 4].copy_from_slice(&value.to_le_bytes()); - } - _ => {} - } -} - -fn xybitmap_to_target_zpixmap( - data: &[u8], - width: u16, - height: u16, - left_pad: u8, - target_depth: u8, - fg: u32, - bg: u32, -) -> Option> { - let bits_per_row = usize::from(width).checked_add(usize::from(left_pad))?; - let src_row_stride = bits_per_row.div_ceil(32).checked_mul(4)?; - if data.len() < src_row_stride.checked_mul(usize::from(height))? { - return None; - } - let dst_row_stride = zpixmap_row_stride(width, target_depth)?; - let mut out = vec![0u8; dst_row_stride.checked_mul(usize::from(height))?]; - let left_pad = usize::from(left_pad); - let width = usize::from(width); - let fg = fg & depth_plane_mask(target_depth); - let bg = bg & depth_plane_mask(target_depth); - for row in 0..usize::from(height) { - let src_row = &data[row * src_row_stride..(row + 1) * src_row_stride]; - for x in 0..width { - let src_bit = left_pad + x; - let src_byte = src_row[src_bit / 8]; - let pixel = if (src_byte >> (src_bit % 8)) & 1 != 0 { - fg - } else { - bg - }; - write_zpixmap_pixel(&mut out, width, target_depth, x, row, pixel); - } - } - Some(out) -} - -/// Extract a tightly-packed `src_width × src_height × bpp(depth)` -/// region from an MIT-SHM ZPixmap buffer laid out as `total_width × -/// total_height` with the server's standard scanline padding. The -/// caller passes the full shm segment in `bytes`; `offset` is the -/// byte offset to the START of the image (not the region). -/// -/// Returns `None` if any computed offset would exceed `bytes.len()`, -/// or the depth is unsupported, or any required arithmetic -/// overflows. For `depth == 1` (bit-packed), `src_x` must be a -/// multiple of 8 — non-byte-aligned bit extraction is not -/// implemented; in practice all known clients use `src_x = 0` for -/// bitmasks. -fn extract_shm_zpixmap_region( - bytes: &[u8], - offset: u32, - total_width: u16, - total_height: u16, - src_x: i16, - src_y: i16, - src_width: u16, - src_height: u16, - depth: u8, -) -> Option> { - if src_x < 0 || src_y < 0 { - return None; - } - let src_x = u32::try_from(src_x).ok()?; - let src_y = u32::try_from(src_y).ok()?; - // The region must fit inside the declared total image. - let src_x_end = src_x.checked_add(u32::from(src_width))?; - let src_y_end = src_y.checked_add(u32::from(src_height))?; - if src_x_end > u32::from(total_width) || src_y_end > u32::from(total_height) { - return None; - } - - let total_stride = zpixmap_row_stride(total_width, depth)?; - let src_stride = zpixmap_row_stride(src_width, depth)?; - - // Per-row leading-byte offset within the source row. - let src_x_bytes: usize = match depth { - 1 => { - if src_x % 8 != 0 { - return None; - } - (src_x / 8) as usize - } - 4 => { - if src_x % 2 != 0 { - return None; - } - (src_x / 2) as usize - } - 8 => src_x as usize, - 24 | 32 => (src_x as usize).checked_mul(4)?, - _ => return None, - }; - - let base = usize::try_from(offset).ok()?; - // Bytes-per-source-row that actually carry image data (no trailing pad). - let row_bytes: usize = match depth { - 24 | 32 => (src_width as usize).checked_mul(4)?, - 8 => src_width as usize, - 4 => (src_width as usize).div_ceil(2), - 1 => (src_width as usize).div_ceil(8), - _ => return None, - }; - if row_bytes > src_stride { - return None; - } - - // Fast path: full-frame extract (src origin = (0,0), src dims = total - // dims) AND no trailing per-row pad gap (`row_bytes == src_stride == - // total_stride`). The wanted bytes are contiguous in the SHM segment - // starting at `offset` — borrow directly instead of per-row memcpy - // into a fresh Vec. 2026-05-28 cinnamon telemetry showed 28MB full- - // frame extracts at ~8-10ms each; this fast path drops them to a - // bounds-check + slice. The slow per-row path stays for partial - // regions (src offset != 0 or src dims != total dims) and for depths - // where `row_bytes < src_stride` (padding fills required). - if src_x == 0 - && src_y == 0 - && src_width == total_width - && src_height == total_height - && row_bytes == src_stride - { - let total_bytes = src_stride.checked_mul(usize::from(src_height))?; - let end = base.checked_add(total_bytes)?; - if end > bytes.len() { - return None; - } - return Some(std::borrow::Cow::Borrowed(&bytes[base..end])); - } - - let mut out = Vec::with_capacity(src_stride.checked_mul(usize::from(src_height))?); - for r in 0..usize::from(src_height) { - let row_y = (src_y as usize).checked_add(r)?; - let row_start = base - .checked_add(row_y.checked_mul(total_stride)?)? - .checked_add(src_x_bytes)?; - let row_end = row_start.checked_add(row_bytes)?; - if row_end > bytes.len() { - return None; - } - out.extend_from_slice(&bytes[row_start..row_end]); - // Pad scanline to 32-bit boundary if needed (d1/d4/d8 with - // width not a multiple of the pad unit). Output buffer's - // row stride is `src_stride`; pad with zeros so downstream - // consumers see the standard ZPixmap layout. - if src_stride > row_bytes { - out.resize(out.len() + (src_stride - row_bytes), 0); - } - } - Some(std::borrow::Cow::Owned(out)) -} - -fn handle_image_text8( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some((drawable_raw, gc_id, text_body)) = x11::image_text8_data(body) { - let drawable = ResourceId(drawable_raw); - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 76); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - backend.image_text8( - origin, - target.host_xid(), - st.foreground, - st.background, - header.data, - text_body, - )?; - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!("client {} #{} ImageText8", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_image_text16( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some((drawable_raw, gc_id, text_body)) = x11::image_text8_data(body) { - let drawable = ResourceId(drawable_raw); - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 77); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - backend.image_text16( - origin, - target.host_xid(), - st.foreground, - st.background, - header.data, - text_body, - )?; - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!("client {} #{} ImageText16", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_map_window( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(window) = x11::map_window_id(body) else { - return Ok(RequestOutcome::Handled); - }; - let Some((parent, override_redirect, current_map_state)) = state - .resources - .window(window) - .map(|w| (w.parent, w.override_redirect, w.map_state)) - else { - // Xorg `dix/dispatch.c::ProcMapWindow` does `dixLookupWindow` - // first and returns BadWindow on lookup failure. xts5 Xlib4 - // probes XMapWindow on a freed xid (badwin()) and expects the - // protocol error. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 8, - ); - }; - - // Per X11 protocol (Xorg `dix/window.c:2661`): "If the window is - // already mapped, this request has no effect." This MUST guard - // the MapRequest dispatch below, not just the local mapping — - // otherwise (a) the root window, which is permanently - // `Viewable` and whose `parent` field points to itself, fans a - // phantom MapRequest(parent=root, window=root) to any WM with - // SubstructureRedirect on root (mate-screensaver hits this on - // activation; marco's panic-response drops its substructure - // subscription and breaks compositing of every subsequent - // top-level); and (b) brisk-menu's ~50 Hz - // `gtk_window_present`/`XMapRaised` loop on its already-viewable - // popup re-fans MapNotify → Expose → full-extent damage, - // triggering marco's per-MapNotify `COMPOSITE::NameWindowPixmap` - // + recomposite (visible as menu flicker on KMS). - if current_map_state != MapState::Unmapped { - debug!( - "client {} #{} MapWindow 0x{:x} (already mapped — no-op)", - client_id.0, sequence.0, window.0 - ); - return Ok(RequestOutcome::Handled); - } - - // SubstructureRedirect on the parent: forward MapRequest to the - // first subscriber that isn't the requester (the WM), and skip - // mapping locally. - let redirect_targets: Vec = if !override_redirect { - let requester_has = state - .clients - .get(&client_id.0) - .and_then(|c| c.event_masks.get(&parent).copied()) - .is_some_and(|m| m & 0x0010_0000 != 0); - if requester_has { - Vec::new() - } else { - subscribers_by_id(state, parent, 0x0010_0000) - } - } else { - Vec::new() - }; - - if !redirect_targets.is_empty() { - debug!( - "client {} MapWindow 0x{:x} -> MapRequest to WM", - client_id.0, window.0 - ); - let _dropped = fanout_event_to_clients(state, &redirect_targets, |buf, seq, order| { - x11::encode_map_request_event(buf, seq, order, parent, window); - }); - return Ok(RequestOutcome::Handled); - } - - let transition = state.resources.map_window(window); - debug_assert!( - transition.mapping_changed, - "current_map_state == Unmapped guard above was checked; \ - map_window should now transition", - ); - let host_xid = state.resources.window(window).and_then(|w| w.host_xid); - let map_info = state - .resources - .window(window) - .map(|w| (w.parent, w.override_redirect)); - if let Some(xid) = host_xid { - let _ = backend.map_subwindow(origin, xid.as_raw()); - } - realize_storage_for_delta(state, backend, origin, &transition.delta); - // Every window that became viewable under a redirect (its own, or its - // parent's RedirectSubwindows) gets a backing, as Xorg allocates on - // realize (`compwindow.c:274`). AFTER `map_subwindow` per the plan's - // codex-round-6 ordering fix — `map_subwindow` blindly flips - // `scene_participating = true`, so the Manual participation flip - // inside `activate_redirect_backing_for` must land last. - apply_viewability_delta_to_redirects(state, backend, origin, &transition.delta); - if host_xid.is_some() { - reapply_redirect_mode_after_map(state, backend, origin, window); - } - - if let Some((parent, override_redir)) = map_info { - let _dropped = emit_window_event_to_state(state, window, 0x0002_0000, |buf, seq, order| { - x11::encode_map_notify_event(buf, seq, order, window, window, override_redir); - }); - let _dropped = emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { - x11::encode_map_notify_event(buf, seq, order, parent, window, override_redir); - }); - // Emit VisibilityNotify(Unobscured) then Expose on the window - // itself when it becomes viewable. Subscribed clients want the - // newly-viewable window to redraw. - let extents = state - .resources - .window(window) - .filter(|w| w.map_state == crate::resources::MapState::Viewable) - .map(|w| (w.width, w.height)); - if let Some((w, h)) = extents { - // VisibilityNotify(Unobscured) for clients selecting - // VisibilityChangeMask (0x10000). Under yserver's compositor - // model every viewable top-level is effectively unobscured. - // Without this, GTK3 leaves the window in a non-paintable - // visibility state and suppresses all frame-clock paints - // after the first expose-driven frame — the - // cinnamon-settings "title changes but content never - // repaints" freeze. Xorg sends Unobscured on map; we mirror - // that. (We never send Obscured: a composited top-level is - // always paintable, and unmap is signalled by UnmapNotify - // per spec, not VisibilityNotify.) - let _dropped = - emit_window_event_to_state(state, window, 0x0001_0000, |buf, seq, order| { - x11::encode_visibility_notify_event(buf, seq, order, window, 0); - }); - // Descendants that were MapWindow'd while this window was - // still unmapped were Unviewable; mapping this window - // transitions them to Viewable. Xorg fires - // VisibilityNotify(Unobscured) on every such descendant - // (mate-xorg.xtrace seq 0x0147 shows VisibilityNotify on - // both the FF main window and its child 0x02400010). - // yserver previously only notified the directly-mapped - // window, so GTK3's frame clock for the child never woke - // and the profile chooser stayed blank — the "empty shadow" - // FF bug on bee. Order with the Expose subtree walk below - // doesn't matter; both are subtree-wide and idempotent. - let _dropped = emit_visibility_unobscured_subtree_to_state(state, window); - let _dropped = - emit_window_event_to_state(state, window, 0x0000_8000, |buf, seq, order| { - x11::encode_expose_event(buf, seq, order, window, 0, 0, w, h, 0); - }); - let _dropped = emit_expose_subtree_to_state(state, window); - } - } - // Audit #11: Xorg's `miPaintWindow` fires damage on the window's - // extent when the window becomes viewable (the server-background - // fill is itself a paint, and DAMAGE hooks every paint). - // Compositors that subscribe via `XDamageCreate(window)` rely on - // that first DamageNotify to read the freshly-mapped window's - // pixels into their own offscreen. - // - // Order matters: this MUST come AFTER the MapNotify emissions - // above. Marco subscribes to SubstructureNotify on root, registers - // the window in its compositor tree on receiving MapNotify, and - // only then accepts DAMAGE-Notify on it as a NameWindowPixmap - // trigger. Pre-fix (damage emitted before MapNotify) marco saw the - // damage on a window it didn't yet track and silently dropped it, - // causing mate-panel-top to render blank until a later resize - // damage finally landed. See mate.xtrace lines 4938→4940 vs - // mate-xorg.xtrace lines 5164→5173. - if host_xid.is_some() { - let _dropped = accumulate_damage_full_to_state(state, window); - // The mapped window itself keeps its just-fired notify cycle. - for promoted in transition - .delta - .became_viewable - .iter() - .filter(|w| **w != window) - { - reset_damage_notify_cycle_for_drawable(state, *promoted); - } - accumulate_damage_viewable_descendants_to_state(state, window); - } - debug!( - "client {} #{} MapWindow 0x{:x} viewable+{}", - client_id.0, - sequence.0, - window.0, - transition.delta.became_viewable.len() - ); - Ok(RequestOutcome::Handled) -} - -fn accumulate_damage_viewable_descendants_to_state(state: &mut ServerState, root: ResourceId) { - let children: Vec = state.resources.children(root).to_vec(); - for child in children { - let child_window = state.resources.window(child); - let viewable = child_window.is_some_and(|w| w.map_state == MapState::Viewable); - if !viewable { - continue; - } - let _dropped = accumulate_damage_full_to_state(state, child); - accumulate_damage_viewable_descendants_to_state(state, child); - } -} - -fn handle_map_subwindows( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - map_subwindows_with_delta(state, backend, origin, client_id, sequence, body) - .map(|(outcome, _delta)| outcome) -} - -/// MapSubwindows; also returns the union of the children's viewability deltas. -fn map_subwindows_with_delta( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result<(RequestOutcome, ViewabilityDelta)> { - let mut delta = ViewabilityDelta::default(); - let Some(parent) = x11::map_window_id(body) else { - return Ok((RequestOutcome::Handled, delta)); - }; - if state.resources.window(parent).is_none() { - // Xorg `dix/dispatch.c::ProcMapSubwindows` returns BadWindow - // for an unknown parent xid. xts5 Xlib4 probes XMapSubwindows - // on badwin() and expects the protocol error. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - parent.0, - 9, - ) - .map(|outcome| (outcome, delta)); - } - let children: Vec = state.resources.children(parent).to_vec(); - for child in children { - let transition = state.resources.map_window(child); - let was_unmapped = transition.mapping_changed; - let host_xid = state.resources.window(child).and_then(|w| w.host_xid); - let extents = state.resources.window(child).map(|w| (w.width, w.height)); - let override_redirect = state - .resources - .window(child) - .is_some_and(|w| w.override_redirect); - if let Some(xid) = host_xid { - let _ = backend.map_subwindow(origin, xid.as_raw()); - } - realize_storage_for_delta(state, backend, origin, &transition.delta); - // Same post-hook as `handle_map_window`: AFTER `map_subwindow`. - apply_viewability_delta_to_redirects(state, backend, origin, &transition.delta); - delta.extend(transition.delta); - if host_xid.is_some() { - reapply_redirect_mode_after_map(state, backend, origin, child); - // Audit #11: see `handle_map_window` for the rationale. - // Mirror the damage bump so MapSubwindows-driven mass - // maps (mate-panel applet realize cascade, GTK - // children-on-show) also notify subscribed compositors. - let _dropped = accumulate_damage_full_to_state(state, child); - } - if was_unmapped { - let _dropped = - emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { - x11::encode_map_notify_event(buf, seq, order, child, child, override_redirect); - }); - let _dropped = - emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { - x11::encode_map_notify_event(buf, seq, order, parent, child, override_redirect); - }); - } - // Only emit Expose if the child is now Viewable (parent must - // also be mapped). When the parent is unmapped, mapping the - // child changes its `map_state` to `Mapped` but not `Viewable`, - // and the spec only fires Expose for newly-viewable areas. - let viewable = state - .resources - .window(child) - .is_some_and(|w| w.map_state == MapState::Viewable); - if was_unmapped - && viewable - && let Some((width, height)) = extents - { - let _dropped = - emit_window_event_to_state(state, child, 0x0000_8000, |buf, seq, order| { - x11::encode_expose_event(buf, seq, order, child, 0, 0, width, height, 0); - }); - // Mapping this child transitioned it Unmapped->Viewable, which - // also promotes any of its descendants that were sitting - // Unviewable (mapped while this ancestor was unmapped) to - // Viewable via the map_window cascade. Xorg fires Expose on - // every newly-viewable window; without this walk the promoted - // grandchildren never get their first Expose and never paint. - // Mirrors handle_map_window's emit_expose_subtree_to_state. - let _dropped = emit_expose_subtree_to_state(state, child); - } - } - debug!( - "client {} #{} MapSubwindows viewable+{}", - client_id.0, - sequence.0, - delta.became_viewable.len() - ); - Ok((RequestOutcome::Handled, delta)) -} - -fn handle_unmap_window( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(window) = x11::map_window_id(body) { - if state.resources.window(window).is_none() { - // Xorg `dix/dispatch.c::ProcUnmapWindow` returns BadWindow - // via dixLookupWindow before unmapping. xts5 Xlib4 probes - // XUnmapWindow on badwin() and expects the protocol error. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 10, - ); - } - let host_xid = state.resources.window(window).and_then(|w| w.host_xid); - let transition = state.resources.unmap_window(window); - let was_mapped = transition.mapping_changed; - let parent = if was_mapped { - state - .resources - .window(window) - .map_or(ROOT_WINDOW, |w| w.parent) - } else { - ROOT_WINDOW - }; - if let Some(xid) = host_xid { - let _ = backend.unmap_subwindow(origin, xid.as_raw()); - } - // Xorg frees each redirect pixmap at unrealize (`compwindow.c:291`). - apply_viewability_delta_to_redirects(state, backend, origin, &transition.delta); - release_storage_for_delta(state, backend, origin, &transition.delta); - // XI1: an active device grab is released automatically when its - // grab window becomes not viewable (XTS XGrabDeviceKey-9; Xorg - // DeactivateGrabsOnWindowUnmap shape). - if was_mapped { - let released: Vec = state - .xi1_active_grabs - .iter() - .filter(|(_, g)| { - state - .resources - .window(g.grab_window) - .is_none_or(|w| w.map_state != crate::resources::MapState::Viewable) - }) - .map(|(d, _)| *d) - .collect(); - for dev in released { - state.xi1_active_grabs.remove(&dev); - let xid_map = backend.xid_map().clone(); - crate::core_loop::pointer_fanout::xi1_thaw_device(state, backend, &xid_map, dev); - } - } - if was_mapped { - let _dropped = - emit_window_event_to_state(state, window, 0x0002_0000, |buf, seq, order| { - x11::encode_unmap_notify_event(buf, seq, order, window, window, false); - }); - let _dropped = - emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { - x11::encode_unmap_notify_event(buf, seq, order, parent, window, false); - }); - // XI1: a device focus on a window that just became - // unviewable reverts per its revert_to, emitting - // DeviceFocusIn/Out (Xi/exevents.c - // DeleteDeviceFromAnyExtEvents). After UnmapNotify, matching - // Xorg's UnmapWindow → UnrealizeTree ordering. - crate::core_loop::xi1_focus::revert_unviewable_focus(state); - // Core focus likewise (Xorg UnrealizeTree → - // DeleteWindowFromAnyEvents): covers the focus window - // itself or any unmapped ancestor. - revert_core_focus_if_unviewable(state); - // Active grabs on a window that just became unviewable - // deactivate too (same Xorg path). - release_core_grabs_for_unviewable(state, backend); - } - } - debug!("client {} #{} UnmapWindow", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_unmap_subwindows( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - unmap_subwindows_with_delta(state, backend, origin, client_id, sequence, body) - .map(|(outcome, _delta)| outcome) -} - -/// UnmapSubwindows; also returns the union of the children's viewability deltas. -fn unmap_subwindows_with_delta( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result<(RequestOutcome, ViewabilityDelta)> { - let mut delta = ViewabilityDelta::default(); - let Some(parent) = x11::map_window_id(body) else { - return Ok((RequestOutcome::Handled, delta)); - }; - struct PendingUnmap { - child: ResourceId, - host_xid: Option, - } - let Some(children) = state.resources.mapped_children_bottom_to_top(parent) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - parent.0, - 11, - ) - .map(|outcome| (outcome, delta)); - }; - // Snapshot mapping order + collect host xids; unmap each in the - // resource table. - let mut pending: Vec = Vec::new(); - for child in children { - let host_xid = state.resources.window(child).and_then(|w| w.host_xid); - let transition = state.resources.unmap_window(child); - delta.extend(transition.delta); - if transition.mapping_changed { - pending.push(PendingUnmap { child, host_xid }); - } - } - for item in pending { - if let Some(xid) = item.host_xid { - let _ = backend.unmap_subwindow(origin, xid.as_raw()); - } - let child = item.child; - let _dropped = emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { - x11::encode_unmap_notify_event(buf, seq, order, child, child, false); - }); - let _dropped = emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { - x11::encode_unmap_notify_event(buf, seq, order, parent, child, false); - }); - } - // Xorg frees each redirect pixmap at unrealize (`compwindow.c:291`). - apply_viewability_delta_to_redirects(state, backend, origin, &delta); - release_storage_for_delta(state, backend, origin, &delta); - crate::core_loop::xi1_focus::revert_unviewable_focus(state); - revert_core_focus_if_unviewable(state); - release_core_grabs_for_unviewable(state, backend); - debug!( - "client {} #{} UnmapSubwindows viewable-{}", - client_id.0, - sequence.0, - delta.became_unviewable.len() - ); - Ok((RequestOutcome::Handled, delta)) -} - -fn handle_ge_request( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, -) -> io::Result { - if header.data == 0 { - debug!("client {} #{} GEQueryVersion", client_id.0, sequence.0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_ge_query_version_reply(&mut buf, byte_order, sequence)?; - return Ok(write_to_client(client, client_id, &buf)); - } - emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(header.data), - header.opcode, - ) -} - -fn handle_big_requests_request( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, -) -> io::Result { - if header.data != 0 { - // Malformed minor — the reader thread parked waiting for an - // Apply / Ignore signal after sending the Enable through the - // channel; unblock it with `IgnoreBigRequests` so it doesn't - // deadlock. - if let Some(client) = state.clients.get(&client_id.0) - && let Some(tx) = client.reader_control.as_ref() - { - let _ = tx.send(crate::server::ReaderControl::IgnoreBigRequests); - } - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(header.data), - header.opcode, - ); - } - debug!("client {} #{} BigRequestsEnable", client_id.0, sequence.0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - client.big_requests_enabled = true; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_big_requests_enable_reply( - &mut buf, - byte_order, - sequence, - x11::MAX_BIG_REQUEST_UNITS, - )?; - let outcome = write_to_client(client, client_id, &buf); - // Unblock the reader so subsequent requests use big-framing. - if let Some(tx) = client.reader_control.as_ref() { - let _ = tx.send(crate::server::ReaderControl::ApplyBigRequests); - } - Ok(outcome) -} - -fn handle_get_window_attributes( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let id = x11::drawable_request_id(body).unwrap_or(ROOT_WINDOW); - debug!( - "client {} #{} GetWindowAttributes 0x{:x}", - client_id.0, sequence.0, id.0, - ); - // Spec: BadWindow on unknown window ID. Don't silently fall back to - // ROOT_WINDOW — xts probes stale/destroyed XIDs and expects the - // protocol error. - if state.resources.window(id).is_none() { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_WINDOW, id.0, 3); - } - let target = id; - let your_event_mask = state - .clients - .get(&client_id.0) - .and_then(|c| c.event_masks.get(&target).copied()) - .unwrap_or(0); - let all_event_masks: u32 = state - .clients - .values() - .filter_map(|c| c.event_masks.get(&target).copied()) - .fold(0u32, |a, b| a | b); - let attrs = window_attributes( - state.resources.window(target), - all_event_masks, - your_event_mask, - ); - if let Some(window) = state.resources.window(target) { - debug!( - "client {} #{} GetWindowAttributes reply 0x{:x}: parent=0x{:x} map_state={} override_redirect={}", - client_id.0, - sequence.0, - target.0, - window.parent.0, - attrs.map_state, - attrs.override_redirect, - ); - } - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(48); - x11::write_get_window_attributes_reply(&mut buf, byte_order, sequence, attrs)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn window_attributes( - window: Option<&Window>, - all_event_masks: u32, - your_event_mask: u32, -) -> x11::WindowAttributes { - let window = window.expect("root window exists"); - x11::WindowAttributes { - visual: window.visual, - class: window.class.protocol_value(), - bit_gravity: window.bit_gravity, - win_gravity: window.win_gravity, - backing_store: window.backing_store, - backing_planes: window.backing_planes, - backing_pixel: window.backing_pixel, - save_under: window.save_under, - map_is_installed: true, - map_state: window.map_state.protocol_value(), - override_redirect: window.override_redirect, - colormap: window.colormap, - all_event_masks, - your_event_mask, - do_not_propagate_mask: window.do_not_propagate_mask, - } -} - -fn handle_circulate_window( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if body.len() < 4 { - debug!( - "client {} #{} CirculateWindow (short body)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - let container = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let direction = header.data; - if state.resources.window(container).is_none() { - // Xorg `dix/dispatch.c::ProcCirculateWindow` returns BadWindow - // via dixLookupWindow on an unknown xid. xts5 Xlib4 probes - // XCirculateSubwindows{,Up,Down} on badwin() and expects it. - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - container.0, - 13, - ); - } - let chosen_child = { - let kids = state.resources.children(container); - match (direction, kids.first(), kids.last()) { - (0, _, Some(&back)) => Some(back), - (1, Some(&front), _) => Some(front), - _ => None, - } - }; - let Some(child) = chosen_child else { - return Ok(RequestOutcome::Handled); - }; - // SubstructureRedirect on container takes priority — redirect the - // request to the first subscriber instead of performing the - // circulate. - let redirect_target = subscribers_by_id(state, container, 0x0010_0000) - .into_iter() - .next(); - if let Some(target) = redirect_target { - let _dropped = fanout_event_to_clients(state, &[target], |buf, seq, order| { - let _ = - x11::write_circulate_request_event(buf, order, seq, container, child, direction); - }); - } else { - let _ = state.resources.circulate_window(container, direction); - let on_child = subscribers_by_id(state, child, 0x0002_0000); - let on_container = subscribers_by_id(state, container, 0x0008_0000); - let mut targets = on_child; - for cid in on_container { - if !targets.contains(&cid) { - targets.push(cid); - } - } - let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { - let _ = x11::write_circulate_notify_event(buf, order, seq, child, child, direction); - }); - } - debug!("client {} #{} CirculateWindow", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_create_cursor( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 28 { - let cursor_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - if state.resources.xid_in_use(cursor_id) - || xid_out_of_client_range(state, client_id, cursor_id.0) - { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - cursor_id.0, - 93, - ); - } - let source_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let mask_id = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let fore = ( - u16::from_le_bytes([body[12], body[13]]), - u16::from_le_bytes([body[14], body[15]]), - u16::from_le_bytes([body[16], body[17]]), - ); - let back = ( - u16::from_le_bytes([body[18], body[19]]), - u16::from_le_bytes([body[20], body[21]]), - u16::from_le_bytes([body[22], body[23]]), - ); - let hot_x = u16::from_le_bytes([body[24], body[25]]); - let hot_y = u16::from_le_bytes([body[26], body[27]]); - - let src_host = state.resources.pixmap(source_id).and_then(|p| p.host_xid); - let mask_host = if mask_id.0 == 0 { - None - } else { - state.resources.pixmap(mask_id).and_then(|p| p.host_xid) - }; - state.resources.create_cursor(client_id, cursor_id); - if let Some(src_host) = src_host { - match backend.create_cursor(origin, src_host, mask_host, fore, back, hot_x, hot_y) { - Ok(handle) => { - state.resources.set_cursor_host_xid(cursor_id, handle); - } - Err(err) => { - log::warn!("client {} CreateCursor failed: {err}", client_id.0); - } - } - } - } - debug!("client {} #{} CreateCursor", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_create_glyph_cursor( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 28 - && let Some(cursor) = x11::create_glyph_cursor_id(body) - { - let new_id = cursor.0; - let validation_failed = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - let owned = crate::server::IdAllocator::validate_owned( - new_id, - handle.resource_id_base, - handle.resource_id_mask, - ); - let in_use = state.xid_occupied(cursor.0); - !owned || in_use - }; - if validation_failed { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - new_id, - 94, - ); - } - - let source_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let mask_id = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let source_char = u16::from_le_bytes([body[12], body[13]]); - let mask_char = u16::from_le_bytes([body[14], body[15]]); - let fore = ( - u16::from_le_bytes([body[16], body[17]]), - u16::from_le_bytes([body[18], body[19]]), - u16::from_le_bytes([body[20], body[21]]), - ); - let back = ( - u16::from_le_bytes([body[22], body[23]]), - u16::from_le_bytes([body[24], body[25]]), - u16::from_le_bytes([body[26], body[27]]), - ); - - let src_host = state.resources.font(source_id).map(|f| f.host_xid); - let mask_host = if mask_id.0 == 0 { - None - } else { - state.resources.font(mask_id).map(|f| f.host_xid) - }; - - state.resources.create_glyph_cursor(client_id, cursor); - if let Some(src_host) = src_host { - match backend.create_glyph_cursor( - origin, - src_host, - mask_host, - source_char, - mask_char, - fore, - back, - ) { - Ok(handle) => { - state.resources.set_cursor_host_xid(cursor, handle); - } - Err(err) => { - log::warn!("client {} CreateGlyphCursor failed: {err}", client_id.0); - } - } - } else { - log::warn!( - "client {} CreateGlyphCursor: source font 0x{:x} unknown", - client_id.0, - source_id.0 - ); - } - } - debug!("client {} #{} CreateGlyphCursor", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_query_extension( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let name = x11::query_extension_name(body); - let (present, major_opcode, first_event, first_error) = extension_query_reply(&name, backend) - .map(|(major_opcode, first_event, first_error)| { - (true, major_opcode, first_event, first_error) - }) - .unwrap_or((false, 0, 0, 0)); - debug!( - "client {} #{} QueryExtension {:?} -> {}", - client_id.0, - sequence.0, - name, - if present { "present" } else { "absent" } - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_query_extension_reply( - &mut buf, - byte_order, - sequence, - present, - major_opcode, - first_event, - first_error, - )?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_list_extensions( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} ListExtensions", client_id.0, sequence.0); - let names = advertised_extension_names(backend); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32 + names.len() * 16); - x11::write_list_extensions_reply(&mut buf, byte_order, sequence, &names)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_allow_events( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - // Core AllowEvents modes (X11 spec): - // 0 AsyncPointer 1 SyncPointer 2 ReplayPointer - // 3 AsyncKeyboard 4 SyncKeyboard 5 ReplayKeyboard - // 6 AsyncBoth 7 SyncBoth - let mode = header.data; - if mode > 7 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(mode), - 35, - ); - } - let time = body - .get(0..4) - .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - apply_allow_events(state, backend, client_id, sequence, mode, time) -} - -/// Map an XI2 `XIAllowEvents` mode + target `deviceid` onto the equivalent -/// core `AllowSome` mode consumed by [`apply_allow_events`]. `deviceid` 3 is -/// the master keyboard; anything else is the pointer. The paired modes act on -/// the OTHER device. Touch modes (`XIAcceptTouch`=6 / `XIRejectTouch`=7) and -/// anything unknown are unsupported → `None` (no-op). XI2 mode constants per -/// `X11/extensions/XI2.h`: AsyncDevice=0, SyncDevice=1, ReplayDevice=2, -/// AsyncPairedDevice=3, AsyncPair=4, SyncPair=5. -fn xi2_allow_mode_to_core(xi2_mode: u8, deviceid: u16) -> Option { - let kbd = deviceid == 3; - // Core modes: 0 AsyncPointer 1 SyncPointer 2 ReplayPointer - // 3 AsyncKeyboard 4 SyncKeyboard 5 ReplayKeyboard - // 6 AsyncBoth 7 SyncBoth - Some(match xi2_mode { - 0 => u8::from(kbd) * 3, // XIAsyncDevice → Async{Pointer,Keyboard} - 1 => 1 + u8::from(kbd) * 3, // XISyncDevice → Sync{Pointer,Keyboard} - 2 => 2 + u8::from(kbd) * 3, // XIReplayDevice → Replay{Pointer,Keyboard} - 3 => u8::from(!kbd) * 3, // XIAsyncPairedDevice → async the PAIRED device - 4 => 6, // XIAsyncPair → AsyncBoth - 5 => 7, // XISyncPair → SyncBoth - _ => return None, // XIAcceptTouch / XIRejectTouch / unknown - }) -} - -/// Shared `AllowSome` implementation (Xorg `dix/events.c:1823`), driven by -/// BOTH core `AllowEvents` (mode straight from the request) AND XI2 -/// `XIAllowEvents` (mode mapped from the XI2 mode + deviceid; see -/// [`xi2_allow_mode_to_core`]). Routing the XI2 path through here — rather -/// than the old partial reimplementation in the XI2 handler — kills a -/// recurring class of divergence bugs where the XI2 copy mishandled modes -/// the core path got right (the desktop rubber-band = Async/Replay thaw -/// gap; the Cinnamon input freeze = `XISyncDevice`/mode-1 treated as a -/// no-op). `mode` is a CORE AllowEvents mode (0..=7); `time` is the -/// request timestamp. -fn apply_allow_events( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - mode: u8, - time: u32, -) -> io::Result { - // Xorg AllowSome: the request is a no-op when its time is LATER - // than the current time or EARLIER than the client's grab time - // (XAllowEvents-12/13). Pointer modes gate on the pointer's grab - // time, keyboard and *Both modes on the keyboard's. - let grab_time = if matches!(mode, 0..=2) { - state.last_pointer_grab_time - } else { - state.last_keyboard_grab_time - }; - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(grab_time); - if time != 0 - && (crate::core_loop::xi1_focus::time_after(time, now) - || crate::core_loop::xi1_focus::time_after(grab_time, time)) - { - debug!( - "client {} #{} AllowEvents ignored (time {time} outside [{grab_time}, {now}])", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - debug!( - "client {} #{} AllowEvents mode={} frozen_pointer={} frozen_keyboard={}", - client_id.0, - sequence.0, - mode, - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .is_some_and(|f| f.stored.is_some()), - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .is_some_and(|f| f.stored.is_some()), - ); - - // Port of Xorg AllowSome (dix/events.c:1823). `thisDev` is the - // pointer for the pointer modes and the keyboard for the keyboard - // and *Both modes; the request is a no-op unless this client's - // grab holds the device frozen, or the device is synced on this - // client's behalf. - use crate::server::Xi1SyncState; - let dev_this = if matches!(mode, 0..=2) { - crate::xinput::DEVICEID_SLAVE_POINTER - } else { - crate::xinput::DEVICEID_SLAVE_KEYBOARD - }; - let grab_owner_of = |state: &ServerState, dev: u16| -> Option { - crate::core_loop::pointer_fanout::xi1_device_grab_owner(state, dev).or_else(|| { - if dev == crate::xinput::DEVICEID_SLAVE_POINTER { - state.active_pointer_grab.map(|grab| grab.owner) - } else { - None - } - }) - }; - let this_grabbed = grab_owner_of(state, dev_this) == Some(client_id); - let this_state = state - .xi1_frozen - .get(&dev_this) - .map_or(Xi1SyncState::Thawed, |f| f.state); - let this_synced = state.xi1_frozen.get(&dev_this).and_then(|f| f.other) == Some(client_id); - if !((this_grabbed && this_state >= Xi1SyncState::FrozenNoEvent) || this_synced) { - debug!( - "client {} #{} AllowEvents no-op (not frozen by this client: grabbed={this_grabbed} state={this_state:?} synced={this_synced})", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - - let pointer_replay = mode == 2; - let keyboard_replay = mode == 5; - - // State transitions per mode (Xorg AllowSome switch). The queued - // events play AFTER the transition so the freeze gate at fanout - // entry sees the new state: Async → events flow; Sync → - // FreezeNextEvent lets them flow until the next key/button trips - // the re-freeze (FreezeThisEventIfNeededForSyncGrab). - let set_state = |state: &mut ServerState, dev: u16, st: Xi1SyncState| { - let f = state.xi1_frozen.entry(dev).or_default(); - f.state = st; - if f.other == Some(client_id) { - f.other = None; - } - }; - let dev_ptr = crate::xinput::DEVICEID_SLAVE_POINTER; - let dev_kbd = crate::xinput::DEVICEID_SLAVE_KEYBOARD; - // Xorg AllowSome `othersFrozen`: the *Both modes (AsyncBoth / - // SyncBoth) only act when ANOTHER device this client grabbed is - // itself frozen (dix/events.c:1872, 1886 — `if (othersFrozen)`). - // Without this gate a client could thaw/re-freeze its own device - // via *Both even when no paired device is frozen, leaving later - // grabs in the wrong sync state. In the two-device model "others" - // relative to dev_this (keyboard, for *Both) is the pointer. - let others_frozen = { - let other = if dev_this == dev_kbd { - dev_ptr - } else { - dev_kbd - }; - grab_owner_of(state, other) == Some(client_id) - && state - .xi1_frozen - .get(&other) - .is_some_and(|f| f.state >= Xi1SyncState::FrozenNoEvent) - }; - match mode { - 0 | 2 => set_state(state, dev_ptr, Xi1SyncState::Thawed), - 1 => set_state(state, dev_ptr, Xi1SyncState::FreezeNextEvent), - 3 | 5 => set_state(state, dev_kbd, Xi1SyncState::Thawed), - 4 => set_state(state, dev_kbd, Xi1SyncState::FreezeNextEvent), - 6 if others_frozen => { - // AsyncBoth thaws every device this client's grabs froze. - for dev in [dev_ptr, dev_kbd] { - if grab_owner_of(state, dev) == Some(client_id) - || state.xi1_frozen.get(&dev).and_then(|f| f.other) == Some(client_id) - { - set_state(state, dev, Xi1SyncState::Thawed); - } - } - } - 7 if others_frozen => { - // SyncBoth arms FreezeBothNextEvent on the client's - // grabbed devices. - for dev in [dev_ptr, dev_kbd] { - if grab_owner_of(state, dev) == Some(client_id) - || state.xi1_frozen.get(&dev).and_then(|f| f.other) == Some(client_id) - { - set_state(state, dev, Xi1SyncState::FreezeBothNextEvent); - } - } - } - // *Both with no paired device frozen → no-op (Xorg). - 6 | 7 => {} - _ => {} - } - - // Withheld pointer events. The activating press of a sync passive - // grab was already delivered to the grab owner — only Replay - // re-delivers it (to the natural target, grab bypassed); the - // async/sync releases just drop it. The QUEUE (events that arrived - // during the freeze, delivered to nobody) plays through the normal - // pipeline on every pointer-side release — Xorg - // PlayReleasedEvents; with the grab still active they route to - // the grab owner. - let pointer_side = matches!(mode, 0 | 1 | 2 | 6 | 7); - let frozen_pointer = if pointer_side { - state - .xi1_frozen - .get_mut(&dev_ptr) - .and_then(|f| f.stored.take()) - } else { - None - }; - // NOT_GRABBED (Replay) deactivates a frozen-with-event grab on - // this device — passive AND explicit (Xorg dix/events.c:1898 calls - // DeactivateGrab regardless of grab kind). Async/Sync keep the - // grab until the natural button release. Without the explicit - // branch a GrabPointer(GrabModeSync) replays the frozen event but - // stays active → user-visible stuck grab. - let pointer_has_event = frozen_pointer.is_some(); - if pointer_replay && state.active_pointer_grab.is_some_and(|grab| grab.passive) { - // Xorg `DeactivatePointerGrab` → `DoEnterLeaveEvents(grab - // window → sprite, NotifyUngrab)` (dix/events.c:1711): mirror - // the activation chain emitted in pointer_fanout so the client's - // crossing state rebalances. The subsequent replay (below) - // re-delivers the press to the natural target, matching Xorg's - // ungrab-crossings-then-replayed-press order. Shared with the XI1 - // ReplayThisDevice path. - deactivate_passive_pointer_grab_crossings(state); - } else if pointer_replay - && pointer_has_event - && state - .active_pointer_grab - .is_some_and(|g| g.owner == client_id) - { - deactivate_core_pointer_grab(state, backend, client_id); - } - - let keyboard_side = matches!(mode, 3..=7); - let frozen_keyboard = if keyboard_side { - state - .xi1_frozen - .get_mut(&dev_kbd) - .and_then(|f| f.stored.take()) - } else { - None - }; - // The activating core key was already delivered to the grab owner. Its - // parallel XI1 form can be pending from the device enqueue path; Sync - // must not replay it and consume the allowance intended for the next - // physical key event. - if mode == 4 - && let Some(crate::server::QueuedInputEvent::HostKey(event)) = frozen_keyboard.as_ref() - { - let press_evcode = - crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; - if let Some(index) = state.sync_pending.iter().position(|pending| { - pending.device == dev_kbd - && matches!(&pending.event, crate::server::QueuedInputEvent::Xi1Routed(q) - if q.evcode == press_evcode && q.detail == event.keycode && q.time == event.time) - }) { - state.sync_pending.remove(index); - } - } - // GH #59: a synchronous passive key grab's activating press is - // recorded in BOTH the unified activating slot (`Xi1Freeze::stored`, - // taken above) AND the XI1 pending queue. Xorg's ComputeFreezes replays the stored - // activating event only for Replay*, never for Sync* - // (dix/events.c:1320-1370). On SyncKeyboard, drop that duplicate - // queued XI1 DeviceKeyPress so the closing `xi1_compute_freezes` - // doesn't replay the grab's own already-delivered press — that - // replay would trip FreezeNextEvent → FrozenWithEvent, consuming the - // SyncKeyboard allowance meant for the next *physical* event and - // withholding the terminating release (sxhkd's dead keyboard). - if keyboard_replay - && state - .active_keyboard_grab - .is_some_and(|g| g.owner == client_id) - { - let is_passive = matches!( - state.active_keyboard_grab.map(|g| g.source), - Some(crate::server::ActiveKeyboardGrabSource::PassiveKey { .. }) - ); - let kbd_has_event = frozen_keyboard.is_some() - || state - .sync_pending - .iter() - .any(|pending| pending.device == dev_kbd); - if is_passive { - state.active_keyboard_grab = None; - } else if kbd_has_event { - // Explicit GrabKeyboard(GrabModeSync): deactivate on replay - // too (Xorg NOT_GRABBED → DeactivateGrab), emitting the - // FocusOut(NotifyUngrab) chain. Else the grab stays stuck. - deactivate_core_keyboard_grab(state, client_id); - } - } - - if pointer_replay - && let Some(crate::server::QueuedInputEvent::HostPointer(event)) = frozen_pointer - { - // Snapshot the xid_map so we can release the immutable - // borrow on `backend` before pointer_event_fanout_to_state - // mutates `state`. The map is small (a few hundred entries) - // and AllowEvents-replay is rare, so the clone is cheap - // compared to the wire writes the fanout produces. - let xid_map = backend.xid_map().clone(); - // Deliver core and XI2 device events to the natural target on - // replay, but do not regenerate XI_RawButtonPress: raw events - // describe physical input and were delivered before the grab froze. - // The XI2 freeze-filter at pointer_fanout.rs:309-316 (cinnamon - // aea9b0f) restricts XI2 press to the grab owner ONLY - // during sync-passive-grab freeze; the natural target - // never received XI2 during the freeze. Trace evidence - // from MATE on silence (2026-05-28): marco activates - // passive grab on the panel, AllowEvents fires, mate-panel - // (only XI2 mask, no core mask) saw the queued release - // but no press → menu clicks dead. - let _dropped = replay_frozen_pointer_event_to_state(state, backend, &xid_map, event); - } - if keyboard_replay - && let Some(crate::server::QueuedInputEvent::HostKey(event)) = frozen_keyboard - { - let _dropped = replay_frozen_key_to_focus(state, event); - } - // ComputeFreezes: replay the per-device XI1 queues + withheld - // core keys now that the sync states changed (Xorg has ONE - // AllowSome for both protocols). - let xid_map = backend.xid_map().clone(); - crate::core_loop::pointer_fanout::xi1_compute_freezes(state, backend, &xid_map); - Ok(RequestOutcome::Handled) -} - -/// Record a client's XI version the way Xorg `ProcXIQueryVersion` stores -/// it in `XIClientRec`: the first query sets it; a later query raises it -/// only when both the stored and the new version are 2.2 or newer -/// ("Peter promises to never again break backward compatibility"). -/// Otherwise the stored version stays — Xorg then answers a lower request -/// with BadValue and a higher one with the stored version; yserver keeps -/// answering with the negotiated version, so only the stored value (what -/// `FilterRawEvents` reads) follows Xorg here. -fn record_xi2_client_version(state: &mut ServerState, client_id: ClientId, version: (u16, u16)) { - match state.xi2_client_versions.get(&client_id) { - None => { - state.xi2_client_versions.insert(client_id, version); - } - Some(&stored) => { - if version >= (2, 2) && stored >= (2, 2) && version > stored { - state.xi2_client_versions.insert(client_id, version); - } - } - } -} - -fn handle_set_input_focus( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some(window) = x11::input_focus_window(body) { - // Validation per Xorg SetInputFocus (dix/events.c): revert_to - // ∈ {None, PointerRoot, Parent} else BadValue; a focus window - // (anything other than None(0)/PointerRoot(1)) must exist - // (BadWindow) and be viewable (BadMatch). - let revert_to = header.data; - if revert_to > 2 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(revert_to), - 42, - ); - } - if let Some((code, value)) = core_focus_window_error(state, window) { - return emit_x11_error(state, client_id, sequence, code, value, 42); - } - let time = body - .get(4..8) - .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - apply_core_input_focus(state, client_id, sequence, window, revert_to, time); - } - debug!("client {} #{} SetInputFocus", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// The window check of Xorg `SetInputFocus`: a focus other than -/// None(0)/PointerRoot(1) must be an existing window (BadWindow) that is -/// viewable (BadMatch). Returns `(error code, errorValue)`. -fn core_focus_window_error(state: &ServerState, window: ResourceId) -> Option<(u8, u32)> { - if window.0 <= 1 { - return None; - } - match state.resources.window(window) { - None => Some((x11::error::BAD_WINDOW, window.0)), - Some(w) if w.map_state != crate::resources::MapState::Viewable => { - Some((x11::error::BAD_MATCH, window.0)) - } - Some(_) => None, - } -} - -/// The rest of Xorg `SetInputFocus` for the master keyboard, whose focus -/// is the core focus (core SetInputFocus and XISetFocus on device 3 both -/// land here): the timestamp gate, the FocusOut/FocusIn chain, and the -/// new focus/revert_to/time. `window` has passed -/// [`core_focus_window_error`]. -fn apply_core_input_focus( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - window: ResourceId, - revert_to: u8, - time: u32, -) { - // Xorg SetInputFocus: requests with a time LATER than the - // current time or EARLIER than the last focus time are - // silently ignored. - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.core_focus.time); - if time != 0 - && (crate::core_loop::xi1_focus::time_after(time, now) - || crate::core_loop::xi1_focus::time_after(state.core_focus.time, time)) - { - debug!( - "client {} #{} SetInputFocus ignored (time {time} outside [{}, {now}])", - client_id.0, sequence.0, state.core_focus.time - ); - return; - } - debug!( - "focus decision: client {} SetInputFocus 0x{:x} revert_to={revert_to}", - client_id.0, window.0 - ); - log::trace!( - target: "yserver::input::focus", - "SetInputFocus client={} window={} revert_to={revert_to}", - state.debug_client_label(client_id), - state.debug_window_label(window), - ); - let from_raw = state.core_focus.raw; - let to_raw = window.0; - if from_raw != to_raw { - // Xorg SetInputFocus (dix/events.c:4923): the focus transition - // is reported NotifyWhileGrabbed (3) while a keyboard grab is - // active, else NotifyNormal (0). bspwm focuses a newly-mapped - // window WHILE sxhkd's synchronous passive key grab is still - // active; emitting NotifyNormal there told GLFW/kitty it had - // genuinely taken focus mid-grab, and its focus state machine - // then ignored every typed key (the keys still routed - // correctly to its window — only the FocusIn mode was wrong). - // Mirrors the same gate in `revert_core_focus_from`. - let mode = if state.active_keyboard_grab.is_some() { - 3 // NotifyWhileGrabbed - } else { - 0 // NotifyNormal - }; - emit_core_focus_transition(state, from_raw, to_raw, mode); - } - state.core_focus = crate::server::CoreFocus { - raw: to_raw, - revert_to, - time: if time == 0 { now } else { time }, - }; - // Legacy mirror — the key fanout's `current_focus` and other - // readers still consult the per-client field; None/PointerRoot - // map to ROOT_WINDOW there (the fanout resolves PointerRoot - // through `state.core_focus` directly). - let mirror = match to_raw { - 0 | 1 => ROOT_WINDOW, - w => ResourceId(w), - }; - for c in state.clients.values_mut() { - c.focused_window = mirror; - } -} - -/// Focus revert when the focus window (or an ancestor) becomes -/// unviewable or is destroyed — Xorg `DeleteWindowFromAnyEvents` -/// (dix/events.c:5889-5931), reached from both `UnrealizeTree` -/// (unmap) and window deletion. Reverts per `revert_to`: None → -/// None; PointerRoot → PointerRoot; Parent → nearest viewable -/// ancestor, and `revert_to` collapses to RevertToNone. -fn revert_core_focus_from(state: &mut ServerState, win: ResourceId, dying: &[ResourceId]) { - if state.core_focus.raw != win.0 || win == ROOT_WINDOW { - return; - } - let mode = if state.active_keyboard_grab.is_some() { - 3 // NotifyWhileGrabbed - } else { - 0 // NotifyNormal - }; - let (to_raw, new_revert) = match state.core_focus.revert_to { - 2 => { - // RevertToParent: the nearest surviving viewable ancestor - // (Xorg's `while (!parent->realized)` walk — `dying` - // marks windows in a subtree being destroyed, which are - // still Viewable at this point but won't survive). - let mut parent = state - .resources - .window(win) - .map_or(ROOT_WINDOW, |w| w.parent); - loop { - if parent == ROOT_WINDOW { - break; - } - let Some(w) = state.resources.window(parent) else { - parent = ROOT_WINDOW; - break; - }; - if w.map_state == crate::resources::MapState::Viewable && !dying.contains(&parent) { - break; - } - if w.parent == parent { - break; - } - parent = w.parent; - } - (parent.0, 0) - } - 1 => (1, state.core_focus.revert_to), - _ => (0, state.core_focus.revert_to), - }; - emit_core_focus_transition(state, win.0, to_raw, mode); - state.core_focus.raw = to_raw; - state.core_focus.revert_to = new_revert; - let mirror = match to_raw { - 0 | 1 => ROOT_WINDOW, - w => ResourceId(w), - }; - for c in state.clients.values_mut() { - c.focused_window = mirror; - } -} - -/// Unmap-side focus revert: fire `revert_core_focus_from` when the -/// focus window stopped being viewable (covers an unmapped ancestor — -/// Xorg unrealizes the whole tree and hits the focus check per child). -fn revert_core_focus_if_unviewable(state: &mut ServerState) { - let raw = state.core_focus.raw; - if raw <= 1 { - return; - } - let viewable = state - .resources - .window(ResourceId(raw)) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - if !viewable { - revert_core_focus_from(state, ResourceId(raw), &[]); - } -} - -/// Emit the FocusOut/FocusIn chain for a core focus transition -/// (`crate::crossings::focus_transition_events`) through the normal -/// per-window event-mask filter, plus the matching XI2 focus events -/// on the endpoint windows. `mode` is the wire NotifyNormal(0) / -/// NotifyWhileGrabbed(3) / NotifyGrab(1) / NotifyUngrab(2) value. -pub(crate) fn emit_core_focus_transition( - state: &mut ServerState, - from_raw: u32, - to_raw: u32, - mode: u8, -) { - log::trace!( - target: "yserver::input::focus", - "FOCUS-EMIT from={} to={} mode={mode}", - state.debug_window_label(ResourceId(from_raw)), - state.debug_window_label(ResourceId(to_raw)), - ); - let pointer_win = crate::core_loop::key_fanout::deepest_window_at_pointer(state); - // Xorg DoFocusEvents (dix/enterleave.c:1557) short-circuits a - // same-window transition ONLY for non-grab modes: - // `if (from == to && mode != NotifyGrab && mode != NotifyUngrab) return;` - // For NotifyGrab/NotifyUngrab with from == to (the grab window is - // already the focus), CoreFocusEvents still runs and reaches - // CoreFocusNonLinear(W, W) — CommonAncestor(W,W) is W's parent, so - // both the Out/In endpoint events fire on W with NotifyNonlinear - // (the intermediate walks are empty). focus_transition_events - // returns nothing for from == to, so synthesize that pair here. - // (Grab windows are always real windows, so the None/PointerRoot - // same-window branch is unreachable from our call sites.) - let events = if from_raw == to_raw && (mode == 1 || mode == 2) && to_raw > 1 { - vec![ - crate::crossings::FocusEvent { - window: ResourceId(to_raw), - focus_in: false, - detail: crate::crossings::NOTIFY_NONLINEAR, - }, - crate::crossings::FocusEvent { - window: ResourceId(to_raw), - focus_in: true, - detail: crate::crossings::NOTIFY_NONLINEAR, - }, - ] - } else { - crate::crossings::focus_transition_events(state, from_raw, to_raw, pointer_win) - }; - let (ptr_x, ptr_y) = state.pointer_root; - for e in events { - let _dropped = - emit_window_event_to_state(state, e.window, FOCUS_CHANGE_MASK, |buf, seq, order| { - x11::encode_focus_event_with_mode_detail( - buf, seq, order, e.focus_in, e.window, mode, e.detail, - ); - }); - // XI2 mirrors only the real FocusIn/FocusOut pairs (evtype - // 9/10) on the windows the core chain touches. - let evtype = if e.focus_in { 9 } else { 10 }; - let _dropped = emit_xi2_focus_event_to_state( - state, - e.window, - evtype, - XI2_MAJOR_OPCODE, - mode, - e.detail, - ptr_x, - ptr_y, - ); - } -} - -fn handle_get_image( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - debug!("client {} #{} GetImage", client_id.0, sequence.0); - let Some(req) = x11::get_image_request(header.data, body) else { - return Ok(RequestOutcome::Handled); - }; - // Validation per Xorg ProcGetImage: format ∈ {XYPixmap, ZPixmap} - // → BadValue; drawable must exist → BadDrawable; the rect must - // lie fully within the drawable (windows additionally must be - // viewable) → BadMatch. - if req.format != 1 && req.format != 2 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.format), - 73, - ); - } - let rx0 = i32::from(req.x); - let ry0 = i32::from(req.y); - let rx1 = rx0 + i32::from(req.width); - let ry1 = ry0 + i32::from(req.height); - if let Some(w) = state.resources.window(req.drawable) { - // Windows: must be viewable; the rect may include the BORDER - // (xts XGetImage-7 reads (-1,-1)) but not extend past its - // outside edges; and — ignoring overlaps — the rect must be - // fully on the screen (XGetImage-15). Both → BadMatch. - let bw = i32::from(w.border_width); - let (ww, wh) = (i32::from(w.width), i32::from(w.height)); - let viewable = w.map_state == crate::resources::MapState::Viewable; - let in_window = rx0 >= -bw && ry0 >= -bw && rx1 <= ww + bw && ry1 <= wh + bw; - let (abs_x, abs_y) = state.resources.window_absolute_position(req.drawable); - let (root_w, root_h) = state - .resources - .window(crate::resources::ROOT_WINDOW) - .map_or((i32::MAX, i32::MAX), |r| { - (i32::from(r.width), i32::from(r.height)) - }); - let on_screen = - abs_x + rx0 >= 0 && abs_y + ry0 >= 0 && abs_x + rx1 <= root_w && abs_y + ry1 <= root_h; - if !viewable || !in_window || !on_screen { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.drawable.0, - 73, - ); - } - } else if let Some(p) = state.resources.pixmap(req.drawable) { - if rx0 < 0 || ry0 < 0 || rx1 > i32::from(p.width) || ry1 > i32::from(p.height) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.drawable.0, - 73, - ); - } - } else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - req.drawable.0, - 73, - ); - } - let byte_order = state - .clients - .get(&client_id.0) - .map_or(yserver_protocol::x11::ClientByteOrder::LittleEndian, |c| { - c.byte_order - }); - let host_xid = if req.drawable == ROOT_WINDOW { - Some(backend.window_id()) - } else { - state - .resources - .host_drawable_target(req.drawable) - .map(|t| t.host_xid()) - }; - let host_reply = host_xid.and_then(|xid| { - backend - .get_image( - origin, - xid, - req.format, - req.x, - req.y, - req.width.max(1), - req.height.max(1), - req.plane_mask, - ) - .ok() - .flatten() - }); - let buf: Vec = if let Some(bytes) = host_reply { - patch_get_image_reply_header(bytes, byte_order, sequence, crate::resources::ROOT_VISUAL.0) - } else { - let mut buf: Vec = Vec::with_capacity(64); - x11::write_get_image_reply( - &mut buf, - byte_order, - sequence, - &req, - crate::resources::ROOT_VISUAL.0, - )?; - buf - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - Ok(write_to_client(client, client_id, &buf)) -} - -fn patch_get_image_reply_header( - mut bytes: Vec, - byte_order: x11::ClientByteOrder, - sequence: SequenceNumber, - visual: u32, -) -> Vec { - if bytes.len() < 32 { - return bytes; - } - let seq = match byte_order { - x11::ClientByteOrder::LittleEndian => sequence.0.to_le_bytes(), - x11::ClientByteOrder::BigEndian => sequence.0.to_be_bytes(), - }; - let len_words = u32::try_from((bytes.len() - 32) / 4).unwrap_or(u32::MAX); - let len = match byte_order { - x11::ClientByteOrder::LittleEndian => len_words.to_le_bytes(), - x11::ClientByteOrder::BigEndian => len_words.to_be_bytes(), - }; - let vis = match byte_order { - x11::ClientByteOrder::LittleEndian => visual.to_le_bytes(), - x11::ClientByteOrder::BigEndian => visual.to_be_bytes(), - }; - bytes[2..4].copy_from_slice(&seq); - bytes[4..8].copy_from_slice(&len); - bytes[8..12].copy_from_slice(&vis); - bytes -} - -#[cfg(test)] -mod get_image_reply_tests { - use super::patch_get_image_reply_header; - use yserver_protocol::x11::{ClientByteOrder, SequenceNumber}; - - #[test] - fn patch_get_image_reply_header_honors_big_endian() { - let bytes = vec![0u8; 40]; - let patched = patch_get_image_reply_header( - bytes, - ClientByteOrder::BigEndian, - SequenceNumber(0x0102), - 0xA1B2_C3D4, - ); - assert_eq!(&patched[2..4], &0x0102u16.to_be_bytes()); - assert_eq!(&patched[4..8], &2u32.to_be_bytes()); - assert_eq!(&patched[8..12], &0xA1B2_C3D4u32.to_be_bytes()); - } -} - -/// Rewrite PolyText8/16 embedded font-change items (len == 255): -/// the wire carries the CLIENT font XID, the backend's font table is -/// keyed by HOST xids. Returns the translated body plus the last -/// font's client id (committed to the GC per X11 §8), or -/// `Err(client_xid)` when an id doesn't resolve (→ BadFont). -fn translate_poly_text_fonts( - state: &ServerState, - body: &[u8], - two_byte: bool, -) -> Result<(Vec, Option), u32> { - let mut out = body.to_vec(); - let mut last: Option = None; - let mut off = 12usize; - while off + 2 <= out.len() { - let len = out[off]; - if len == 255 { - if off + 5 > out.len() { - break; - } - let client_xid = - u32::from_be_bytes([out[off + 1], out[off + 2], out[off + 3], out[off + 4]]); - let Some(font) = state.resources.font(ResourceId(client_xid)) else { - return Err(client_xid); - }; - out[off + 1..off + 5].copy_from_slice(&font.host_xid.as_raw().to_be_bytes()); - last = Some(ResourceId(client_xid)); - off += 5; - } else { - let n = usize::from(len); - off += 2 + if two_byte { 2 * n } else { n }; - } - } - Ok((out, last)) -} - -fn handle_poly_text8( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((drawable_raw, gc_id, text_body)) = x11::poly_text_data(body) { - let drawable = ResourceId(drawable_raw); - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 74); - } - let (text_body, last_font) = match translate_poly_text_fonts(state, text_body, false) { - Ok(pair) => pair, - Err(bad_font) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_FONT, - bad_font, - 74, - ); - } - }; - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - backend.poly_text8(origin, target.host_xid(), st.foreground, &text_body)?; - } - if let Some(font) = last_font { - state.resources.set_gc_font(ResourceId(gc_id), font); - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!("client {} #{} PolyText8", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_text16( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((drawable_raw, gc_id, text_body)) = x11::poly_text_data(body) { - let drawable = ResourceId(drawable_raw); - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 75); - } - let (text_body, last_font) = match translate_poly_text_fonts(state, text_body, true) { - Ok(pair) => pair, - Err(bad_font) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_FONT, - bad_font, - 75, - ); - } - }; - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - backend.poly_text16(origin, target.host_xid(), st.foreground, &text_body)?; - } - if let Some(font) = last_font { - state.resources.set_gc_font(ResourceId(gc_id), font); - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!("client {} #{} PolyText16", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_point( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if body.len() >= 8 { - let drawable = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let gc_id = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let points = &body[8..]; - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 64); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - if let Err(err) = (|| -> io::Result<()> { - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - backend.poly_point( - origin, - target.host_xid(), - st.foreground, - header.data, - points, - ) - })() { - log::warn!( - "client {} #{} PolyPoint backend error: {err}", - client_id.0, - sequence.0 - ); - } - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolyPoint drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_line( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some((gc_id, points)) = x11::poly_line_data(body) - && let Some(drawable) = x11::drawable_request_id(body) - { - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 65); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - let _ = backend.poly_line( - origin, - target.host_xid(), - st.foreground, - header.data, - points, - ); - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolyLine drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_segment( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((gc_id, segments)) = x11::poly_segment_data(body) - && let Some(drawable) = x11::drawable_request_id(body) - { - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 66); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - let _ = backend.poly_segment(origin, target.host_xid(), st.foreground, segments); - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolySegment drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_rectangle( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((gc_id, rectangles)) = x11::poly_fill_rectangle_data(body) - && let Some(drawable) = x11::drawable_request_id(body) - { - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 67); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - let _ = backend.poly_rectangle(origin, target.host_xid(), st.foreground, rectangles); - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolyRectangle drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_arc( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((gc_id, arcs)) = x11::poly_arc_data(body) - && let Some(drawable) = x11::drawable_request_id(body) - { - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 68); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - let _ = backend.poly_arc(origin, target.host_xid(), st.foreground, arcs); - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolyArc drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_fill_poly( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 12 { - let drawable = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let gc_id = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let coord_mode = body[9]; - let points = &body[12..]; - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 69); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - let needs_fill_reset = !matches!(st.fill, FillState::Solid); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_fill_state(origin, &st.fill)?; - backend.apply_draw_state(origin, &st)?; - let _ = backend.fill_poly(origin, target.host_xid(), st.foreground, coord_mode, points); - if needs_fill_reset { - let _ = backend.set_gc_fill_solid(origin); - } - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} FillPoly drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_fill_rectangle( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((gc_id, rectangles)) = x11::poly_fill_rectangle_data(body) - && let Some(drawable) = x11::drawable_request_id(body) - { - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 70); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - let needs_fill_reset = !matches!(st.fill, FillState::Solid); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_fill_state(origin, &st.fill)?; - backend.apply_draw_state(origin, &st)?; - let _ = - backend.poly_fill_rectangle(origin, target.host_xid(), st.foreground, rectangles); - if needs_fill_reset { - let _ = backend.set_gc_fill_solid(origin); - } - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolyFillRectangle drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_poly_fill_arc( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some((gc_id, arcs)) = x11::poly_fill_arc_data(body) - && let Some(drawable) = x11::drawable_request_id(body) - { - if let Err((code, bad_value)) = validate_drawable_and_gc(state, drawable, ResourceId(gc_id)) - { - return emit_x11_error(state, client_id, sequence, code, bad_value, 71); - } - let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); - let target = state.resources.host_drawable_target(drawable); - if let Some(target) = target { - let st = draw_state.unwrap_or_default(); - let needs_fill_reset = !matches!(st.fill, FillState::Solid); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_fill_state(origin, &st.fill)?; - backend.apply_draw_state(origin, &st)?; - let _ = backend.poly_fill_arc(origin, target.host_xid(), st.foreground, arcs); - if needs_fill_reset { - let _ = backend.set_gc_fill_solid(origin); - } - } - let _dropped = accumulate_damage_full_to_state(state, drawable); - } - debug!( - "client {} #{} PolyFillArc drawable=0x{:x}", - client_id.0, - sequence.0, - x11::drawable_request_id(body).map_or(0, |d| d.0), - ); - Ok(RequestOutcome::Handled) -} - -fn handle_clear_area( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let exposures = header.data != 0; - if let Some(request) = x11::clear_area_request(body) { - // Validation per Xorg ProcClearToBackground: exposures must - // be a BOOL (0/1) → BadValue; the drawable must be a window - // → BadWindow; InputOnly windows can't be cleared → BadMatch. - if header.data > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 61, - ); - } - let Some(window) = state.resources.window(request.window) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - request.window.0, - 61, - ); - }; - if matches!(window.class, crate::resources::WindowClass::InputOnly) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - request.window.0, - 61, - ); - } - let extents = state - .resources - .window(request.window) - .map(|w| (w.width, w.height)); - let resolved_bg = state.resources.window_resolved_background(request.window); - let target = state.resources.host_drawable_target(request.window); - if let Some((w_width, w_height)) = extents - && let Some(target) = target - { - let width = clear_extent(request.width, request.x, w_width); - let height = clear_extent(request.height, request.y, w_height); - if width != 0 && height != 0 { - // Background None (X11 §ClearArea): the contents are - // left untouched — no paint, no damage. Expose events - // (below) still fire when requested. - if let Some(bg) = resolved_bg { - backend.clear_area( - origin, - target.host_xid(), - bg.background_pixel, - bg.background_pixmap_host_xid.map(|h| h.as_raw()), - request.x, - request.y, - width, - height, - bg.tile_origin_offset, - )?; - let _dropped = accumulate_damage_to_state( - state, - request.window, - request.x, - request.y, - width, - height, - ); - } - // X11 spec: when `exposures` is True (header.data), - // the server sends an Expose event for visible regions - // of the cleared rectangle. - if exposures { - let req = request; - let _dropped = emit_window_event_to_state( - state, - req.window, - 0x0000_8000, - |buf, seq, order| { - x11::encode_expose_event( - buf, - seq, - order, - req.window, - req.x as u16, - req.y as u16, - width, - height, - 0, - ); - }, - ); - } - } - } - } - debug!( - "client {} #{} ClearArea drawable=0x{:x}", - client_id.0, - sequence.0, - x11::clear_area_request(body).map_or(0, |r| r.window.0), - ); - Ok(RequestOutcome::Handled) -} - -/// Drawable size in its own coordinate space (windows: interior -/// w×h; pixmaps: w×h). None for unknown resources. -fn drawable_size(state: &ServerState, id: ResourceId) -> Option<(u16, u16)> { - if let Some(w) = state.resources.window(id) { - return Some((w.width, w.height)); - } - state.resources.pixmap(id).map(|p| (p.width, p.height)) -} - -/// Xorg VERIFY_PICTURE (`render/picturestr.h:363`, error value set at -/// `render/render.c:252`): the first of `ids` that names no Picture. -fn first_missing_picture(state: &ServerState, ids: &[ResourceId]) -> Option { - ids.iter() - .copied() - .find(|id| state.resources.picture(*id).is_none()) -} - -/// A RENDER destination Picture on an unviewable window: Xorg's composite clip is the -/// window's clipList/borderClip (`render/mipict.c:114-118`), emptied when it stops being -/// viewable (`mi/mivaltree.c:690-695`, `mi/miwindow.c:738-745`), so nothing is drawn. -fn dst_picture_window_unviewable(state: &ServerState, pic: ResourceId) -> bool { - state - .resources - .picture(pic) - .and_then(|p| p.window) - .is_some_and(|w| window_unviewable(state, w)) -} - -/// True for a window that is not viewable (Xorg: not realized); false for pixmaps. -fn window_unviewable(state: &ServerState, id: ResourceId) -> bool { - state - .resources - .window(id) - .is_some_and(|w| w.map_state != crate::resources::MapState::Viewable) -} - -/// Source-availability split for CopyArea/CopyPlane (X11 §CopyArea; -/// Xorg miHandleExposures): the part of the requested source rect -/// outside the source drawable's bounds is not copied. Returns the -/// available source sub-rect (None when fully outside) and the -/// missing sub-rects translated to DESTINATION coordinates — each -/// becomes one GraphicsExpose; an empty list means NoExposure. -#[allow(clippy::type_complexity)] -fn copy_area_source_split( - state: &ServerState, - src: ResourceId, - src_x: i16, - src_y: i16, - dst_x: i16, - dst_y: i16, - width: u16, - height: u16, -) -> ( - Option<(i16, i16, i16, i16, u16, u16)>, - Vec<(i16, i16, u16, u16)>, -) { - if window_unviewable(state, src) { - // Xorg: an unrealized window's clipList is empty, so nothing copies (micopy.c:282). - return (None, vec![(dst_x, dst_y, width, height)]); - } - let Some((sw, sh)) = drawable_size(state, src) else { - // Unknown source geometry: keep the old conservative - // behavior (copy as requested, no missing region). - return ( - Some((src_x, src_y, dst_x, dst_y, width, height)), - Vec::new(), - ); - }; - let rx0 = i32::from(src_x); - let ry0 = i32::from(src_y); - let rx1 = rx0 + i32::from(width); - let ry1 = ry0 + i32::from(height); - let ax0 = rx0.max(0); - let ay0 = ry0.max(0); - let ax1 = rx1.min(i32::from(sw)); - let ay1 = ry1.min(i32::from(sh)); - // Translate a source-coordinate sub-rect into dst coordinates. - let to_dst = |x0: i32, y0: i32, x1: i32, y1: i32| -> (i16, i16, u16, u16) { - let dx = i32::from(dst_x) + (x0 - rx0); - let dy = i32::from(dst_y) + (y0 - ry0); - ( - i16::try_from(dx).unwrap_or(i16::MAX), - i16::try_from(dy).unwrap_or(i16::MAX), - u16::try_from(x1 - x0).unwrap_or(0), - u16::try_from(y1 - y0).unwrap_or(0), - ) - }; - if ax1 <= ax0 || ay1 <= ay0 { - // Fully outside: nothing copies, the whole rect is exposed. - return (None, vec![to_dst(rx0, ry0, rx1, ry1)]); - } - let mut missing: Vec<(i16, i16, u16, u16)> = Vec::new(); - // Band decomposition of requested − available: top, bottom, - // left-of-middle, right-of-middle. - if ay0 > ry0 { - missing.push(to_dst(rx0, ry0, rx1, ay0)); - } - if ay1 < ry1 { - missing.push(to_dst(rx0, ay1, rx1, ry1)); - } - if ax0 > rx0 { - missing.push(to_dst(rx0, ay0, ax0, ay1)); - } - if ax1 < rx1 { - missing.push(to_dst(ax1, ay0, rx1, ay1)); - } - let avail = ( - i16::try_from(ax0).unwrap_or(0), - i16::try_from(ay0).unwrap_or(0), - i16::try_from(i32::from(dst_x) + (ax0 - rx0)).unwrap_or(i16::MAX), - i16::try_from(i32::from(dst_y) + (ay0 - ry0)).unwrap_or(i16::MAX), - u16::try_from(ax1 - ax0).unwrap_or(0), - u16::try_from(ay1 - ay0).unwrap_or(0), - ); - (Some(avail), missing) -} - -/// Emit the CopyArea/CopyPlane graphics-exposures contract events to -/// the requesting client: one GraphicsExpose per missing dst-coord -/// sub-rect (count = number still to follow), or one NoExposure when -/// the source was fully available. Only called when the GC has -/// graphics-exposures=True; the events go to the REQUESTOR -/// unconditionally (not gated by any event mask). -fn emit_copy_exposures( - state: &mut ServerState, - client_id: ClientId, - dst: ResourceId, - missing: &[(i16, i16, u16, u16)], - major_opcode: u8, -) { - let Some(client) = state.clients.get_mut(&client_id.0) else { - return; - }; - let seq = SequenceNumber( - client - .last_sequence - .load(std::sync::atomic::Ordering::Relaxed), - ); - if missing.is_empty() { - let mut buf = Vec::with_capacity(32); - x11::encode_no_exposure_event(&mut buf, seq, client.byte_order, dst, 0, major_opcode); - let _ = write_to_client(client, client_id, &buf); - return; - } - let total = missing.len(); - for (i, (x, y, w, h)) in missing.iter().enumerate() { - let mut buf = Vec::with_capacity(32); - x11::encode_graphics_expose_event( - &mut buf, - seq, - client.byte_order, - dst, - u16::try_from(*x).unwrap_or(0), - u16::try_from(*y).unwrap_or(0), - *w, - *h, - 0, - u16::try_from(total - 1 - i).unwrap_or(0), - major_opcode, - ); - let _ = write_to_client(client, client_id, &buf); - } -} - -fn handle_copy_area( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(request) = x11::copy_area_request(body) else { - return Ok(RequestOutcome::Handled); - }; - if request.width == 0 || request.height == 0 { - return Ok(RequestOutcome::Handled); - } - debug!( - "client {} #{} CopyArea src=0x{:x} dst=0x{:x} gc=0x{:x} src=({},{}) dst=({},{}) {}x{}", - client_id.0, - sequence.0, - request.src.0, - request.dst.0, - request.gc.0, - request.src_x, - request.src_y, - request.dst_x, - request.dst_y, - request.width, - request.height - ); - // Validate src + dst + gc together. Order mirrors Xorg's - // VALIDATE_DRAWABLE_AND_GC: src-side first (BadDrawable / BadMatch - // inputonly), then GC (BadGC), then dst-side, then cross-depth - // (BadMatch). Note: each call covers BadGC; the second is a - // redundant lookup but the cost is tiny and the deduplicated form - // would obscure the per-side error ordering Xorg follows. - if let Err((code, bad_value)) = validate_drawable_and_gc(state, request.src, request.gc) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 62); - } - if let Err((code, bad_value)) = validate_drawable_and_gc(state, request.dst, request.gc) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 62); - } - let draw_state = state.resources.resolve_draw_state(request.gc); - let src = state.resources.host_drawable_target(request.src); - let dst = state.resources.host_drawable_target(request.dst); - if let (Some(src), Some(dst)) = (src.as_ref(), dst.as_ref()) { - // Keep window identity so the backend applies its content offset - // and clip before resolving a redirect backing. Named pixmaps still - // address the entire backing, including its border. - let src_host = state - .resources - .window(request.src) - .and_then(|w| w.host_xid) - .map_or_else(|| src.host_xid(), |h| h.as_raw()); - let dst_host = state - .resources - .window(request.dst) - .and_then(|w| w.host_xid) - .map_or_else(|| dst.host_xid(), |h| h.as_raw()); - if src.depth() != dst.depth() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - request.dst.0, - 62, - ); - } - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - // Clamp the copy to the AVAILABLE part of the source drawable - // (X11 §CopyArea): out-of-bounds source regions are never - // copied; they become the GraphicsExpose region below. - let (avail, missing) = if window_unviewable(state, request.dst) { - // Xorg miDoCopy returns before copying or exposing: NoExpose (micopy.c:157). - (None, Vec::new()) - } else { - copy_area_source_split( - state, - request.src, - request.src_x, - request.src_y, - request.dst_x, - request.dst_y, - request.width, - request.height, - ) - }; - let request = match avail { - Some((sx, sy, dx, dy, w, h)) => x11::CopyAreaRequest { - src_x: sx, - src_y: sy, - dst_x: dx, - dst_y: dy, - width: w, - height: h, - ..request - }, - None => x11::CopyAreaRequest { - width: 0, - height: 0, - ..request - }, - }; - // Stage 4d Manual-redirect fix (codex 2026-05-18): when the - // destination is a window, the X11 spec requires copy_area to - // honour (a) the GC's clip-mask if rectangular and (b) the - // `subwindow-mode=ClipByChildren` default by subtracting every - // mapped child window's geometry from the destination rect. - // - // Split in window-local coordinates before the backend translates - // each piece to backing space. - // ClipState::Pixmap (mask-pixmap clip) is out of scope for this - // fix and passes through untouched. - let copy_sub_rects = if request.width == 0 || request.height == 0 { - Vec::new() - } else { - copy_area_effective_dst_rects(state, request.dst, &st, &request) - }; - if copy_sub_rects.is_empty() { - debug!( - "client {} #{} CopyArea fully clipped, no backend call", - client_id.0, sequence.0, - ); - } - for sub in ©_sub_rects { - // src coords shift by the same delta the dst sub-rect - // shifted from the original dst_xy. - let sub_src_x = request - .src_x - .saturating_add(sub.x.saturating_sub(request.dst_x)); - let sub_src_y = request - .src_y - .saturating_add(sub.y.saturating_sub(request.dst_y)); - backend.copy_area( - origin, src_host, dst_host, sub_src_x, sub_src_y, sub.x, sub.y, sub.width, - sub.height, - )?; - } - let dst_id = request.dst; - // Damage per actually-copied sub-rect rather than the original - // full rect — avoids over-damaging the children's areas a - // ClipByChildren split just excluded. Skipped naturally when - // the slice is empty (fully-clipped copy). - for sub in ©_sub_rects { - let _dropped = - accumulate_damage_to_state(state, dst_id, sub.x, sub.y, sub.width, sub.height); - } - // X11 §CopyArea: destination regions corresponding to - // unavailable source are TILED WITH THE DST WINDOW'S - // BACKGROUND (bg != None), with GXcopy + all-ones plane-mask - // — independent of the graphics-exposures setting. - if !missing.is_empty() && state.resources.window(request.dst).is_some() { - for (mx, my, mw, mh) in &missing { - backend.paint_window_background_rect(origin, dst_host, *mx, *my, *mw, *mh)?; - let _dropped = accumulate_damage_to_state(state, request.dst, *mx, *my, *mw, *mh); - } - } - // Graphics-exposures contract (still fires when the copy was - // fully clipped — codex 2026-05-18 follow-up): GraphicsExpose - // per missing source sub-rect (out-of-bounds source region), - // NoExposure when the source was fully available. Events go - // to the requestor unconditionally (not mask-gated). - let graphics_exposures = state - .resources - .gc(request.gc) - .is_some_and(|g| g.graphics_exposures); - if graphics_exposures { - emit_copy_exposures(state, client_id, request.dst, &missing, 62); - } - } - Ok(RequestOutcome::Handled) -} - -/// Rectangle in destination-window-local coordinates, used by the -/// X11 CopyArea clipping pipeline. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -struct CopyAreaSubRect { - x: i16, - y: i16, - width: u16, - height: u16, -} - -/// Compute the surviving destination sub-rectangles for an X11 -/// CopyArea request after applying: -/// -/// 1. GC rectangular clip-mask (`ClipState::Rectangles`). Empty or -/// completely-disjoint clip → empty Vec (spec-correct no-op). -/// `ClipState::Pixmap` is currently NOT honoured here (out of -/// scope for the Stage 4d fix — see the inline TODO below). -/// 2. `subwindow-mode == ClipByChildren` (X11 default): subtract -/// every mapped child window's geometry from the destination -/// rectangle. v2 collapses a redirected subtree into a single -/// backing pixmap, so this is the layer that prevents marco's -/// decoration copies into a frame window from clobbering the -/// reparented client child area. -/// -/// Pixmap destinations skip clipping entirely (no children to -/// subtract; rectangular clip already applies via the same path). -/// -/// Returns rectangles in the **destination window's** coordinate -/// space (matching the wire `dst_x` / `dst_y` units). -fn copy_area_effective_dst_rects( - state: &crate::server::ServerState, - dst_id: ResourceId, - draw_state: &crate::backend::DrawState, - req: &yserver_protocol::x11::CopyAreaRequest, -) -> Vec { - let mut current: Vec = vec![CopyAreaSubRect { - x: req.dst_x, - y: req.dst_y, - width: req.width, - height: req.height, - }]; - let mut gc_clip_rects: Vec = Vec::new(); - // Step 1: GC rectangular clip-mask. `ClipState::None` is - // "no clip" (pass through); `ClipState::Pixmap` is the - // depth-1 mask form — TODO: rasterise to rect-band; for now - // pass through (mirrors v1's `intersect_with_current_clip` - // pixmap-clip skip). - if let crate::backend::ClipState::Rectangles { origin, rects } = &draw_state.clip { - gc_clip_rects = Vec::with_capacity(rects.rectangles.len() / 8); - for chunk in rects.rectangles.chunks_exact(8) { - let cx = i16::from_le_bytes([chunk[0], chunk[1]]).saturating_add(origin.0); - let cy = i16::from_le_bytes([chunk[2], chunk[3]]).saturating_add(origin.1); - let cw = u16::from_le_bytes([chunk[4], chunk[5]]); - let ch = u16::from_le_bytes([chunk[6], chunk[7]]); - if cw > 0 && ch > 0 { - gc_clip_rects.push(CopyAreaSubRect { - x: cx, - y: cy, - width: cw, - height: ch, - }); - } - } - current = current - .into_iter() - .flat_map(|r| { - gc_clip_rects - .iter() - .filter_map(move |c| intersect_sub_rects(r, *c)) - }) - .collect(); - if current.is_empty() { - log::debug!( - target: "yserver_core::core_loop", - "copy_area clip empty after GC clip dst=0x{:x} req=({},{}) {}x{} subwindow_mode={:?} gc_clip_rects={:?}", - dst_id.0, - req.dst_x, - req.dst_y, - req.width, - req.height, - draw_state.subwindow_mode, - gc_clip_rects, - ); - return current; - } - } - // Step 2: ClipByChildren. Only meaningful when: - // - dst is a window (pixmaps have no children), - // - subwindow-mode is ClipByChildren (default), - // - the window has mapped children. - let Some(dst_window) = state.resources.window(dst_id) else { - return current; - }; - if !matches!( - draw_state.subwindow_mode, - crate::backend::SubwindowMode::ClipByChildren - ) { - return current; - } - let child_rects: Vec = dst_window - .children - .iter() - .filter_map(|cid| { - let c = state.resources.window(*cid)?; - // Manually-redirected children don't claim the parent's - // pixmap real estate — the redirecting compositor (which - // may BE the parent's own client; see - // notification-area-applet for a live example) puts the - // children's pixels there itself. Subtracting them - // strips the compositor's own composite-target rect to - // empty, blocking the icons from reaching the parent's - // backing. Automatic-redirected children are still - // subtracted: under Automatic mode the X server - // auto-composites them into the parent's pixmap, so the - // parent's own paint must avoid those rects to stay - // out of the auto-composite's way. - let is_manual = matches!( - effective_redirect_mode_for_window(state, *cid), - Some(crate::server::CompositeRedirectMode::Manual) - ); - (c.class == crate::resources::WindowClass::InputOutput - && c.map_state == crate::resources::MapState::Viewable - && c.width > 0 - && c.height > 0 - && !is_manual) - .then_some(CopyAreaSubRect { - x: c.x, - y: c.y, - width: c.width, - height: c.height, - }) - }) - .collect(); - if child_rects.is_empty() { - return current; - } - for child in &child_rects { - let mut next = Vec::new(); - for r in current { - next.extend(subtract_sub_rect(r, *child)); - } - current = next; - if current.is_empty() { - let redirect_mode = effective_redirect_mode_for_window(state, dst_id); - log::debug!( - target: "yserver_core::core_loop", - "copy_area clip empty after ClipByChildren dst=0x{:x} req=({},{}) {}x{} subwindow_mode={:?} \ - redirect_mode={:?} gc_clip_rects={:?} child_rects={:?}", - dst_id.0, - req.dst_x, - req.dst_y, - req.width, - req.height, - draw_state.subwindow_mode, - redirect_mode, - gc_clip_rects, - child_rects, - ); - return current; - } - } - current -} - -/// Rect ∩ rect. Returns `None` for disjoint or zero-area input. -fn intersect_sub_rects(a: CopyAreaSubRect, b: CopyAreaSubRect) -> Option { - let ax0 = i32::from(a.x); - let ay0 = i32::from(a.y); - let ax1 = ax0 + i32::from(a.width); - let ay1 = ay0 + i32::from(a.height); - let bx0 = i32::from(b.x); - let by0 = i32::from(b.y); - let bx1 = bx0 + i32::from(b.width); - let by1 = by0 + i32::from(b.height); - let ix0 = ax0.max(bx0); - let iy0 = ay0.max(by0); - let ix1 = ax1.min(bx1); - let iy1 = ay1.min(by1); - if ix0 >= ix1 || iy0 >= iy1 { - return None; - } - Some(CopyAreaSubRect { - x: i16::try_from(ix0).ok()?, - y: i16::try_from(iy0).ok()?, - width: u16::try_from(ix1 - ix0).ok()?, - height: u16::try_from(iy1 - iy0).ok()?, - }) -} - -/// `outer \ inner` → up to 4 disjoint sub-rectangles (top strip, -/// bottom strip, left middle, right middle). If `inner` doesn't -/// intersect `outer`, returns `[outer]` unchanged. -fn subtract_sub_rect(outer: CopyAreaSubRect, inner: CopyAreaSubRect) -> Vec { - let ox0 = i32::from(outer.x); - let oy0 = i32::from(outer.y); - let ox1 = ox0 + i32::from(outer.width); - let oy1 = oy0 + i32::from(outer.height); - let ix0 = i32::from(inner.x).max(ox0); - let iy0 = i32::from(inner.y).max(oy0); - let ix1 = (i32::from(inner.x) + i32::from(inner.width)).min(ox1); - let iy1 = (i32::from(inner.y) + i32::from(inner.height)).min(oy1); - if ix0 >= ix1 || iy0 >= iy1 { - return vec![outer]; - } - let mk = |x: i32, y: i32, w: i32, h: i32| -> Option { - Some(CopyAreaSubRect { - x: i16::try_from(x).ok()?, - y: i16::try_from(y).ok()?, - width: u16::try_from(w).ok()?, - height: u16::try_from(h).ok()?, - }) - }; - let mut out = Vec::with_capacity(4); - // Top strip - if oy0 < iy0 - && let Some(r) = mk(ox0, oy0, ox1 - ox0, iy0 - oy0) - { - out.push(r); - } - // Bottom strip - if iy1 < oy1 - && let Some(r) = mk(ox0, iy1, ox1 - ox0, oy1 - iy1) - { - out.push(r); - } - // Left middle - if ox0 < ix0 - && let Some(r) = mk(ox0, iy0, ix0 - ox0, iy1 - iy0) - { - out.push(r); - } - // Right middle - if ix1 < ox1 - && let Some(r) = mk(ix1, iy0, ox1 - ix1, iy1 - iy0) - { - out.push(r); - } - out -} - -fn handle_copy_plane( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 28 { - return Ok(RequestOutcome::Handled); - } - let src = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let dst = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let gc = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let sx = i16::from_le_bytes([body[12], body[13]]); - let sy = i16::from_le_bytes([body[14], body[15]]); - let dx = i16::from_le_bytes([body[16], body[17]]); - let dy = i16::from_le_bytes([body[18], body[19]]); - let w = u16::from_le_bytes([body[20], body[21]]); - let h = u16::from_le_bytes([body[22], body[23]]); - let plane = u32::from_le_bytes([body[24], body[25], body[26], body[27]]); - if w == 0 || h == 0 { - return Ok(RequestOutcome::Handled); - } - // CopyPlane: dst.depth must match gc.depth; src can be any depth - // (the plane mask extracts a single bit from src). - if let Err((code, bad_value)) = validate_drawable_only(state, src) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 63); - } - if let Err((code, bad_value)) = validate_drawable_and_gc(state, dst, gc) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 63); - } - let draw_state = state.resources.resolve_draw_state(gc); - let src_target = state.resources.host_drawable_target(src); - let dst_target = state.resources.host_drawable_target(dst); - if let (Some(srct), Some(dstt)) = (src_target, dst_target) { - let st = draw_state.unwrap_or_default(); - backend.apply_clip_state(origin, &st.clip)?; - backend.apply_draw_state(origin, &st)?; - // Clamp to the available source region (same contract as - // CopyArea — out-of-bounds source becomes GraphicsExpose). - let (avail, missing) = if window_unviewable(state, dst) { - // Xorg miDoCopy returns before copying or exposing: NoExpose (micopy.c:157). - (None, Vec::new()) - } else { - copy_area_source_split(state, src, sx, sy, dx, dy, w, h) - }; - if let Some((asx, asy, adx, ady, aw, ah)) = avail { - backend.copy_plane( - origin, - srct.host_xid(), - dstt.host_xid(), - asx, - asy, - adx, - ady, - aw, - ah, - plane, - )?; - let _dropped = accumulate_damage_to_state(state, dst, adx, ady, aw, ah); - } - // Missing-source dst regions get the dst window's background - // (same contract as CopyArea). - if !missing.is_empty() && state.resources.window(dst).is_some() { - for (mx, my, mw, mh) in &missing { - backend.paint_window_background_rect( - origin, - dstt.host_xid(), - *mx, - *my, - *mw, - *mh, - )?; - let _dropped = accumulate_damage_to_state(state, dst, *mx, *my, *mw, *mh); - } - } - // GraphicsExpose / NoExposure to the requestor when - // graphics-exposures is True. - let graphics_exposures = state.resources.gc(gc).is_some_and(|g| g.graphics_exposures); - if graphics_exposures { - emit_copy_exposures(state, client_id, dst, &missing, 63); - } - } - debug!( - "client {} #{} CopyPlane src=0x{:x} dst=0x{:x} src=({},{}) dst=({},{}) {}x{} plane=0x{:x}", - client_id.0, sequence.0, src.0, dst.0, sx, sy, dx, dy, w, h, plane, - ); - Ok(RequestOutcome::Handled) -} - -fn handle_create_gc( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(request) = x11::create_gc_request(body) { - let new_id = request.gc.0; - let validation_failed = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - let owned = crate::server::IdAllocator::validate_owned( - new_id, - handle.resource_id_base, - handle.resource_id_mask, - ); - let in_use = state.xid_occupied(request.gc.0); - !owned || in_use - }; - if validation_failed { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - new_id, - 55, - ); - } - state.resources.create_gc(client_id, request); - } - debug!("client {} #{} CreateGC", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_change_gc( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(request) = x11::change_gc_request(body) { - if let Err((code, bad_value)) = validate_gc_only(state, request.gc) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 56); - } - state.resources.change_gc(client_id, request); - } - debug!("client {} #{} ChangeGC", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_copy_gc( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 12 { - let src_gc = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let dst_gc = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let value_mask = u32::from_le_bytes([body[8], body[9], body[10], body[11]]); - state.resources.copy_gc(src_gc, dst_gc, value_mask); - } - debug!("client {} #{} CopyGC", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_set_clip_rectangles( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some(request) = x11::set_clip_rectangles_request(header.data, body) { - if let Err((code, bad_value)) = validate_gc_only(state, request.gc) { - return emit_x11_error(state, client_id, sequence, code, bad_value, 59); - } - state.resources.set_clip_rectangles(client_id, request); - } - debug!("client {} #{} SetClipRectangles", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// Xorg `ProcFreeGC` (`../xserver/dix/dispatch.c:1677`) resolves the id -/// with `dixLookupGC` -> `dixLookupResourceByType(X11_RESTYPE_GC)`, which -/// on a miss returns that resource type's `errorValue` — `BadGC` -/// (`../xserver/dix/resource.c:454`) — after setting `client->errorValue` -/// to the id exactly as sent. Silently succeeding is the same defect -/// class as #143 on FreePixmap: for a *checked void* request the error -/// packet is the only thing that can carry a higher sequence number back -/// to XCB, so swallowing it leaves every preceding checked request of -/// that client uncompleted. -fn handle_free_gc( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(gc) = x11::free_resource_id(body) else { - debug!( - "client {} #{} FreeGC (parse failed)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - }; - if state.resources.gc(gc).is_none() { - debug!( - "client {} #{} FreeGC gc=0x{:x} unknown -> BadGC", - client_id.0, sequence.0, gc.0 - ); - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_GC, - gc.0, - FREE_GC_OPCODE, - ); - } - state.resources.free_gc(gc); - debug!( - "client {} #{} FreeGC gc=0x{:x} freed", - client_id.0, sequence.0, gc.0 - ); - Ok(RequestOutcome::Handled) -} - -fn handle_change_save_set( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if body.len() >= 4 - && let Some(c) = state.clients.get_mut(&client_id.0) - { - let win = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - match header.data { - 0 => { - c.save_set.insert(win); - } - 1 => { - c.save_set.remove(&win); - } - _ => {} - } - } - debug!("client {} #{} ChangeSaveSet", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// Xorg `ProcFreeCursor` (`../xserver/dix/dispatch.c:3100`) looks the id -/// up with `dixLookupResourceByType(X11_RESTYPE_CURSOR)` and on a miss -/// sets `client->errorValue = stuff->id` and returns the type's -/// `errorValue`, `BadCursor` (`../xserver/dix/resource.c:466`). Same -/// checked-void-request reasoning as `handle_free_gc` above. -fn handle_free_cursor( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(cursor) = x11::free_resource_id(body) else { - debug!( - "client {} #{} FreeCursor (parse failed)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - }; - if !state.resources.cursor_exists(cursor) { - debug!( - "client {} #{} FreeCursor cursor=0x{:x} unknown -> BadCursor", - client_id.0, sequence.0, cursor.0 - ); - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - FREE_CURSOR_OPCODE, - ); - } - let host_xid = state.resources.free_cursor(cursor); - if let Some(host_xid) = host_xid { - let _ = backend.free_cursor(origin, host_xid); - } - debug!( - "client {} #{} FreeCursor cursor=0x{:x} freed host_xid={host_xid:?}", - client_id.0, sequence.0, cursor.0 - ); - Ok(RequestOutcome::Handled) -} - -fn handle_create_pixmap( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let Some(request) = x11::create_pixmap_request(header.data, body) else { - debug!( - "client {} #{} CreatePixmap (parse failed)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - }; - debug!( - "client {} #{} CreatePixmap pid=0x{:x} depth={} {}x{} drawable=0x{:x}", - client_id.0, - sequence.0, - request.pixmap.0, - request.depth, - request.width, - request.height, - request.drawable.0, - ); - let new_id = request.pixmap.0; - let (owned, in_use, drawable_exists) = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - let owned = crate::server::IdAllocator::validate_owned( - new_id, - handle.resource_id_base, - handle.resource_id_mask, - ); - let in_use = state.xid_occupied(request.pixmap.0); - let drawable_exists = state.resources.window(request.drawable).is_some() - || state.resources.pixmap(request.drawable).is_some(); - (owned, in_use, drawable_exists) - }; - if !owned || in_use { - log::warn!( - "client {} CreatePixmap BadIDChoice pid=0x{:x} ({})", - client_id.0, - new_id, - if !owned { "out-of-range" } else { "in-use" }, - ); - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - new_id, - 53, - ); - } - if !drawable_exists { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_DRAWABLE, - request.drawable.0, - 53, - ); - } - if !supported_pixmap_depth(request.depth) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(request.depth), - 53, - ); - } - let host_xid = match backend.create_pixmap(origin, request.depth, request.width, request.height) - { - Ok(handle) => Some(handle), - Err(err) => { - log::warn!("client {} host CreatePixmap failed: {err}", client_id.0); - None - } - }; - state.resources.create_pixmap(client_id, request); - if let Some(xid) = host_xid { - let updated = state.resources.set_pixmap_host_xid(request.pixmap, xid); - debug_assert!(updated, "pixmap was just inserted above"); - } - Ok(RequestOutcome::Handled) -} - -/// Xorg `ProcFreePixmap` (`../xserver/dix/dispatch.c:1529`) resolves the -/// id with `dixLookupResourceByType(X11_RESTYPE_PIXMAP)`; on a miss it -/// sets `client->errorValue = stuff->id` and returns that resource -/// type's `errorValue`, i.e. `BadPixmap` (`../xserver/dix/resource.c:448`) -/// — `None` (0) included, since 0 is simply an XID that is not a pixmap. -/// -/// #143: picom sends a deliberate `FreePixmap(drawable=None)` as a sync -/// barrier before every sleep (`x_prepare_for_sleep`, picom `src/x.c:1194`) -/// and *expects* `BadPixmap` back. XCB can only mark a checked **void** -/// request complete once it reads a packet carrying a higher sequence -/// number, and for a void request that packet is the error. Returning -/// silent success left picom's nine checked `ChangeWindowAttributes` -/// uncompleted, so `wm_handle_set_event_mask_reply` never fired and the -/// second half of its window import stalled ~10s (Xorg: ~120ms). -fn handle_free_pixmap( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(pixmap) = x11::free_resource_id(body) else { - debug!( - "client {} #{} FreePixmap (parse failed)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - }; - let Some(removed) = state.resources.free_pixmap(pixmap) else { - debug!( - "client {} #{} FreePixmap pixmap=0x{:x} unknown -> BadPixmap", - client_id.0, sequence.0, pixmap.0 - ); - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_PIXMAP, - pixmap.0, - FREE_PIXMAP_OPCODE, - ); - }; - if removed.composite_name { - // A name owns its own alias ref: a sibling name sharing the backing must not hide it. - let names: Vec<_> = removed.host_xid.into_iter().collect(); - let last = crate::core_loop::process_disconnect::release_removed_names( - state, backend, origin, &names, - ); - crate::core_loop::process_disconnect::free_orphaned_host_pixmaps( - state, - backend, - last.clone(), - &last, - None, - ); - debug!( - "client {} #{} FreePixmap pixmap=0x{:x} (window name) host_xid={:?}", - client_id.0, - sequence.0, - pixmap.0, - removed.host_xid.map(crate::backend::PixmapHandle::as_raw), - ); - return Ok(RequestOutcome::Handled); - } - let still_referenced = removed - .host_xid - // The BORDER reference is as load-bearing as the background one: - // `XCreatePixmap` → `XSetWindowBorderPixmap` → `XFreePixmap` is - // ordinary client code, and X11 keeps the storage alive because - // the window still names it (Xorg refcounts - // `pWin->border.pixmap`). Omitting it freed the host handle - // underneath a ring that was still sampling it (#133). All four - // release sites now share one rule. - .is_some_and(|xid| state.resources.host_xid_still_referenced(xid)); - if let Some(xid) = removed.host_xid - && !still_referenced - { - backend.free_pixmap(origin, xid.as_raw())?; - } - debug!( - "client {} #{} FreePixmap pixmap=0x{:x} freed host_xid={:?} retained={}", - client_id.0, - sequence.0, - pixmap.0, - removed.host_xid.map(crate::backend::PixmapHandle::as_raw), - still_referenced - ); - Ok(RequestOutcome::Handled) -} - -fn handle_list_fonts( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(request) = x11::list_fonts_request(body) { - debug!( - "client {} #{} ListFonts max={} pattern={:?}", - client_id.0, sequence.0, request.max_names, request.pattern - ); - if let Ok(mut reply) = backend.list_fonts_proxy(origin, request.max_names, &request.pattern) - { - let names_returned = u16::from_le_bytes([reply[8], reply[9]]); - debug!( - "client {} #{} ListFonts → {} names", - client_id.0, sequence.0, names_returned - ); - rewrite_reply_sequence(&mut reply, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - return Ok(write_to_client(client, client_id, &reply)); - } - } else { - debug!( - "client {} #{} ListFonts (unparsed)", - client_id.0, sequence.0 - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_list_fonts_with_info( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(request) = x11::list_fonts_request(body) { - debug!( - "client {} #{} ListFontsWithInfo max={} pattern={:?}", - client_id.0, sequence.0, request.max_names, request.pattern - ); - // Thread the atom interner so the backend can attach the FONT - // property (value = atom of the resolved XLFD) — XCreateFontSet - // resolves non-XLFD base names exclusively through it. Same - // disjoint-borrow pattern as handle_xkb_request. - let replies = { - let atoms = &mut state.atoms; - let mut intern = |name: &str| atoms.intern(name, false).0; - backend.list_fonts_with_info_proxy( - origin, - request.max_names, - &request.pattern, - &mut intern, - ) - }; - if let Ok(replies) = replies { - debug!( - "client {} #{} ListFontsWithInfo → {} replies (incl. terminator)", - client_id.0, - sequence.0, - replies.len() - ); - for mut reply in replies { - rewrite_reply_sequence(&mut reply, sequence); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let _byte_order = client.byte_order; - let outcome = write_to_client(client, client_id, &reply); - if matches!(outcome, RequestOutcome::Disconnect(_)) { - return Ok(outcome); - } - } - } - } else { - debug!( - "client {} #{} ListFontsWithInfo (unparsed)", - client_id.0, sequence.0 - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_change_keyboard_mapping( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let first_keycode = body.first().copied().unwrap_or(8); - let kpk = body.get(1).copied().unwrap_or(0); - let count = header.data; - // Xorg ProcChangeKeyboardMapping (dix/devices.c); BadLength is checked at dispatch. - if first_keycode < 8 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(first_keycode), - 100, - ); - } - // Xorg reports keySymsPerKeyCode as the error value for both conditions. - if u32::from(first_keycode) + u32::from(count) > 256 || kpk == 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(kpk), - 100, - ); - } - // XkbApplyMappingChange changes nothing (and notifies nothing) for zero keys. - if count == 0 { - return Ok(RequestOutcome::Handled); - } - // Body: first_keycode(1) keysyms_per_keycode(1) pad(2) then count × kpk CARD32 keysyms. - let xkb_change = apply_keymap_change( - state, - backend, - first_keycode, - kpk, - count, - &body[4.min(body.len())..], - ); - // Xorg's order (XkbSendNotification): XkbMapNotify, then the core - // MappingNotify (XkbSendLegacyMapNotify), then the ControlsNotify of a - // per-key repeat change and an IndicatorMapNotify. - let xkb_event_base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); - if let Some(change) = &xkb_change { - crate::core_loop::xkb_layout::send_xkb_map_notify(state, xkb_event_base, change.map_notify); - } - // The core MappingNotify (Xorg XkbSendLegacyMapNotify): every client - // but an XKB client that didn't select the change as a MapNotify detail. - legacy_keyboard_mapping_notify(state, xkb_change.as_ref(), first_keycode, count); - if let Some(change) = &xkb_change { - crate::core_loop::xkb_layout::send_keyboard_mapping_followups( - state, - xkb_event_base, - change, - (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), - ); - } - debug!( - "client {} #{} ChangeKeyboardMapping", - client_id.0, sequence.0 - ); - Ok(RequestOutcome::Handled) -} - -/// Hand the rows to the backend's XKB keymap (Xorg `XkbApplyMappingChange`), -/// else to `state.keymap_overrides`. Returns what the XKB keymap change did, -/// for the XKB notifications; `None` for the core-only store. -fn apply_keymap_change( - state: &mut ServerState, - backend: &mut dyn Backend, - first_keycode: u8, - kpk: u8, - count: u8, - syms: &[u8], -) -> Option { - let n = usize::from(count) * usize::from(kpk); - let keysyms: Vec = syms - .chunks_exact(4) - .take(n) - .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); - let change = backend.change_keyboard_mapping(first_keycode, kpk, &keysyms); - if change.is_none() { - store_keymap_overrides(state, first_keycode, kpk, count, syms); - } - change -} - -/// The core MappingNotify(Keyboard) of a keyboard mapping change, as Xorg's -/// `XkbSendLegacyMapNotify` sends it from the change's MapNotify: to every -/// client but an XKB-initialised one whose map details miss the change. -/// Without an XKB keymap (`None`) the change counts as KeySyms over the -/// request's keys. -fn legacy_keyboard_mapping_notify( - state: &mut ServerState, - change: Option<&crate::backend::KeyboardMappingChange>, - first_keycode: u8, - count: u8, -) { - let (changed, first, num) = change.map_or((0x0002, first_keycode, count), |c| { - let m = c.map_notify; - (m.changed, m.first_key_sym, m.n_key_syms) - }); - crate::core_loop::xkb_select::send_legacy_core_map_notify( - state, - crate::core_loop::xkb_select::LegacyCause::MapNotify, - changed, - first, - num, - ); -} - -/// Install `count` keysym rows starting at `first_keycode` into -/// `state.keymap_overrides`, each row `kpk` keysyms wide, read from -/// `syms` as little-endian CARD32s (the wire is normalised to native -/// byte order before reaching here). Shared by core `ChangeKeyboardMapping` -/// (opcode 100) and XI1 `ChangeDeviceKeyMapping` (minor 25) — Xorg drives -/// both through the same `XkbApplyMappingChange`, so the device map and the -/// core map must stay one store. -fn store_keymap_overrides( - state: &mut ServerState, - first_keycode: u8, - kpk: u8, - count: u8, - syms: &[u8], -) { - for i in 0..usize::from(count) { - let mut row: Vec = Vec::with_capacity(usize::from(kpk)); - for j in 0..usize::from(kpk) { - let off = (i * usize::from(kpk) + j) * 4; - let Some(b) = syms.get(off..off + 4) else { - break; - }; - row.push(u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - } - #[allow(clippy::cast_possible_truncation)] - state - .keymap_overrides - .insert(first_keycode.wrapping_add(i as u8), row); - } -} - -/// Fetch the merged keyboard mapping for keycodes `[first_keycode, -/// first_keycode + keycode_count)`: the backend (host/KMS) keymap with -/// any `ChangeKeyboardMapping` rows layered on top. Returns -/// `(keysyms_per_keycode, keysyms)` where `keysyms.len() == -/// keycode_count * keysyms_per_keycode`. Shared by core -/// `GetKeyboardMapping` (opcode 101) and XI1 `GetDeviceKeyMapping` -/// (minor 24) — Xorg derives both from the same `XkbGetCoreMap`. -fn fetch_merged_keymap( - state: &ServerState, - backend: &mut dyn Backend, - origin: Option, - first_keycode: u8, - keycode_count: u8, -) -> (u8, Vec) { - let proxied = backend - .get_keyboard_mapping(origin, first_keycode, keycode_count) - .ok(); - // Merge ChangeKeyboardMapping rows over the backend keymap. - { - let (mut kpc, mut keysyms) = proxied.unwrap_or((4, Vec::new())); - if keysyms.is_empty() { - keysyms = vec![0u32; usize::from(keycode_count) * usize::from(kpc)]; - } - let override_kpk = (0..keycode_count) - .filter_map(|i| { - state - .keymap_overrides - .get(&first_keycode.wrapping_add(i)) - .map(Vec::len) - }) - .max() - .unwrap_or(0); - if override_kpk > usize::from(kpc) { - // Widen each row to the override width. - let old = usize::from(kpc); - let mut widened = Vec::with_capacity(usize::from(keycode_count) * override_kpk); - for row in keysyms.chunks(old.max(1)) { - widened.extend_from_slice(row); - widened.extend(std::iter::repeat_n(0u32, override_kpk - row.len())); - } - keysyms = widened; - #[allow(clippy::cast_possible_truncation)] - { - kpc = override_kpk as u8; - } - } - let w = usize::from(kpc); - for i in 0..usize::from(keycode_count) { - #[allow(clippy::cast_possible_truncation)] - let kc = first_keycode.wrapping_add(i as u8); - if let Some(row) = state.keymap_overrides.get(&kc) { - for j in 0..w { - keysyms[i * w + j] = row.get(j).copied().unwrap_or(0); - } - } - } - (kpc, keysyms) - } -} - -fn handle_get_keyboard_mapping( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - debug!("client {} #{} GetKeyboardMapping", client_id.0, sequence.0); - let first_keycode = body.first().copied().unwrap_or(8); - let keycode_count = body.get(1).copied().unwrap_or(0); - // Xorg ProcGetKeyboardMapping: first < min_keycode or first + - // count - 1 > max_keycode → BadValue. - if first_keycode < 8 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(first_keycode), - 101, - ); - } - if u32::from(first_keycode) + u32::from(keycode_count) > 256 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(first_keycode) + u32::from(keycode_count) - 1, - 101, - ); - } - let merged = fetch_merged_keymap(state, backend, origin, first_keycode, keycode_count); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(64); - x11::write_get_keyboard_mapping_reply_from_keysyms( - &mut buf, byte_order, sequence, merged.0, &merged.1, - )?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_alloc_color( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - debug!("client {} #{} AllocColor", client_id.0, sequence.0); - let color = x11::alloc_color_request(body).unwrap_or_default(); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_alloc_color_reply(&mut buf, byte_order, sequence, color)?; - Ok(write_to_client(client, client_id, &buf)) -} - -/// FreeColors (88): release a client's color allocations. -/// -/// yserver currently exposes only fixed TrueColor visuals and does not retain -/// per-client references for the read-only colors returned by AllocColor / -/// AllocNamedColor. Validate the colormap and the Xorg-detectable BadValue -/// cases, then complete without a reply. Xorg additionally returns BadAccess -/// for unallocated or already-freed pixels; without allocation accounting, -/// yserver deliberately accepts those frees as a permissive no-op. -fn handle_free_colors( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(prefix) = body.get(..8) else { - return Ok(RequestOutcome::Handled); - }; - let cmap = ResourceId(u32::from_le_bytes( - prefix[..4].try_into().expect("four-byte colormap id"), - )); - let plane_mask = u32::from_le_bytes(prefix[4..8].try_into().expect("four-byte plane mask")); - let mut pixels = body[8..] - .chunks_exact(4) - .map(|pixel| u32::from_le_bytes(pixel.try_into().expect("four-byte pixel"))); - let pixel_count = pixels.len(); - debug!( - "client {} #{} FreeColors cmap=0x{:x} plane_mask=0x{:08x} pixels={}", - client_id.0, sequence.0, cmap.0, plane_mask, pixel_count - ); - let Some(colormap) = state.resources.colormap(cmap) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - cmap.0, - 88, - ); - }; - let Some(visual) = state.resources.visual(colormap.visual) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_COLORMAP, - cmap.0, - 88, - ); - }; - let valid_mask = visual.red_mask | visual.green_mask | visual.blue_mask | visual.alpha_mask; - if pixel_count != 0 && plane_mask & !valid_mask != 0 { - let first_pixel = pixels.clone().next().expect("non-empty pixel list"); - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - first_pixel | plane_mask, - 88, - ); - } - if let Some(invalid_pixel) = pixels.find(|pixel| pixel & !valid_mask != 0) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - invalid_pixel, - 88, - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_alloc_named_color( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let name = x11::alloc_named_color_name(body); - let Some(color) = x11::lookup_color_name(&name) else { - // Unknown color name → BadName (Xorg), not a silent gray - // fallback that hands the client the wrong pixel. - debug!( - "client {} #{} AllocNamedColor unknown name {:?} -> BadName", - client_id.0, sequence.0, name - ); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_NAME, 0, 85); - }; - debug!( - "client {} #{} AllocNamedColor {:?}", - client_id.0, sequence.0, name - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_alloc_named_color_reply(&mut buf, byte_order, sequence, color)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_query_colors( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let pixels = x11::query_colors_pixels(body); - debug!( - "client {} #{} QueryColors {} pixels", - client_id.0, - sequence.0, - pixels.len() - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32 + pixels.len() * 8); - x11::write_query_colors_reply(&mut buf, byte_order, sequence, &pixels)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_lookup_color( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let name = x11::alloc_named_color_name(body); - let Some(color) = x11::lookup_color_name(&name) else { - // Unknown color name → BadName (Xorg), not a silent gray fallback. - debug!( - "client {} #{} LookupColor unknown name {:?} -> BadName", - client_id.0, sequence.0, name - ); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_NAME, 0, 92); - }; - debug!( - "client {} #{} LookupColor {:?}", - client_id.0, sequence.0, name - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_lookup_color_reply(&mut buf, byte_order, sequence, color)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_open_font( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(request) = x11::open_font_request(body) else { - debug!( - "client {} #{} OpenFont (parse failed)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - }; - debug!( - "client {} #{} OpenFont {:?}", - client_id.0, sequence.0, request.name - ); - let new_id = request.font.0; - let validation_failed = { - let handle = state.clients.get(&client_id.0).expect("client registered"); - !crate::server::IdAllocator::validate_owned( - new_id, - handle.resource_id_base, - handle.resource_id_mask, - ) || state.xid_occupied(request.font.0) - }; - if validation_failed { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ID_CHOICE, - new_id, - 45, - ); - } - let host_result = match backend.open_font(origin, &request.name) { - Ok(pair) => Some(pair), - Err(err) if err.kind() == io::ErrorKind::NotFound => { - // Font-path resolution exhausted with no match → BadName - // (Xorg dix OpenFont semantics). KMS signals this with - // ErrorKind::NotFound; host-proxy failures use other - // kinds and keep the sentinel path below. - debug!( - "client {} OpenFont {:?}: no match on font path → BadName", - client_id.0, request.name - ); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_NAME, 0, 45); - } - Err(err) => { - log::warn!( - "client {} OpenFont {:?} failed on host: {err}", - client_id.0, - request.name - ); - None - } - }; - // Even when the host font open failed, install the font ID locally - // so subsequent OpenFont calls on the same XID raise BadIDChoice - // (X11 spec: BadIDChoice fires on duplicate IDs regardless of - // whether the resource is actually backed). Use a sentinel host - // handle that drawing paths will recognise as "no glyph data". - let (host_handle, mut metrics) = host_result.unwrap_or_else(|| { - ( - crate::backend::FontHandle::from_raw(0xffff_ffff).expect("nonzero sentinel"), - x11::FontMetrics { - min_bounds: x11::CharInfo::default(), - max_bounds: x11::CharInfo::default(), - min_char_or_byte2: 0, - max_char_or_byte2: 0, - default_char: 0, - draw_direction: 0, - min_byte1: 0, - max_byte1: 0, - all_chars_exist: false, - font_ascent: 0, - font_descent: 0, - properties: Vec::new(), - named_properties: Vec::new(), - char_infos: Vec::new(), - }, - ) - }); - { - // Properties read from the font file (BDF/PCF) arrive as - // named (String, value) pairs — convert to wire (atom, CARD32) - // pairs here where the atom table lives. String values are - // themselves atoms (BDF ATOM-typed properties). - if !metrics.named_properties.is_empty() { - let named = std::mem::take(&mut metrics.named_properties); - let mut out: Vec = Vec::with_capacity(named.len() * 8 + 8); - let mut has_font_prop = false; - for (name, value) in &named { - if name == "FONT" { - has_font_prop = true; - } - let name_atom = state.atoms.intern(name, false).0; - let v: u32 = match value { - x11::FontPropValue::Card(c) => *c, - #[allow(clippy::cast_sign_loss)] - x11::FontPropValue::Int(i) => *i as u32, - x11::FontPropValue::Str(s) => state.atoms.intern(s, false).0, - }; - out.extend_from_slice(&name_atom.to_le_bytes()); - out.extend_from_slice(&v.to_le_bytes()); - } - // libX11's XCreateFontSet resolves non-XLFD base names - // exclusively through the FONT property (omGeneric.c) — - // always present on Xorg fonts; append if the file's - // property list lacked it. - if !has_font_prop { - let name_atom = state.atoms.intern("FONT", false).0; - let value_atom = state.atoms.intern(&request.name, false).0; - out.extend_from_slice(&name_atom.to_le_bytes()); - out.extend_from_slice(&value_atom.to_le_bytes()); - } - metrics.properties = out; - } - // Backends that don't proxy to a real X server (KMS) can't - // populate font properties from upstream and return an empty - // properties vec. Synthesize the standard XLFD-derived - // properties (FOUNDRY, FAMILY_NAME, WEIGHT_NAME, ..., FONT) - // so apps that interrogate them — fvwm3 menu rendering, - // Xt/Athena widgets — don't silently skip text drawing. - if metrics.properties.is_empty() { - metrics.properties = synthesize_font_properties(&mut state.atoms, &request.name); - log::debug!( - "OpenFont {:?}: synthesized {} property bytes ({} props), {} char_infos", - request.name, - metrics.properties.len(), - metrics.properties.len() / 8, - metrics.char_infos.len(), - ); - } - state - .resources - .install_font(client_id, request.font, request.name, host_handle, metrics); - } - Ok(RequestOutcome::Handled) -} - -/// Build a `FontProp` byte sequence (8 bytes per property: name atom + -/// CARD32 value) from an XLFD font name. String-typed properties get -/// their value interned as an atom; integer-typed properties carry -/// the int directly per the XLFD spec. -/// -/// XLFD components: -/// `-foundry-family-weight-slant-setwidth-addstyle-pixelsize-pointsize-resx-resy-spacing-avgwidth-charset-encoding` -fn synthesize_font_properties(atoms: &mut crate::server::AtomTable, xlfd: &str) -> Vec { - let parts: Vec<&str> = xlfd.split('-').collect(); - // Real XLFDs start with '-' so split yields an empty first element. - // Names that aren't proper XLFDs (e.g. "fixed", "cursor") get only a - // FONT property pointing at the literal string — better than empty. - let mut out: Vec = Vec::with_capacity(15 * 8); - - let put_string = - |atoms: &mut crate::server::AtomTable, out: &mut Vec, name: &str, value: &str| { - let name_atom = atoms.intern(name, false).0; - let value_atom = atoms.intern(value, false).0; - out.extend_from_slice(&name_atom.to_le_bytes()); - out.extend_from_slice(&value_atom.to_le_bytes()); - }; - let put_int = - |atoms: &mut crate::server::AtomTable, out: &mut Vec, name: &str, value: i32| { - let name_atom = atoms.intern(name, false).0; - out.extend_from_slice(&name_atom.to_le_bytes()); - out.extend_from_slice(&(value as u32).to_le_bytes()); - }; - - // FONT property always: the full XLFD as an atom value. - put_string(atoms, &mut out, "FONT", xlfd); - - // XLFD-shaped name: -foundry-family-weight-slant-setwidth-addstyle-pixel-point-resx-resy-spacing-avgwidth-charset-encoding - // parts[0] is the empty leading "" before the first '-'. - if parts.len() >= 15 { - put_string(atoms, &mut out, "FOUNDRY", parts[1]); - put_string(atoms, &mut out, "FAMILY_NAME", parts[2]); - put_string(atoms, &mut out, "WEIGHT_NAME", parts[3]); - put_string(atoms, &mut out, "SLANT", parts[4]); - put_string(atoms, &mut out, "SETWIDTH_NAME", parts[5]); - put_string(atoms, &mut out, "ADD_STYLE_NAME", parts[6]); - if let Ok(v) = parts[7].parse::() { - put_int(atoms, &mut out, "PIXEL_SIZE", v); - } - if let Ok(v) = parts[8].parse::() { - put_int(atoms, &mut out, "POINT_SIZE", v); - } - if let Ok(v) = parts[9].parse::() { - put_int(atoms, &mut out, "RESOLUTION_X", v); - } - if let Ok(v) = parts[10].parse::() { - put_int(atoms, &mut out, "RESOLUTION_Y", v); - } - put_string(atoms, &mut out, "SPACING", parts[11]); - if let Ok(v) = parts[12].parse::() { - put_int(atoms, &mut out, "AVERAGE_WIDTH", v); - } - put_string(atoms, &mut out, "CHARSET_REGISTRY", parts[13]); - put_string(atoms, &mut out, "CHARSET_ENCODING", parts[14]); - } - out -} - -fn handle_close_font( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if let Some(font) = x11::free_resource_id(body) { - let removed = state.resources.close_font(font); - if let Some(removed) = removed { - let _ = backend.close_font(origin, removed.host_xid.as_raw()); - } - } - debug!("client {} #{} CloseFont", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_set_selection_owner( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 8 { - debug!( - "client {} #{} SetSelectionOwner (short body)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let selection = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let time_val = if body.len() >= 12 { - u32::from_le_bytes([body[8], body[9], body[10], body[11]]) - } else { - 0u32 - }; - - // Xorg `dixSetSelectionOwner` (dix/selection.c:156-211) ordering: - // 1. Reject future timestamps silently (line 166-167) - // 2. Validate window + atom (line 169-178) — we accept any - // window here pre-existing behaviour; tightening that is - // a separate audit item - // 3. Reject stale timestamps silently vs prior lastTimeChanged - // (line 192-193) - // 4. Update ownership + lastTimeChanged (line 204-207) - // 5. Call the SelectionCallback → XFixesSelectionNotify - // with timestamp = currentTime, selection_timestamp = the - // *new* lastTimeChanged (xfixes/select.c:88-89) - let current_time = state.timestamp_now(); - // `ClientTimeToServerTime`: X11 time=0 (`CurrentTime`) resolves - // to the server's current time; otherwise the client's value - // wins unless future-shifted by step 1 above. - let resolved_time = if time_val == 0 { - current_time - } else { - time_val - }; - if time_val != 0 && time_val > current_time { - // Future-shifted: silent no-op (Success per Xorg). - return Ok(RequestOutcome::Handled); - } - // BadWindow if `window != None` and the xid doesn't resolve - // (`dix/selection.c:169-173`). `window == 0` (None) means - // "release ownership" and is the only valid non-existent value. - // The major opcode in the error reply is the core - // SetSelectionOwner opcode (22), not 0 — clients keying on - // `major_opcode` see a malformed error otherwise. - if window.0 != 0 && state.resources.window(window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - window.0, - 22, - ); - } - // BadAtom if the selection atom isn't allocated - // (`dix/selection.c:175-178`). `state.atoms.exists` is the - // equivalent of Xorg's `ValidAtom`. - if !state.atoms.exists(selection) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - selection.0, - 22, - ); - } - if let Some(&(_, prior_last_time)) = state.selections.get(&selection) - && resolved_time < prior_last_time - { - // Stale: silent no-op. - return Ok(RequestOutcome::Handled); - } - - // Snapshot prior ownership BEFORE we mutate state.selections so - // the SelectionClear gate / event payload sees the previous - // owner. `selection_owner_target_id` returns the prior - // owner's window + the ClientId we should target. - let old = selection_owner_target_id(state, selection); - if window.0 == 0 { - state.selections.remove(&selection); - } else { - state.selections.insert(selection, (window, resolved_time)); - } - let name = state.atoms.name(selection).map(str::to_owned); - debug!( - "client {} #{} SetSelectionOwner {} -> 0x{:x}", - client_id.0, - sequence.0, - name.as_deref().unwrap_or("?"), - window.0 - ); - - // SelectionClear gating per Xorg `dix/selection.c:194`: - // if (pSel->client && (!pWin || (pSel->client != client))) - // i.e. fire only when there WAS a prior owner AND either the - // new owner is None OR the new owner is a different client. - // Same-client moves between own windows must NOT spawn a - // SelectionClear. The event's time field carries the resolved - // server time (`time.milliseconds` post-`ClientTimeToServerTime` - // at line 196), not the raw `time_val` — a client sending - // `CurrentTime`/0 must NOT see 0 in the event payload. - if let Some((old_window, old_target)) = old - && (window.0 == 0 || old_target != client_id) - { - let _dropped = fanout_event_to_clients(state, &[old_target], |buf, seq, order| { - x11::encode_selection_clear_event( - buf, - seq, - order, - resolved_time, - old_window, - selection, - ); - }); - } - - // Audit #9 (docs/protocol-audit-2026-05-19.md) — fire - // XFixesSelectionNotify(SetSelectionOwner) to every client that - // subscribed to this selection via `SelectSelectionInput` with - // the matching mask bit. Xorg fires this from - // `XFixesSelectionCallback` (`xfixes/select.c:158-210`) which - // is registered as a `SelectionCallback` against the core - // selection-mgmt code. Without it, clipboard managers wedge - // forever waiting for the "selection changed" signal. - // - // Wire payload per Xorg `xfixes/select.c:88-89`: - // timestamp = currentTime (NOT the request's time arg) - // selection_timestamp = pSel->lastTimeChanged (= resolved_time - // we just stored) - fanout_xfixes_selection_notify( - state, - selection, - yserver_protocol::x11::xfixes::SELECTION_NOTIFY_SET_OWNER, - window.0, - current_time, - resolved_time, - ); - - Ok(RequestOutcome::Handled) -} - -/// Audit #9 fanout helper — emits an `XFixesSelectionNotify` to every -/// `SelectSelectionInput` subscription on this selection whose mask -/// includes the matching subtype bit. Each subscription gets its own -/// event (the `window` field carries the *subscriber's* window, not -/// the owner's, per the X11 protocol). -/// -/// `owner_window` is the new owner (or 0 = `None`). `timestamp` / -/// `selection_timestamp` follow Xorg's -/// `XFixesSelectionCallback` (`xfixes/select.c:158-210`): for the -/// SetOwner subtype both equal the request's `time` argument; for -/// WindowDestroy / ClientClose the timestamp is currentTime and -/// selection_timestamp is the last-set time of the selection (which -/// yserver doesn't currently track per-selection — we pass the same -/// `timestamp` for both for now; refine if a clipboard manager turns -/// out to gate on selection_timestamp). -/// Audit #9 — for every selection whose owner is in `owned_windows`, -/// fire `XFixesSelectionNotify(subtype)` to subscribers and clear the -/// ownership entry. Used by both `destroy_window_subtree` (with -/// `subtype = WindowDestroy`) and the client-disconnect path -/// (with `subtype = ClientClose`). -fn drop_selections_owned_by_windows( - state: &mut ServerState, - owned_windows: &[ResourceId], - subtype: u8, -) { - // Capture (selection, prior_last_time_changed) BEFORE clearing so - // the notify can carry the prior `selection_timestamp` — Xorg's - // `DeleteWindowFromAnySelections` / `DeleteClientFromAnySelections` - // (`dix/selection.c:131-138, 145-153`) fire the callback BEFORE - // mutating `pSel->window`/`pSel->client`, and the callback at - // `xfixes/select.c:89` reads `selection->lastTimeChanged`. - let to_drop: Vec<(AtomId, u32)> = state - .selections - .iter() - .filter_map(|(sel, (owner, last_time_changed))| { - if owned_windows.contains(owner) { - Some((*sel, *last_time_changed)) - } else { - None - } - }) - .collect(); - if to_drop.is_empty() { - return; - } - // `timestamp_now()` matches Xorg's `UpdateCurrentTimeIf` shape - // (`dix/dispatch.c:226-236`): bare monotonic-ms snapshot, no - // floor. X11 timestamp 0 only has dedicated semantics on the - // INPUT side (request `time` arg = "use CurrentTime"); event - // payloads emitted in the first ms after server start carry the - // actual `0` per Xorg, so the clamp this used to apply was a - // protocol mismatch. - let now = state.timestamp_now(); - for (sel, prior_last_time_changed) in to_drop { - // owner=0 (None) — see Xorg `xfixes/select.c:85-86`: - // destroy/close subtypes always carry owner=None. - fanout_xfixes_selection_notify(state, sel, subtype, 0, now, prior_last_time_changed); - state.selections.remove(&sel); - } -} - -/// Audit #9 — client-disconnect cleanup: find every window the -/// disconnecting client owns, check if any of them owns a selection, -/// and fire `XFixesSelectionNotify(ClientClose)` + clear ownership. -/// Reference: Xorg `xfixes/select.c`'s -/// `SelectionClientClose` callback registered against -/// `clientGoneSelectionRequest`. -pub(crate) fn fanout_xfixes_selection_client_close_for_client( - state: &mut ServerState, - cid: ClientId, -) { - let client_windows: Vec = state - .selections - .values() - .map(|(win, _)| *win) - .filter(|win| state.resources.window_owner(*win) == Some(cid)) - .collect(); - if client_windows.is_empty() { - return; - } - drop_selections_owned_by_windows( - state, - &client_windows, - yserver_protocol::x11::xfixes::SELECTION_NOTIFY_CLIENT_CLOSE, - ); -} - -fn fanout_xfixes_selection_notify( - state: &mut ServerState, - selection: AtomId, - subtype: u8, - owner_window: u32, - timestamp: u32, - selection_timestamp: u32, -) { - use yserver_protocol::x11::xfixes as x11xfixes; - - let mask_bit = 1u32 << subtype; - // Snapshot matching subscriptions before mutating `state.clients` - // inside the fanout writer (which needs `&mut state`). - let matched: Vec<(ClientId, u32)> = state - .xfixes_selection_masks - .iter() - .filter_map(|((cid, win, sel), mask)| { - if *sel == selection && mask & mask_bit != 0 { - Some((ClientId(*cid), win.0)) - } else { - None - } - }) - .collect(); - for (cid, subscriber_window) in matched { - let _dropped = fanout_event_to_clients(state, &[cid], |buf, seq, order| { - x11xfixes::encode_selection_notify_event( - buf, - order, - crate::nested::XFIXES_FIRST_EVENT, - subtype, - seq, - subscriber_window, - owner_window, - selection.0, - timestamp, - selection_timestamp, - ); - }); - } -} - -fn handle_convert_selection( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() < 20 { - return Ok(RequestOutcome::Handled); - } - let requestor = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let selection = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let target_atom = AtomId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let property = AtomId(u32::from_le_bytes([body[12], body[13], body[14], body[15]])); - let time_val = u32::from_le_bytes([body[16], body[17], body[18], body[19]]); - - if let Some((owner_window, owner_id)) = selection_owner_target_id(state, selection) { - let _dropped = fanout_event_to_clients(state, &[owner_id], |buf, seq, order| { - x11::encode_selection_request_event( - buf, - seq, - order, - time_val, - owner_window, - requestor, - selection, - target_atom, - property, - ); - }); - debug!( - "client {} #{} ConvertSelection -> owner 0x{:x}", - client_id.0, sequence.0, owner_window.0 - ); - } else { - // No owner — send SelectionNotify(None) to the requestor. - let requestor_id = state - .resources - .window_owner(requestor) - .and_then(|cid| client_target_id(state, cid)); - if let Some(rt) = requestor_id { - let mut template = [0u8; 32]; - template[0] = 31; // SelectionNotify - template[4..8].copy_from_slice(&time_val.to_le_bytes()); - template[8..12].copy_from_slice(&requestor.0.to_le_bytes()); - template[12..16].copy_from_slice(&selection.0.to_le_bytes()); - template[16..20].copy_from_slice(&target_atom.0.to_le_bytes()); - // property = 0 (None): conversion failed. - let _dropped = fanout_raw_event_to_clients( - state, - &[rt], - &template, - yserver_protocol::x11::ClientByteOrder::LittleEndian, - ); - } - debug!( - "client {} #{} ConvertSelection: no owner, sent SelectionNotify(None)", - client_id.0, sequence.0 - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_send_event( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::ClientByteOrder; - // The 32-byte event template inside SendEvent is in the *sender's* - // byte order. Note: the request body's typed prefix (destination + - // event_mask) was already swapped to LE by request_swap; only the - // template itself stays in the sender's byte order so we can - // re-encode per recipient. - let sender_byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let Some(req) = x11::send_event_request(header.data, body) else { - debug!( - "client {} #{} SendEvent (parse failed)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - }; - // Set the sent-event bit (bit 7 of first byte). - let mut event_copy = *req.event; - event_copy[0] |= 0x80; - - let mut targets: Vec = if req.destination.0 == 0xffff_ffff { - subscribers_by_id(state, ROOT_WINDOW, req.event_mask) - } else if req.event_mask == 0 { - state - .resources - .window_owner(req.destination) - .and_then(|owner| client_target_id(state, owner)) - .into_iter() - .collect() - } else { - let mut current = req.destination; - loop { - let t = subscribers_by_id(state, current, req.event_mask); - if !t.is_empty() || !req.propagate { - break t; - } - let Some(parent) = state.resources.parent_of(current) else { - break Vec::new(); - }; - if parent == current { - break Vec::new(); - } - current = parent; - } - }; - // GDK3 has a NULL-device crash in `proxy_button_event` when its - // XI2 wrapper's `get_client_pointer()` returns NULL for a - // synthetic core ButtonPress/Release/Motion/Enter/Leave: the - // ensuing `_gdk_display_get_pointer_info(display, NULL)` returns - // NULL and the next line dereferences it. The crash fires on the - // master-pointer alias even when XIQueryDevice and - // XIGetClientPointer both report device 2 — somewhere the - // id_table lookup miscarries. Mate-panel hits it on every - // workspace-switch click because wnck-applet SendEvents a - // synthetic ButtonRelease into the panel. - // - // For event types that have XI2 counterparts (4–8 = Button*, - // Motion, Enter, Leave), drop any target client that has an XI2 - // selection covering the destination (or any ancestor) for the - // matching XI2 type bit. The XI2 bit index equals the core type - // for these five events. Core-only clients (fvwm, wmaker, e16, - // legacy X apps) still receive the event unchanged. - // - // ONLY for mask-based (passive-selection) delivery. An empty - // `event_mask` addresses the event to the client that *created* the - // destination window (X11 SendEvent semantics) — the XEmbed - // input-forwarding contract a systray manager (cinnamon) uses to - // forward a real tray-icon click to the embedded client. That - // client explicitly needs the synthetic core event (Xorg delivers - // it); dropping it left pamac's tray icon unclickable. The GDK3 - // guard targets the wnck/mate-panel case, which delivers by mask. - let core_type = req.event[0] & 0x7f; - if req.event_mask != 0 && matches!(core_type, 4..=8) { - let xi2_bit = 1u64 << core_type; - let before = targets.len(); - targets.retain(|target| { - let Some(target_client) = state.clients.get(&target.0) else { - return true; - }; - let mut current = req.destination; - loop { - for deviceid in [0u16, 1, 2, 3] { - if let Some(m) = target_client.xi2_masks.get(&(current, deviceid)) - && (m & xi2_bit) != 0 - { - return false; - } - } - let Some(parent) = state.resources.parent_of(current) else { - return true; - }; - if parent == current { - return true; - } - current = parent; - } - }); - if targets.len() != before { - debug!( - "client {} #{} SendEvent core type={} dest=0x{:x} dropped \ - {} target(s) with overlapping XI2 selection (GDK3 NULL-device guard)", - client_id.0, - sequence.0, - core_type, - req.destination.0, - before - targets.len(), - ); - } - } - let _dropped = fanout_raw_event_to_clients(state, &targets, &event_copy, sender_byte_order); - let core_type_logged = req.event[0] & 0x7f; - // For synthetic ConfigureNotify (type=22), decode and log x/y/w/h - // so we can see what the WM tells clients about their root - // position. The wire body (after the 4-byte type/seq prefix) is: - // event_window(4) + window(4) + above_sibling(4) + - // x(2) + y(2) + width(2) + height(2) + border(2) + - // override_redirect(1) + pad(1) - if core_type_logged == 22 { - let e = &req.event; - let event_w = u32::from_le_bytes([e[4], e[5], e[6], e[7]]); - let window_w = u32::from_le_bytes([e[8], e[9], e[10], e[11]]); - let above = u32::from_le_bytes([e[12], e[13], e[14], e[15]]); - let x = i16::from_le_bytes([e[16], e[17]]); - let y = i16::from_le_bytes([e[18], e[19]]); - let w = u16::from_le_bytes([e[20], e[21]]); - let h = u16::from_le_bytes([e[22], e[23]]); - let bw = u16::from_le_bytes([e[24], e[25]]); - let or = e[26]; - debug!( - "client {} #{} SendEvent type=22 (ConfigureNotify) dest=0x{:x} \ - ev_win=0x{:x} win=0x{:x} above=0x{:x} pos=({},{}) size=({}x{}) \ - border={} override={} targets={:?}", - client_id.0, - sequence.0, - req.destination.0, - event_w, - window_w, - above, - x, - y, - w, - h, - bw, - or, - targets.iter().map(|c| c.0).collect::>(), - ); - } else { - debug!( - "client {} #{} SendEvent type={} dest=0x{:x} event_mask=0x{:x} propagate={} targets={:?}", - client_id.0, - sequence.0, - core_type_logged, - req.destination.0, - req.event_mask, - req.propagate, - targets.iter().map(|c| c.0).collect::>(), - ); - } - Ok(RequestOutcome::Handled) -} - -fn handle_get_atom_name( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let atom = x11::request_atom(body); - debug!( - "client {} #{} GetAtomName {}", - client_id.0, sequence.0, atom.0 - ); - let local = state.atoms.name(atom).map(str::to_owned); - let name = match local { - Some(n) => Some(n), - None => backend.get_atom_name(origin, atom.0).ok().flatten(), - }; - match name { - Some(name) => { - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32 + name.len()); - x11::write_get_atom_name_reply(&mut buf, byte_order, sequence, &name)?; - Ok(write_to_client(client, client_id, &buf)) - } - None => emit_x11_error(state, client_id, sequence, x11::error::BAD_ATOM, atom.0, 17), - } -} - -fn handle_query_pointer( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let queried_window = if body.len() >= 4 { - ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])) - } else { - ROOT_WINDOW - }; - let pointer = backend.query_pointer(origin).ok().filter(|p| p.same_screen); - let reply_data = if let Some(pointer) = pointer { - // The KMS backend's PointerPosition carries cursor coordinates - // in root-absolute screen space (win_x/win_y are misnamed - // historical fields). Compute win-relative by subtracting the - // queried window's absolute origin. Without this xeyes (and - // any other client doing per-window pointer queries) sees - // win_x/win_y unchanged after the WM moves the window, so - // the iris locks to a fixed offset and stops tracking. - let (origin_x, origin_y) = state.resources.window_absolute_position(queried_window); - let root_x = pointer.win_x; - let root_y = pointer.win_y; - let win_x = i16::try_from(i32::from(root_x).saturating_sub(origin_x)).unwrap_or(i16::MAX); - let win_y = i16::try_from(i32::from(root_y).saturating_sub(origin_y)).unwrap_or(i16::MAX); - // Per X11 spec, `child` is the direct child of `queried_window` - // that contains the pointer, or None (0) if the pointer is on - // the queried window itself or on no descendant. Previously - // this was hardcoded to ROOT_WINDOW, which made GTK's - // QueryPointer-based hover/tooltip polling never see a - // transition between children — xfce4-panel spun 3500 times - // per second on QueryPointer, starving its event loop and - // dropping clicks on every panel applet. - let child = state - .direct_child_at(queried_window, win_x, win_y) - .unwrap_or(ResourceId(0)); - x11::QueryPointerReply { - root: ROOT_WINDOW, - child, - root_x, - root_y, - win_x, - win_y, - mask: pointer.mask, - } - } else { - x11::QueryPointerReply { - root: ROOT_WINDOW, - child: ResourceId(0), - ..Default::default() - } - }; - debug!( - "client {} #{} QueryPointer queried=0x{:x} -> root=({},{}) win=({},{}) child=0x{:x} mask=0x{:x}", - client_id.0, - sequence.0, - queried_window.0, - reply_data.root_x, - reply_data.root_y, - reply_data.win_x, - reply_data.win_y, - reply_data.child.0, - reply_data.mask, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_query_pointer_reply(&mut buf, byte_order, sequence, reply_data)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_warp_pointer( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 20 { - let rd16 = |o: usize| i16::from_le_bytes([body[o], body[o + 1]]); - let rdu16 = |o: usize| u16::from_le_bytes([body[o], body[o + 1]]); - let req = WarpRequest { - src: ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])), - dst: ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])), - src_x: i32::from(rd16(8)), - src_y: i32::from(rd16(10)), - src_w: rdu16(12), - src_h: rdu16(14), - dst_x: i32::from(rd16(16)), - dst_y: i32::from(rd16(18)), - }; - if let Some(bad) = warp_pointer_bad_window(state, &req) { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_WINDOW, bad, 41); - } - if !warp_pointer_src_allows(state, &req, WarpSrcRule::Core) { - debug!( - "client {} #{} WarpPointer no-op (pointer outside src rect)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - apply_pointer_warp(state, backend, origin, &req); - } - debug!("client {} #{} WarpPointer", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// Which of Xorg's two source-rectangle tests a warp uses. Xorg keeps -/// two copies that differ in one term (see [`warp_pointer_src_allows`]). -#[derive(Clone, Copy, PartialEq, Eq)] -enum WarpSrcRule { - /// `ProcWarpPointer` (dix/events.c). - Core, - /// `ProcXIWarpPointer` (Xi/xiwarppointer.c). - XInput2, -} - -/// A decoded core `WarpPointer` or `XIWarpPointer`. The XI FP16.16 -/// coordinates are already converted to whole pixels the way Xorg does -/// it (`int src_x = stuff->src_x / (double)(1 << 16)`, which truncates -/// toward zero). -struct WarpRequest { - src: ResourceId, - dst: ResourceId, - src_x: i32, - src_y: i32, - src_w: u16, - src_h: u16, - dst_x: i32, - dst_y: i32, -} - -/// The first nonexistent window of a warp, in Xorg's lookup order: the -/// destination is looked up before the source in both ProcWarpPointer -/// and ProcXIWarpPointer. -fn warp_pointer_bad_window(state: &ServerState, req: &WarpRequest) -> Option { - [req.dst, req.src] - .into_iter() - .find(|w| w.0 != 0 && state.resources.window(*w).is_none()) - .map(|w| w.0) -} - -/// Whether the pointer is inside the warp's source rectangle, so the -/// warp goes ahead (always true without a source window). -/// -/// Ported term for term, including the XI copy's slip: its right-edge -/// test compares against 0 instead of the pointer x -/// (`winX + src_x + src_width < 0`, Xi/xiwarppointer.c), so an XI warp -/// ignores the right edge of the rectangle — only the window's own -/// extent (via the visibility test) bounds it. Both copies treat the -/// right/bottom edges as inclusive, and a zero width/height as "to the -/// window's edge". The core copy skips the visibility test for the root -/// window (`source->parent &&`); the XI copy always runs it. -fn warp_pointer_src_allows(state: &ServerState, req: &WarpRequest, rule: WarpSrcRule) -> bool { - if req.src.0 == 0 { - return true; - } - let (x, y) = ( - i32::from(state.pointer_root.0), - i32::from(state.pointer_root.1), - ); - let (win_x, win_y) = state.resources.window_absolute_position(req.src); - let left = win_x + req.src_x; - let top = win_y + req.src_y; - let right_limit = match rule { - WarpSrcRule::Core => x, - WarpSrcRule::XInput2 => 0, - }; - let outside = x < left - || y < top - || (req.src_w != 0 && left + i32::from(req.src_w) < right_limit) - || (req.src_h != 0 && top + i32::from(req.src_h) < y); - if outside { - return false; - } - let check_visibility = rule == WarpSrcRule::XInput2 || req.src != ROOT_WINDOW; - !check_visibility || point_in_window_is_visible(state, req.src, x, y) -} - -/// Xorg `PointInWindowIsVisible` (dix/window.c): the window is viewable -/// and the root point lies in its visible border-inclusive region and -/// input shape. The pointer hit test resolves exactly that — the point is -/// in `window`'s region iff the deepest window under it is `window` or -/// one of its inferiors. -fn point_in_window_is_visible(state: &ServerState, window: ResourceId, x: i32, y: i32) -> bool { - if window == ROOT_WINDOW { - return true; - } - let viewable = state - .resources - .window(window) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - if !viewable { - return false; - } - let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else { - return false; - }; - state - .root_pointer_target_at(x, y) - .is_some_and(|(hit, _, _)| { - hit == window || crate::core_loop::xi1_focus::is_ancestor(state, window, hit) - }) -} - -/// Move the sprite for a validated warp: relative to the destination -/// window's origin, or to the current position when there is none, -/// clamped to the screen like ProcWarpPointer/ProcXIWarpPointer, then -/// through the backend's absolute-motion path (which generates the -/// crossing and motion events a warp is specified to produce). Warps -/// bypass pointer barriers. -fn apply_pointer_warp( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - req: &WarpRequest, -) { - let (base_x, base_y) = if req.dst.0 == 0 { - ( - i32::from(state.pointer_root.0), - i32::from(state.pointer_root.1), - ) - } else { - state.resources.window_absolute_position(req.dst) - }; - let (root_w, root_h) = state - .resources - .window(ROOT_WINDOW) - .map_or((1, 1), |r| (i32::from(r.width), i32::from(r.height))); - let x = base_x - .saturating_add(req.dst_x) - .clamp(0, (root_w - 1).max(0)); - let y = base_y - .saturating_add(req.dst_y) - .clamp(0, (root_h - 1).max(0)); - if req.dst.0 != 0 { - // Proxy backends warp the host pointer relative to the host - // window (a no-op on KMS, which only uses `warp_pointer_root`). - let to_i16 = |v: i32| i16::try_from(v).unwrap_or(if v < 0 { i16::MIN } else { i16::MAX }); - if let Some(target) = state.resources.host_drawable_target(req.dst) { - let _ = backend.warp_pointer( - origin, - target.host_xid(), - to_i16(req.dst_x), - to_i16(req.dst_y), - ); - } - } - let prev = state.barrier_bypass; - state.barrier_bypass = true; - backend.warp_pointer_root(state, x, y); - state.barrier_bypass = prev; -} - -fn handle_get_modifier_mapping( - state: &mut ServerState, - backend: &mut dyn Backend, - origin: Option, - client_id: ClientId, - sequence: SequenceNumber, -) -> io::Result { - debug!("client {} #{} GetModifierMapping", client_id.0, sequence.0); - let proxied = state - .modifier_mapping_override - .clone() - .or_else(|| backend.get_modifier_mapping(origin).ok()); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(64); - if let Some((kpm, keys)) = proxied { - x11::write_get_modifier_mapping_reply_with_keycodes( - &mut buf, byte_order, sequence, kpm, &keys, - )?; - } else { - x11::write_get_modifier_mapping_reply(&mut buf, byte_order, sequence)?; - } - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_change_property( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let Some(req) = x11::change_property_request(header.data, body) else { - // Diagnostic: dump the request header + body shape that we - // rejected as malformed, so we can see what the client sent. - let preview_len = body.len().min(64); - let body_preview = &body[..preview_len]; - debug!( - "ChangeProperty BadLength (parse-fail): client={} seq={} \ - header.data={:#x} body.len={} length_units={} preview={:02x?}", - client_id.0, - sequence.0, - header.data, - body.len(), - header.length_units, - body_preview, - ); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 18); - }; - let Some(mode) = properties::ChangeMode::from_protocol(req.mode) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.mode), - 18, - ); - }; - let Some(format) = properties::PropertyFormat::from_protocol(req.format) else { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.format), - 18, - ); - }; - let expected_bytes = (req.length as usize).checked_mul(format.bytes()); - if expected_bytes != Some(req.data.len()) { - debug!( - "ChangeProperty BadLength (length mismatch): client={} seq={} \ - req.length={} format={} expected={:?} got={}", - client_id.0, - sequence.0, - req.length, - req.format, - expected_bytes, - req.data.len(), - ); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 18); - } - if state.resources.window(req.window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window.0, - 18, - ); - } - if !state.atoms.exists(req.property) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.property.0, - 18, - ); - } - if !state.atoms.exists(req.r#type) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.r#type.0, - 18, - ); - } - // Diagnostic: log WM_CLASS (and _NET_WM_PID) so we can map - // yserver client_id → user-space process when debugging - // missing-click / dead-applet issues. WM_CLASS is two - // null-terminated strings (instance, class); _NET_WM_PID is a - // CARD32. Both are set once near client init, so noise is - // bounded. - if let Some(prop_name) = state.atoms.name(req.property) { - if prop_name == "WM_CLASS" && req.format == 8 { - let s = String::from_utf8_lossy(&req.data).replace('\0', " | "); - let trimmed = s.trim_end_matches(" | ").to_string(); - log::debug!( - "client {} WM_CLASS on 0x{:x}: {}", - client_id.0, - req.window.0, - trimmed, - ); - // Mirror into the side-table so the MIT-SHM PutImage perf - // log (and any future client-attributed diagnostics) can - // resolve drawable owner → recognisable process name - // without re-grepping the log. - state.client_wm_class.entry(client_id.0).or_insert(trimmed); - } else if prop_name == "_NET_WM_PID" && req.format == 32 && req.data.len() >= 4 { - let pid = u32::from_le_bytes([req.data[0], req.data[1], req.data[2], req.data[3]]); - log::debug!( - "client {} _NET_WM_PID on 0x{:x}: {}", - client_id.0, - req.window.0, - pid, - ); - } else if prop_name == "_NET_FRAME_EXTENTS" && req.format == 32 && req.data.len() >= 16 { - // 4× CARDINAL: left, right, top, bottom (frame inset - // around the client window). GTK reads this to position - // popups; if it's corrupted we'd see the popup-placement - // bug for reparented application windows. - let l = u32::from_le_bytes([req.data[0], req.data[1], req.data[2], req.data[3]]); - let r = u32::from_le_bytes([req.data[4], req.data[5], req.data[6], req.data[7]]); - let t = u32::from_le_bytes([req.data[8], req.data[9], req.data[10], req.data[11]]); - let b = u32::from_le_bytes([req.data[12], req.data[13], req.data[14], req.data[15]]); - log::info!( - "client {} _NET_FRAME_EXTENTS on 0x{:x}: left={} right={} top={} bottom={}", - client_id.0, - req.window.0, - l, - r, - t, - b, - ); - } else if prop_name == "_NET_WORKAREA" && req.format == 32 && req.data.len() >= 16 { - // 4× CARDINAL per desktop: x, y, width, height. Log - // the first desktop's quad; subsequent desktops are - // rare and the first is the one popup placement uses. - let x = u32::from_le_bytes([req.data[0], req.data[1], req.data[2], req.data[3]]); - let y = u32::from_le_bytes([req.data[4], req.data[5], req.data[6], req.data[7]]); - let w = u32::from_le_bytes([req.data[8], req.data[9], req.data[10], req.data[11]]); - let h = u32::from_le_bytes([req.data[12], req.data[13], req.data[14], req.data[15]]); - log::info!( - "client {} _NET_WORKAREA on 0x{:x}: x={} y={} w={} h={} (desktop 0)", - client_id.0, - req.window.0, - x, - y, - w, - h, - ); - } - } - let existing = state - .resources - .window_property(req.window, req.property) - .cloned(); - let new_value = - match properties::apply_change(existing.as_ref(), mode, req.r#type, format, &req.data) { - Ok(v) => v, - Err(properties::ChangePropertyError::BadMatch) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_MATCH, - req.window.0, - 18, - ); - } - Err(properties::ChangePropertyError::BadAlloc) => { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 18); - } - Err(properties::ChangePropertyError::BadValue) => { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 18); - } - }; - state - .resources - .set_window_property(req.window, req.property, new_value); - backend.on_window_property_changed(state, window_host_xid(state, req.window), req.property); - if req.window == crate::resources::ROOT_WINDOW - && state.atoms.name(req.property) == Some("_XKB_RULES_NAMES") - && let Some(value) = state - .resources - .window_property(req.window, req.property) - .map(|p| p.data.clone()) - { - crate::core_loop::xkb_layout::apply_rules_names_change(state, backend, &value); - } - let timestamp = state.timestamp_now(); - let window = req.window; - let property = req.property; - let _dropped = emit_window_event_to_state( - state, - window, - 0x0040_0000, // PropertyChangeMask - |buf, seq, order| { - x11::encode_property_notify_event(buf, seq, order, window, property, timestamp, false); - }, - ); - debug!("client {} #{} ChangeProperty", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_get_property( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::ClientByteOrder; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let Some(req) = x11::get_property_request(header.data, body) else { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 20); - }; - if state.resources.window(req.window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window.0, - 20, - ); - } - if !state.atoms.exists(req.property) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.property.0, - 20, - ); - } - if req.r#type.0 != 0 && !state.atoms.exists(req.r#type) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_ATOM, - req.r#type.0, - 20, - ); - } - // Build the reply against an immutable borrow of state.resources, - // copy the bytes into an owned buffer, then drop the borrow before - // we touch state again for the optional delete + fanout. - let (reply_bytes, type_matched, slice_bytes_after, existing_some) = { - let existing = state - .resources - .window_property(req.window, req.property) - .cloned(); - let slice = match properties::slice_for_get( - existing.as_ref(), - req.r#type, - req.long_offset, - req.long_length, - ) { - Ok(s) => s, - Err(properties::ChangePropertyError::BadValue) => { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - req.long_offset, - 20, - ); - } - Err(_) => unreachable!("slice_for_get only returns BadValue on error"), - }; - let value_len_units = if slice.format == 0 { - 0 - } else { - slice.value.len() as u32 / u32::from(slice.format / 8) - }; - let mut buf: Vec = Vec::with_capacity(32 + slice.value.len()); - x11::write_get_property_reply( - &mut buf, - byte_order, - sequence, - x11::GetPropertyReply { - format: slice.format, - r#type: slice.r#type, - bytes_after: slice.bytes_after, - value_len: value_len_units, - value: slice.value, - }, - )?; - let type_matched = existing - .as_ref() - .is_some_and(|p| req.r#type.0 == 0 || req.r#type == p.r#type); - (buf, type_matched, slice.bytes_after, existing.is_some()) - }; - // Send reply bytes through client_io::write_or_buffer. - let outcome = match state.clients.get_mut(&client_id.0) { - Some(client) => write_to_client(client, client_id, &reply_bytes), - None => RequestOutcome::Handled, - }; - if matches!(outcome, RequestOutcome::Disconnect(_)) { - return Ok(outcome); - } - // Optional delete + PropertyNotify fanout (state=true) when - // delete=1 fires per spec. - if req.delete && type_matched && slice_bytes_after == 0 && existing_some { - let _ = state - .resources - .delete_window_property(req.window, req.property); - backend.on_window_property_changed(state, window_host_xid(state, req.window), req.property); - let timestamp = state.timestamp_now(); - let window = req.window; - let property = req.property; - let _dropped = emit_window_event_to_state(state, window, 0x0040_0000, |buf, seq, order| { - x11::encode_property_notify_event(buf, seq, order, window, property, timestamp, true); - }); - } - debug!("client {} #{} GetProperty", client_id.0, sequence.0); - Ok(outcome) -} - -fn handle_delete_property( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let Some(req) = x11::delete_property_request(body) else { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 19); - }; - if state.resources.window(req.window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - req.window.0, - 19, - ); - } - let removed = state - .resources - .delete_window_property(req.window, req.property); - if removed.is_some() { - backend.on_window_property_changed(state, window_host_xid(state, req.window), req.property); - let timestamp = state.timestamp_now(); - let window = req.window; - let property = req.property; - let _dropped = emit_window_event_to_state(state, window, 0x0040_0000, |buf, seq, order| { - x11::encode_property_notify_event(buf, seq, order, window, property, timestamp, true); - }); - } - debug!("client {} #{} DeleteProperty", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_query_font( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - debug!("client {} #{} QueryFont", client_id.0, sequence.0); - let font_id = x11::drawable_request_id(body); - let Some(metrics) = font_id - .and_then(|id| state.resources.fontable(id)) - .map(|font| font.metrics.clone()) - else { - // Unknown/invalid fontable → BadFont (Xorg), not a zeroed - // metrics reply that misleads the client into thinking the - // font loaded. - let bad = font_id.map_or(0, |id| id.0); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, bad, 47); - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(64); - x11::write_query_font_reply(&mut buf, byte_order, sequence, &metrics)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_query_text_extents( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - debug!("client {} #{} QueryTextExtents", client_id.0, sequence.0); - let req = x11::query_text_extents_request(header.data, body); - let extents = req.as_ref().and_then(|req| { - state - .resources - .fontable(req.fontable) - .map(|font| font.metrics.text_extents(&req.chars)) - }); - let Some(extents) = extents else { - // Unknown/invalid fontable → BadFont (Xorg), not zeroed extents. - let bad = req.map_or(0, |r| r.fontable.0); - return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, bad, 48); - }; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_query_text_extents_reply(&mut buf, byte_order, sequence, extents)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_query_best_size( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let width = if body.len() >= 8 { - u16::from_le_bytes([body[4], body[5]]) - } else { - 0 - }; - let height = if body.len() >= 8 { - u16::from_le_bytes([body[6], body[7]]) - } else { - 0 - }; - debug!("client {} #{} QueryBestSize", client_id.0, sequence.0); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_query_best_size_reply(&mut buf, byte_order, sequence, width, height)?; - Ok(write_to_client(client, client_id, &buf)) -} - -/// Core pointer-grab event mask: ButtonPress..KeymapState — X.h -/// `PointerGrabMask`. Requests selecting bits outside this set get -/// `BadValue` (Xorg `ProcGrabPointer` / `ProcGrabButton` / -/// `ProcChangeActivePointerGrab`). -const POINTER_GRAB_MASK: u32 = 0x7FFC; -/// X.h `AnyModifier` — wire encoding 1<<15. -const ANY_MODIFIER: u16 = 0x8000; -/// X.h `AllModifiersMask` — Shift..Mod5, the 8 real modifier bits. -/// `modifiers` values outside this (other than `AnyModifier`) get -/// `BadValue` (Xorg `CheckGrabValues`). -const ALL_MODIFIERS_MASK: u16 = 0x00FF; - -fn handle_grab_pointer( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let mut status: u8 = 0; - // Logged with the grab result so an input trace shows whether the - // client asked for pointer confinement at all — SDL's relative-mouse - // mode passes its own window as confine_to (#99). - let mut logged_grab_window = ResourceId(0); - let mut logged_confine_to = ResourceId(0); - if body.len() >= 20 { - // GrabPointer wire shape: header opcode/data/length, then - // window(4) event-mask(2) pointer-mode(1) keyboard-mode(1) - // confine-to(4) cursor(4) time(4). The `owner_events` BOOL - // lives in the request header's `data` byte (header.data), - // not in the body. - let owner_events = header.data != 0; - let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let event_mask = u16::from_le_bytes([body[4], body[5]]); - let confine_to = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let cursor = ResourceId(u32::from_le_bytes([body[12], body[13], body[14], body[15]])); - let time = u32::from_le_bytes([body[16], body[17], body[18], body[19]]); - logged_grab_window = grab_window; - logged_confine_to = confine_to; - // Validation, in Xorg's order (ProcGrabPointer → GrabDevice): - // eventMask → confine_to lookup → keyboard/pointer mode → - // owner_events → grab_window lookup → cursor lookup. - if u32::from(event_mask) & !POINTER_GRAB_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(event_mask), - 26, - ); - } - if confine_to.0 != 0 && state.resources.window(confine_to).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - confine_to.0, - 26, - ); - } - if body[7] > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(body[7]), - 26, - ); - } - if body[6] > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(body[6]), - 26, - ); - } - if header.data > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 26, - ); - } - if state.resources.window(grab_window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - grab_window.0, - 26, - ); - } - if cursor.0 != 0 && !state.resources.cursor_exists(cursor) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - 26, - ); - } - // Grab status, in Xorg GrabDevice's check order (X.h values: - // GrabSuccess 0, AlreadyGrabbed 1, GrabInvalidTime 2, - // GrabNotViewable 3, GrabFrozen 4). Failure leaves all grab - // state untouched. - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.last_pointer_grab_time); - let viewable = state - .resources - .window(grab_window) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - let confine_viewable = confine_to.0 == 0 - || state - .resources - .window(confine_to) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - let grabbed_by_other = state - .active_pointer_grab - .is_some_and(|grab| grab.owner != client_id); - // Frozen on behalf of another client's grab on the paired - // device (Xorg: sync.frozen && sync.other && !SameClient). - let frozen_by_other = state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .is_some_and(|f| f.frozen() && f.other.is_some_and(|c| c != client_id)); - if grabbed_by_other { - status = 1; // AlreadyGrabbed - } else if !viewable || !confine_viewable { - status = 3; // GrabNotViewable - } else if time != 0 - && (crate::core_loop::xi1_focus::time_after(state.last_pointer_grab_time, time) - || crate::core_loop::xi1_focus::time_after(time, now)) - { - status = 2; // GrabInvalidTime - } else if frozen_by_other { - status = 4; // GrabFrozen - } else { - let prev_grab_window = state - .active_pointer_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window); - state.set_pointer_grab(crate::server::ActivePointerGrab { - owner: client_id, - grab_window, - event_mask, - cursor, - time, - owner_events, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }); - state.last_pointer_grab_time = if time == 0 { now } else { time }; - // Core↔XI bridge (Xorg has ONE deviceGrab per device): a core - // sync grab freezes the device's XI1 event stream too — XTS - // XAllowDeviceEvents-3 freezes via XGrabPointer(GrabModeSync) - // and thaws via XAllowDeviceEvents. body[6]=pointer_mode, - // body[7]=keyboard_mode (0 = GrabModeSync). - crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( - state, - crate::xinput::DEVICEID_SLAVE_POINTER, - client_id, - body[6] == 0, - body[7] == 0, - ); - // Xorg ActivatePointerGrab: DoEnterLeaveEvents(oldWin → - // grab window, NotifyGrab), where oldWin is the prior - // grab's window when re-grabbing, else the pointer window. - // marco's title-bar popup and GTK3 menus key off these. - let from_win = prev_grab_window - .unwrap_or_else(|| crate::core_loop::key_fanout::deepest_window_at_pointer(state)); - emit_core_pointer_grab_chain(state, from_win, grab_window, 1); - // ConfineCursorToWindow: record the confinement and pull - // the pointer inside the confine window if it is outside. - state.pointer_confine_to = confine_to; - confine_pointer_now(state, backend); - // Xorg ActivatePointerGrab installs the grab's cursor on the - // displayed sprite for the grab's duration (ImageMagick - // `import` grabs with a crosshair — #90). `cursor == None` - // (xid 0) means "no override"; per-window cursors show - // through. A re-grab by the same client with a new cursor - // replaces the override here. Resolved to a host cursor - // handle the same way XIChangeCursor does. - if cursor.0 == 0 { - let _ = backend.set_grab_cursor(None, None); - } else if let Some(host) = state.resources.cursor_host_xid(cursor) { - let _ = backend.set_grab_cursor(None, Some(host)); - } - } - } - debug!( - "client {} #{} GrabPointer status={status} window={:#x} confine_to={:#x}", - client_id.0, sequence.0, logged_grab_window.0, logged_confine_to.0 - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_grab_reply(&mut buf, byte_order, sequence, status)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_ungrab_pointer( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - // Xorg ProcUngrabPointer: deactivate only when the request time is - // neither LATER than the current time nor EARLIER than the - // last-grab time, AND the active grab belongs to this client. - let time = body - .get(0..4) - .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.last_pointer_grab_time); - if time != 0 - && (crate::core_loop::xi1_focus::time_after(time, now) - || crate::core_loop::xi1_focus::time_after(state.last_pointer_grab_time, time)) - { - debug!( - "client {} #{} UngrabPointer ignored (time {time} outside [{}, {now}])", - client_id.0, sequence.0, state.last_pointer_grab_time - ); - return Ok(RequestOutcome::Handled); - } - let held_by_client = state - .active_pointer_grab - .is_some_and(|grab| grab.owner == client_id); - if !held_by_client { - debug!( - "client {} #{} UngrabPointer ignored (no grab held by client)", - client_id.0, sequence.0 - ); - return Ok(RequestOutcome::Handled); - } - deactivate_core_pointer_grab(state, backend, client_id); - debug!("client {} #{} UngrabPointer", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// Tear down the active core pointer grab held by `client_id` — -/// shared by UngrabPointer and the unmap/destroy deactivation path -/// (Xorg `DeactivateGrab` reached from `DeleteWindowFromAnyEvents`). -/// Passive-grab NOT_GRABBED (Replay) teardown: clear the active passive -/// pointer grab and emit the `NotifyUngrab` crossing chain (grab window -/// → sprite), mirroring the activation chain from pointer_fanout. Does -/// NOT release any core↔XI grab bridge — the Replay path deliberately -/// omits `xi1_core_grab_bridge_release` (Xorg re-checks device grabs on -/// the replayed event). Shared by `apply_allow_events` and the XI1 -/// ReplayThisDevice path. -fn deactivate_passive_pointer_grab_crossings(state: &mut ServerState) { - let prev_grab_window = state - .active_pointer_grab - .filter(|grab| grab.passive) - .map(|grab| grab.grab_window); - state.clear_pointer_grab(); - state.pointer_confine_to = ResourceId(0); - if let Some(prev) = prev_grab_window { - let to_win = crate::core_loop::key_fanout::deepest_window_at_pointer(state); - emit_core_pointer_grab_chain(state, prev, to_win, 2); // NotifyUngrab - } -} - -fn deactivate_core_pointer_grab( - state: &mut ServerState, - backend: &mut dyn Backend, - client_id: ClientId, -) { - state.pointer_confine_to = ResourceId(0); - let prev_grab_window = state - .active_pointer_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window); - state.clear_pointer_grab(); - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default() - .stored = None; - // Xorg DeactivatePointerGrab reverts the sprite from the grab - // cursor back to the per-window/default cursor. Clearing an - // override that was never set is a cheap no-op. - let _ = backend.set_grab_cursor(None, None); - // Core↔XI bridge: release any XI1-side hold the core grab placed. - crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( - state, - crate::xinput::DEVICEID_SLAVE_POINTER, - client_id, - ); - if let Some(prev) = prev_grab_window { - // Xorg DeactivatePointerGrab: DoEnterLeaveEvents(grab window - // → pointer window, NotifyUngrab). - let to_win = crate::core_loop::key_fanout::deepest_window_at_pointer(state); - emit_core_pointer_grab_chain(state, prev, to_win, 2); - } -} - -/// Pull the pointer inside the current confinement rectangle when it -/// sits outside — Xorg `ConfineCursorToWindow` → `CheckPhysLimits` -/// (the warp generates motion/crossing events through the normal -/// input path). Used at grab activation and when the confine window -/// moves/resizes. -pub(crate) fn confine_pointer_now(state: &mut ServerState, backend: &mut dyn Backend) { - let win = state.pointer_confine_to; - if win.0 == 0 { - return; - } - let Some(w) = state.resources.window(win) else { - return; - }; - if w.map_state != crate::resources::MapState::Viewable { - return; - } - let (x0, y0) = state.resources.window_absolute_position(win); - let (x1, y1) = (x0 + i32::from(w.width), y0 + i32::from(w.height)); - let (px, py) = state.pointer_root; - let cx = i32::from(px).clamp(x0, (x1 - 1).max(x0)); - let cy = i32::from(py).clamp(y0, (y1 - 1).max(y0)); - if cx != i32::from(px) || cy != i32::from(py) { - debug!( - "confine_pointer_now: warping ({px},{py}) -> ({cx},{cy}) inside 0x{:x}", - win.0 - ); - backend.warp_pointer_root(state, cx, cy); - } -} - -/// Full Enter/Leave chain for pointer-grab activation/deactivation — -/// Xorg `ActivatePointerGrab`/`DeactivatePointerGrab` → -/// `DoEnterLeaveEvents(sprite.win ↔ grab window, NotifyGrab/Ungrab)`. -/// Events flow through the normal per-window mask filter (EnterWindow -/// 0x10 / LeaveWindow 0x20) to every selecting client. -pub(crate) fn emit_core_pointer_grab_chain( - state: &mut ServerState, - from_win: ResourceId, - to_win: ResourceId, - mode: u8, -) { - if from_win == to_win { - return; - } - let chain = crate::crossings::normal_mode_crossings(state, from_win, to_win); - let (root_x, root_y) = state.pointer_root; - let server_time = state.timestamp_now(); - for e in chain { - let (mask, enter) = match e.kind { - crate::crossings::CrossingKind::Enter => (0x10u32, true), - crate::crossings::CrossingKind::Leave => (0x20u32, false), - }; - let (ox, oy) = state.resources.window_absolute_position(e.window); - let event_x = i16::try_from(i32::from(root_x) - ox).unwrap_or(i16::MAX); - let event_y = i16::try_from(i32::from(root_y) - oy).unwrap_or(i16::MAX); - let _dropped = emit_window_event_to_state(state, e.window, mask, |buf, seq, order| { - let crossing = yserver_protocol::x11::CrossingEvent { - sequence: seq, - time: server_time, - root: ROOT_WINDOW, - event: e.window, - child: e.child, - root_x, - root_y, - event_x, - event_y, - state: 0, - detail: e.detail, - mode, - }; - if enter { - x11::encode_enter_notify_event(buf, order, crossing); - } else { - x11::encode_leave_notify_event(buf, order, crossing); - } - }); - } -} - -fn handle_grab_button( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if body.len() >= 20 { - let button = body[16]; - let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let event_mask = u32::from(u16::from_le_bytes([body[4], body[5]])); - let pointer_mode = body[6]; - let keyboard_mode = body[7]; - let confine_to = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); - let cursor = ResourceId(u32::from_le_bytes([body[12], body[13], body[14], body[15]])); - let owner_events = header.data != 0; - let modifiers = u16::from_le_bytes([body[18], body[19]]); - // Validation, in Xorg's ProcGrabButton order: pointer_mode → - // keyboard_mode → modifiers → owner_events → event_mask → - // grab_window → confine_to → cursor → conflicting-grab - // BadAccess (AddPassiveGrabToList). - if pointer_mode > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(pointer_mode), - 28, - ); - } - if keyboard_mode > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(keyboard_mode), - 28, - ); - } - if modifiers != ANY_MODIFIER && modifiers & !ALL_MODIFIERS_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(modifiers), - 28, - ); - } - if header.data > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 28, - ); - } - if event_mask & !POINTER_GRAB_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - event_mask, - 28, - ); - } - if state.resources.window(grab_window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - grab_window.0, - 28, - ); - } - if confine_to.0 != 0 && state.resources.window(confine_to).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - confine_to.0, - 28, - ); - } - if cursor.0 != 0 && !state.resources.cursor_exists(cursor) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - 28, - ); - } - // A passive grab that would override another client's grab on - // the same window is a BadAccess (Xorg GrabMatchesSecond via - // AddPassiveGrabToList): button details overlap when either - // side is AnyButton(0) or they are equal; modifiers likewise - // with AnyModifier. Core grabs only conflict with core grabs - // (grabtype mismatch never matches). - let conflicts = state.button_grabs.iter().any(|g| { - g.grab_window == grab_window - && g.owner != client_id - && !g.via_xi2 - && (g.button == button || g.button == 0 || button == 0) - && (g.modifiers == modifiers - || g.modifiers == ANY_MODIFIER - || modifiers == ANY_MODIFIER) - }); - if conflicts { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 28); - } - state.button_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window == grab_window - && g.button == button - && g.modifiers == modifiers) - }); - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: client_id, - grab_window, - button, - modifiers, - owner_events, - event_mask, - pointer_mode, - keyboard_mode, - confine_to, - via_xi2: false, - }); - debug!( - "client {} GrabButton window=0x{:x} button={} modifiers=0x{:x}", - client_id.0, grab_window.0, button, modifiers - ); - } - debug!("client {} #{} GrabButton", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_ungrab_button( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if body.len() >= 6 { - let button = header.data; - let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let modifiers = u16::from_le_bytes([body[4], body[5]]); - // Xorg ProcUngrabButton: modifiers BadValue → window BadWindow. - if modifiers != ANY_MODIFIER && modifiers & !ALL_MODIFIERS_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(modifiers), - 29, - ); - } - if state.resources.window(grab_window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - grab_window.0, - 29, - ); - } - state.button_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window == grab_window - && (g.button == button || button == 0) - && (g.modifiers == modifiers || modifiers == 0x8000)) - }); - debug!( - "client {} UngrabButton window=0x{:x} button={} modifiers=0x{:x}", - client_id.0, grab_window.0, button, modifiers - ); - } - debug!("client {} #{} UngrabButton", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_change_active_pointer_grab( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - if body.len() >= 12 { - let cursor = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let event_mask = u16::from_le_bytes([body[8], body[9]]); - // Xorg ProcChangeActivePointerGrab: eventMask BadValue → - // cursor BadCursor; both fire even when no grab is active. - if u32::from(event_mask) & !POINTER_GRAB_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(event_mask), - 30, - ); - } - if cursor.0 != 0 && !state.resources.cursor_exists(cursor) { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_CURSOR, - cursor.0, - 30, - ); - } - // Xorg ProcChangeActivePointerGrab: no-op when the request - // time is LATER than current or EARLIER than the grab time. - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.last_pointer_grab_time); - let time_ok = time == 0 - || (!crate::core_loop::xi1_focus::time_after(state.last_pointer_grab_time, time) - && !crate::core_loop::xi1_focus::time_after(time, now)); - if time_ok - && let Some(g) = state.active_pointer_grab.as_mut() - && g.owner == client_id - { - g.event_mask = event_mask; - g.cursor = cursor; - } - } - debug!( - "client {} #{} ChangeActivePointerGrab", - client_id.0, sequence.0 - ); - Ok(RequestOutcome::Handled) -} - -fn handle_grab_keyboard( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - let mut status: u8 = 0; - if body.len() >= 12 { - let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - // Validation per Xorg GrabDevice: keyboard_mode (body[9]) → - // pointer_mode (body[8]) → owner_events (header data byte) → - // grab_window lookup. - if body[9] > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(body[9]), - 31, - ); - } - if body[8] > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(body[8]), - 31, - ); - } - if header.data > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 31, - ); - } - if state.resources.window(grab_window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - grab_window.0, - 31, - ); - } - // Grab status, mirroring handle_grab_pointer (Xorg GrabDevice - // check order). Failure leaves all grab state untouched. - let time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.last_keyboard_grab_time); - let viewable = state - .resources - .window(grab_window) - .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); - let grabbed_by_other = state - .active_keyboard_grab - .is_some_and(|g| g.owner != client_id); - let frozen_by_other = state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .is_some_and(|f| f.frozen() && f.other.is_some_and(|c| c != client_id)); - if grabbed_by_other { - status = 1; // AlreadyGrabbed - } else if !viewable { - status = 3; // GrabNotViewable - } else if time != 0 - && (crate::core_loop::xi1_focus::time_after(state.last_keyboard_grab_time, time) - || crate::core_loop::xi1_focus::time_after(time, now)) - { - status = 2; // GrabInvalidTime - } else if frozen_by_other { - status = 4; // GrabFrozen - } else { - let prev_grab_window = state - .active_keyboard_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window); - state.active_keyboard_grab = Some(crate::server::ActiveKeyboardGrab { - owner: client_id, - grab_window, - source: crate::server::ActiveKeyboardGrabSource::Explicit, - owner_events: header.data != 0, - via_xi2: false, - xi2_mask: 0, - }); - state.last_keyboard_grab_time = if time == 0 { now } else { time }; - // Core↔XI bridge — see handle_grab_pointer. GrabKeyboard wire: - // window(4) time(4) pointer_mode(1) keyboard_mode(1); this - // device = keyboard, other = pointer. - crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( - state, - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - client_id, - body[9] == 0, - body[8] == 0, - ); - // Xorg ActivateKeyboardGrab: DoFocusEvents(oldWin → - // grab_window, NotifyGrab), where oldWin is the prior - // grab's window if one was active, else the focus. - let from_raw = prev_grab_window.map_or(state.core_focus.raw, |w| w.0); - emit_core_focus_transition(state, from_raw, grab_window.0, 1); - } - } - debug!( - "client {} #{} GrabKeyboard status={status}", - client_id.0, sequence.0 - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_grab_reply(&mut buf, byte_order, sequence, status)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn handle_ungrab_keyboard( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - // Time validation — see handle_ungrab_pointer (Xorg - // ProcUngrabKeyboard has the identical CompareTimeStamps gate). - let time = body - .get(0..4) - .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); - let now = state - .timestamp_now() - .max(state.xi1_last_input_time) - .max(state.last_keyboard_grab_time); - if time != 0 - && (crate::core_loop::xi1_focus::time_after(time, now) - || crate::core_loop::xi1_focus::time_after(state.last_keyboard_grab_time, time)) - { - debug!( - "client {} #{} UngrabKeyboard ignored (time {time} outside [{}, {now}])", - client_id.0, sequence.0, state.last_keyboard_grab_time - ); - return Ok(RequestOutcome::Handled); - } - deactivate_core_keyboard_grab(state, client_id); - debug!("client {} #{} UngrabKeyboard", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -/// Tear down the active core keyboard grab held by `client_id` — -/// shared by UngrabKeyboard and the unmap/destroy deactivation path -/// (see [`deactivate_core_pointer_grab`]). -fn deactivate_core_keyboard_grab(state: &mut ServerState, client_id: ClientId) { - let prev_grab_window = state - .active_keyboard_grab - .filter(|g| g.owner == client_id) - .map(|g| g.grab_window); - if state - .active_keyboard_grab - .is_some_and(|g| g.owner == client_id) - { - state.active_keyboard_grab = None; - state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .or_default() - .stored = None; - // Core↔XI bridge: release any XI1-side hold the grab placed. - crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( - state, - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - client_id, - ); - } - if let Some(prev) = prev_grab_window { - // Xorg DeactivateKeyboardGrab: DoFocusEvents(grab_window → - // focus, NotifyUngrab). - emit_core_focus_transition(state, prev.0, state.core_focus.raw, 2); - } -} - -/// Xorg `DeleteWindowFromAnyEvents` grab leg: an active core grab -/// whose grab window stopped being viewable (unmap of it or an -/// ancestor, or destroy) deactivates. Call after the map-state / -/// resource changes have landed. -fn release_core_grabs_for_unviewable(state: &mut ServerState, backend: &mut dyn Backend) { - let viewable = |state: &ServerState, w: ResourceId| { - state - .resources - .window(w) - .is_some_and(|win| win.map_state == crate::resources::MapState::Viewable) - }; - if let Some(grab) = state.active_pointer_grab - && (!viewable(state, grab.grab_window) - || (state.pointer_confine_to.0 != 0 && !viewable(state, state.pointer_confine_to))) - { - deactivate_core_pointer_grab(state, backend, grab.owner); - } - if let Some(g) = state.active_keyboard_grab - && !viewable(state, g.grab_window) - { - deactivate_core_keyboard_grab(state, g.owner); - } -} - -fn handle_grab_key( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some(req) = x11::parse_grab_key(body, header.data != 0) { - let grab_window = ResourceId(req.grab_window); - // Validation per Xorg ProcGrabKey: CheckGrabValues (modes, - // owner_events, modifiers) → keycode range → grab_window - // lookup → conflicting-grab BadAccess. - if req.keyboard_mode > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.keyboard_mode), - 33, - ); - } - if req.pointer_mode > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.pointer_mode), - 33, - ); - } - if header.data > 1 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(header.data), - 33, - ); - } - if req.modifiers != ANY_MODIFIER && req.modifiers & !ALL_MODIFIERS_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.modifiers), - 33, - ); - } - // Keycode must be within the advertised [min_keycode, - // max_keycode] range (8..=255 — the setup reply's values) or - // AnyKey(0). - if req.keycode != 0 && req.keycode < 8 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.keycode), - 33, - ); - } - if state.resources.window(grab_window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - grab_window.0, - 33, - ); - } - // BadAccess when another client already holds an overlapping - // passive key grab on this window — see the GrabButton - // conflict check for the overlap rule. - let conflicts = state.key_grabs.iter().any(|g| { - g.grab_window == grab_window - && g.owner != client_id - && !g.via_xi2 - && (g.keycode == req.keycode || g.keycode == 0 || req.keycode == 0) - && (g.modifiers == req.modifiers - || g.modifiers == ANY_MODIFIER - || req.modifiers == ANY_MODIFIER) - }); - if conflicts { - return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 33); - } - state.key_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window == grab_window - && g.keycode == req.keycode - && g.modifiers == req.modifiers) - }); - state.key_grabs.push(crate::server::KeyGrab { - owner: client_id, - grab_window, - keycode: req.keycode, - modifiers: req.modifiers, - owner_events: req.owner_events, - pointer_mode: req.pointer_mode, - keyboard_mode: req.keyboard_mode, - via_xi2: false, - xi2_mask: 0, - }); - debug!( - "client {} GrabKey window=0x{:x} keycode={} modifiers=0x{:x}", - client_id.0, req.grab_window, req.keycode, req.modifiers - ); - } - debug!("client {} #{} GrabKey", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_ungrab_key( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - if let Some(req) = x11::parse_ungrab_key(body, header.data) { - let grab_window = ResourceId(req.grab_window); - // Xorg ProcUngrabKey: window lookup → keycode range → - // modifiers BadValue. - if state.resources.window(grab_window).is_none() { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_WINDOW, - grab_window.0, - 34, - ); - } - if req.keycode != 0 && req.keycode < 8 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.keycode), - 34, - ); - } - if req.modifiers != ANY_MODIFIER && req.modifiers & !ALL_MODIFIERS_MASK != 0 { - return emit_x11_error( - state, - client_id, - sequence, - x11::error::BAD_VALUE, - u32::from(req.modifiers), - 34, - ); - } - state.key_grabs.retain(|g| { - !(g.owner == client_id - && g.grab_window == grab_window - && (g.keycode == req.keycode || req.keycode == 0) - && (g.modifiers == req.modifiers || req.modifiers == 0x8000)) - }); - } - debug!("client {} #{} UngrabKey", client_id.0, sequence.0); - Ok(RequestOutcome::Handled) -} - -fn handle_get_selection_owner( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let owner = if body.len() >= 4 { - let selection = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - state - .selections - .get(&selection) - .map(|(w, _)| *w) - .unwrap_or(ResourceId(0)) - } else { - ResourceId(0) - }; - debug!( - "client {} #{} GetSelectionOwner -> 0x{:x}", - client_id.0, sequence.0, owner.0 - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_get_selection_owner_reply(&mut buf, byte_order, sequence, owner)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn window_geometry(window: &Window) -> x11::Geometry { - x11::Geometry { - root: ROOT_WINDOW, - x: window.x, - y: window.y, - width: window.width, - height: window.height, - border_width: window.border_width, - depth: window.depth, - } -} - -fn pixmap_geometry(pixmap: &Pixmap) -> x11::Geometry { - x11::Geometry { - root: ROOT_WINDOW, - x: 0, - y: 0, - width: pixmap.width, - height: pixmap.height, - border_width: 0, - depth: pixmap.depth, - } -} - -/// Geometry of a GLX pbuffer (#96). Pbuffers are tracked in `glx_drawables` -/// with their `CreatePbuffer` size but are absent from the core resource -/// store, so `GetGeometry` must resolve them here. A 0×0 pbuffer returns -/// `None` (size guard preserved): the caller then falls through to the -/// backing pixmap clamped to 1×1 by `CREATE_PBUFFER`, and a missing -/// drawable stays `BadDrawable` instead of becoming a Success(0×0). -fn glx_pbuffer_geometry(state: &ServerState, drawable: ResourceId) -> Option { - let d = state.glx_drawables.get(&drawable.0)?; - if d.kind != crate::server::GlxDrawableKind::Pbuffer || (d.width == 0 && d.height == 0) { - return None; - } - Some(x11::Geometry { - root: ROOT_WINDOW, - x: 0, - y: 0, - width: u16::try_from(d.width).unwrap_or(u16::MAX), - height: u16::try_from(d.height).unwrap_or(u16::MAX), - border_width: 0, - depth: glx_fbconfig_depth(d.fbconfig), - }) -} - -/// Record a GLXPixmap over the (already validated) X pixmap `x_pixmap` and -/// take its export-lifetime ref — the one resource model behind GLX 1.0 -/// `CreateGLXPixmap`, GLX 1.3 `CreatePixmap` and -/// `CreateGLXPixmapWithConfigSGIX`, as Xorg funnels all three through -/// `DoCreateGLXPixmap` (glxcmds.c:1198-1220). -/// -/// The host xid is resolved NOW and stored on the record so release is -/// robust to the X pixmap being freed (X11 `FreePixmap`) before the GLX -/// destroy / disconnect — re-resolving `x_drawable → host_xid` at release -/// time would fail once the resource is gone, leaking the ref forever. The -/// ref keeps the `ExportedBacking` entry (and its dmabuf fd) alive past an -/// early `FreePixmap`, the counterpart of Xorg's `pixmap->refcnt++`. -fn insert_glx_pixmap_record( - state: &mut ServerState, - backend: &mut dyn Backend, - owner: ClientId, - glx_pixmap: u32, - x_pixmap: u32, - fbconfig: u32, - texture_target: u32, -) { - let acquire_host_xid = state - .resources - .pixmap(ResourceId(x_pixmap)) - .and_then(|p| p.host_xid.map(|h| h.as_raw())); - state.glx_drawables.insert( - glx_pixmap, - crate::server::GlxDrawable { - owner, - kind: crate::server::GlxDrawableKind::Pixmap, - x_drawable: x_pixmap, - fbconfig, - width: 0, - height: 0, - event_mask: 0, - glx_export_host_xid: acquire_host_xid, - texture_target, - }, - ); - if let Some(host_xid) = acquire_host_xid { - backend.acquire_glx_pixmap_export(host_xid); - } -} - -/// The context XID of a `QueryContext` / `IsDirect` request, or the error -/// Xorg sends: `BadLength` for a body that is not exactly one XID -/// (`REQUEST_SIZE_MATCH`), `GLXBadContext` with the XID as bad value when -/// it names no live context (glx/vnd_dispatch_stubs.c:492-525). -fn glx_request_context(state: &ServerState, body: &[u8]) -> Result { - use yserver_protocol::x11::glx as g; - let Some(xid) = g::parse_single_xid(body) else { - return Err((x11::error::BAD_LENGTH, 0)); - }; - if state.glx_contexts.contains_key(&xid) { - Ok(xid) - } else { - Err(( - crate::nested::GLX_FIRST_ERROR + g::ERROR_GLX_BAD_CONTEXT, - xid, - )) - } -} - -/// The FBConfig behind a GLX *visual*, or `None` when `visual` is not one -/// of the GLX visuals `GetVisualConfigs` advertises. Mirrors Xorg's -/// `validGlxVisual`, which searches `pGlxScreen->visuals` only — an -/// FBConfig ID, or an X visual without a GLX config, is not a GLX visual -/// (glxcmds.c:90-107). `synthesise_glx_fb_configs` stays the single source -/// of the visual → FBConfig pairing. -fn glx_visual_fbconfig(visual: u32) -> Option { - use yserver_protocol::x11::glx as g; - if !synthesise_glx_visual_configs() - .iter() - .any(|v| v.visual_id == visual) - { - return None; - } - synthesise_glx_fb_configs(false).iter().find_map(|cfg| { - cfg.iter() - .any(|(a, v)| *a == g::GLX_VISUAL_ID && *v == visual) - .then(|| { - cfg.iter() - .find(|(a, _)| *a == g::GLX_FBCONFIG_ID) - .map(|(_, v)| *v) - }) - .flatten() - }) -} - -/// The X visual of a synthesised FBConfig (`GLX_VISUAL_ID`), 0 for a -/// visual-less or unknown FBConfig — Xorg's `ctx->config->visualID`. -fn glx_fbconfig_visual(fbconfig: u32) -> u32 { - use yserver_protocol::x11::glx as g; - synthesise_glx_fb_configs(false) - .iter() - .find(|cfg| { - cfg.iter() - .any(|(a, v)| *a == g::GLX_FBCONFIG_ID && *v == fbconfig) - }) - .and_then(|cfg| { - cfg.iter() - .find(|(a, _)| *a == g::GLX_VISUAL_ID) - .map(|(_, v)| *v) - }) - .unwrap_or(0) -} - -/// Depth (24 or 32) of a synthesised GLX FBConfig, derived from the X visual -/// it maps to (`ROOT_VISUAL` depth-24 / `ARGB_VISUAL` depth-32) — the single -/// source of truth is `synthesise_glx_fb_configs`, so this stays correct if -/// the config table changes. Defaults to 24 for an unknown fbconfig. -fn glx_fbconfig_depth(fbconfig: u32) -> u8 { - use yserver_protocol::x11::glx as g; - synthesise_glx_fb_configs(false) - .iter() - .find(|cfg| { - cfg.iter() - .any(|(a, v)| *a == g::GLX_FBCONFIG_ID && *v == fbconfig) - }) - .and_then(|cfg| { - cfg.iter() - .find(|(a, _)| *a == g::GLX_VISUAL_ID) - .map(|(_, v)| *v) - }) - .map_or(24, |visual| { - if visual == crate::resources::ARGB_VISUAL.0 { - 32 - } else { - 24 - } - }) -} - -#[allow(clippy::cast_possible_truncation)] -fn handle_translate_coordinates( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - body: &[u8], -) -> io::Result { - let (child, dst_x, dst_y, log_src, log_dst, log_src_xy) = if body.len() >= 12 { - let src_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); - let dst_window = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); - let src_x = i16::from_le_bytes([body[8], body[9]]); - let src_y = i16::from_le_bytes([body[10], body[11]]); - let (src_abs_x, src_abs_y) = state.resources.window_absolute_position(src_window); - let abs_x = src_abs_x + i32::from(src_x); - let abs_y = src_abs_y + i32::from(src_y); - let (dst_abs_x, dst_abs_y) = state.resources.window_absolute_position(dst_window); - let dst_x = (abs_x - dst_abs_x) as i16; - let dst_y = (abs_y - dst_abs_y) as i16; - // Xorg ProcTranslateCoords checks both bounding and input shapes - // while walking the destination's direct children. Reuse the - // server's shape-aware hit test so the Composite Overlay Window's - // empty input shape does not hide a mapped popup beneath it. - let child = state - .direct_child_at(dst_window, dst_x, dst_y) - .unwrap_or(ResourceId(0)); - ( - child, - dst_x, - dst_y, - src_window.0, - dst_window.0, - (src_x, src_y), - ) - } else { - (ResourceId(0), 0i16, 0i16, 0u32, 0u32, (0i16, 0i16)) - }; - debug!( - "client {} #{} TranslateCoordinates src=0x{:x} dst=0x{:x} src_xy=({},{}) -> dst_xy=({},{}) child=0x{:x}", - client_id.0, - sequence.0, - log_src, - log_dst, - log_src_xy.0, - log_src_xy.1, - dst_x, - dst_y, - child.0, - ); - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - let byte_order = client.byte_order; - let mut buf: Vec = Vec::with_capacity(32); - x11::write_translate_coordinates_reply(&mut buf, byte_order, sequence, child, dst_x, dst_y)?; - Ok(write_to_client(client, client_id, &buf)) -} - -fn write_to_client( - client: &mut crate::server::ClientState, - client_id: ClientId, - bytes: &[u8], -) -> RequestOutcome { - crate::core_loop::fanout::record_outbound_telemetry(client_id, client.byte_order, bytes); - match client_io::write_or_buffer(client, bytes) { - Ok(WriteOutcome::Done | WriteOutcome::WouldBlock) => RequestOutcome::Handled, - Ok(WriteOutcome::Disconnect) => RequestOutcome::Disconnect(client_id), - Err(_) => RequestOutcome::Disconnect(client_id), - } -} - -fn emit_xi2_device_changed_bootstrap( - state: &mut ServerState, - _backend: &mut dyn Backend, - _origin: Option, - client_id: ClientId, - sequence: SequenceNumber, - major_opcode: u8, -) -> io::Result<()> { - fn write_button_class(buf: &mut Vec, sourceid: u16, label_atoms: &[AtomId]) { - let le = x11::ClientByteOrder::LittleEndian; - let num_buttons = u16::try_from(label_atoms.len()).unwrap_or(u16::MAX); - let state_words = num_buttons.div_ceil(32) as usize; - let byte_len = 8 + 4 * state_words + 4 * num_buttons as usize; - x11::write_u16(le, buf, 1); - x11::write_u16(le, buf, (byte_len / 4) as u16); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, num_buttons); - buf.extend(std::iter::repeat_n(0u8, 4 * state_words)); - for atom in label_atoms { - x11::write_u32(le, buf, atom.0); - } - } - - fn write_valuator_class( - buf: &mut Vec, - sourceid: u16, - number: u16, - label_atom: AtomId, - value: i32, - ) { - let le = x11::ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, 2); - x11::write_u16(le, buf, 11); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, number); - x11::write_u32(le, buf, label_atom.0); - x11::write_u32(le, buf, u32::MAX); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, u32::MAX); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, value as u32); - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, 0); - buf.push(0); - buf.extend_from_slice(&[0u8; 3]); - } - - fn write_scroll_class(buf: &mut Vec, sourceid: u16, number: u16, scroll_type: u16) { - let le = x11::ClientByteOrder::LittleEndian; - x11::write_u16(le, buf, 3); - x11::write_u16(le, buf, 6); - x11::write_u16(le, buf, sourceid); - x11::write_u16(le, buf, number); - x11::write_u16(le, buf, scroll_type); - x11::write_u16(le, buf, 0); - // Flags = 0 to match the XIQueryDevice encoder's `write_scroll_class` - // (the canonical comment lives there). XIScrollFlagNoEmulation would - // be a contract violation while we still emit emulated XI_ButtonPress - // 4..7 — release Chrome crashes on it (2026-05-29). xserver's - // XIQueryDevice and DeviceChanged paths populate this field from a - // single `axis->scroll.flags` source - // (`Xi/xiquerydevice.c:ListScrollInfo` and - // `dix/eventconvert.c:appendScrollInfo`), so the two encoders here - // must agree. - x11::write_u32(le, buf, 0); - x11::write_u32(le, buf, 1); - x11::write_u32(le, buf, 0); - } - - let pointer = ( - i32::from(state.randr.screen_width) / 2, - i32::from(state.randr.screen_height) / 2, - ); - let button_labels = [ - state.atoms.intern("Button Left", false), - state.atoms.intern("Button Middle", false), - state.atoms.intern("Button Right", false), - state.atoms.intern("Button Wheel Up", false), - state.atoms.intern("Button Wheel Down", false), - state.atoms.intern("Button Horiz Wheel Left", false), - state.atoms.intern("Button Horiz Wheel Right", false), - ]; - let axis_labels = [ - state.atoms.intern("Rel X", false), - state.atoms.intern("Rel Y", false), - state.atoms.intern("Rel Vert Scroll", false), - state.atoms.intern("Rel Horiz Scroll", false), - ]; - let mut classes = Vec::new(); - write_button_class(&mut classes, 4, &button_labels); - write_valuator_class(&mut classes, 4, 0, axis_labels[0], pointer.0); - write_valuator_class(&mut classes, 4, 1, axis_labels[1], pointer.1); - write_valuator_class( - &mut classes, - 4, - 2, - axis_labels[2], - state.scroll_axis_value[0], - ); - write_valuator_class( - &mut classes, - 4, - 3, - axis_labels[3], - state.scroll_axis_value[1], - ); - write_scroll_class(&mut classes, 4, 2, 1); - write_scroll_class(&mut classes, 4, 3, 2); - let time = state.timestamp_now(); - - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(()); - }; - let mut buf = Vec::new(); - x11::encode_xi2_device_changed_event( - &mut buf, - client.byte_order, - sequence, - major_opcode, - 2, - time, - 7, - 4, - 1, - &classes, - ); - let _outcome = write_to_client(client, client_id, &buf); - Ok(()) -} - -/// Largest contiguous free run in `[max(base,1) .. base|mask]`, -/// given the SORTED+DEDUPED occupied ids in that range. Returns -/// Xorg's exact exhaustion wire shape `(0, 1)` when nothing is free -/// (dix/resource.c:733-737 zeroes min/max; the reply encodes -/// max-min+1 = 1; libxcb treats start 0 as exhausted). Largest-gap -/// is an implementation choice — the protocol promises only "a -/// contiguous range of unused IDs" (spec "GetXIDRange algorithm"). -fn largest_free_xid_gap(base: u32, mask: u32, used_sorted: &[u32]) -> (u32, u32) { - let lo = base.max(1); // XID 0 is never allocatable - let hi = base | mask; - let mut best_start = 0u32; - let mut best_len = 0u64; - let mut cursor = lo; - for &u in used_sorted { - if u < lo { - continue; - } - if u > hi { - break; - } - if u > cursor { - let len = u64::from(u - cursor); - if len > best_len { - best_len = len; - best_start = cursor; - } - } - cursor = cursor.max(u.saturating_add(1)); - } - if cursor <= hi { - let len = u64::from(hi - cursor) + 1; - if len > best_len { - best_len = len; - best_start = cursor; - } - } - if best_len == 0 { - (0, 1) - } else { - #[allow(clippy::cast_possible_truncation)] - (best_start, best_len as u32) // len ≤ hi - lo + 1 ≤ hi ≤ u32::MAX - } -} - -#[cfg(test)] -mod largest_free_xid_gap_tests { - use super::largest_free_xid_gap; - - #[test] - fn largest_free_xid_gap_cases() { - let base = 0x0010_0000u32; - let mask = 0x000F_FFFFu32; - let hi = base | mask; - // empty range → whole range (lo = base since base != 0) - assert_eq!(largest_free_xid_gap(base, mask, &[]), (base, mask + 1)); - // one used id at the start → gap after it - assert_eq!(largest_free_xid_gap(base, mask, &[base]), (base + 1, mask)); - // split: small gap low, big gap high → picks the big one - let used: Vec = (base..base + 10).chain([base + 12]).collect(); - assert_eq!( - largest_free_xid_gap(base, mask, &used), - (base + 13, hi - (base + 13) + 1) - ); - // fully exhausted → Xorg wire shape (0, 1) - let all: Vec = (base..=hi).collect(); // NOTE: 1M entries — fine in a test - assert_eq!(largest_free_xid_gap(base, mask, &all), (0, 1)); - // base 0 (hypothetical) excludes XID 0 - assert_eq!(largest_free_xid_gap(0, 0xFF, &[]), (1, 0xFF)); - } -} - -/// XC-MISC (major opcode 152) — XID recycling for long-lived clients. -/// Spec docs/superpowers/specs/2026-06-12-xcmisc-design.md; Xorg ref -/// Xext/xcmisc.c. Length validation lives here because the top-level -/// exact-length table is core-opcode-only. -fn handle_xcmisc_request( - state: &mut ServerState, - client_id: ClientId, - sequence: SequenceNumber, - header: RequestHeader, - body: &[u8], -) -> io::Result { - use yserver_protocol::x11::ClientByteOrder; - let byte_order = state - .clients - .get(&client_id.0) - .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); - let minor = header.data; - match minor { - // GetVersion — req 8 bytes (client version, ignored). - 0 => { - if body.len() != 4 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - let mut buf: Vec = Vec::with_capacity(32); - x11::write_xcmisc_get_version_reply(&mut buf, byte_order, sequence)?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, &buf)) - } - // GetXIDRange — req 4 bytes (header only). - 1 => { - if !body.is_empty() { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - let Some((base, mask)) = state - .clients - .get(&client_id.0) - .map(|c| (c.resource_id_base, c.resource_id_mask)) - else { - return Ok(RequestOutcome::Handled); - }; - let used = state.used_xids_in(base, mask); - let (start_id, count) = largest_free_xid_gap(base, mask, &used); - log::info!( - "client {} XC-MISC GetXIDRange → start=0x{start_id:x} count={count} \ - ({} ids in use)", - client_id.0, - used.len(), - ); - let mut buf: Vec = Vec::with_capacity(32); - x11::write_xcmisc_get_xid_range_reply(&mut buf, byte_order, sequence, start_id, count)?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, &buf)) - } - // GetXIDList — req 8 bytes: count(4). - 2 => { - if body.len() != 4 { - return emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_LENGTH, - 0, - u16::from(minor), - header.opcode, - ); - } - let want = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); - let Some((base, mask)) = state - .clients - .get(&client_id.0) - .map(|c| (c.resource_id_base, c.resource_id_mask)) - else { - return Ok(RequestOutcome::Handled); - }; - // Clamp to the range size — never allocate - // client-controlled gigabytes (explicit Xorg deviation, - // spec "Edge cases"; Xorg would BadAlloc instead). - let limit = u64::from(want).min(u64::from(mask) + 1); - let mut ids: Vec = Vec::new(); - let lo = base.max(1); - let hi = base | mask; - let mut id = lo; - while ids.len() < limit as usize { - if !state.xid_occupied(id) { - ids.push(id); - } - if id == hi { - break; - } - id += 1; - } - log::info!( - "client {} XC-MISC GetXIDList want={want} → {} ids", - client_id.0, - ids.len(), - ); - let mut buf: Vec = Vec::with_capacity(32 + ids.len() * 4); - x11::write_xcmisc_get_xid_list_reply(&mut buf, byte_order, sequence, &ids)?; - let Some(client) = state.clients.get_mut(&client_id.0) else { - return Ok(RequestOutcome::Handled); - }; - Ok(write_to_client(client, client_id, &buf)) - } - other => emit_x11_error_with_minor( - state, - client_id, - sequence, - x11::error::BAD_REQUEST, - 0, - u16::from(other), - header.opcode, - ), - } -} - -#[cfg(test)] -mod tests { - use std::{ - collections::{HashMap, HashSet, VecDeque}, - io::Read, - os::unix::net::UnixStream, - sync::{Arc, Mutex, atomic::AtomicU16}, - }; - - use yserver_protocol::x11::{ - ClientByteOrder, ClientId, CreateGcRequest, CreatePixmapRequest, CreateWindowRequest, - RequestHeader, ResourceId, SequenceNumber, screensaver as x11screensaver, sync as x11sync, - }; - - use super::*; - use crate::{ - backend::{ - FillStyle, - recording::{RecordedCall, RecordingBackend}, - }, - resources::ROOT_WINDOW, - server::{ClientState, ScreenSaverActive, ServerState}, - }; - - fn seed_present_clock(state: &mut ServerState, msc: u64, ust: u64) { - seed_present_domain_clock(state, 0, 0, msc, ust); - } - - fn seed_present_domain_clock( - state: &mut ServerState, - crtc_id: u32, - crtc_epoch: u64, - msc: u64, - ust: u64, - ) { - let completion = crate::backend::PresentClockSample { - msc, - ust, - source: crate::backend::PresentClockSource::PageFlip, - }; - state.present_crtc_clocks.insert( - (crtc_id, crtc_epoch), - crate::server::PresentCrtcClock { - epoch: crtc_epoch, - msc, - ust, - completion, - }, - ); - } - - fn present_test_output( - output_id: u32, - crtc_id: u32, - x: i16, - y: i16, - width: u16, - height: u16, - enabled: bool, - ) -> crate::randr::RandrOutput { - let mode_id = if enabled { - crtc_id.wrapping_add(0x1000) - } else { - 0 - }; - crate::randr::RandrOutput { - name: format!("test-{output_id}"), - output_id, - crtc_id, - mode_id, - connected: true, - x, - y, - width: if enabled { width } else { 0 }, - height: if enabled { height } else { 0 }, - vrefresh: if enabled { 60 } else { 0 }, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![crtc_id.wrapping_add(0x1000)], - num_preferred: 1, - } - } - - fn create_present_test_window( - state: &mut ServerState, - xid: u32, - x: i16, - y: i16, - width: u16, - height: u16, - ) { - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x, - y, - width, - height, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - - // #96: each visual-backed GLX FBConfig must advertise GLX_PBUFFER_BIT plus - // the three GLX_MAX_PBUFFER_* caps, or Chromium/ANGLE can't allocate its - // offscreen pbuffer surface and falls back to software (no WebGL/Maps 3D). - // The #152 native-pixmap config is deliberately pixmap-only. Property - // counts must stay uniform across configs (GetFBConfigs encodes a single - // num_properties for all of them). - #[test] - fn glx_fb_configs_advertise_pbuffer() { - use yserver_protocol::x11::glx as g; - for tfp in [false, true] { - let configs = synthesise_glx_fb_configs(tfp); - assert!(!configs.is_empty()); - let prop_count = configs[0].len(); - for config in &configs { - assert_eq!(config.len(), prop_count, "non-uniform property count"); - let get = |attr: u32| config.iter().find(|(a, _)| *a == attr).map(|(_, v)| *v); - let drawable = get(g::GLX_DRAWABLE_TYPE).expect("DRAWABLE_TYPE present"); - if drawable == g::GLX_PIXMAP_BIT { - assert_eq!(get(g::GLX_VISUAL_ID), Some(0)); - assert_eq!(get(g::GLX_X_RENDERABLE), Some(0)); - continue; - } - assert_ne!( - drawable & g::GLX_PBUFFER_BIT, - 0, - "config must advertise GLX_PBUFFER_BIT (tfp={tfp})" - ); - let max_w = get(g::GLX_MAX_PBUFFER_WIDTH).expect("MAX_PBUFFER_WIDTH present"); - let max_h = get(g::GLX_MAX_PBUFFER_HEIGHT).expect("MAX_PBUFFER_HEIGHT present"); - assert!(max_w > 0 && max_h > 0, "pbuffer caps must be non-zero"); - assert!(get(g::GLX_MAX_PBUFFER_PIXELS).is_some()); - } - } - } - - #[test] - fn glx_visuals_have_one_unambiguous_double_buffered_config() { - use yserver_protocol::x11::glx as g; - - let visuals = synthesise_glx_visual_configs(); - assert_eq!(visuals.len(), 3); - assert!(visuals.iter().all(|visual| visual.double_buffer)); - - let configs = synthesise_glx_fb_configs(false); - assert_eq!(configs.len(), 4); - let mut visual_ids = HashSet::new(); - for config in configs { - let get = |attr: u32| config.iter().find(|(a, _)| *a == attr).map(|(_, v)| *v); - let visual_id = get(g::GLX_VISUAL_ID).expect("VISUAL_ID present"); - if visual_id == 0 { - assert_eq!(get(g::GLX_DRAWABLE_TYPE), Some(g::GLX_PIXMAP_BIT)); - assert_eq!(get(g::GLX_DOUBLEBUFFER), Some(0)); - } else { - assert!( - visual_ids.insert(visual_id), - "duplicate visual 0x{visual_id:x}" - ); - assert_eq!(get(g::GLX_DOUBLEBUFFER), Some(1)); - } - } - assert_eq!(visual_ids.len(), 3); - } - - // glmark2 2023.01 defaults to stencil=0 and rejects any positive - // stencil count while choosing its default FBConfig. Keep that config on - // a distinct X visual: reusing ROOT_VISUAL would recreate the config / - // visual ambiguity that made Mesa allocate fake front buffers (#96). - #[test] - fn glmark_can_choose_an_opaque_zero_stencil_window_config() { - use yserver_protocol::x11::glx as g; - - let config = synthesise_glx_fb_configs(false) - .into_iter() - .find(|config| { - let get = |attribute| { - config - .iter() - .find(|(key, _)| *key == attribute) - .map(|(_, value)| *value) - }; - get(g::GLX_DRAWABLE_TYPE).is_some_and(|value| value & g::GLX_WINDOW_BIT != 0) - && get(g::GLX_DOUBLEBUFFER) == Some(1) - && get(g::GLX_STENCIL_SIZE) == Some(0) - }) - .expect("a double-buffered stencil-0 window FBConfig for glmark2"); - let get = |attribute| { - config - .iter() - .find(|(key, _)| *key == attribute) - .map(|(_, value)| *value) - }; - assert_ne!(get(g::GLX_VISUAL_ID), Some(crate::resources::ROOT_VISUAL.0)); - assert_ne!(get(g::GLX_VISUAL_ID), Some(crate::resources::ARGB_VISUAL.0)); - assert_eq!( - get(g::GLX_VISUAL_ID), - Some(crate::resources::GLMARK_VISUAL.0) - ); - } - - // QtWebEngine's GLXHelper chooses a native-pixmap config with this exact - // attribute set before it imports a DMA-BUF through DRI3. In particular, - // it requires GLX_DOUBLEBUFFER=false. It must not reuse either real X - // visual: doing so recreates #96, where Mesa paired a single-buffered - // context with a double-buffered window and allocated a fake front buffer. - #[test] - fn qtwebengine_can_choose_an_isolated_single_buffered_pixmap_config() { - use yserver_protocol::x11::glx as g; - - let configs = synthesise_glx_fb_configs(true); - let config = configs - .iter() - .find(|config| { - let get = |attr: u32| { - config - .iter() - .find(|(key, _)| *key == attr) - .map(|(_, value)| *value) - }; - get(g::GLX_RED_SIZE).is_some_and(|value| value >= 8) - && get(g::GLX_GREEN_SIZE).is_some_and(|value| value >= 8) - && get(g::GLX_BLUE_SIZE).is_some_and(|value| value >= 8) - && get(g::GLX_ALPHA_SIZE).is_some_and(|value| value >= 8) - && get(g::GLX_BUFFER_SIZE).is_some_and(|value| value >= 32) - && get(g::GLX_BIND_TO_TEXTURE_RGBA_EXT) == Some(1) - && get(g::GLX_DRAWABLE_TYPE).is_some_and(|value| value & g::GLX_PIXMAP_BIT != 0) - && get(g::GLX_BIND_TO_TEXTURE_TARGETS_EXT) - .is_some_and(|value| value & g::GLX_TEXTURE_2D_BIT_EXT != 0) - && get(g::GLX_DOUBLEBUFFER) == Some(0) - }) - .expect("a QtWebEngine native-pixmap FBConfig"); - let get = |attr: u32| { - config - .iter() - .find(|(key, _)| *key == attr) - .map(|(_, value)| *value) - }; - assert_eq!(get(g::GLX_VISUAL_ID), Some(0)); - assert_eq!(get(g::GLX_DRAWABLE_TYPE), Some(g::GLX_PIXMAP_BIT)); - assert_eq!(get(g::GLX_X_RENDERABLE), Some(0)); - } - - // #96: pbuffer GetGeometry must report the fbconfig's true depth so Mesa's - // loader_dri3 backs it correctly. fbconfig 0x101 maps to ROOT_VISUAL - // (depth 24), while 0x103 maps to ARGB_VISUAL (depth 32). - #[test] - fn glx_fbconfig_depth_tracks_visual() { - assert_eq!(glx_fbconfig_depth(0x101), 24); - assert_eq!(glx_fbconfig_depth(0x103), 32); - // Unknown fbconfig falls back to the depth-24 default. - assert_eq!(glx_fbconfig_depth(0xDEAD), 24); - } - - /// Every GLX visual `GetVisualConfigs` advertises has an FBConfig carrying - /// that visual (Xorg's `pGlxScreen->visuals[i]` *is* a config), and the - /// pairing round-trips. FBConfig IDs and the visual-less FBConfig are - /// not GLX visuals. - #[test] - fn glx_visual_fbconfig_pairs_every_advertised_visual() { - for visual in synthesise_glx_visual_configs() { - let fbconfig = glx_visual_fbconfig(visual.visual_id) - .unwrap_or_else(|| panic!("visual 0x{:x} has no FBConfig", visual.visual_id)); - assert_eq!(glx_fbconfig_visual(fbconfig), visual.visual_id); - } - assert_eq!(glx_visual_fbconfig(0x101), None); - assert_eq!(glx_visual_fbconfig(0x104), None); - assert_eq!(glx_fbconfig_visual(0x104), 0); - assert_eq!(glx_fbconfig_visual(0xDEAD), 0); - } - - fn install_client(state: &mut ServerState, id: u32) -> UnixStream { - let (a, b) = UnixStream::pair().unwrap(); - state.clients.insert( - id, - ClientState { - writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), - byte_order: ClientByteOrder::LittleEndian, - last_sequence: Arc::new(AtomicU16::new(0)), - // Permissive resource-id range so tests driving - // `process_request` can use arbitrary non-zero - // resource xids without tripping - // `xid_out_of_client_range`. Real clients get a - // tight base/mask from the connection handshake; - // this is the test-fixture analogue of "every xid - // is in range". - resource_id_base: 0, - resource_id_mask: u32::MAX, - event_masks: HashMap::new(), - save_set: HashSet::new(), - big_requests_enabled: false, - xi2_masks: HashMap::new(), - xi1_event_classes: HashSet::new(), - xi1_window_event_classes: HashMap::new(), - outbound: VecDeque::new(), - watching_writable: false, - focused_window: ROOT_WINDOW, - reader_control: None, - is_local: true, - fd_passing: true, - }, - ); - b - } - - #[test] - fn remote_clients_are_rejected_before_dri3_and_mit_shm_handlers() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").is_local = false; - let mut backend = RecordingBackend::new(); - - for (sequence, minor) in (0u8..=11).enumerate() { - #[allow(clippy::cast_possible_truncation)] - let sequence = sequence as u16 + 1; - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(sequence), - RequestHeader { - opcode: 147, - data: minor, - length_units: 1, - }, - &[], - None, - ) - .expect("dispatch"); - let reply = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(reply.len(), 32); - assert_eq!(reply[0], 0); - assert_eq!(reply[1], x11::error::BAD_MATCH); - assert_eq!( - u16::from_le_bytes(reply[8..10].try_into().unwrap()), - u16::from(minor) - ); - assert_eq!(reply[10], 147); - } - - for (sequence, minor) in (1u8..=7).enumerate() { - #[allow(clippy::cast_possible_truncation)] - let sequence = sequence as u16 + 20; - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(sequence), - RequestHeader { - opcode: 130, - data: minor, - length_units: 1, - }, - &[], - None, - ) - .expect("dispatch"); - let reply = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(reply.len(), 32); - assert_eq!(reply[0], 0); - assert_eq!(reply[1], x11::error::BAD_REQUEST); - assert_eq!( - u16::from_le_bytes(reply[8..10].try_into().unwrap()), - u16::from(minor) - ); - assert_eq!(reply[10], 130); - } - } - - #[test] - fn remote_mit_shm_query_version_remains_reachable() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").is_local = false; - let mut backend = RecordingBackend::new(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 130, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .expect("ShmQueryVersion dispatch"); - let reply = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(reply[0], 1, "ShmQueryVersion must not be locality-gated"); - } - - #[test] - fn local_clients_reach_dri3_and_mit_shm_handlers() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: yserver_protocol::x11::dri3::QUERY_VERSION, - length_units: 3, - }, - &[1, 0, 0, 0, 4, 0, 0, 0], - None, - ) - .expect("DRI3::QueryVersion dispatch"); - let reply = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(reply[0], 1, "local DRI3 request reaches its handler"); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 130, - data: yserver_protocol::x11::mit_shm::ATTACH, - length_units: 1, - }, - &[], - None, - ) - .expect("MIT-SHM Attach dispatch"); - let reply = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(reply[0], 0, "malformed local request reaches the handler"); - assert_eq!(reply[1], x11::error::BAD_LENGTH); - } - - #[test] - fn remote_client_can_query_present() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").is_local = false; - let mut backend = RecordingBackend::new(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::QUERY_VERSION, - length_units: 1, - }, - &[], - None, - ) - .expect("Present::QueryVersion dispatch"); - let reply = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(reply[0], 1, "Present must not be locality-gated"); - } - - #[test] - fn locality_gated_extensions_remain_advertised() { - let mut backend = syncobj_cap_backend(); - let names = advertised_extension_names(&mut backend); - - for name in ["MIT-SHM", "DRI3", "XFree86-VidModeExtension"] { - assert!( - extension_query_reply(name, &mut backend).is_some(), - "{name} must be advertised before its per-client locality gate" - ); - assert!( - names.contains(&name), - "{name} must remain in ListExtensions" - ); - } - } - - #[test] - fn fd_reply_refuses_a_client_without_fd_passing() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let client = state.clients.get_mut(&1).expect("test client"); - client.fd_passing = false; - let file = std::fs::File::open("/dev/null").expect("open null device"); - - let error = send_reply_with_fd(client, &[1; 32], std::os::fd::AsRawFd::as_raw_fd(&file)) - .expect_err("non-FD-capable clients must reject descriptor replies"); - assert_eq!(error.kind(), io::ErrorKind::Unsupported); - } - - fn set_test_pointer_grab( - state: &mut ServerState, - owner: u32, - window: u32, - passive: bool, - via_xi2: bool, - ) { - state.set_pointer_grab(crate::server::ActivePointerGrab { - owner: ClientId(owner), - grab_window: ResourceId(window), - event_mask: u16::MAX, - cursor: ResourceId(0), - time: 0, - owner_events: false, - via_xi2, - implicit: false, - passive, - xi2_mask: if via_xi2 { u64::MAX } else { 0 }, - }); - } - - fn read_all_available(peer: &mut UnixStream) -> Vec { - peer.set_nonblocking(true).expect("set_nonblocking"); - let mut out = Vec::new(); - let mut buf = [0u8; 512]; - loop { - match peer.read(&mut buf) { - Ok(0) => break, - Ok(n) => out.extend_from_slice(&buf[..n]), - Err(err) if err.kind() == io::ErrorKind::WouldBlock => break, - Err(err) => panic!("read failed: {err}"), - } - } - peer.set_nonblocking(false).expect("unset_nonblocking"); - out - } - - fn read_all_or_buffered( - state: &mut ServerState, - client_id: u32, - peer: &mut UnixStream, - ) -> Vec { - let mut out = read_all_available(peer); - let client = state.clients.get_mut(&client_id).expect("test client"); - out.extend(client.outbound.drain(..)); - out - } - - fn poly_fill_rectangle_body(drawable: u32, gc: u32) -> Vec { - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&drawable.to_le_bytes()); - body.extend_from_slice(&gc.to_le_bytes()); - body.extend_from_slice(&0i16.to_le_bytes()); - body.extend_from_slice(&0i16.to_le_bytes()); - body.extend_from_slice(&1u16.to_le_bytes()); - body.extend_from_slice(&1u16.to_le_bytes()); - body - } - - fn free_pixmap_body(pixmap: u32) -> Vec { - pixmap.to_le_bytes().to_vec() - } - - /// Wire body for a ConfigureWindow request: window, value_mask, the - /// 2-byte request pad, then one CARD32 per set value-mask bit in bit - /// order (x,y,w,h,border,sibling,stack_mode). - fn cw_restack_body(window: u32, value_mask: u16, values: &[u32]) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&value_mask.to_le_bytes()); - body.extend_from_slice(&[0u8, 0u8]); // request pad - for v in values { - body.extend_from_slice(&v.to_le_bytes()); - } - body - } - - /// Two children (0x200 created first, then 0x300 → 0x300 ends on top) - /// under root, plus client 1's drained peer socket. - fn two_children_under_root() -> (ServerState, UnixStream) { - let mut state = ServerState::new(); - let peer = install_client(&mut state, 1); - for id in [0x200u32, 0x300u32] { - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(id), - parent: ROOT_WINDOW, - width: 50, - height: 50, - ..Default::default() - }, - ); - } - (state, peer) - } - - fn count_configure_notifies(bytes: &[u8]) -> usize { - // X11 events are 32 bytes; ConfigureNotify event code is 22. - bytes.chunks(32).filter(|e| e[0] & 0x7f == 22).count() - } - - /// Extract the `mode` byte (wire offset 11) of every Present - /// `CompleteNotify` in a raw byte stream, in wire order — an - /// emit_idle-independent delivery-order oracle for tests mixing Copy - /// and Skip (Skip's gated `signal_present_wake` means - /// `RecordingBackend::signalled_present_wakes` alone can't order - /// them). Callers must select ONLY `EVENT_MASK_COMPLETE_NOTIFY` (no - /// `IdleNotify`/`ConfigureNotify`), so every event in the stream is a - /// fixed 40-byte `CompleteNotify` and the chunking can't desync. - fn complete_notify_modes(bytes: &[u8]) -> Vec { - bytes - .chunks(40) - .map(|chunk| { - assert_eq!(chunk.len(), 40, "truncated CompleteNotify"); - assert_eq!(chunk[0], 35, "GenericEvent"); - assert_eq!(chunk[1], 145, "PRESENT major opcode"); - chunk[11] - }) - .collect() - } - - #[test] - fn configure_window_noop_restack_emits_no_configure_notify() { - // Regression (Enlightenment e27 restack war): a stacking-only - // ConfigureWindow that does NOT change the child order must emit - // zero ConfigureNotify, matching Xorg dix/window.c. A spurious - // notify makes the WM re-restack forever (~8000 req/s observed), - // pegging the desktop so clicks never get processed. - let (mut state, mut peer) = two_children_under_root(); - // 0x300 was created last → already on top. Subscribe to its - // StructureNotify, then drain any setup traffic. - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(ResourceId(0x300), 0x0002_0000); - let _ = read_all_available(&mut peer); - - // Raise the already-top window to the top: a positional no-op. - let body = cw_restack_body(0x300, 0x0040, &[0]); // CWStackMode=Above - let mut backend = RecordingBackend::new(); - handle_configure_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &body, - ) - .expect("handle_configure_window"); - - let out = read_all_available(&mut peer); - assert_eq!( - count_configure_notifies(&out), - 0, - "no-op restack must not emit ConfigureNotify (got {} bytes)", - out.len() - ); - } - - #[test] - fn configure_window_real_restack_emits_one_configure_notify() { - // Guard against over-suppression: a restack that DOES reorder the - // children must still emit exactly one ConfigureNotify. - let (mut state, mut peer) = two_children_under_root(); - // 0x200 was created first → currently at the bottom. - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(ResourceId(0x200), 0x0002_0000); - let _ = read_all_available(&mut peer); - - // Raise 0x200 to the top: a real reorder. - let body = cw_restack_body(0x200, 0x0040, &[0]); // CWStackMode=Above - let mut backend = RecordingBackend::new(); - handle_configure_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &body, - ) - .expect("handle_configure_window"); - - let out = read_all_available(&mut peer); - assert_eq!( - count_configure_notifies(&out), - 1, - "a real restack must emit exactly one ConfigureNotify" - ); - } - - // ── #143 — a resize must report the window exposed, either way ── - // - // Xorg's `miResizeWindow` copies the NEW clip list wholesale into - // `after.exposed` — "the entire window is trashed unless bitGravity - // recovers portions of it" (`mi/miwindow.c:466-472`) — and only a - // non-Forget `bitGravity` subtracts the bits it actually moved - // (`:596-599`). There is no grow/shrink branch: under the default - // ForgetGravity the full window is reported in both directions. - // Nor does the background gate the EVENT — `miWindowExposures` - // paints, then sends (`mi/miexpose.c:387-389`), and the - // background-None early-out is inside the paint (`:438-440`). - // - // We emitted this for a grow only. On HW that is the #143 xterm: - // awesome retiles it smaller, the leaf is re-tiled from the - // window's black background, and with no Expose nothing asks xterm - // to repaint its static banner rows — they stay black while the - // prompt line, which xterm redraws unprompted, comes back. - - /// One viewable, Expose-selecting child of root at `w`x`h`, plus - /// client 1's already-drained peer socket. `background_pixel` picks - /// the two shapes that matter here: `Some` is the xterm case (the - /// resize re-tiles the leaf and destroys the content), `None` is the - /// background-None case (the content survives). - fn one_viewable_expose_child( - w: u16, - h: u16, - background_pixel: Option, - ) -> (ServerState, UnixStream) { - const XID: u32 = 0x400; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(XID), - parent: ROOT_WINDOW, - width: w, - height: h, - background_pixel, - ..Default::default() - }, - ); - assert_eq!( - state - .resources - .window(ResourceId(XID)) - .map(|win| win.background_none), - Some(background_pixel.is_none()), - "harness sanity: the background shape under test", - ); - state - .resources - .window_mut(ResourceId(XID)) - .expect("child installed") - .map_state = crate::resources::MapState::Viewable; - state - .clients - .get_mut(&1) - .expect("test client") - .event_masks - .insert(ResourceId(XID), 0x0000_8000); // ExposureMask - let _ = read_all_available(&mut peer); - (state, peer) - } - - /// Every Expose in `bytes` for `window`, as `(x, y, width, height)`. - fn expose_rects(bytes: &[u8], window: u32) -> Vec<(u16, u16, u16, u16)> { - bytes - .chunks(32) - .filter(|e| { - e.len() == 32 - && e[0] & 0x7f == 12 - && u32::from_le_bytes([e[4], e[5], e[6], e[7]]) == window - }) - .map(|e| { - ( - u16::from_le_bytes([e[8], e[9]]), - u16::from_le_bytes([e[10], e[11]]), - u16::from_le_bytes([e[12], e[13]]), - u16::from_le_bytes([e[14], e[15]]), - ) - }) - .collect() - } - - /// Resize `window` to `w`x`h` (CWWidth|CWHeight) and return whatever - /// reached the client. - fn resize_and_read( - state: &mut ServerState, - peer: &mut UnixStream, - window: u32, - w: u32, - h: u32, - ) -> Vec { - let body = cw_restack_body(window, 0x000C, &[w, h]); - let mut backend = RecordingBackend::new(); - handle_configure_window( - state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &body, - ) - .expect("handle_configure_window"); - read_all_available(peer) - } - - #[test] - fn configure_window_shrink_exposes_the_whole_window() { - // The #143 case. `configure_subwindow` re-tiles the leaf from - // the window's background on a shrink, so without this Expose - // the discarded pixels are unrecoverable. - let (mut state, mut peer) = one_viewable_expose_child(200, 100, Some(0x0000_0000)); - let out = resize_and_read(&mut state, &mut peer, 0x400, 100, 60); - assert_eq!( - expose_rects(&out, 0x400), - vec![(0, 0, 100, 60)], - "a shrink must report the whole NEW window exposed, exactly once \ - (`mi/miwindow.c:466-472`); emitting none leaves an idle client \ - showing the background fill forever (#143)", - ); - } - - #[test] - fn configure_window_grow_exposes_the_whole_window() { - // Over-suppression guard: the grow path predates the shrink one - // and must keep its single full-window Expose. - let (mut state, mut peer) = one_viewable_expose_child(100, 60, Some(0x0000_0000)); - let out = resize_and_read(&mut state, &mut peer, 0x400, 200, 100); - assert_eq!( - expose_rects(&out, 0x400), - vec![(0, 0, 200, 100)], - "a grow must still report exactly one full-window Expose", - ); - } - - #[test] - fn configure_window_shrink_exposes_a_background_none_window_too() { - // A background-None window keeps its pixels across the resize - // (`mi/miexpose.c:438-440` returns before painting) but STILL - // gets the Expose: `miWindowExposures` calls `PaintWindow` and - // `miSendExposures` in sequence and only the paint is skipped - // (`mi/miexpose.c:387-389`). Nothing on this path may start - // reading the background state to suppress the event. - let (mut state, mut peer) = one_viewable_expose_child(200, 100, None); - let out = resize_and_read(&mut state, &mut peer, 0x400, 100, 60); - assert_eq!( - expose_rects(&out, 0x400), - vec![(0, 0, 100, 60)], - "a background-None window is not painted but is still told what \ - was exposed", - ); - } - - #[test] - fn configure_window_pure_move_emits_no_expose() { - // Under-suppression guard: `after.exposed` is seeded from the - // clip list only when the size changes; a pure move of an - // unobscured window exposes nothing of the window itself. - let (mut state, mut peer) = one_viewable_expose_child(200, 100, Some(0x0000_0000)); - let body = cw_restack_body(0x400, 0x0003, &[37, 41]); // CWX|CWY - let mut backend = RecordingBackend::new(); - handle_configure_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &body, - ) - .expect("handle_configure_window"); - let out = read_all_available(&mut peer); - assert_eq!( - expose_rects(&out, 0x400), - Vec::new(), - "a move is not a resize and must not expose the window", - ); - } - - /// Xorg's Present screen hook receives every real ConfigNotify, including - /// a pure move. Steam's DRI3 popup windows select this event and use its - /// x/y to keep the presentation surface synchronized with the native - /// override-redirect window. - #[test] - fn configure_window_pure_move_emits_present_configure_notify() { - use crate::server::PresentEventSelection; - use yserver_protocol::x11::present as x11present; - - const WINDOW: ResourceId = ResourceId(0x200); - const PRESENT_EID: u32 = 0x0010_0042; - - let (mut state, mut peer) = two_children_under_root(); - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(WINDOW, 0x0002_0000); - state.present_event_selections.insert( - PRESENT_EID, - PresentEventSelection { - owner: ClientId(1), - window: WINDOW, - event_mask: x11present::EVENT_MASK_CONFIGURE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - - let body = cw_restack_body(WINDOW.0, 0x0003, &[610, 250]); // CWX|CWY - let mut backend = RecordingBackend::new(); - handle_configure_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &body, - ) - .expect("handle_configure_window"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 72, "Present XGE plus core ConfigureNotify"); - // Xorg dix/window.c invokes the Present ConfigNotify screen hook - // before DeliverEvents sends the core ConfigureNotify. This ordering - // matters to clients which merge the two configure streams. - assert_eq!(bytes[0], 35, "GenericEvent"); - assert_eq!(bytes[1], 145, "PRESENT major opcode"); - assert_eq!( - u16::from_le_bytes(bytes[8..10].try_into().unwrap()), - u16::from(x11present::EVENT_CONFIGURE_NOTIFY), - ); - assert_eq!( - u32::from_le_bytes(bytes[12..16].try_into().unwrap()), - PRESENT_EID, - ); - assert_eq!( - u32::from_le_bytes(bytes[16..20].try_into().unwrap()), - WINDOW.0, - ); - assert_eq!(i16::from_le_bytes(bytes[20..22].try_into().unwrap()), 610); - assert_eq!(i16::from_le_bytes(bytes[22..24].try_into().unwrap()), 250); - assert_eq!(u16::from_le_bytes(bytes[24..26].try_into().unwrap()), 50); - assert_eq!(u16::from_le_bytes(bytes[26..28].try_into().unwrap()), 50); - assert_eq!(bytes[40] & 0x7f, 22, "core ConfigureNotify follows Present"); - assert_eq!( - u32::from_le_bytes(bytes[48..52].try_into().unwrap()), - WINDOW.0, - ); - } - - /// ProcTranslateCoords applies child input shapes. The Composite Overlay - /// Window is the top root child but has an empty input shape by default, - /// so a mapped popup below it must be returned as `child`, as on Xorg. - #[test] - fn translate_coordinates_skips_empty_input_shaped_cow() { - use crate::{backend::WindowHandle, resources::COMPOSITE_OVERLAY_WINDOW}; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let popup = ResourceId(0x200); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: popup, - parent: ROOT_WINDOW, - x: 715, - y: 327, - width: 132, - height: 165, - ..Default::default() - }, - ); - let _ = state.resources.map_window(popup); - state - .resources - .materialize_cow_resource(WindowHandle::from_raw_for_test(COMPOSITE_OVERLAY_WINDOW.0)); - state.materialize_cow_input_shape(); - let _ = read_all_available(&mut peer); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&715i16.to_le_bytes()); - body.extend_from_slice(&327i16.to_le_bytes()); - handle_translate_coordinates(&mut state, ClientId(1), SequenceNumber(1), &body) - .expect("handle_translate_coordinates"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[0], 1, "reply"); - assert_eq!( - u32::from_le_bytes(bytes[8..12].try_into().unwrap()), - popup.0, - "empty-input COW must not hide the popup child", - ); - assert_eq!(i16::from_le_bytes(bytes[12..14].try_into().unwrap()), 715); - assert_eq!(i16::from_le_bytes(bytes[14..16].try_into().unwrap()), 327); - } - - #[test] - fn configure_window_resize_applies_win_gravity_and_emits_gravity_notify() { - // X11 window gravity: growing a parent moves a South-gravity child - // down by the height delta and delivers a GravityNotify (Xorg - // ResizeChildrenWinSize). fvwm's window-shade relies on exactly - // this to reveal a client it parked above the fold. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let parent = ResourceId(0x400); - let child = ResourceId(0x401); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: parent, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - ..Default::default() - }, - ); - let _ = state.resources.map_window(parent); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: child, - parent, - x: 10, - y: -100, - width: 100, - height: 100, - win_gravity: Some(8), // South - ..Default::default() - }, - ); - let _ = state.resources.map_window(child); - state - .clients - .get_mut(&1) - .unwrap() - .event_masks - .insert(child, 0x0002_0000); // StructureNotify - let _ = read_all_available(&mut peer); - - // Grow the parent 100×100 → 100×200 (dh=+100): CWWidth|CWHeight. - let body = cw_restack_body(0x400, 0x000C, &[100, 200]); - let mut backend = RecordingBackend::new(); - handle_configure_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &body, - ) - .expect("handle_configure_window"); - - // South gravity: child.y += 100 → (10, 0). - let c = state.resources.window(child).expect("child"); - assert_eq!( - (c.x, c.y), - (10, 0), - "South-gravity child follows the parent's height growth", - ); - - // Exactly one GravityNotify (type 24) delivered to the child. - let out = read_all_available(&mut peer); - let gravity: Vec<&[u8]> = out - .chunks(32) - .filter(|e| e.len() == 32 && e[0] & 0x7f == 24) - .collect(); - assert_eq!(gravity.len(), 1, "exactly one GravityNotify to the child"); - let g = gravity[0]; - assert_eq!(&g[4..8], &child.0.to_le_bytes(), "event window = child"); - assert_eq!(&g[8..12], &child.0.to_le_bytes(), "reported window = child"); - assert_eq!(i16::from_le_bytes([g[12], g[13]]), 10, "GravityNotify x"); - assert_eq!(i16::from_le_bytes([g[14], g[15]]), 0, "GravityNotify y"); - } - - #[test] - fn active_monitors_matches_outputs_and_order() { - let mut state = ServerState::new(); - state.randr.outputs = vec![ - crate::randr::RandrOutput { - name: "DP-1".into(), - output_id: 1, - crtc_id: 1, - mode_id: 1, - connected: true, - x: 0, - y: 0, - width: 2560, - height: 1440, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![1], - num_preferred: 1, - }, - crate::randr::RandrOutput { - name: "HDMI-A-1".into(), - output_id: 2, - crtc_id: 2, - mode_id: 1, - connected: false, - x: 2560, - y: 0, - width: 2560, - height: 1440, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![1], - num_preferred: 1, - }, - ]; - - let monitors = active_monitors(&state); - assert_eq!(monitors.len(), state.randr.outputs.len()); - assert_eq!(monitors.len(), 2); - assert!(monitors[0].primary); - assert!(!monitors[1].primary); - assert_eq!(monitors[1].x, 2560); - assert_eq!( - (monitors[1].width_mm, monitors[1].height_mm), - (677, 381), - "automatic monitor geometry still derives physical size from its retained CRTC", - ); - } - - #[test] - fn vidmode_retains_a_light_disconnected_assigned_primary() { - let mut state = ServerState::new(); - let primary = state.randr.primary_output; - let expected = state - .randr - .outputs - .iter_mut() - .find(|output| output.output_id == primary) - .map(|output| { - output.connected = false; - (output.output_id, output.crtc_id) - }) - .unwrap(); - - let current = current_vidmode_output(&state).expect("the CRTC remains assigned"); - assert_eq!((current.output_id, current.crtc_id), expected); - } - - #[test] - fn xybitmap_to_zpixmap_preserves_lsb_first_bits_without_left_pad() { - let src = [ - 0b0000_1101u8, - 0, - 0, - 0, // row 0: 1 0 1 1 - 0b0000_0010u8, - 0, - 0, - 0, // row 1: 0 1 0 0 - ]; - let out = xybitmap_to_zpixmap(&src, 4, 2, 0).expect("convert"); - assert_eq!(out, src); - } - - #[test] - fn xybitmap_to_zpixmap_strips_left_pad_bits() { - let src = [ - 0b0011_0100u8, - 0, - 0, - 0, // left_pad=2, payload bits => 1 0 1 1 - ]; - let out = xybitmap_to_zpixmap(&src, 4, 1, 2).expect("convert"); - assert_eq!(out, vec![0b0000_1101u8, 0, 0, 0]); - } - - #[test] - fn xybitmap_to_target_zpixmap_expands_bits_with_fg_bg_at_depth_24() { - let src = [ - 0b0000_0101u8, - 0, - 0, - 0, // row: 1 0 1 - ]; - let out = xybitmap_to_target_zpixmap(&src, 3, 1, 0, 24, 0x0000_00ff, 0x0000_ff00) - .expect("convert"); - assert_eq!(out.len(), 12); - assert_eq!(&out[0..4], &0x0000_00ffu32.to_le_bytes()); - assert_eq!(&out[4..8], &0x0000_ff00u32.to_le_bytes()); - assert_eq!(&out[8..12], &0x0000_00ffu32.to_le_bytes()); - } - - #[test] - fn xybitmap_to_target_zpixmap_expands_bits_with_fg_bg_at_depth_4() { - let src = [ - 0b0000_0110u8, - 0, - 0, - 0, // row: 0 1 1 - ]; - let out = xybitmap_to_target_zpixmap(&src, 3, 1, 0, 4, 0x0d, 0x02).expect("convert"); - assert_eq!(out, vec![0xd2, 0x0d, 0, 0]); - } - - fn sync_header(minor: u8) -> RequestHeader { - RequestHeader { - opcode: 142, - data: minor, - length_units: 0, - } - } - - fn counter_value_body(counter: u32, value: i64) -> Vec { - let mut b = Vec::new(); - b.extend_from_slice(&counter.to_le_bytes()); - b.extend_from_slice(&xsync_i64(value)); - b - } - - // The exact CreateAlarm muffin issues under Cinnamon: Relative - // value 1, PositiveComparison, delta 1, events true, watching - // counter 0x02600006. - fn muffin_alarm_body() -> Vec { - let mut b = Vec::new(); - b.extend_from_slice(&0x01e0_0019u32.to_le_bytes()); - let mask = x11sync::CA_COUNTER - | x11sync::CA_VALUE_TYPE - | x11sync::CA_VALUE - | x11sync::CA_TEST_TYPE - | x11sync::CA_DELTA - | x11sync::CA_EVENTS; - b.extend_from_slice(&mask.to_le_bytes()); - b.extend_from_slice(&0x0260_0006u32.to_le_bytes()); - b.extend_from_slice(&x11sync::VALUE_TYPE_RELATIVE.to_le_bytes()); - b.extend_from_slice(&0i32.to_le_bytes()); // value hi - b.extend_from_slice(&1u32.to_le_bytes()); // value lo - b.extend_from_slice(&x11sync::TEST_POSITIVE_COMPARISON.to_le_bytes()); - b.extend_from_slice(&0i32.to_le_bytes()); // delta hi - b.extend_from_slice(&1u32.to_le_bytes()); // delta lo - b.push(1); // events = true - b.extend_from_slice(&[0u8; 3]); - b - } - - #[test] - fn poly_fill_rectangle_unknown_drawable_returns_bad_drawable() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(0x2000), - drawable: ROOT_WINDOW, - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - let body = poly_fill_rectangle_body(0xdead_beef, 0x2000); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 70, - data: 0, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - - let bytes = read_all_available(&mut peer); - assert!( - bytes.len() >= 32, - "expected 32-byte error reply, got {} bytes: {:02x?}", - bytes.len(), - bytes - ); - let buf = &bytes[..32]; - assert_eq!(buf[1], x11::error::BAD_DRAWABLE); - assert_eq!(buf[10], 70); - } - - #[test] - fn query_font_invalid_fontable_returns_bad_font() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // QueryFont (op 47) body = FONTABLE(4). 0xdeadbeef is unregistered. - let body = 0xdead_beefu32.to_le_bytes(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 47, - data: 0, - length_units: 2, - }, - &body, - None, - ) - .expect("process_request"); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); - assert_eq!(bytes[1], x11::error::BAD_FONT, "code"); - assert_eq!(bytes[10], 47, "major opcode"); - assert_eq!(&bytes[4..8], &0xdead_beefu32.to_le_bytes(), "bad font id"); - } - - #[test] - fn query_text_extents_invalid_fontable_returns_bad_font() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // QueryTextExtents (op 48) body = FONTABLE(4) + STRING16 (zero chars). - let body = 0xdead_beefu32.to_le_bytes(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 48, - data: 0, - length_units: 2, - }, - &body, - None, - ) - .expect("process_request"); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); - assert_eq!(bytes[1], x11::error::BAD_FONT, "code"); - assert_eq!(bytes[10], 48, "major opcode"); - assert_eq!( - &bytes[4..8], - &0xdead_beefu32.to_le_bytes(), - "bad fontable id" - ); - } - - fn named_color_body(name: &[u8]) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&0x2000_0001u32.to_le_bytes()); // cmap - body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); - body.extend_from_slice(&[0, 0]); // pad - body.extend_from_slice(name); - body - } - - fn free_colors_body(cmap: u32, plane_mask: u32, pixels: &[u32]) -> Vec { - let mut body = Vec::with_capacity(8 + pixels.len() * 4); - body.extend_from_slice(&cmap.to_le_bytes()); - body.extend_from_slice(&plane_mask.to_le_bytes()); - for pixel in pixels { - body.extend_from_slice(&pixel.to_le_bytes()); - } - body - } - - fn dispatch_free_colors(cmap: u32, plane_mask: u32, pixels: &[u32]) -> Vec { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = free_colors_body(cmap, plane_mask, pixels); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(0x1234), - RequestHeader { - opcode: 88, - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - assert!( - matches!(outcome, RequestOutcome::Handled), - "unexpected outcome: {outcome:?}" - ); - read_all_available(&mut peer) - } - - fn assert_free_colors_error(error: &[u8], code: u8, bad_value: u32) { - assert_eq!(error.len(), 32, "one fixed-size X11 error"); - assert_eq!(error[0], 0, "Error"); - assert_eq!(error[1], code); - assert_eq!(&error[2..4], &0x1234u16.to_le_bytes()); - assert_eq!(&error[4..8], &bad_value.to_le_bytes()); - assert_eq!(error[10], 88, "major opcode"); - } - - #[test] - fn free_colors_is_dispatched_as_a_successful_core_request() { - let output = dispatch_free_colors( - crate::resources::ROOT_COLORMAP.0, - 0, - &[0x00aa_bbcc, 0x0011_2233], - ); - assert!(output.is_empty(), "successful FreeColors is a void request"); - } - - #[test] - fn free_colors_accepts_valid_nonzero_plane_mask() { - let output = dispatch_free_colors( - crate::resources::ROOT_COLORMAP.0, - 0x0000_000f, - &[0x0011_2230], - ); - assert!(output.is_empty()); - } - - #[test] - fn free_colors_empty_pixel_list_ignores_outside_plane_mask() { - let output = dispatch_free_colors(crate::resources::ROOT_COLORMAP.0, 0xff00_0000, &[]); - assert!(output.is_empty()); - } - - #[test] - fn free_colors_argb_visual_accepts_alpha_bits() { - let output = dispatch_free_colors( - crate::resources::ARGB_COLORMAP.0, - 0x0f00_0000, - &[0xf011_2233], - ); - assert!(output.is_empty()); - } - - #[test] - fn free_colors_outside_plane_mask_returns_bad_value() { - let error = dispatch_free_colors( - crate::resources::ROOT_COLORMAP.0, - 0xff00_0000, - &[0x0011_2233], - ); - assert_free_colors_error(&error, x11::error::BAD_VALUE, 0xff11_2233); - } - - #[test] - fn free_colors_outside_pixel_bits_return_bad_value() { - let error = dispatch_free_colors(crate::resources::ROOT_COLORMAP.0, 0, &[0x8011_2233]); - assert_free_colors_error(&error, x11::error::BAD_VALUE, 0x8011_2233); - } - - #[test] - fn free_colors_unknown_colormap_returns_bad_colormap() { - let error = dispatch_free_colors(0xdead_beef, 0, &[0]); - assert_free_colors_error(&error, x11::error::BAD_COLORMAP, 0xdead_beef); - } - - #[test] - fn alloc_named_color_unknown_name_returns_bad_name() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = named_color_body(b"definitelynotacolor"); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 85, - data: 0, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); - assert_eq!(bytes[1], x11::error::BAD_NAME, "code"); - assert_eq!(bytes[10], 85, "major opcode"); - } - - #[test] - fn lookup_color_unknown_name_returns_bad_name() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = named_color_body(b"definitelynotacolor"); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 92, - data: 0, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); - assert_eq!(bytes[1], x11::error::BAD_NAME, "code"); - assert_eq!(bytes[10], 92, "major opcode"); - } - - #[test] - fn xi_get_focus_returns_real_focus_window() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Master keyboard (device 3) focused on a real window. The master - // keyboard's focus IS the core focus (Xorg: `inputInfo.keyboard-> - // focus`, which ProcSetInputFocus and ProcXIGetFocus share). - let win = 0x4000_0005u32; - state.core_focus = crate::server::CoreFocus { - raw: win, - revert_to: 0, - time: 0, - }; - // XIGetFocus { deviceid:CARD16=3 } + pad. - let header = RequestHeader { - opcode: 137, - data: 50, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[3u8, 0, 0, 0], - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert_eq!( - bytes.len(), - 32, - "XIGetFocus reply is 32 bytes: {bytes:02x?}" - ); - assert_eq!(bytes[0], 1, "X_Reply"); - assert_eq!(&bytes[8..12], &win.to_le_bytes(), "focus window @ byte 8"); - } - - #[test] - fn xi_get_focus_invalid_device_returns_bad_device() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // deviceid 0 = XIAllDevices: not a specific device → BadDevice. - let header = RequestHeader { - opcode: 137, - data: 50, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[0u8, 0, 0, 0], - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "expected error reply: {bytes:02x?}"); - assert_eq!(bytes[0], 0, "error packet"); - assert_eq!(bytes[1], XI1_ERROR_BAD_DEVICE, "BadDevice"); - assert_eq!(&bytes[8..10], &50u16.to_le_bytes(), "minor echoed"); - } - - // ── XIWarpPointer / XISetFocus / XIChangeHierarchy / XISelectEvents ── - // - // Expected values below are Xvfb 21.1.24 captures (raw-socket probe, - // little-endian client unless noted), cross-checked against - // Xi/xiwarppointer.c, Xi/xisetdevfocus.c, Xi/xichangehierarchy.c and - // Xi/xiselectev.c. - - /// Send one XInput request (major 137) from client 1 and return what - /// the client received. - fn send_xi_request( - state: &mut ServerState, - backend: &mut RecordingBackend, - peer: &mut UnixStream, - minor: u8, - body: &[u8], - ) -> Vec { - let header = RequestHeader { - opcode: 137, - data: minor, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }; - handle_xi2_request( - state, - backend, - None, - ClientId(1), - SequenceNumber(1), - header, - body, - ) - .expect("xi request"); - read_all_available(peer) - } - - fn assert_xi_error(bytes: &[u8], code: u8, value: u32, minor: u16) { - assert_eq!(bytes.len(), 32, "one error packet: {bytes:02x?}"); - assert_eq!(bytes[0], 0, "error packet: {bytes:02x?}"); - assert_eq!(bytes[1], code, "error code: {bytes:02x?}"); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - value, - "errorValue: {bytes:02x?}" - ); - assert_eq!( - u16::from_le_bytes(bytes[8..10].try_into().unwrap()), - minor, - "minor opcode: {bytes:02x?}" - ); - assert_eq!(bytes[10], XI2_MAJOR_OPCODE, "major opcode"); - } - - /// A mapped 100×100 child of the root at (100, 100), owned by client 1. - fn seed_mapped_window_at_100(state: &mut ServerState, xid: u32) { - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x: 100, - y: 100, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(xid)); - } - - fn fp1616(v: f64) -> i32 { - #[allow(clippy::cast_possible_truncation)] - let raw = (v * 65536.0).round() as i32; - raw - } - - #[allow(clippy::too_many_arguments)] - fn xi_warp_body( - src: u32, - dst: u32, - src_x: f64, - src_y: f64, - src_w: u16, - src_h: u16, - dst_x: f64, - dst_y: f64, - deviceid: u16, - ) -> Vec { - let mut b = Vec::with_capacity(32); - b.extend_from_slice(&src.to_le_bytes()); - b.extend_from_slice(&dst.to_le_bytes()); - b.extend_from_slice(&fp1616(src_x).to_le_bytes()); - b.extend_from_slice(&fp1616(src_y).to_le_bytes()); - b.extend_from_slice(&src_w.to_le_bytes()); - b.extend_from_slice(&src_h.to_le_bytes()); - b.extend_from_slice(&fp1616(dst_x).to_le_bytes()); - b.extend_from_slice(&fp1616(dst_y).to_le_bytes()); - b.extend_from_slice(&deviceid.to_le_bytes()); - b.extend_from_slice(&[0, 0]); - b - } - - #[allow(clippy::too_many_arguments)] - fn send_core_warp( - state: &mut ServerState, - backend: &mut RecordingBackend, - src: u32, - dst: u32, - src_x: i16, - src_y: i16, - src_w: u16, - src_h: u16, - dst_x: i16, - dst_y: i16, - ) { - let mut b = Vec::with_capacity(20); - b.extend_from_slice(&src.to_le_bytes()); - b.extend_from_slice(&dst.to_le_bytes()); - b.extend_from_slice(&src_x.to_le_bytes()); - b.extend_from_slice(&src_y.to_le_bytes()); - b.extend_from_slice(&src_w.to_le_bytes()); - b.extend_from_slice(&src_h.to_le_bytes()); - b.extend_from_slice(&dst_x.to_le_bytes()); - b.extend_from_slice(&dst_y.to_le_bytes()); - process_request( - state, - backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 41, - data: 0, - length_units: 6, - }, - &b, - None, - ) - .expect("WarpPointer"); - } - - #[test] - fn xi_warp_pointer_moves_to_truncated_fp1616_destination() { - // Xvfb: XIWarpPointer(dst=root, 10.75, 20.25) → pointer (10, 20); - // then relative (-0.5, -1.5) → (10, 19); relative (+0.99, +2.5) - // → (10, 21). ProcXIWarpPointer stores the FP16.16 values in - // ints, so the fraction truncates toward zero. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = xi_warp_body(0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 10.75, 20.25, 2); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert!(bytes.is_empty(), "XIWarpPointer has no reply: {bytes:02x?}"); - assert_eq!(backend.warped_to, Some((10, 20))); - - state.pointer_root = (10, 20); - let body = xi_warp_body(0, 0, 0.0, 0.0, 0, 0, -0.5, -1.5, 2); - let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_eq!(backend.warped_to, Some((10, 19))); - - state.pointer_root = (10, 19); - let body = xi_warp_body(0, 0, 0.0, 0.0, 0, 0, 0.99, 2.5, 2); - let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_eq!(backend.warped_to, Some((10, 21))); - } - - #[test] - fn xi_warp_pointer_to_window_and_clamped_to_the_screen() { - // Xvfb (1024×768): dst=W(100,100) (5, 6) → (105, 106); - // (-5.5, -6.5) → (95, 94); dst=root (5000, 5000) → (w-1, h-1); - // (-3, -3) → (0, 0). The test root is 800×600. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - const W: u32 = 0x0040_0001; - seed_mapped_window_at_100(&mut state, W); - for (dx, dy, want) in [(5.0, 6.0, (105, 106)), (-5.5, -6.5, (95, 94))] { - let body = xi_warp_body(0, W, 0.0, 0.0, 0, 0, dx, dy, 2); - let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_eq!(backend.warped_to, Some(want), "dst=W ({dx}, {dy})"); - } - for (dx, dy, want) in [ - (5000.0, 5000.0, (799, 599)), - (800.0, 600.0, (799, 599)), - (-3.0, -3.0, (0, 0)), - ] { - let body = xi_warp_body(0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, dx, dy, 2); - let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_eq!(backend.warped_to, Some(want), "dst=root ({dx}, {dy})"); - } - } - - #[test] - fn xi_warp_pointer_rejects_everything_but_the_master_pointer() { - // ProcXIWarpPointer: BadDevice unless the device is a master - // pointer or a floating slave (yserver has no floating slaves). - // errorValue = deviceid. Xvfb: devices 0,1,3,4,5,99 → BadDevice. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - for dev in [0u16, 1, 3, 4, 5, 99] { - let body = xi_warp_body(0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 5.0, 5.0, dev); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, u32::from(dev), 41); - } - // The device is checked before the windows. - let body = xi_warp_body(0, 0x00de_ad00, 0.0, 0.0, 0, 0, 5.0, 5.0, 3); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, 3, 41); - assert_eq!(backend.warped_to, None, "no rejected request may warp"); - } - - #[test] - fn xi_warp_pointer_bad_windows_report_dst_before_src() { - // Xvfb: dst bad → BadWindow(dst); src bad → BadWindow(src); both - // bad → BadWindow(dst). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = xi_warp_body(0, 0x00de_ad00, 0.0, 0.0, 0, 0, 5.0, 5.0, 2); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00de_ad00, 41); - let body = xi_warp_body(0x00be_ef00, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 5.0, 5.0, 2); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00be_ef00, 41); - let body = xi_warp_body(0x00be_ef00, 0x00de_ad00, 0.0, 0.0, 0, 0, 5.0, 5.0, 2); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00de_ad00, 41); - assert_eq!(backend.warped_to, None); - } - - #[test] - fn xi_warp_pointer_source_rectangle_follows_xorgs_xi_arithmetic() { - // Xorg keeps two copies of the source-rectangle test. The XI one - // compares the right edge against 0 instead of the pointer x - // (`winX + src_x + src_width < 0`), so with W at (100,100) 100×100 - // and src rect (0,0,10,10): - // pointer (160,105): XIWarpPointer WARPS, core WarpPointer doesn't; - // pointer (105,160): neither warps (the bottom edge is checked); - // pointer (105,110): XI warps (bottom edge inclusive). - // Both also require the pointer to be visible in the source window: - // pointer (50,50), src rect (-100,-100,0,0): no warp. - // The src coordinates truncate: pointer (104,104) with src_x 4.9 - // warps, with 5.0 doesn't; pointer (99,99) with -0.9 doesn't. - const W: u32 = 0x0040_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_mapped_window_at_100(&mut state, W); - let cases = [ - ((160_i16, 105_i16), (0.0, 0.0, 10_u16, 10_u16), true), - ((105, 160), (0.0, 0.0, 10, 10), false), - ((105, 110), (0.0, 0.0, 10, 10), true), - ((50, 50), (-100.0, -100.0, 0, 0), false), - ((104, 104), (4.9, 4.9, 0, 0), true), - ((104, 104), (5.0, 5.0, 0, 0), false), - ((99, 99), (-0.9, -0.9, 0, 0), false), - ]; - for (pointer, (sx, sy, sw, sh), warps) in cases { - let mut backend = RecordingBackend::new(); - state.pointer_root = pointer; - let body = xi_warp_body(W, ROOT_WINDOW.0, sx, sy, sw, sh, 300.0, 300.0, 2); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert!(bytes.is_empty(), "no error: {bytes:02x?}"); - assert_eq!( - backend.warped_to, - warps.then_some((300, 300)), - "pointer {pointer:?} src ({sx},{sy},{sw},{sh})" - ); - } - // src = root: always inside. - let mut backend = RecordingBackend::new(); - state.pointer_root = (50, 50); - let body = xi_warp_body(ROOT_WINDOW.0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 70.0, 70.0, 2); - let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); - assert_eq!(backend.warped_to, Some((70, 70))); - } - - #[test] - fn core_warp_pointer_source_rectangle_matches_xorg() { - // ProcWarpPointer (Xvfb): W at (100,100) 100×100, src rect - // (0,0,10,10): pointer (160,105) → no warp; (110,105) → warp (the - // right edge is inclusive: `winX + srcX + srcWidth < x`); - // (50,50) with src rect (-100,-100,0,0) → no warp (the pointer is - // not visible in W). Bad windows report dst before src. - const W: u32 = 0x0040_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_mapped_window_at_100(&mut state, W); - for (pointer, (sx, sy, sw, sh), warps) in [ - ((160, 105), (0, 0, 10, 10), false), - ((110, 105), (0, 0, 10, 10), true), - ((105, 110), (0, 0, 10, 10), true), - ((50, 50), (-100, -100, 0, 0), false), - ] { - let mut backend = RecordingBackend::new(); - state.pointer_root = pointer; - send_core_warp( - &mut state, - &mut backend, - W, - ROOT_WINDOW.0, - sx, - sy, - sw, - sh, - 300, - 300, - ); - assert_eq!( - backend.warped_to, - warps.then_some((300, 300)), - "pointer {pointer:?} src ({sx},{sy},{sw},{sh})" - ); - } - let mut backend = RecordingBackend::new(); - send_core_warp( - &mut state, - &mut backend, - 0x00be_ef00, - 0x00de_ad00, - 0, - 0, - 0, - 0, - 5, - 5, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_WINDOW); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - 0x00de_ad00, - "dst is looked up first" - ); - } - - fn xi_set_focus_body(focus: u32, time: u32, deviceid: u16) -> Vec { - let mut b = Vec::with_capacity(12); - b.extend_from_slice(&focus.to_le_bytes()); - b.extend_from_slice(&time.to_le_bytes()); - b.extend_from_slice(&deviceid.to_le_bytes()); - b.extend_from_slice(&[0, 0]); - b - } - - /// Split a byte stream into X packets (GenericEvents carry a tail). - fn split_packets(bytes: &[u8]) -> Vec<&[u8]> { - let mut out = Vec::new(); - let mut pos = 0; - while pos + 32 <= bytes.len() { - let mut len = 32; - if bytes[pos] & 0x7f == 35 || bytes[pos] == 1 { - len += 4 * u32::from_le_bytes(bytes[pos + 4..pos + 8].try_into().unwrap()) as usize; - } - out.push(&bytes[pos..pos + len]); - pos += len; - } - out - } - - #[test] - fn xi_set_focus_on_the_master_keyboard_is_core_set_input_focus() { - // Xvfb: XISetFocus(dev 3, W) → GetInputFocus = W with revert_to - // RevertToParent (ProcXISetFocus passes RevertToParent), XIGetFocus - // (3) = W, and the core + XI2 FocusIn/FocusOut chain is delivered. - const W: u32 = 0x0040_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_mapped_window_at_100(&mut state, W); - { - let client = state.clients.get_mut(&1).unwrap(); - client.event_masks.insert(ResourceId(W), FOCUS_CHANGE_MASK); - client - .xi2_masks - .insert((ResourceId(W), 0), (1 << 9) | (1 << 10)); - } - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(W, 0, 3), - ); - assert_eq!(state.core_focus.raw, W); - assert_eq!(state.core_focus.revert_to, 2, "RevertToParent"); - let packets = split_packets(&bytes); - assert!( - packets - .iter() - .any(|p| p[0] == 9 && u32::from_le_bytes(p[4..8].try_into().unwrap()) == W), - "core FocusIn on W: {packets:02x?}" - ); - assert!( - packets.iter().any(|p| p[0] == 35 - && u16::from_le_bytes(p[8..10].try_into().unwrap()) == 9 - && u32::from_le_bytes(p[24..28].try_into().unwrap()) == W), - "XI2 FocusIn on W: {packets:02x?}" - ); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[3, 0, 0, 0]); - assert_eq!(&bytes[8..12], &W.to_le_bytes(), "XIGetFocus(3) = W"); - - // Xvfb: None and PointerRoot are accepted and reported back. - for focus in [0u32, 1] { - let _ = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(focus, 0, 3), - ); - assert_eq!(state.core_focus.raw, focus); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[3, 0, 0, 0]); - let bytes = split_packets(&bytes).last().unwrap().to_vec(); - assert_eq!(&bytes[8..12], &focus.to_le_bytes()); - } - - // A time later than the server's clock is silently ignored. - let _ = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(W, 0x7fff_ffff, 3), - ); - assert_eq!(state.core_focus.raw, 1, "future-timestamp request ignored"); - } - - #[test] - fn xi_set_focus_errors_match_xorg() { - // Xvfb: devices without a focus class (the pointers) and unknown - // ids → BadDevice, errorValue 0 (ProcXISetFocus sets none); a - // missing window → BadWindow; an unviewable one → BadMatch with - // the window as errorValue. - const UNMAPPED: u32 = 0x0040_0002; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(UNMAPPED), - parent: ROOT_WINDOW, - width: 10, - height: 10, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - for dev in [0u16, 1, 2, 4, 99] { - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(ROOT_WINDOW.0, 0, dev), - ); - assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, 0, 49); - } - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(0x00de_ad00, 0, 3), - ); - assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00de_ad00, 49); - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(UNMAPPED, 0, 3), - ); - assert_xi_error(&bytes, x11::error::BAD_MATCH, UNMAPPED, 49); - // FollowKeyboard on the master keyboard itself would make it - // follow itself (Xvfb segfaults on it); yserver rejects it. - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(3, 0, 3), - ); - assert_xi_error(&bytes, x11::error::BAD_VALUE, 3, 49); - assert_eq!(state.core_focus.raw, 1, "focus untouched by errors"); - } - - #[test] - fn xi_set_focus_on_the_slave_keyboard_sets_its_own_focus() { - // Xvfb: XISetFocus(dev 5, W) leaves the core focus alone and - // XIGetFocus(5) = W; FollowKeyboard (3) is accepted on a slave - // and reported back as 3. - const W: u32 = 0x0040_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_mapped_window_at_100(&mut state, W); - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(W, 0, 5), - ); - assert!(bytes.is_empty(), "{bytes:02x?}"); - assert_eq!(state.core_focus.raw, 1, "core focus unchanged"); - let f = crate::core_loop::xi1_focus::device_focus(&state, 5); - assert_eq!((f.focus, f.revert_to), (W, 2)); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[5, 0, 0, 0]); - assert_eq!(&bytes[8..12], &W.to_le_bytes()); - let _ = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 49, - &xi_set_focus_body(3, 0, 5), - ); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[5, 0, 0, 0]); - assert_eq!(&bytes[8..12], &3u32.to_le_bytes(), "FollowKeyboard"); - } - - #[test] - fn xi_get_focus_rejects_pointer_devices() { - // Xvfb: XIGetFocus on devices without a focus class (2, 4) → - // BadDevice, errorValue 0. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - for dev in [2u8, 4] { - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[dev, 0, 0, 0]); - assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, 0, 50); - } - } - - fn xi_hierarchy_body(num_changes: u8, changes: &[&[u8]]) -> Vec { - let mut b = vec![num_changes, 0, 0, 0]; - for c in changes { - b.extend_from_slice(c); - } - b - } - - fn le_u16s(values: &[u16]) -> Vec { - values.iter().flat_map(|v| v.to_le_bytes()).collect() - } - - fn remove_master_change(dev: u16, mode: u8) -> Vec { - let mut c = le_u16s(&[2, 3, dev]); - c.extend_from_slice(&[mode, 0]); - c.extend_from_slice(&le_u16s(&[2, 3])); - c - } - - #[test] - fn xi_change_hierarchy_answers_like_xorg_for_the_fixed_devices() { - // Every row is an Xvfb 21.1.24 capture. Xvfb's devices 4/5 are the - // XTest slaves, which Xorg refuses to attach/detach ("these are - // fixed"); yserver's 4/5 are fixed too, so the answers match - // device-for-device. `None` = Success (no reply, no event). - const BAD_DEVICE: u8 = XI1_ERROR_BAD_DEVICE; - let attach = |dev: u16, master: u16| le_u16s(&[3, 2, dev, master]); - let detach = |dev: u16| le_u16s(&[4, 2, dev, 0]); - // (label, request body, expected error (code, errorValue)). - type Case = (&'static str, Vec, Option<(u8, u32)>); - let cases: Vec = vec![ - ("empty", xi_hierarchy_body(0, &[]), None), - ( - "remove 2 float", - xi_hierarchy_body(1, &[&remove_master_change(2, 2)]), - Some((BAD_DEVICE, 0)), - ), - ( - "remove 3 attach", - xi_hierarchy_body(1, &[&remove_master_change(3, 1)]), - Some((BAD_DEVICE, 0)), - ), - ( - "remove 2 mode 5", - xi_hierarchy_body(1, &[&remove_master_change(2, 5)]), - Some((x11::error::BAD_VALUE, 0)), - ), - ( - "remove 4", - xi_hierarchy_body(1, &[&remove_master_change(4, 2)]), - Some((BAD_DEVICE, 4)), - ), - ( - "remove 99", - xi_hierarchy_body(1, &[&remove_master_change(99, 2)]), - Some((BAD_DEVICE, 0)), - ), - ( - "remove 0", - xi_hierarchy_body(1, &[&remove_master_change(0, 2)]), - Some((BAD_DEVICE, 0)), - ), - ( - "attach 4->2", - xi_hierarchy_body(1, &[&attach(4, 2)]), - Some((BAD_DEVICE, 4)), - ), - ( - "attach 4->3", - xi_hierarchy_body(1, &[&attach(4, 3)]), - Some((BAD_DEVICE, 4)), - ), - ( - "attach 5->3", - xi_hierarchy_body(1, &[&attach(5, 3)]), - Some((BAD_DEVICE, 5)), - ), - ( - "attach 2->3", - xi_hierarchy_body(1, &[&attach(2, 3)]), - Some((BAD_DEVICE, 2)), - ), - ( - "attach 99->2", - xi_hierarchy_body(1, &[&attach(99, 2)]), - Some((BAD_DEVICE, 0)), - ), - ( - "detach 4", - xi_hierarchy_body(1, &[&detach(4)]), - Some((BAD_DEVICE, 4)), - ), - ( - "detach 5", - xi_hierarchy_body(1, &[&detach(5)]), - Some((BAD_DEVICE, 5)), - ), - ( - "detach 2", - xi_hierarchy_body(1, &[&detach(2)]), - Some((BAD_DEVICE, 2)), - ), - ( - "detach 99", - xi_hierarchy_body(1, &[&detach(99)]), - Some((BAD_DEVICE, 0)), - ), - ( - "unknown type skipped", - xi_hierarchy_body(1, &[&le_u16s(&[9, 1])]), - None, - ), - ( - "unknown then remove 2", - xi_hierarchy_body(2, &[&le_u16s(&[9, 1]), &remove_master_change(2, 2)]), - Some((BAD_DEVICE, 0)), - ), - ( - "remove with length 2", - xi_hierarchy_body(1, &[&le_u16s(&[2, 2, 2, 2, 0, 3])]), - Some((x11::error::BAD_LENGTH, 0)), - ), - ( - "attach with length 3", - xi_hierarchy_body(1, &[&le_u16s(&[3, 3, 4, 2, 0, 0])]), - Some((x11::error::BAD_LENGTH, 0)), - ), - ( - "num_changes 2, one change", - xi_hierarchy_body(2, &[&remove_master_change(2, 2)]), - Some((BAD_DEVICE, 0)), - ), - ( - "change length past the request", - xi_hierarchy_body(1, &[&le_u16s(&[3, 9, 4, 2])]), - Some((x11::error::BAD_LENGTH, 0)), - ), - ( - "add master, name longer than the request", - xi_hierarchy_body(1, &[&[1, 0, 2, 0, 4, 0, 1, 1]]), - Some((x11::error::BAD_LENGTH, 0)), - ), - ]; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - for (label, body, want) in cases { - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 43, &body); - match want { - None => assert!(bytes.is_empty(), "{label}: {bytes:02x?}"), - Some((code, value)) => { - assert!(!bytes.is_empty(), "{label}: expected an error"); - assert_eq!(bytes[1], code, "{label}: {bytes:02x?}"); - assert_xi_error(&bytes, code, value, 43); - } - } - } - } - - #[test] - fn xi_change_hierarchy_add_master_is_refused_with_bad_alloc() { - // Xorg creates the pair; yserver's device set is fixed, so it - // answers the way Xorg does when it cannot allocate a device - // (AllocDevicePair → BadAlloc) and sends no HierarchyChanged. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state - .clients - .get_mut(&1) - .unwrap() - .xi2_masks - .insert((ROOT_WINDOW, 0), 1 << 11); - let mut add = le_u16s(&[1, 3, 3]); - add.extend_from_slice(&[1, 1]); - add.extend_from_slice(b"foo\0"); - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 43, - &xi_hierarchy_body(1, &[&add]), - ); - assert_xi_error(&bytes, x11::error::BAD_ALLOC, 0, 43); - } - - #[test] - fn xi_change_hierarchy_reads_changes_in_client_byte_order() { - // The change list is opaque to the request swapper; a big-endian - // client's AttachSlave(4 → 2) must still name device 4. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.clients.get_mut(&1).unwrap().byte_order = ClientByteOrder::BigEndian; - let change: Vec = [3u16, 2, 4, 2] - .iter() - .flat_map(|v| v.to_be_bytes()) - .collect(); - let bytes = send_xi_request( - &mut state, - &mut backend, - &mut peer, - 43, - &xi_hierarchy_body(1, &[&change]), - ); - assert_eq!(bytes[1], XI1_ERROR_BAD_DEVICE, "{bytes:02x?}"); - assert_eq!(&bytes[4..8], &4u32.to_be_bytes(), "errorValue = device 4"); - } - - #[test] - fn xi_unknown_minor_is_bad_request() { - // Xvfb: XI minors 0, 62, 200, 255 → BadRequest (ProcIDispatch). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - for minor in [0u8, 62, 200, 255] { - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, minor, &[0; 8]); - assert_xi_error(&bytes, x11::error::BAD_REQUEST, 0, u16::from(minor)); - } - } - - fn xi_select_body(window: u32, masks: &[(u16, &[u32])]) -> Vec { - let mut b = Vec::new(); - b.extend_from_slice(&window.to_le_bytes()); - b.extend_from_slice(&u16::try_from(masks.len()).unwrap().to_le_bytes()); - b.extend_from_slice(&[0, 0]); - for (dev, words) in masks { - b.extend_from_slice(&dev.to_le_bytes()); - b.extend_from_slice(&u16::try_from(words.len()).unwrap().to_le_bytes()); - for w in *words { - // Event masks are bit arrays: byte i holds bits 8i..8i+7. - b.extend_from_slice(&w.to_le_bytes()); - } - } - b - } - - #[test] - fn xi_select_events_keeps_bit_32_and_rejects_bits_past_the_last_event() { - // Xvfb: select dev 2 = {2, 30, 31, 32} (mask_len 2) + dev 3 = {3}; - // XIGetSelectedEvents returns exactly - // 02000200 040000c0 01000000 03000100 08000000 - // (masks in device order, trailing zero words trimmed). Selecting - // bit 33 → BadValue(33), bit 69 → BadValue(69), and the rejected - // request changes nothing. - const W: u32 = 0x0040_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_mapped_window_at_100(&mut state, W); - let lo = (1u32 << 2) | (1 << 30) | (1 << 31); - let body = xi_select_body(W, &[(2, &[lo, 1]), (3, &[1 << 3])]); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); - assert!(bytes.is_empty(), "{bytes:02x?}"); - let expected_tail: [u8; 20] = [ - 0x02, 0x00, 0x02, 0x00, 0x04, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, - 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, - ]; - let reply = send_xi_request(&mut state, &mut backend, &mut peer, 60, &W.to_le_bytes()); - assert_eq!(reply.len(), 52, "{reply:02x?}"); - assert_eq!(&reply[4..8], &5u32.to_le_bytes(), "reply length"); - assert_eq!(&reply[8..10], &2u16.to_le_bytes(), "num_masks"); - assert_eq!(&reply[32..], &expected_tail); - - let body = xi_select_body(W, &[(2, &[0, 1 << 1])]); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); - assert_xi_error(&bytes, x11::error::BAD_VALUE, 33, 46); - let body = xi_select_body(W, &[(2, &[1 << 2, 0, 1 << 5])]); - let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); - assert_xi_error(&bytes, x11::error::BAD_VALUE, 69, 46); - let reply = send_xi_request(&mut state, &mut backend, &mut peer, 60, &W.to_le_bytes()); - assert_eq!( - &reply[32..], - &expected_tail, - "rejected selects applied nothing" - ); - } - - #[test] - fn xi_get_selected_events_header_fields_use_client_byte_order() { - // Xvfb, big-endian client, same selection as above: - // 00020002 040000c0 01000000 00030001 08000000 - // deviceid/mask_len/num_masks swap; the mask bytes don't. - const W: u32 = 0x0040_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_mapped_window_at_100(&mut state, W); - state.clients.get_mut(&1).unwrap().byte_order = ClientByteOrder::BigEndian; - let lo = (1u32 << 2) | (1 << 30) | (1 << 31); - // Request bodies reach the handler already swapped to LE. - let body = xi_select_body(W, &[(2, &[lo, 1]), (3, &[1 << 3])]); - let _ = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); - let reply = send_xi_request(&mut state, &mut backend, &mut peer, 60, &W.to_le_bytes()); - assert_eq!(&reply[4..8], &5u32.to_be_bytes(), "reply length"); - assert_eq!(&reply[8..10], &2u16.to_be_bytes(), "num_masks"); - assert_eq!( - &reply[32..], - &[ - 0x00, 0x02, 0x00, 0x02, 0x04, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x03, - 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, - ] - ); - } - - #[test] - fn xi_get_device_key_mapping_matches_core_keyboard_mapping() { - // yserver models a single keyboard, so XI1 GetDeviceKeyMapping on - // a key-class device must surface the same keysyms a client reads - // via core GetKeyboardMapping (Xorg drives both from - // XkbGetCoreMap). Inject deterministic ChangeKeyboardMapping rows - // and assert the two replies carry identical map data. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // RecordingBackend reports keysyms-per-keycode = 2; match it. - state.keymap_overrides.insert(10, vec![0x0061, 0x0041]); - state.keymap_overrides.insert(11, vec![0x0062, 0x0042]); - - // Core GetKeyboardMapping { first=10, count=2 }. - handle_get_keyboard_mapping( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &[10u8, 2], - ) - .expect("core"); - let core = read_all_available(&mut peer); - // byte[1] = keysyms-per-keycode; payload from byte 32. - let core_kpc = core[1]; - let core_syms = core[32..].to_vec(); - - // XI1 GetDeviceKeyMapping on master keyboard (device 3), - // { deviceid=3, first=10, count=2 }. - let header = RequestHeader { - opcode: 137, - data: 24, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - header, - &[3u8, 10, 2, 0], - ) - .expect("xi1"); - let xi = read_all_available(&mut peer); - - assert_eq!(xi[0], 1, "X_Reply"); - assert_eq!(xi[1], 24, "RepType = X_GetDeviceKeyMapping"); - // byte[8] = keysyms-per-keycode for XI1 (vs byte[1] for core). - assert_eq!(xi[8], core_kpc, "XI1 kpc matches core kpc"); - assert_eq!( - &xi[32..], - &core_syms[..], - "XI1 device keymap payload matches core keyboard mapping" - ); - // And the injected keysyms actually came through. - let expect: Vec = [0x0061u32, 0x0041, 0x0062, 0x0042] - .iter() - .flat_map(|k| k.to_le_bytes()) - .collect(); - assert_eq!(&xi[32..], &expect[..], "injected keysyms surfaced"); - } - - #[test] - fn xi_get_device_key_mapping_on_pointer_device_is_bad_match() { - // Device 2 is the master pointer — no key class → BadMatch - // (Xorg getkmap.c: dev->key == NULL → BadMatch). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 137, - data: 24, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[2u8, 8, 1, 0], - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0, "error packet"); - assert_eq!(bytes[1], x11::error::BAD_MATCH, "BadMatch"); - } - - #[test] - fn xi_change_device_key_mapping_round_trips_via_get() { - // XI1 ChangeDeviceKeyMapping (minor 25) must write the same - // `keymap_overrides` rows that GetDeviceKeyMapping (minor 24) / - // core GetKeyboardMapping read back — Xorg drives both off the - // shared XkbGetCoreMap. Regression for the XTS - // `XChangeDeviceKeyMapping-3` round-trip that used to fail - // because minor 25 emitted MappingNotify but never stored. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // ChangeDeviceKeyMapping { deviceid=3, first=10, kpk=2, count=2 } - // with fresh keysyms (distinct from any read-path defaults). - let mut body: Vec = vec![3, 10, 2, 2]; - for k in [0x0078u32, 0x0058, 0x0079, 0x0059] { - body.extend_from_slice(&k.to_le_bytes()); - } - let header = RequestHeader { - opcode: 137, - data: 25, - length_units: 2 + 2 * 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &body, - ) - .expect("change"); - // Drain the MappingNotify the change fans out. - let _ = read_all_available(&mut peer); - - // The override store now reflects the write. - assert_eq!( - state.keymap_overrides.get(&10), - Some(&vec![0x0078u32, 0x0058]) - ); - assert_eq!( - state.keymap_overrides.get(&11), - Some(&vec![0x0079u32, 0x0059]) - ); - - // GetDeviceKeyMapping { deviceid=3, first=10, count=2 } surfaces it. - let header = RequestHeader { - opcode: 137, - data: 24, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - header, - &[3u8, 10, 2, 0], - ) - .expect("get"); - let xi = read_all_available(&mut peer); - assert_eq!(xi[0], 1, "X_Reply"); - assert_eq!(xi[1], 24, "RepType = X_GetDeviceKeyMapping"); - let expect: Vec = [0x0078u32, 0x0058, 0x0079, 0x0059] - .iter() - .flat_map(|k| k.to_le_bytes()) - .collect(); - assert_eq!( - &xi[32..32 + expect.len()], - &expect[..], - "written keysyms read back" - ); - } - - #[test] - fn xi_get_device_motion_events_pointer_returns_history() { - let mut state = ServerState::new(); - state.start_instant = std::time::Instant::now() - std::time::Duration::from_secs(1); - state - .pointer_motion_history - .push_back(crate::server::PointerMotionRecord { - time: 500, - root_x: 120, - root_y: 45, - }); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 137, - data: 10, - length_units: 4, - }; - // { start:CARD32, stop:CARD32, deviceid@8 }. - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[144, 1, 0, 0, 88, 2, 0, 0, 2, 0, 0, 0], // 400..600 - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 52); - assert_eq!(bytes[0], 1, "X_Reply"); - assert_eq!(bytes[1], 10, "RepType = X_GetDeviceMotionEvents"); - assert_eq!(&bytes[8..12], &1u32.to_le_bytes(), "nEvents"); - assert_eq!(bytes[12], XI1_POINTER_AXES, "axes = device valuator count"); - assert_eq!(bytes[13], 1, "mode = Absolute"); - assert_eq!(u32::from_le_bytes(bytes[32..36].try_into().unwrap()), 500); - assert_eq!(i32::from_le_bytes(bytes[36..40].try_into().unwrap()), 120); - assert_eq!(i32::from_le_bytes(bytes[40..44].try_into().unwrap()), 45); - } - - #[test] - fn xi_get_device_motion_events_keyboard_is_bad_match() { - // Device 3 = master keyboard (no valuators) → BadMatch - // (Xorg gtmotion.c: v == NULL → BadMatch). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 137, - data: 10, - length_units: 4, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0], - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0, "error packet"); - assert_eq!(bytes[1], x11::error::BAD_MATCH, "BadMatch"); - } - - #[test] - fn xi_get_feedback_control_kbd_mirrors_keyboard_control() { - // The XI1 KbdFeedbackState must carry the same bell/click/LED - // state as core GetKeyboardControl (Xorg: the KbdFeedback ctrl - // *is* the keyboard control). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.keyboard_control.bell_pitch = 0x0321; - state.keyboard_control.bell_duration = 0x0654; - state.keyboard_control.bell_percent = 77; - state.keyboard_control.key_click_percent = 42; - state.keyboard_control.led_mask = 0x0000_0003; - state.keyboard_control.global_auto_repeat = true; - - // GetFeedbackControl { deviceid=3 } (master keyboard). - let header = RequestHeader { - opcode: 137, - data: 22, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[3u8, 0, 0, 0], - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 1, "X_Reply"); - assert_eq!(bytes[1], 22, "RepType"); - assert_eq!(&bytes[8..10], &1u16.to_le_bytes(), "num_feedbacks"); - // KbdFeedbackState begins at byte 32. - let kbd = &bytes[32..]; - assert_eq!(kbd[0], 0, "KbdFeedbackClass"); - assert_eq!(&kbd[4..6], &0x0321u16.to_le_bytes(), "pitch == bell_pitch"); - assert_eq!(&kbd[6..8], &0x0654u16.to_le_bytes(), "duration"); - assert_eq!(&kbd[8..12], &0x0000_0003u32.to_le_bytes(), "led_mask"); - assert_eq!(kbd[16], 1, "global_auto_repeat"); - assert_eq!(kbd[17], 42, "click == key_click_percent"); - assert_eq!(kbd[18], 77, "percent == bell_percent"); - } - - #[test] - fn xi_get_feedback_control_ptr_mirrors_pointer_control() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.pointer_control.accel_numerator = 5; - state.pointer_control.accel_denominator = 3; - state.pointer_control.threshold = 9; - - // GetFeedbackControl { deviceid=2 } (master pointer). - let header = RequestHeader { - opcode: 137, - data: 22, - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[2u8, 0, 0, 0], - ) - .expect("process"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], 22, "RepType"); - assert_eq!(&bytes[8..10], &1u16.to_le_bytes(), "num_feedbacks"); - let ptr = &bytes[32..]; - assert_eq!(ptr[0], 1, "PtrFeedbackClass"); - assert_eq!(&ptr[6..8], &5u16.to_le_bytes(), "accelNum"); - assert_eq!(&ptr[8..10], &3u16.to_le_bytes(), "accelDenom"); - assert_eq!(&ptr[10..12], &9u16.to_le_bytes(), "threshold"); - } - - #[test] - fn xi_change_keyboard_feedback_updates_shared_control_atomically() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = vec![0; 28]; - body[0..4].copy_from_slice(&0x1fu32.to_le_bytes()); - body[4] = 3; // key device - body[5] = 0; // KbdFeedbackClass - body[9] = 0; // feedback id - body[10..12].copy_from_slice(&20u16.to_le_bytes()); - body[14] = 42; - body[15] = 77; - body[16..18].copy_from_slice(&801i16.to_le_bytes()); - body[18..20].copy_from_slice(&321i16.to_le_bytes()); - body[20..24].copy_from_slice(&3u32.to_le_bytes()); - body[24..28].copy_from_slice(&2u32.to_le_bytes()); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(23, &body), - &body, - ) - .unwrap(); - assert_eq!(state.keyboard_control.key_click_percent, 42); - assert_eq!(state.keyboard_control.bell_percent, 77); - assert_eq!(state.keyboard_control.bell_pitch, 801); - assert_eq!(state.keyboard_control.bell_duration, 321); - assert_eq!(state.keyboard_control.led_mask, 2); - - let before = state.keyboard_control.clone(); - body[14] = 10; - body[15] = 101; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header_for_body(23, &body), - &body, - ) - .unwrap(); - assert_eq!( - state.keyboard_control.key_click_percent, - before.key_click_percent - ); - assert_eq!(state.keyboard_control.bell_percent, before.bell_percent); - } - - #[test] - fn xi_change_pointer_feedback_updates_shared_control() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = vec![0; 20]; - body[0..4].copy_from_slice(&7u32.to_le_bytes()); - body[4] = 2; // pointer device - body[5] = 1; // PtrFeedbackClass - body[8] = 1; - body[9] = 0; - body[10..12].copy_from_slice(&12u16.to_le_bytes()); - body[14..16].copy_from_slice(&5i16.to_le_bytes()); - body[16..18].copy_from_slice(&3i16.to_le_bytes()); - body[18..20].copy_from_slice(&9i16.to_le_bytes()); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(23, &body), - &body, - ) - .unwrap(); - assert_eq!(state.pointer_control.accel_numerator, 5); - assert_eq!(state.pointer_control.accel_denominator, 3); - assert_eq!(state.pointer_control.threshold, 9); - } - - #[test] - fn xi_change_device_resolution_zero_round_trips() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut change = vec![0; 16]; - change[0..2].copy_from_slice(&1u16.to_le_bytes()); - change[2] = 2; - change[4..6].copy_from_slice(&1u16.to_le_bytes()); - change[6..8].copy_from_slice(&12u16.to_le_bytes()); - change[8] = 0; - change[9] = 1; - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(35, &change), - &change, - ) - .unwrap(); - let change_reply = read_all_available(&mut peer); - assert_eq!(change_reply[0], 1); - assert_eq!(change_reply[8], 0, "Success"); - - let get = [1, 0, 2, 0]; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header_for_body(34, &get), - &get, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 88); - assert_eq!(u32::from_le_bytes(wire[36..40].try_into().unwrap()), 4); - for value in wire[40..].chunks_exact(4) { - assert_eq!(u32::from_le_bytes(value.try_into().unwrap()), 0); - } - } - - #[test] - fn xi1_device_bell_rejects_feedback_without_bell_proc() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Device 3 advertises KbdFeedback id 0, but yserver has no audible - // BellProc. Xorg Xi/devbell.c returns BadValue in this case. - let body = [3, 0, 0, 50]; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(7), - xi2_header_for_body(32, &body), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "X error"); - assert_eq!(wire[1], x11::error::BAD_VALUE); - assert_eq!(u16::from_le_bytes(wire[2..4].try_into().unwrap()), 7); - assert_eq!(u16::from_le_bytes(wire[8..10].try_into().unwrap()), 32); - assert_eq!(wire[10], XI2_MAJOR_OPCODE); - } - - #[test] - fn xi1_device_bell_validates_percent_before_feedback_class() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Both percent=101 and feedbackclass=99 are invalid. Xorg reports - // the percent first and places its raw CARD8 value in errorValue. - let body = [3, 0, 99, 101]; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(8), - xi2_header_for_body(32, &body), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire[1], x11::error::BAD_VALUE); - assert_eq!(u32::from_le_bytes(wire[4..8].try_into().unwrap()), 101); - } - - fn randr_unimplemented_reply_bearing(minor: u8) -> Vec { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 128, - data: minor, - length_units: 1, - }; - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[], - ) - .expect("process"); - read_all_available(&mut peer) - } - - fn randr_transform_body(crtc: u32, matrix: [i32; 9], filter_name: &[u8]) -> Vec { - let mut body = Vec::with_capacity(44 + filter_name.len().next_multiple_of(4)); - body.extend_from_slice(&crtc.to_le_bytes()); - for cell in matrix { - body.extend_from_slice(&cell.to_le_bytes()); - } - body.extend_from_slice(&(filter_name.len() as u16).to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(filter_name); - body.resize(body.len().next_multiple_of(4), 0); - body - } - - fn randr_panning_body(crtc: u32, width: u16, height: u16) -> Vec { - let mut body = vec![0u8; 32]; - body[0..4].copy_from_slice(&crtc.to_le_bytes()); - body[12..14].copy_from_slice(&width.to_le_bytes()); - body[14..16].copy_from_slice(&height.to_le_bytes()); - body - } - - fn randr_provider(provider_id: u32, capabilities: u32) -> crate::randr::RandrProvider { - crate::randr::RandrProvider { - provider_id, - name: format!("card{provider_id}"), - capabilities, - is_gpu: true, - crtcs: Vec::new(), - outputs: Vec::new(), - associations: Vec::new(), - } - } - - fn randr_provider_request_body(minor: u8, provider: u32) -> Vec { - use yserver_protocol::x11::randr as x11randr; - - let mut body = Vec::new(); - body.extend_from_slice(&provider.to_le_bytes()); - match minor { - x11randr::RR_GET_PROVIDER_INFO => { - body.extend_from_slice(&0u32.to_le_bytes()); - } - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK | x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE => { - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - } - x11randr::RR_LIST_PROVIDER_PROPERTIES => {} - x11randr::RR_QUERY_PROVIDER_PROPERTY | x11randr::RR_DELETE_PROVIDER_PROPERTY => { - body.extend_from_slice(&0u32.to_le_bytes()); - } - x11randr::RR_CONFIGURE_PROVIDER_PROPERTY => { - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&[0u8; 4]); - } - x11randr::RR_CHANGE_PROVIDER_PROPERTY => { - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&[8, 0, 0, 0]); - body.extend_from_slice(&0u32.to_le_bytes()); - } - x11randr::RR_GET_PROVIDER_PROPERTY => { - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&[0u8; 4]); - } - _ => panic!("not a provider request minor: {minor}"), - } - body - } - - fn randr_output_source_body(provider: u32, source_provider: u32, timestamp: u32) -> Vec { - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&provider.to_le_bytes()); - body.extend_from_slice(&source_provider.to_le_bytes()); - body.extend_from_slice(×tamp.to_le_bytes()); - body - } - - #[test] - fn randr_create_mode_unimplemented_returns_error_not_hang() { - // RRCreateMode (minor 16): reply-bearing, unimplemented → error. - let bytes = randr_unimplemented_reply_bearing(16); - assert!( - bytes.len() >= 32, - "expected error, not a hang: {bytes:02x?}" - ); - assert_eq!(bytes[1], x11::error::BAD_IMPLEMENTATION, "code"); - assert_eq!(&bytes[8..10], &16u16.to_le_bytes(), "minor"); - assert_eq!(bytes[10], 128, "major = RANDR"); - } - - #[test] - fn randr_crtc_setters_reject_short_bodies_with_bad_length() { - for minor in [ - yserver_protocol::x11::randr::RR_SET_CRTC_TRANSFORM, - yserver_protocol::x11::randr::RR_SET_PANNING, - ] { - let bytes = randr_unimplemented_reply_bearing(minor); - assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); - assert_eq!(bytes[1], x11::error::BAD_LENGTH, "minor {minor} code"); - assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); - assert_eq!(bytes[10], 128, "major = RANDR"); - } - } - - #[test] - fn randr_create_lease_unimplemented_returns_error_not_hang() { - // RRCreateLease (minor 45): reply-bearing, unimplemented → error. - let bytes = randr_unimplemented_reply_bearing(45); - assert!( - bytes.len() >= 32, - "expected error, not a hang: {bytes:02x?}" - ); - assert_eq!(bytes[1], x11::error::BAD_IMPLEMENTATION, "code"); - assert_eq!(&bytes[8..10], &45u16.to_le_bytes(), "minor"); - assert_eq!(bytes[10], 128, "major = RANDR"); - } - - #[test] - fn randr_unsupported_warning_latch_is_per_minor() { - let mut state = ServerState::new(); - assert!(mark_randr_unsupported_warned(&mut state, 18)); - assert!(!mark_randr_unsupported_warned(&mut state, 18)); - assert!(mark_randr_unsupported_warned(&mut state, 19)); - } - - #[test] - fn randr_set_crtc_transform_accepts_only_direct_identity_state() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let crtc = state.randr.outputs[0].crtc_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let identity = [0x0001_0000, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x0001_0000]; - let header = RequestHeader { - opcode: 128, - data: x11randr::RR_SET_CRTC_TRANSFORM, - length_units: 12, - }; - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &randr_transform_body(crtc, identity, &[]), - ) - .expect("identity transform"); - assert!(read_all_available(&mut peer).is_empty(), "void no-op"); - assert_eq!( - state.randr_unsupported_warned_mask & (1 << x11randr::RR_SET_CRTC_TRANSFORM), - 0, - ); - - // An identity filter is harmless and remains a wire-success no-op, - // but its parameters are not retained for GetCrtcTransform, so even - // an empty filter name with a parameter tail must warn. - let mut parameter_only = randr_transform_body(crtc, identity, &[]); - parameter_only.extend_from_slice(&0x0001_0000i32.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - length_units: 13, - ..header - }, - ¶meter_only, - ) - .expect("identity transform with filter parameter"); - assert!(read_all_available(&mut peer).is_empty(), "void no-op"); - assert_ne!( - state.randr_unsupported_warned_mask & (1 << x11randr::RR_SET_CRTC_TRANSFORM), - 0, - ); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - RequestHeader { - length_units: 13, - ..header - }, - &randr_transform_body(crtc, identity, b"box"), - ) - .expect("identity transform with named filter"); - assert!(read_all_available(&mut peer).is_empty(), "void no-op"); - - let mut projective = identity; - projective[6] = 1; - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(4), - header, - &randr_transform_body(crtc, projective, &[]), - ) - .expect("reject non-identity transform"); - let error = read_all_available(&mut peer); - assert_eq!(error.len(), 32); - assert_eq!(error[0], 0); - assert_eq!(error[1], x11::error::BAD_MATCH); - assert_eq!(u32::from_le_bytes(error[4..8].try_into().unwrap()), crtc); - assert_eq!(&error[8..10], &u16::from(header.data).to_le_bytes()); - assert_eq!(error[10], 128); - } - - #[test] - fn randr_set_panning_accepts_disabled_and_refuses_active_viewport() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let crtc = state.randr.outputs[0].crtc_id; - let timestamp = state.randr.timestamp; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 128, - data: x11randr::RR_SET_PANNING, - length_units: 9, - }; - - let mut disabled = randr_panning_body(crtc, 0, 0); - disabled[8..10].copy_from_slice(&15u16.to_le_bytes()); - disabled[24..26].copy_from_slice(&(-3i16).to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &disabled, - ) - .expect("disabled panning"); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - header, - &randr_panning_body(crtc, 1920, 1080), - ) - .expect("active panning refusal"); - - let replies = read_all_available(&mut peer); - assert_eq!(replies.len(), 64); - assert_eq!(replies[0], 1); - assert_eq!(replies[1], x11randr::SET_CONFIG_SUCCESS); - assert_eq!( - u32::from_le_bytes(replies[8..12].try_into().unwrap()), - timestamp - ); - assert_eq!(replies[32], 1); - assert_eq!(replies[33], x11randr::SET_CONFIG_FAILED); - assert_ne!( - state.randr_unsupported_warned_mask & (1 << x11randr::RR_SET_PANNING), - 0, - ); - } - - #[test] - fn randr_provider_queries_report_sorted_topology_in_both_byte_orders() { - use yserver_protocol::x11::randr as x11randr; - - for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { - let mut state = ServerState::new(); - state.randr.set_providers(vec![ - randr_provider(20, 0), - crate::randr::RandrProvider { - name: "card0".to_string(), - capabilities: x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT, - crtcs: vec![2], - outputs: vec![1], - associations: vec![crate::randr::RandrProviderAssociation { - provider_id: 20, - capability: x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT, - }], - ..randr_provider(10, 0) - }, - ]); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").byte_order = byte_order; - let mut backend = RecordingBackend::new(); - - let mut providers_body = match byte_order { - ClientByteOrder::LittleEndian => ROOT_WINDOW.0.to_le_bytes().to_vec(), - ClientByteOrder::BigEndian => ROOT_WINDOW.0.to_be_bytes().to_vec(), - }; - yserver_protocol::x11::request_swap::swap_request_body( - 128, - x11randr::RR_GET_PROVIDERS, - byte_order, - &mut providers_body, - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: x11randr::RR_GET_PROVIDERS, - length_units: 2, - }, - &providers_body, - ) - .expect("get providers"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 40); - match byte_order { - ClientByteOrder::LittleEndian => { - assert_eq!(&bytes[4..8], &2u32.to_le_bytes()); - assert_eq!(&bytes[12..14], &2u16.to_le_bytes()); - assert_eq!(&bytes[32..36], &10u32.to_le_bytes()); - assert_eq!(&bytes[36..40], &20u32.to_le_bytes()); - } - ClientByteOrder::BigEndian => { - assert_eq!(&bytes[4..8], &2u32.to_be_bytes()); - assert_eq!(&bytes[12..14], &2u16.to_be_bytes()); - assert_eq!(&bytes[32..36], &10u32.to_be_bytes()); - assert_eq!(&bytes[36..40], &20u32.to_be_bytes()); - } - } - - let mut info_body = Vec::new(); - match byte_order { - ClientByteOrder::LittleEndian => { - info_body.extend_from_slice(&10u32.to_le_bytes()); - info_body.extend_from_slice(&0u32.to_le_bytes()); - } - ClientByteOrder::BigEndian => { - info_body.extend_from_slice(&10u32.to_be_bytes()); - info_body.extend_from_slice(&0u32.to_be_bytes()); - } - } - yserver_protocol::x11::request_swap::swap_request_body( - 128, - x11randr::RR_GET_PROVIDER_INFO, - byte_order, - &mut info_body, - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: x11randr::RR_GET_PROVIDER_INFO, - length_units: 3, - }, - &info_body, - ) - .expect("get provider info"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 56); - assert_eq!(bytes[1], x11randr::SET_CONFIG_SUCCESS); - match byte_order { - ClientByteOrder::LittleEndian => { - assert_eq!(&bytes[4..8], &6u32.to_le_bytes()); - assert_eq!( - &bytes[12..16], - &x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT.to_le_bytes() - ); - assert_eq!(&bytes[16..18], &1u16.to_le_bytes()); - assert_eq!(&bytes[18..20], &1u16.to_le_bytes()); - assert_eq!(&bytes[20..22], &1u16.to_le_bytes()); - assert_eq!(&bytes[32..36], &2u32.to_le_bytes()); - assert_eq!(&bytes[36..40], &1u32.to_le_bytes()); - assert_eq!(&bytes[40..44], &20u32.to_le_bytes()); - assert_eq!( - &bytes[44..48], - &x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT.to_le_bytes() - ); - } - ClientByteOrder::BigEndian => { - assert_eq!(&bytes[4..8], &6u32.to_be_bytes()); - assert_eq!( - &bytes[12..16], - &x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT.to_be_bytes() - ); - assert_eq!(&bytes[16..18], &1u16.to_be_bytes()); - assert_eq!(&bytes[18..20], &1u16.to_be_bytes()); - assert_eq!(&bytes[20..22], &1u16.to_be_bytes()); - assert_eq!(&bytes[32..36], &2u32.to_be_bytes()); - assert_eq!(&bytes[36..40], &1u32.to_be_bytes()); - assert_eq!(&bytes[40..44], &20u32.to_be_bytes()); - assert_eq!( - &bytes[44..48], - &x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT.to_be_bytes() - ); - } - } - assert_eq!(&bytes[48..53], b"card0"); - assert!(bytes[53..].iter().all(|byte| *byte == 0)); - } - } - - #[test] - fn randr_provider_requests_validate_exact_or_minimum_wire_size_first() { - use yserver_protocol::x11::randr as x11randr; - - let mut valid_bodies = vec![( - x11randr::RR_GET_PROVIDERS, - ROOT_WINDOW.0.to_le_bytes().to_vec(), - )]; - valid_bodies.extend( - (33..=41).map(|minor| (minor, randr_provider_request_body(minor, 0x00ab_cdef))), - ); - for (minor, valid) in valid_bodies { - let mut malformed_bodies = vec![valid[..valid.len() - 4].to_vec()]; - if minor != x11randr::RR_CONFIGURE_PROVIDER_PROPERTY { - let mut extra = valid.clone(); - extra.extend_from_slice(&[0; 4]); - malformed_bodies.push(extra); - } - for malformed in malformed_bodies { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(u16::from(minor)), - RequestHeader { - opcode: 128, - data: minor, - length_units: 1 + malformed.len().div_ceil(4) as u32, - }, - &malformed, - ) - .expect("process malformed provider request"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); - assert_eq!(bytes[1], x11::error::BAD_LENGTH, "minor {minor} code"); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 0); - } - } - } - - #[test] - fn randr_unknown_provider_requests_use_valid_shapes_then_bad_provider() { - const PROVIDER: u32 = 0x00ab_cdef; - for minor in 33..=41 { - let body = randr_provider_request_body(minor, PROVIDER); - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(u16::from(minor)), - RequestHeader { - opcode: 128, - data: minor, - length_units: 1 + (body.len() / 4) as u32, - }, - &body, - ) - .expect("process provider request"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); - assert_eq!(bytes[1], RANDR_BAD_PROVIDER, "minor {minor} error"); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - PROVIDER, - "minor {minor} bad provider", - ); - assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); - assert_eq!(bytes[10], 128); - } - } - - #[test] - fn randr_provider_relationships_validate_roles_in_xorg_order() { - use yserver_protocol::x11::randr as x11randr; - - let cases: &[(u8, u32, u32, u8, u32)] = &[ - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 99, - 0, - RANDR_BAD_PROVIDER, - 99, - ), - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 5, - 99, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 1, - 99, - RANDR_BAD_PROVIDER, - 99, - ), - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 1, - 5, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 6, - 99, - RANDR_BAD_PROVIDER, - 99, - ), - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 6, - 2, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - 6, - 0, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 99, - 0, - RANDR_BAD_PROVIDER, - 99, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 5, - 99, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 7, - 99, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 7, - 0, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 3, - 99, - RANDR_BAD_PROVIDER, - 99, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 3, - 5, - x11::error::BAD_VALUE, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 3, - 0, - x11::error::BAD_IMPLEMENTATION, - 0, - ), - ( - x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, - 3, - 4, - x11::error::BAD_IMPLEMENTATION, - 0, - ), - ]; - for &(minor, provider, peer_provider, error_code, error_value) in cases { - let mut state = ServerState::new(); - state.randr.set_providers(vec![ - randr_provider(1, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), - randr_provider(2, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), - randr_provider(3, x11randr::PROVIDER_CAPABILITY_SOURCE_OFFLOAD), - randr_provider(4, x11randr::PROVIDER_CAPABILITY_SINK_OFFLOAD), - randr_provider(5, 0), - crate::randr::RandrProvider { - is_gpu: false, - ..randr_provider(6, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT) - }, - crate::randr::RandrProvider { - is_gpu: false, - ..randr_provider(7, x11randr::PROVIDER_CAPABILITY_SOURCE_OFFLOAD) - }, - ]); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = Vec::new(); - body.extend_from_slice(&provider.to_le_bytes()); - body.extend_from_slice(&peer_provider.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(u16::from(minor)), - RequestHeader { - opcode: 128, - data: minor, - length_units: 4, - }, - &body, - ) - .expect("process provider relationship"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], error_code, "minor={minor} provider={provider}"); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - error_value, - "minor={minor} provider={provider}", - ); - } - } - - #[test] - fn randr_set_provider_output_source_reaches_backend_for_attach_and_detach() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - state.randr.set_providers(vec![ - randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), - randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), - ]); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - for (sequence, source_provider) in [(1, 10), (2, 0)] { - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(sequence), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - length_units: 4, - }, - &randr_output_source_body(11, source_provider, 77), - ) - .expect("set provider output source"); - assert!( - read_all_available(&mut peer).is_empty(), - "successful void requests do not emit a reply" - ); - } - - assert_eq!( - backend.calls(), - vec![ - RecordedCall::SetProviderOutputSource { - provider: 11, - source_provider: Some(10), - }, - RecordedCall::SetProviderOutputSource { - provider: 11, - source_provider: None, - }, - ] - ); - } - - #[test] - fn randr_set_provider_output_source_notifies_in_both_byte_orders() { - use yserver_protocol::x11::randr as x11randr; - - for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { - let mut state = ServerState::new(); - state.randr.timestamp = 0x0102_0304; - state.randr.config_timestamp = 0x0506_0708; - state.randr.set_providers(vec![ - randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), - randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), - ]); - let mut peer = install_client(&mut state, 1); - let client = state.clients.get_mut(&1).expect("test client"); - client.byte_order = byte_order; - client - .last_sequence - .store(14, std::sync::atomic::Ordering::Relaxed); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_PROVIDER_CHANGE); - let mut backend = RecordingBackend::new(); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(14), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - length_units: 4, - }, - &randr_output_source_body(11, 10, 99), - ) - .expect("set provider output source"); - - let event = read_all_available(&mut peer); - let (sequence, timestamp, request_window, provider) = match byte_order { - ClientByteOrder::LittleEndian => ( - 14u16.to_le_bytes(), - 0x0102_0304u32.to_le_bytes(), - ROOT_WINDOW.0.to_le_bytes(), - 11u32.to_le_bytes(), - ), - ClientByteOrder::BigEndian => ( - 14u16.to_be_bytes(), - 0x0102_0304u32.to_be_bytes(), - ROOT_WINDOW.0.to_be_bytes(), - 11u32.to_be_bytes(), - ), - }; - assert_eq!(event.len(), 32); - assert_eq!(event[0], 90, "RANDR Notify event"); - assert_eq!(event[1], x11randr::NOTIFY_PROVIDER_CHANGE); - assert_eq!(&event[2..4], &sequence); - assert_eq!(&event[4..8], ×tamp); - assert_eq!(&event[8..12], &request_window); - assert_eq!(&event[12..16], &provider); - assert_eq!(state.randr.timestamp, 0x0102_0304); - assert_eq!(state.randr.config_timestamp, 0x0506_0708); - } - } - - #[test] - fn randr_idempotent_provider_output_source_skips_notify() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - state.randr.timestamp = 40; - state.randr.config_timestamp = 50; - state.randr.set_providers(vec![ - randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), - randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), - ]); - let mut peer = install_client(&mut state, 1); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_PROVIDER_CHANGE); - let mut backend = RecordingBackend::new(); - backend.provider_output_source_changed = false; - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - length_units: 4, - }, - &randr_output_source_body(11, 10, 99), - ) - .expect("idempotent provider output source"); - - assert!(read_all_available(&mut peer).is_empty()); - assert_eq!(state.randr.timestamp, 40); - assert_eq!(state.randr.config_timestamp, 50); - assert_eq!( - backend.calls(), - vec![RecordedCall::SetProviderOutputSource { - provider: 11, - source_provider: Some(10), - }] - ); - } - - #[test] - fn randr_provider_output_source_maps_backend_errors_by_kind() { - use yserver_protocol::x11::randr as x11randr; - - for (kind, error_code, error_value) in [ - (io::ErrorKind::InvalidInput, x11::error::BAD_MATCH, 11), - (io::ErrorKind::Other, x11::error::BAD_IMPLEMENTATION, 0), - ] { - let mut state = ServerState::new(); - state.randr.set_providers(vec![ - randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), - randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), - ]); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - backend.provider_output_source_error = Some(kind); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, - length_units: 4, - }, - &randr_output_source_body(11, 10, 99), - ) - .expect("backend provider output source error"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], error_code, "backend error kind {kind:?}"); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - error_value, - "backend error kind {kind:?}" - ); - } - } - - #[test] - fn randr_known_provider_property_requests_are_explicitly_unsupported() { - use yserver_protocol::x11::randr as x11randr; - - for minor in x11randr::RR_LIST_PROVIDER_PROPERTIES..=x11randr::RR_GET_PROVIDER_PROPERTY { - let mut body = randr_provider_request_body(minor, 10); - if minor == x11randr::RR_CONFIGURE_PROVIDER_PROPERTY { - // This request is variable-sized: trailing INT32 values are - // part of a valid request shape, not an overlong request. - body.extend_from_slice(&17i32.to_le_bytes()); - } - let mut state = ServerState::new(); - state.randr.set_providers(vec![randr_provider(10, 0)]); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(u16::from(minor)), - RequestHeader { - opcode: 128, - data: minor, - length_units: 1 + (body.len() / 4) as u32, - }, - &body, - ) - .expect("process known provider property request"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_IMPLEMENTATION, "minor {minor}"); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 0); - } - } - - #[test] - fn randr_change_provider_property_pins_xorg_error_precedence() { - use yserver_protocol::x11::randr as x11randr; - - let mut cases = Vec::new(); - let mut bad_mode = randr_provider_request_body(x11randr::RR_CHANGE_PROVIDER_PROPERTY, 99); - bad_mode[13] = 99; - bad_mode[16..20].copy_from_slice(&1u32.to_le_bytes()); - cases.push((bad_mode, x11::error::BAD_VALUE, 99)); - let mut bad_format = randr_provider_request_body(x11randr::RR_CHANGE_PROVIDER_PROPERTY, 99); - bad_format[12] = 7; - bad_format[16..20].copy_from_slice(&1u32.to_le_bytes()); - cases.push((bad_format, x11::error::BAD_VALUE, 7)); - let mut bad_length = randr_provider_request_body(x11randr::RR_CHANGE_PROVIDER_PROPERTY, 99); - bad_length[16..20].copy_from_slice(&1u32.to_le_bytes()); - cases.push((bad_length, x11::error::BAD_LENGTH, 0)); - - for (body, error_code, error_value) in cases { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(39), - RequestHeader { - opcode: 128, - data: x11randr::RR_CHANGE_PROVIDER_PROPERTY, - length_units: 1 + (body.len() / 4) as u32, - }, - &body, - ) - .expect("process malformed ChangeProviderProperty"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], error_code); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - error_value - ); - } - } - - /// RANDR minors 1 (`RROldGetScreenInfo`) and 3 - /// (`RROldScreenChangeSelectInput`) are NULL entries in Xorg's - /// `ProcRandrVector`, and `ProcRRDispatch` treats a NULL slot exactly like - /// an out-of-range minor — `BadRequest`. They previously fell through to - /// the silent "known unsupported" arm and reported success. - #[test] - fn randr_null_dispatch_slots_return_bad_request() { - for minor in [1u8, 3] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(u16::from(minor)), - RequestHeader { - opcode: 128, - data: minor, - length_units: 1, - }, - &[], - ) - .expect("process request"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "minor {minor} must answer"); - assert_eq!(bytes[0], 0, "minor {minor} must be an error, not a reply"); - assert_eq!(bytes[1], x11::error::BAD_REQUEST, "minor {minor} code"); - assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); - assert_eq!(bytes[10], 128); - } - } - - /// Xorg emits plain `BadValue` here, NOT `BadRRLease`: RRLeaseType is - /// created without `SetResourceTypeErrorValue`, so it keeps dix's default - /// errorValue, and `BadRRLease` is referenced nowhere in the Xorg tree. - /// Expected value measured on real Xorg via `tools/randr-probe` - /// (`RRFreeLease(bogus) -> code=2 (BadValue)`), not derived from this - /// implementation. - #[test] - fn randr_free_lease_without_live_lease_returns_bad_value() { - const LEASE: u32 = 0x0012_3456; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(46), - RequestHeader { - opcode: 128, - data: 46, - length_units: 2, - }, - &LEASE.to_le_bytes(), - ) - .expect("process FreeLease"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), LEASE); - assert_eq!(&bytes[8..10], &46u16.to_le_bytes()); - assert_eq!(bytes[10], 128); - } - - /// SetScreenConfig resolves its xid as a DRAWABLE, so a PIXMAP is a legal - /// target and must get a normal reply rather than a resource error. Xorg - /// takes `pDraw->pScreen` from whatever drawable it finds (rrscreen.c). - /// Measured on real Xorg with `tools/randr-probe`: a live pixmap returns - /// Success, while yserver used to answer BadWindow. - #[test] - fn randr_set_screen_config_accepts_a_pixmap_drawable() { - const PIXMAP: u32 = 0x0020_0007; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.resources.create_pixmap( - ClientId(1), - x11::CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP), - drawable: crate::resources::ROOT_WINDOW, - width: 32, - height: 32, - }, - ); - - let mut body = vec![0; 20]; - body[0..4].copy_from_slice(&PIXMAP.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: 2, - length_units: 6, - }, - &body, - ) - .expect("process SetScreenConfig"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "expected a 32-byte reply"); - assert_eq!(bytes[0], 1, "must be a reply (1), not an error (0)"); - } - - #[test] - fn randr_resource_queries_validate_xids_before_replying() { - const MISSING: u32 = 0x00de_ad01; - let cases = [ - // SetScreenConfig takes a DRAWABLE (`dixLookupDrawable`), whose - // BadValue is remapped to BadDrawable — verified on real Xorg with - // `tools/randr-probe` (bogus xid -> code=9). Every other minor here - // takes a window and reports BadWindow. - (2, 20usize, x11::error::BAD_DRAWABLE), - (4, 8, x11::error::BAD_WINDOW), - (5, 4usize, x11::error::BAD_WINDOW), - (6, 4, x11::error::BAD_WINDOW), - (7, 16, x11::error::BAD_WINDOW), - (8, 4, x11::error::BAD_WINDOW), - (25, 4, x11::error::BAD_WINDOW), - (31, 4, x11::error::BAD_WINDOW), - (32, 4, x11::error::BAD_WINDOW), - (42, 8, x11::error::BAD_WINDOW), - (9, 8, RANDR_BAD_OUTPUT), - (10, 4, RANDR_BAD_OUTPUT), - (11, 8, RANDR_BAD_OUTPUT), - (15, 24, RANDR_BAD_OUTPUT), - (20, 8, RANDR_BAD_CRTC), - (22, 4, RANDR_BAD_CRTC), - (23, 4, RANDR_BAD_CRTC), - (24, 8, RANDR_BAD_CRTC), - (26, 44, RANDR_BAD_CRTC), - (27, 4, RANDR_BAD_CRTC), - (28, 4, RANDR_BAD_CRTC), - (29, 32, RANDR_BAD_CRTC), - ]; - - for (minor, body_len, expected_error) in cases { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = vec![0; body_len]; - body[0..4].copy_from_slice(&MISSING.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(u16::from(minor)), - RequestHeader { - opcode: 128, - data: minor, - length_units: u32::try_from(1 + body_len / 4).unwrap(), - }, - &body, - ) - .expect("process RANDR resource request"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); - assert_eq!(bytes[1], expected_error, "minor {minor} error"); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - MISSING, - "minor {minor} bad resource", - ); - assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); - assert_eq!(bytes[10], 128); - } - } - - /// Xorg treats a primary change as a layout change and fans out - /// ScreenChangeNotify + OutputChangeNotify via `RRTellChanged` - /// (randr/rroutput.c `RRSetPrimaryOutput`). yserver used to just assign the - /// field, so panels never learned the primary moved — they wait for the - /// notify rather than polling GetOutputPrimary. Also pins the idempotent - /// case: re-setting the same output must NOT emit anything. - #[test] - fn randr_set_output_primary_notifies_selecting_clients() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Subscribe to both the screen-change and output-change notifies. - state.randr_select_masks.insert( - (1, ROOT_WINDOW), - x11randr::NOTIFY_MASK_SCREEN_CHANGE | x11randr::NOTIFY_MASK_OUTPUT_CHANGE, - ); - state.randr.timestamp = 41; - state.randr.config_timestamp = 37; - - let request = |target: u32| { - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&target.to_le_bytes()); - body - }; - let header = RequestHeader { - opcode: 128, - data: x11randr::RR_SET_OUTPUT_PRIMARY, - length_units: 3, - }; - - // Re-selecting the topology-derived default is wire-idempotent, but - // records that the client now owns this primary choice. - assert!(!state.randr_primary_output_explicit); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(0), - header, - &request(output), - ) - .expect("make default primary explicit"); - assert!(state.randr_primary_output_explicit); - assert!(read_all_available(&mut peer).is_empty()); - - // The first output is primary by default, so clear it first to make the - // set below a real change. (The clear is itself a change and notifies — - // drained here so the assertions below see only the set.) - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &request(0), - ) - .expect("clear primary"); - let _ = read_all_available(&mut peer); - assert_eq!( - (state.randr.timestamp, state.randr.config_timestamp), - (41, 37) - ); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - header, - &request(output), - ) - .expect("set primary"); - - // Two 32-byte events: ScreenChangeNotify then OutputChangeNotify for - // the newly-primary output (the previous primary was None, so it - // contributes nothing). - let events = read_all_available(&mut peer); - assert_eq!(events.len(), 64, "expected ScreenChange + OutputChange"); - const RANDR_FIRST_EVENT: u8 = 89; - assert_eq!(events[0] & 0x7f, RANDR_FIRST_EVENT, "ScreenChangeNotify"); - assert_eq!( - events[32] & 0x7f, - RANDR_FIRST_EVENT + 1, - "RRNotify (OutputChange)" - ); - for event in events.chunks_exact(32) { - assert_eq!(u32::from_le_bytes(event[4..8].try_into().unwrap()), 41); - assert_eq!(u32::from_le_bytes(event[8..12].try_into().unwrap()), 37); - } - assert_eq!( - (state.randr.timestamp, state.randr.config_timestamp), - (41, 37) - ); - - // Setting the same output again changes nothing, so it must be silent. - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - header, - &request(output), - ) - .expect("set same primary"); - assert!( - read_all_available(&mut peer).is_empty(), - "idempotent set must not notify", - ); - } - - #[test] - fn randr_set_output_primary_updates_get_output_primary() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let request = |output: u32| { - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&output.to_le_bytes()); - body - }; - let set_header = RequestHeader { - opcode: 128, - data: x11randr::RR_SET_OUTPUT_PRIMARY, - length_units: 3, - }; - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - set_header, - &request(0), - ) - .expect("clear primary"); - assert_eq!(state.randr.primary_output, 0); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - set_header, - &request(output), - ) - .expect("set primary"); - assert_eq!(state.randr.primary_output, output); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - RequestHeader { - opcode: 128, - data: x11randr::RR_GET_OUTPUT_PRIMARY, - length_units: 2, - }, - &ROOT_WINDOW.0.to_le_bytes(), - ) - .expect("get primary"); - let reply = read_all_available(&mut peer); - assert_eq!(reply[0], 1); - assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), output); - - let missing = 0x00de_ad02; - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(4), - set_header, - &request(missing), - ) - .expect("reject unknown primary"); - let error = read_all_available(&mut peer); - assert_eq!(error[1], RANDR_BAD_OUTPUT); - assert_eq!(u32::from_le_bytes(error[4..8].try_into().unwrap()), missing); - assert_eq!(state.randr.primary_output, output); - } - - fn change_output_property_body( - output: u32, - property: u32, - prop_type: u32, - format: u8, - mode: u8, - data: &[u8], - ) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.to_le_bytes()); - body.extend_from_slice(&prop_type.to_le_bytes()); - body.push(format); - body.push(mode); - body.extend_from_slice(&[0, 0]); - let n_units = match format { - 8 => data.len(), - 16 => data.len() / 2, - 32 => data.len() / 4, - _ => 0, - }; - body.extend_from_slice(&(n_units as u32).to_le_bytes()); - body.extend_from_slice(data); - body - } - - fn change_output_property_header(body_len: usize) -> RequestHeader { - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_CHANGE_OUTPUT_PROPERTY, - length_units: u32::try_from(1 + body_len / 4).unwrap(), - } - } - - #[test] - fn randr_change_output_property_creates_and_notifies() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); - - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &42u32.to_le_bytes(), - ); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("ChangeOutputProperty"); - - // Void request: no reply bytes, just the notify event. - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "expected exactly one OutputPropertyNotify"); - const RANDR_FIRST_EVENT: u8 = 89; - assert_eq!(bytes[0] & 0x7f, RANDR_FIRST_EVENT + 1, "RRNotify"); - assert_eq!(bytes[1], x11randr::NOTIFY_OUTPUT_PROPERTY); - assert_eq!(u32::from_le_bytes(bytes[8..12].try_into().unwrap()), output); - assert_eq!( - u32::from_le_bytes(bytes[12..16].try_into().unwrap()), - property.0 - ); - assert_eq!(bytes[20], x11randr::PROPERTY_NEW_VALUE); - - let stored = state - .randr_output_properties - .get(&output) - .and_then(|props| props.iter().find(|(atom, _)| *atom == property)) - .map(|(_, p)| p) - .expect("property stored"); - assert_eq!(stored.current.as_ref().unwrap().data, 42u32.to_le_bytes()); - assert_eq!(stored.current.as_ref().unwrap().r#type, prop_type); - } - - #[test] - fn randr_change_output_property_replace_overwrites() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - - for value in [1u32, 2u32] { - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &value.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("ChangeOutputProperty"); - } - let _ = read_all_available(&mut peer); - - let stored = &state.randr_output_properties[&output] - .iter() - .find(|(atom, _)| *atom == property) - .unwrap() - .1; - assert_eq!(stored.current.as_ref().unwrap().data, 2u32.to_le_bytes()); - } - - #[test] - fn randr_change_output_property_append_concatenates() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("STRING", false); - - let body = change_output_property_body(output, property.0, prop_type.0, 8, 0, b"hello"); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("replace"); - // mode=2 Append - let body = change_output_property_body(output, property.0, prop_type.0, 8, 2, b" world"); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - change_output_property_header(body.len()), - &body, - ) - .expect("append"); - let _ = read_all_available(&mut peer); - - let stored = &state.randr_output_properties[&output] - .iter() - .find(|(atom, _)| *atom == property) - .unwrap() - .1; - assert_eq!( - stored.current.as_ref().unwrap().data, - b"hello world".to_vec() - ); - } - - #[test] - fn randr_change_output_property_accepts_wire_padded_format8_data() { - // A real X11 client pads the trailing value array to a 4-byte - // boundary (here: 2 real bytes + 2 pad bytes). `nUnits` counts real - // elements only, so the parser must recover exactly "hi", not - // "hi\0\0". - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PADDED_PROP", false); - let prop_type = state.atoms.intern("STRING", false); - - let mut body = change_output_property_body(output, property.0, prop_type.0, 8, 0, b"hi"); - body.extend_from_slice(&[0, 0]); // wire padding to a 4-byte boundary - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("padded change"); - let _ = read_all_available(&mut peer); - - let stored = &state.randr_output_properties[&output] - .iter() - .find(|(atom, _)| *atom == property) - .unwrap() - .1; - assert_eq!(stored.current.as_ref().unwrap().data, b"hi".to_vec()); - } - - #[test] - fn randr_change_output_property_append_type_mismatch_is_bad_match() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let type_a = state.atoms.intern("STRING", false); - let type_b = state.atoms.intern("CARDINAL", false); - - let body = change_output_property_body(output, property.0, type_a.0, 8, 0, b"hi"); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("replace"); - let _ = read_all_available(&mut peer); - - // mode=1 Prepend with a different type -> BadMatch. - let body = change_output_property_body(output, property.0, type_b.0, 8, 1, b"yo"); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - change_output_property_header(body.len()), - &body, - ) - .expect("prepend mismatch"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_MATCH); - } - - #[test] - fn randr_change_output_property_invalid_format_is_bad_value() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - let body = change_output_property_body(output, property.0, prop_type.0, 7, 0, &[]); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("bad format"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - } - - #[test] - fn randr_change_output_property_invalid_mode_is_bad_value() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - let body = change_output_property_body(output, property.0, prop_type.0, 32, 9, &[]); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("bad mode"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - } - - #[test] - fn randr_change_output_property_unknown_output_is_bad_output() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - let missing = 0x00de_ad01; - let body = change_output_property_body(missing, property.0, prop_type.0, 32, 0, &[0; 4]); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("bad output"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], RANDR_BAD_OUTPUT); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), missing); - } - - #[test] - fn randr_change_output_property_unknown_atom_is_bad_atom() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let bogus_atom = 0x00de_ad01; - let prop_type = state.atoms.intern("CARDINAL", false); - let body = change_output_property_body(output, bogus_atom, prop_type.0, 32, 0, &[0; 4]); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("bad atom"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_ATOM); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - bogus_atom - ); - } - - fn configure_output_property_body( - output: u32, - property: u32, - pending: bool, - range: bool, - values: &[i32], - ) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.to_le_bytes()); - body.push(u8::from(pending)); - body.push(u8::from(range)); - body.extend_from_slice(&[0, 0]); - for v in values { - body.extend_from_slice(&v.to_le_bytes()); - } - body - } - - fn configure_output_property_header(body_len: usize) -> RequestHeader { - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_CONFIGURE_OUTPUT_PROPERTY, - length_units: u32::try_from(1 + body_len / 4).unwrap(), - } - } - - #[test] - fn randr_configure_output_property_stores_range_and_fires_no_notify() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); - let property = state.atoms.intern("TEST_RANGE_PROP", false); - - let body = configure_output_property_body(output, property.0, false, true, &[0, 100]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - configure_output_property_header(body.len()), - &body, - ) - .expect("ConfigureOutputProperty"); - - assert!( - read_all_available(&mut peer).is_empty(), - "Configure must not notify" - ); - let stored = &state.randr_output_properties[&output] - .iter() - .find(|(atom, _)| *atom == property) - .unwrap() - .1; - assert!(stored.range); - assert!(!stored.is_pending); - assert!(!stored.immutable); - assert_eq!(stored.valid_values, vec![0, 100]); - } - - #[test] - fn randr_configure_output_property_odd_range_values_is_bad_match() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_RANGE_PROP", false); - - let body = configure_output_property_body(output, property.0, false, true, &[0, 50, 100]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - configure_output_property_header(body.len()), - &body, - ) - .expect("odd range values"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_MATCH); - } - - #[test] - fn randr_configure_output_property_leaving_pending_clears_pending_value() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); - let property = state.atoms.intern("TEST_PENDING_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - - // Mark the property pending-capable, then Change it (lands in - // `.pending`, but Xorg's `sendevent` is unconditional in - // `RRChangeOutputProperty` — only the `RRNoticePropertyChange` - // driver hook (unrelated to client notification) is gated on - // `is_pending`, so the wire notify still fires here). - let body = configure_output_property_body(output, property.0, true, false, &[]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - configure_output_property_header(body.len()), - &body, - ) - .expect("configure pending"); - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &7u32.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - change_output_property_header(body.len()), - &body, - ) - .expect("change pending value"); - let notify = read_all_available(&mut peer); - assert_eq!( - notify.len(), - 32, - "ChangeOutputProperty must notify even when staged as pending" - ); - assert_eq!(notify[20], x11randr::PROPERTY_NEW_VALUE); - assert!( - state.randr_output_properties[&output] - .iter() - .find(|(atom, _)| *atom == property) - .unwrap() - .1 - .pending - .is_some(), - "pending value must be staged" - ); - - // Configure(pending=false) drops the staged pending value (Xorg: - // "Property moving from pending to non-pending loses any pending - // values"). - let body = configure_output_property_body(output, property.0, false, false, &[]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - configure_output_property_header(body.len()), - &body, - ) - .expect("configure non-pending"); - let _ = read_all_available(&mut peer); - let stored = &state.randr_output_properties[&output] - .iter() - .find(|(atom, _)| *atom == property) - .unwrap() - .1; - assert!(!stored.is_pending); - assert!(stored.pending.is_none()); - } - - #[test] - fn randr_configure_output_property_unknown_output_is_bad_output() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_RANGE_PROP", false); - let missing = 0x00de_ad01; - - let body = configure_output_property_body(missing, property.0, false, false, &[]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - configure_output_property_header(body.len()), - &body, - ) - .expect("bad output"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], RANDR_BAD_OUTPUT); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), missing); - } - - fn delete_output_property_header() -> RequestHeader { - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_DELETE_OUTPUT_PROPERTY, - length_units: 3, - } - } - - #[test] - fn randr_delete_output_property_removes_and_notifies() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &1u32.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("create property"); - let _ = read_all_available(&mut peer); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - delete_output_property_header(), - &body, - ) - .expect("DeleteOutputProperty"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - const RANDR_FIRST_EVENT: u8 = 89; - assert_eq!(bytes[0] & 0x7f, RANDR_FIRST_EVENT + 1); - assert_eq!(bytes[1], x11randr::NOTIFY_OUTPUT_PROPERTY); - assert_eq!(bytes[20], x11randr::PROPERTY_DELETE); - assert!( - !state.randr_output_properties[&output] - .iter() - .any(|(atom, _)| *atom == property), - "property must be removed" - ); - } - - #[test] - fn randr_delete_output_property_unknown_is_bad_name() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let bogus_atom = state.atoms.intern("NEVER_SET_PROP", false); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&bogus_atom.0.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - delete_output_property_header(), - &body, - ) - .expect("delete unknown"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_NAME); - } - - #[test] - fn randr_delete_output_property_unregistered_atom_is_bad_atom() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let never_interned: u32 = 0x00de_ad02; - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&never_interned.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - delete_output_property_header(), - &body, - ) - .expect("delete unregistered atom"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_ATOM); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - never_interned - ); - } - - #[test] - fn randr_delete_output_property_immutable_is_bad_access() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("IMMUTABLE_PROP", false); - state - .randr_output_properties - .entry(output) - .or_default() - .push(( - property, - crate::randr::RandrOutputProperty { - immutable: true, - ..Default::default() - }, - )); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - delete_output_property_header(), - &body, - ) - .expect("delete immutable"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_ACCESS); - assert!( - state.randr_output_properties[&output] - .iter() - .any(|(atom, _)| *atom == property), - "immutable property must not be removed" - ); - } - - #[test] - fn randr_delete_output_property_unknown_output_is_bad_output() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let missing: u32 = 0x00de_ad01; - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&missing.to_le_bytes()); - body.extend_from_slice(&1u32.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - delete_output_property_header(), - &body, - ) - .expect("bad output"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], RANDR_BAD_OUTPUT); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), missing); - } - - #[test] - fn randr_query_output_property_reports_stored_metadata() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_RANGE_PROP", false); - - let body = configure_output_property_body(output, property.0, false, true, &[0, 100]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - configure_output_property_header(body.len()), - &body, - ) - .expect("configure"); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_QUERY_OUTPUT_PROPERTY, - length_units: 3, - }, - &body, - ) - .expect("query"); - let reply = read_all_available(&mut peer); - assert_eq!(reply[0], 1, "must be a reply"); - assert_eq!(u32::from_le_bytes(reply[4..8].try_into().unwrap()), 2); // length = num_valid - assert_eq!(reply[8], 0, "pending"); - assert_eq!(reply[9], 1, "range"); - assert_eq!(reply[10], 0, "immutable"); - assert_eq!(i32::from_le_bytes(reply[32..36].try_into().unwrap()), 0); - assert_eq!(i32::from_le_bytes(reply[36..40].try_into().unwrap()), 100); - } - - #[test] - fn randr_query_output_property_unknown_atom_is_bad_name() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let bogus_atom = state.atoms.intern("NEVER_CONFIGURED_PROP", false); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&bogus_atom.0.to_le_bytes()); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_QUERY_OUTPUT_PROPERTY, - length_units: 3, - }, - &body, - ) - .expect("query unknown"); - let reply = read_all_available(&mut peer); - assert_eq!(reply.len(), 32); - assert_eq!(reply[1], x11::error::BAD_NAME); - } - - #[test] - fn randr_get_output_property_round_trips_changed_value() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &99u32.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("change"); - let _ = read_all_available(&mut peer); - - // RRGetOutputProperty(output, property, AnyPropertyType, 0, 1, false, false) - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // AnyPropertyType - body.extend_from_slice(&0u32.to_le_bytes()); // long_offset - body.extend_from_slice(&1u32.to_le_bytes()); // long_length - body.push(0); // delete - body.push(0); // pending - body.extend_from_slice(&[0, 0]); // pad - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, - length_units: 6, - }, - &body, - ) - .expect("get"); - let reply = read_all_available(&mut peer); - assert_eq!(reply[0], 1); - assert_eq!(reply[1], 32, "format"); - assert_eq!( - u32::from_le_bytes(reply[8..12].try_into().unwrap()), - prop_type.0 - ); - assert_eq!(u32::from_le_bytes(reply[12..16].try_into().unwrap()), 0); // bytes_after - assert_eq!(u32::from_le_bytes(reply[16..20].try_into().unwrap()), 1); // nItems - assert_eq!(&reply[32..36], &99u32.to_le_bytes()); - } - - #[test] - fn randr_get_output_property_type_mismatch_returns_metadata_only() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let real_type = state.atoms.intern("CARDINAL", false); - let other_type = state.atoms.intern("STRING", false); - - // Two format-32 elements (8 bytes) so byte-count vs element-count - // diverge: Xorg's `bytesAfter` for a type mismatch is - // `prop_value->size`, an ELEMENT count (`rrproperty.c` - // `RRChangeOutputProperty`: `new_value.size = total_len` where - // `total_len` is `nUnits`, not a byte length), not `full.len()`. - let mut value = Vec::new(); - value.extend_from_slice(&1u32.to_le_bytes()); - value.extend_from_slice(&2u32.to_le_bytes()); - let body = change_output_property_body(output, property.0, real_type.0, 32, 0, &value); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("change"); - let _ = read_all_available(&mut peer); - - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - body.extend_from_slice(&other_type.0.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&1u32.to_le_bytes()); - body.push(0); - body.push(0); - body.extend_from_slice(&[0, 0]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, - length_units: 6, - }, - &body, - ) - .expect("get mismatched type"); - let reply = read_all_available(&mut peer); - assert_eq!( - u32::from_le_bytes(reply[8..12].try_into().unwrap()), - real_type.0, - "propertyType must be the real type" - ); - assert_eq!( - u32::from_le_bytes(reply[12..16].try_into().unwrap()), - 2, - "bytes_after is an ELEMENT count (2 x format-32), not a byte count (8)" - ); - assert_eq!(u32::from_le_bytes(reply[16..20].try_into().unwrap()), 0); // nItems - } - - #[test] - fn randr_get_output_property_unregistered_property_atom_is_bad_atom() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let never_interned: u32 = 0x00de_ad03; - - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&never_interned.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&1u32.to_le_bytes()); - body.extend_from_slice(&[0, 0, 0, 0]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, - length_units: 6, - }, - &body, - ) - .expect("get unregistered property atom"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_ATOM); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - never_interned - ); - } - - #[test] - fn randr_get_output_property_unregistered_type_atom_is_bad_atom() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let never_interned: u32 = 0x00de_ad04; - - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - body.extend_from_slice(&never_interned.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&1u32.to_le_bytes()); - body.extend_from_slice(&[0, 0, 0, 0]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, - length_units: 6, - }, - &body, - ) - .expect("get unregistered type atom"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_ATOM); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - never_interned - ); - } - - #[test] - fn randr_get_output_property_invalid_delete_byte_is_bad_value() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&1u32.to_le_bytes()); - body.push(2); // delete: neither xTrue(1) nor xFalse(0) - body.push(0); - body.extend_from_slice(&[0, 0]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, - length_units: 6, - }, - &body, - ) - .expect("get invalid delete byte"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 2); - } - - #[test] - fn randr_get_output_property_delete_removes_and_notifies() { - use yserver_protocol::x11::randr as x11randr; - - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &1u32.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("change"); - let _ = read_all_available(&mut peer); - state - .randr_select_masks - .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); - - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&output.to_le_bytes()); - body.extend_from_slice(&property.0.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // AnyPropertyType - body.extend_from_slice(&0u32.to_le_bytes()); // long_offset - body.extend_from_slice(&1u32.to_le_bytes()); // long_length - body.push(1); // delete = true - body.push(0); - body.extend_from_slice(&[0, 0]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, - length_units: 6, - }, - &body, - ) - .expect("get with delete"); - - let bytes = read_all_available(&mut peer); - // One 32-byte OutputPropertyNotify(state=Delete) followed by the - // 36-byte reply (32-byte header + the just-deleted 4-byte value: - // Xorg reads the value before removing the property). - assert_eq!(bytes.len(), 68); - const RANDR_FIRST_EVENT: u8 = 89; - assert_eq!(bytes[0] & 0x7f, RANDR_FIRST_EVENT + 1, "RRNotify"); - assert_eq!(bytes[20], x11randr::PROPERTY_DELETE); - assert_eq!(bytes[32], 1, "reply type"); - assert!( - !state.randr_output_properties[&output] - .iter() - .any(|(atom, _)| *atom == property), - "property must be removed after delete=true read" - ); - } - - #[test] - fn randr_list_output_properties_includes_stored_atoms() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let property = state.atoms.intern("TEST_PROP", false); - let prop_type = state.atoms.intern("CARDINAL", false); - - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &1u32.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("change"); - let _ = read_all_available(&mut peer); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_LIST_OUTPUT_PROPERTIES, - length_units: 2, - }, - &output.to_le_bytes(), - ) - .expect("list"); - let reply = read_all_available(&mut peer); - assert_eq!(reply[0], 1); - let n_atoms = u16::from_le_bytes(reply[8..10].try_into().unwrap()); - assert_eq!(n_atoms, 1); - assert_eq!( - u32::from_le_bytes(reply[32..36].try_into().unwrap()), - property.0 - ); - } - - #[test] - fn randr_list_output_properties_orders_newest_first() { - let mut state = ServerState::new(); - let output = state.randr.outputs[0].output_id; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let prop_type = state.atoms.intern("CARDINAL", false); - let first = state.atoms.intern("FIRST_PROP", false); - let second = state.atoms.intern("SECOND_PROP", false); - - for property in [first, second] { - let body = change_output_property_body( - output, - property.0, - prop_type.0, - 32, - 0, - &1u32.to_le_bytes(), - ); - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - change_output_property_header(body.len()), - &body, - ) - .expect("change"); - } - let _ = read_all_available(&mut peer); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_LIST_OUTPUT_PROPERTIES, - length_units: 2, - }, - &output.to_le_bytes(), - ) - .expect("list"); - let reply = read_all_available(&mut peer); - let n_atoms = u16::from_le_bytes(reply[8..10].try_into().unwrap()); - assert_eq!(n_atoms, 2); - // Xorg's RRCreateOutputProperty prepends onto a linked list, so - // ListOutputProperties enumerates newest-first. - assert_eq!( - u32::from_le_bytes(reply[32..36].try_into().unwrap()), - second.0, - "most recently created property must list first" - ); - assert_eq!( - u32::from_le_bytes(reply[36..40].try_into().unwrap()), - first.0 - ); - } - - #[test] - fn x_resource_query_clients_lists_connected_clients() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let _peer2 = install_client(&mut state, 2); - { - let c = state.clients.get_mut(&1).unwrap(); - c.resource_id_base = 0x0040_0000; - c.resource_id_mask = 0x001f_ffff; - } - { - let c = state.clients.get_mut(&2).unwrap(); - c.resource_id_base = 0x0080_0000; - c.resource_id_mask = 0x001f_ffff; - } - let mut backend = RecordingBackend::new(); - // X-Resource major op 149, QueryClients minor 1. - let header = RequestHeader { - opcode: 149, - data: 1, - length_units: 1, - }; - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[], - None, - ) - .expect("process_request"); - let bytes = read_all_available(&mut peer); - // 32-byte header + 2 clients × 8 bytes. - assert_eq!(bytes.len(), 48, "two clients listed: {bytes:02x?}"); - assert_eq!(&bytes[8..12], &2u32.to_le_bytes(), "num_clients"); - // Sorted by client id: client 1 then client 2. - assert_eq!(&bytes[32..36], &0x0040_0000u32.to_le_bytes(), "c1 base"); - assert_eq!(&bytes[36..40], &0x001f_ffffu32.to_le_bytes(), "c1 mask"); - assert_eq!(&bytes[40..44], &0x0080_0000u32.to_le_bytes(), "c2 base"); - assert_eq!(&bytes[44..48], &0x001f_ffffu32.to_le_bytes(), "c2 mask"); - } - - #[test] - fn x_resource_query_client_resources_counts_by_type() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - { - let c = state.clients.get_mut(&1).unwrap(); - c.resource_id_base = 0x0040_0000; - c.resource_id_mask = 0x001f_ffff; - } - // Client 1 owns 2 GCs + 1 font. - state - .resources - .seed_gc_for_test(ClientId(1), ResourceId(0x0040_0001)); - state - .resources - .seed_gc_for_test(ClientId(1), ResourceId(0x0040_0002)); - state - .resources - .seed_font_for_test(ClientId(1), ResourceId(0x0040_0003)); - - let mut backend = RecordingBackend::new(); - // QueryClientResources (minor 2), xid = the client's resource base. - let xid = 0x0040_0000u32; - let header = RequestHeader { - opcode: 149, - data: 2, - length_units: 2, - }; - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &xid.to_le_bytes(), - None, - ) - .expect("process_request"); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "got {bytes:02x?}"); - let num_types = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize; - assert_eq!( - bytes.len(), - 32 + num_types * 8, - "reply size matches num_types" - ); - // Resolve each returned type atom back to its name — proves the - // canonical strings, not just the counts. - let mut found = std::collections::HashMap::new(); - for i in 0..num_types { - let off = 32 + i * 8; - let atom = u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()); - let count = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()); - let name = state - .atoms - .name(x11::AtomId(atom)) - .unwrap_or("?") - .to_string(); - found.insert(name, count); - } - assert_eq!(found.get("GC"), Some(&2), "GC count; found={found:?}"); - assert_eq!(found.get("FONT"), Some(&1), "FONT count; found={found:?}"); - assert!( - !found.contains_key("WINDOW"), - "zero-count types omitted; found={found:?}" - ); - } - - #[test] - fn x_resource_query_client_pixmap_bytes_reports_padded_storage() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let _peer2 = install_client(&mut state, 2); - state.clients.get_mut(&1).unwrap().resource_id_base = 0x0040_0000; - state.clients.get_mut(&1).unwrap().resource_id_mask = 0x001f_ffff; - state.clients.get_mut(&2).unwrap().resource_id_base = 0x0080_0000; - state.clients.get_mut(&2).unwrap().resource_id_mask = 0x001f_ffff; - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: ResourceId(0x0040_0001), - drawable: ROOT_WINDOW, - width: 33, - height: 2, - depth: 1, - }, - ); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: ResourceId(0x0040_0002), - drawable: ROOT_WINDOW, - width: 3, - height: 2, - depth: 24, - }, - ); - state.resources.create_pixmap( - ClientId(2), - CreatePixmapRequest { - pixmap: ResourceId(0x0080_0001), - drawable: ROOT_WINDOW, - width: 100, - height: 100, - depth: 32, - }, - ); - let mut backend = RecordingBackend::new(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(7), - RequestHeader { - opcode: 149, - data: 3, - length_units: 2, - }, - &0x0040_0000u32.to_le_bytes(), - None, - ) - .expect("QueryClientPixmapBytes"); - - let reply = read_all_available(&mut peer); - assert_eq!(reply.len(), 32); - // depth-1: 33 bits -> 8-byte padded row * 2 = 16. - // depth-24: 3 pixels * 4 bytes * 2 = 24. Total = 40. - assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), 40); - assert_eq!(u32::from_le_bytes(reply[12..16].try_into().unwrap()), 0); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(8), - RequestHeader { - opcode: 149, - data: 3, - length_units: 2, - }, - &0x00f0_0000u32.to_le_bytes(), - None, - ) - .expect("reject unknown client range"); - let error = read_all_available(&mut peer); - assert_eq!(error[1], x11::error::BAD_VALUE); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - 0x00f0_0000 - ); - } - - #[test] - fn x_resource_query_client_ids_omits_pid_for_nonlocal_client() { - use yserver_protocol::x11::x_resource as x11xres; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).unwrap().is_local = false; - let mut backend = RecordingBackend::new(); - let mut body = 1u32.to_le_bytes().to_vec(); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&x11xres::LOCAL_CLIENT_PID_MASK.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 149, - data: x11xres::QUERY_CLIENT_IDS, - length_units: 4, - }, - &body, - None, - ) - .unwrap(); - let reply = read_all_available(&mut peer); - assert_eq!( - u32::from_le_bytes(reply[8..12].try_into().unwrap()), - 0, - "nonlocal clients have no LocalClientPID even if the underlying socket supports credentials" - ); - assert_eq!(reply.len(), 32); - } - - #[test] - fn x_resource_query_client_ids_reports_xid_and_pid_identities() { - use yserver_protocol::x11::x_resource as x11xres; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let _peer2 = install_client(&mut state, 2); - state.clients.get_mut(&1).unwrap().resource_id_base = 0x0040_0000; - state.clients.get_mut(&1).unwrap().resource_id_mask = 0x001f_ffff; - state.clients.get_mut(&2).unwrap().resource_id_base = 0x0080_0000; - state.clients.get_mut(&2).unwrap().resource_id_mask = 0x001f_ffff; - let mut backend = RecordingBackend::new(); - let query = |mask: u32| { - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&1u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // all clients - body.extend_from_slice(&mask.to_le_bytes()); - body - }; - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(9), - RequestHeader { - opcode: 149, - data: x11xres::QUERY_CLIENT_IDS, - length_units: 4, - }, - &query(x11xres::CLIENT_XID_MASK), - None, - ) - .expect("QueryClientIds XIDs"); - let reply = read_all_available(&mut peer); - assert_eq!(reply.len(), 56); - assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), 2); - assert_eq!( - u32::from_le_bytes(reply[32..36].try_into().unwrap()), - 0x0040_0000 - ); - assert_eq!(u32::from_le_bytes(reply[36..40].try_into().unwrap()), 1); - assert_eq!(u32::from_le_bytes(reply[40..44].try_into().unwrap()), 0); - assert_eq!( - u32::from_le_bytes(reply[44..48].try_into().unwrap()), - 0x0080_0000 - ); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(10), - RequestHeader { - opcode: 149, - data: x11xres::QUERY_CLIENT_IDS, - length_units: 4, - }, - &query(x11xres::LOCAL_CLIENT_PID_MASK), - None, - ) - .expect("QueryClientIds PID-only"); - // A PID-only spec suppresses the XID identity and yields one - // LocalClientPID entry per client. Sizes derived from Xorg's encoder - // (Xext/xres.c `ConstructClientIdValue`): a pid entry is the 12-byte - // header plus one value word, `rep.length = 4` counted in BYTES, and - // `num_ids` counts ENTRIES. Two clients => 2*16 = 32 body bytes, so - // reply length = 32/4 = 8 and the whole reply is 64 bytes. - let pids = read_all_available(&mut peer); - assert_eq!(pids.len(), 64); - assert_eq!(u32::from_le_bytes(pids[4..8].try_into().unwrap()), 8); - assert_eq!(u32::from_le_bytes(pids[8..12].try_into().unwrap()), 2); - // Both test clients are socketpairs owned by this process, so - // SO_PEERCRED reports our own pid for each. - let self_pid = std::process::id(); - for (i, base) in [0x0040_0000u32, 0x0080_0000].into_iter().enumerate() { - let at = 32 + i * 16; - assert_eq!( - u32::from_le_bytes(pids[at..at + 4].try_into().unwrap()), - base, - "entry {i} client", - ); - assert_eq!( - u32::from_le_bytes(pids[at + 4..at + 8].try_into().unwrap()), - x11xres::LOCAL_CLIENT_PID_MASK, - "entry {i} mask", - ); - assert_eq!( - u32::from_le_bytes(pids[at + 8..at + 12].try_into().unwrap()), - 4, - "entry {i} length is in bytes", - ); - assert_eq!( - u32::from_le_bytes(pids[at + 12..at + 16].try_into().unwrap()), - self_pid, - "entry {i} pid", - ); - } - } - - #[test] - fn poly_fill_rectangle_unknown_gc_returns_bad_gc() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let body = poly_fill_rectangle_body(ROOT_WINDOW.0, 0xdead_beef); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 70, - data: 0, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - - let bytes = read_all_available(&mut peer); - assert!( - bytes.len() >= 32, - "expected 32-byte error reply, got {} bytes: {:02x?}", - bytes.len(), - bytes - ); - let buf = &bytes[..32]; - assert_eq!(buf[1], x11::error::BAD_GC); - assert_eq!(buf[10], 70); - } - - /// Decode a 32-byte X11 error at the wire offsets fixed by the core - /// protocol encoding (`Errors`): 0 = 0, 1 = code, 2..4 = sequence, - /// 4..8 = bad resource id / value, 8..10 = minor opcode, 10 = major - /// opcode. Asserted as raw bytes on purpose — running the reply back - /// through our own decoder would pass even if encoder and decoder - /// were wrong together. - fn assert_x11_error_bytes( - bytes: &[u8], - code: u8, - bad_value: u32, - minor: u16, - major: u8, - sequence: u16, - what: &str, - ) { - assert_eq!( - bytes.len(), - 32, - "{what}: expected exactly one 32-byte error, got {:02x?}", - bytes - ); - assert_eq!(bytes[0], 0, "{what}: byte 0 marks a packet as an error"); - assert_eq!(bytes[1], code, "{what}: error code"); - assert_eq!( - u16::from_le_bytes([bytes[2], bytes[3]]), - sequence, - "{what}: sequence number" - ); - assert_eq!( - u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), - bad_value, - "{what}: bad resource id must be the XID exactly as sent" - ); - assert_eq!( - u16::from_le_bytes([bytes[8], bytes[9]]), - minor, - "{what}: minor opcode" - ); - assert_eq!(bytes[10], major, "{what}: major opcode"); - } - - /// Drive one four-byte resource-release request (FreePixmap / FreeGC / - /// FreeCursor: `xResourceReq`, 2 units total) through the real - /// dispatch table and return whatever the client was sent. - fn run_free_resource_request( - state: &mut ServerState, - peer: &mut UnixStream, - opcode: u8, - xid: u32, - sequence: u16, - ) -> Vec { - let mut backend = RecordingBackend::new(); - let body = xid.to_le_bytes().to_vec(); - process_request( - state, - &mut backend, - ClientId(1), - SequenceNumber(sequence), - RequestHeader { - opcode, - data: 0, - length_units: 2, - }, - &body, - None, - ) - .expect("process_request"); - read_all_available(peer) - } - - /// #143. picom's `x_prepare_for_sleep` (picom `src/x.c:1194`) fires a - /// deliberately invalid `FreePixmap(drawable=None)` as a sync barrier - /// and *expects* `BadPixmap`: XCB only completes a checked **void** - /// request once it reads a packet with a higher sequence number, and - /// for a void request that packet is the error. Xorg answers every one - /// of these (measured: 419 requests -> 419 `BadPixmap`); we answered - /// none of 538, so picom's checked `ChangeWindowAttributes` batch never - /// completed and its window import stalled ~10s instead of ~120ms. - #[test] - fn free_pixmap_none_returns_bad_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let bytes = run_free_resource_request(&mut state, &mut peer, 54, 0, 0x0067); - - assert_x11_error_bytes( - &bytes, - x11::error::BAD_PIXMAP, - 0, - 0, - 54, - 0x0067, - "FreePixmap(None)", - ); - } - - #[test] - fn free_pixmap_unknown_xid_returns_bad_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let bytes = run_free_resource_request(&mut state, &mut peer, 54, 0x00de_ad00, 7); - - assert_x11_error_bytes( - &bytes, - x11::error::BAD_PIXMAP, - 0x00de_ad00, - 0, - 54, - 7, - "FreePixmap(unknown)", - ); - } - - /// The error path must not swallow the ordinary one: a pixmap the - /// server knows is freed silently, as Xorg's `Success` return does. - #[test] - fn free_pixmap_known_xid_reports_no_error() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(0x3100), - drawable: ROOT_WINDOW, - width: 8, - height: 8, - }, - ); - - let bytes = run_free_resource_request(&mut state, &mut peer, 54, 0x3100, 8); - - assert!( - bytes.is_empty(), - "FreePixmap(known) must be silent, got {bytes:02x?}" - ); - assert!(state.resources.pixmap(ResourceId(0x3100)).is_none()); - } - - /// Xorg `ProcFreeGC` -> `dixLookupGC` -> `X11_RESTYPE_GC.errorValue` - /// = `BadGC` (`../xserver/dix/resource.c:454`). - #[test] - fn free_gc_none_returns_bad_gc() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let bytes = run_free_resource_request(&mut state, &mut peer, 60, 0, 0x0068); - - assert_x11_error_bytes(&bytes, x11::error::BAD_GC, 0, 0, 60, 0x0068, "FreeGC(None)"); - } - - #[test] - fn free_gc_unknown_xid_returns_bad_gc() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let bytes = run_free_resource_request(&mut state, &mut peer, 60, 0x00be_ef00, 9); - - assert_x11_error_bytes( - &bytes, - x11::error::BAD_GC, - 0x00be_ef00, - 0, - 60, - 9, - "FreeGC(unknown)", - ); - } - - #[test] - fn free_gc_known_xid_reports_no_error() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state - .resources - .seed_gc_for_test(ClientId(1), ResourceId(0x2100)); - - let bytes = run_free_resource_request(&mut state, &mut peer, 60, 0x2100, 10); - - assert!( - bytes.is_empty(), - "FreeGC(known) must be silent, got {bytes:02x?}" - ); - assert!(state.resources.gc(ResourceId(0x2100)).is_none()); - } - - /// Xorg `ProcFreeCursor` -> `X11_RESTYPE_CURSOR.errorValue` = - /// `BadCursor` (`../xserver/dix/resource.c:466`). - #[test] - fn free_cursor_none_returns_bad_cursor() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let bytes = run_free_resource_request(&mut state, &mut peer, 95, 0, 0x0069); - - assert_x11_error_bytes( - &bytes, - x11::error::BAD_CURSOR, - 0, - 0, - 95, - 0x0069, - "FreeCursor(None)", - ); - } - - #[test] - fn free_cursor_unknown_xid_returns_bad_cursor() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let bytes = run_free_resource_request(&mut state, &mut peer, 95, 0x00c0_ff00, 11); - - assert_x11_error_bytes( - &bytes, - x11::error::BAD_CURSOR, - 0x00c0_ff00, - 0, - 95, - 11, - "FreeCursor(unknown)", - ); - } - - #[test] - fn free_cursor_known_xid_reports_no_error() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state - .resources - .create_cursor(ClientId(1), ResourceId(0x4100)); - - let bytes = run_free_resource_request(&mut state, &mut peer, 95, 0x4100, 12); - - assert!( - bytes.is_empty(), - "FreeCursor(known) must be silent, got {bytes:02x?}" - ); - assert!(!state.resources.cursor_exists(ResourceId(0x4100))); - } - - #[test] - fn free_pixmap_retains_host_pixmap_while_gc_clip_mask_still_references_it() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 1, - pixmap: ResourceId(0x3000), - drawable: ROOT_WINDOW, - width: 8, - height: 8, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - ResourceId(0x3000), - crate::backend::PixmapHandle::from_raw(0xcafe).unwrap(), - )); - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(0x2000), - drawable: ROOT_WINDOW, - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: Some(Some(ResourceId(0x3000))), - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &free_pixmap_body(0x3000), - ) - .expect("free pixmap"); - - let calls = backend.calls.lock().expect("calls"); - assert!( - !calls - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(0xcafe))), - "host pixmap must stay alive while retained by GC clip mask" - ); - } - - /// #133: `FreePixmap` has to respect a window's BORDER reference the same - /// way it respects a background one. `XCreatePixmap` → - /// `XSetWindowBorderPixmap` → `XFreePixmap` is ordinary client code, and - /// X11 keeps the storage alive because the window still names it (Xorg - /// refcounts `pWin->border.pixmap`). `handle_free_pixmap` consulted only - /// the background and GC references, so it freed the host handle - /// underneath a ring that was still sampling it — found by auditing this - /// case against `change_window_attributes`'s release path, which does gate - /// on all three. - #[test] - fn free_pixmap_retains_host_pixmap_while_a_window_border_still_references_it() { - const HOST_TILE: u32 = 0x9999_0007; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0011); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - let tile = ResourceId(0x0080_1307); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: tile, - drawable: ROOT_WINDOW, - width: 8, - height: 8, - depth: 24, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - tile, - crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"), - )); - - run_border_request( - &mut state, - 2, - 0, - &border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]), - ); - assert_no_error(&read_all_available(&mut peer), "CWA border-pixmap"); - // Not vacuous: the reference must actually be recorded, or the - // retention below would hold for the wrong reason. - assert!( - state.resources.host_xid_referenced_by_window_border( - crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero") - ), - "the window must hold the tile as its border before FreePixmap" - ); - - let mut backend = RecordingBackend::new(); - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - &free_pixmap_body(tile.0), - ) - .expect("free pixmap"); - - assert!( - !backend - .calls() - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))), - "host pixmap must stay alive while a window still borders with it" - ); - } - - /// The cross-reference case the CWA release path calls out: nothing stops - /// a client naming one pixmap as a background on window A and a border on - /// window B. The order here is deliberate — the background reference is - /// dropped FIRST, so the `FreePixmap` in the middle is suppressed by the - /// BORDER check alone and the step is not vacuous. The final release is - /// the positive control: once nothing holds the tile the host handle must - /// actually be freed, so a test that can never observe a free would fail. - #[test] - fn a_host_pixmap_shared_as_background_and_border_frees_only_when_both_let_go() { - const HOST_TILE: u32 = 0x9999_0008; - let host = crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"); - const CWA_BACK_PIXMAP: u32 = 0x0001; - let freed = |calls: &[RecordedCall]| { - calls - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))) - }; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let bg_win = ResourceId(0x0080_0021); - let border_win = ResourceId(0x0080_0022); - seed_window(&mut state, bg_win, ROOT_WINDOW, 10, 10); - seed_window(&mut state, border_win, ROOT_WINDOW, 10, 10); - let tile = ResourceId(0x0080_1308); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: tile, - drawable: ROOT_WINDOW, - width: 8, - height: 8, - depth: 24, - }, - ); - assert!(state.resources.set_pixmap_host_xid(tile, host)); - - run_border_request( - &mut state, - 2, - 0, - &border_cwa_body(bg_win.0, CWA_BACK_PIXMAP, &[tile.0]), - ); - run_border_request( - &mut state, - 2, - 0, - &border_cwa_body(border_win.0, CWA_BORDER_PIXMAP, &[tile.0]), - ); - assert_no_error(&read_all_available(&mut peer), "CWA shared tile"); - assert!( - state.resources.host_xid_referenced_by_window_bg(host), - "window A must hold the tile as its background" - ); - assert!( - state.resources.host_xid_referenced_by_window_border(host), - "window B must hold the tile as its border" - ); - - // 1. Drop A's background. B's border and the client's own ownership - // both still hold the tile. - let calls = run_border_request_recording( - &mut state, - 2, - 0, - &border_cwa_body(bg_win.0, CWA_BACK_PIXMAP, &[0]), - ); - assert!( - !state.resources.host_xid_referenced_by_window_bg(host), - "window A must no longer hold the tile as its background" - ); - assert!( - !freed(&calls), - "replacing the background must not free storage the other window's \ - border still samples" - ); - - // 2. The client drops the resource id. Only B's border holds the tile - // now, so this step exercises the border check on its own. - let mut backend = RecordingBackend::new(); - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(3), - &free_pixmap_body(tile.0), - ) - .expect("free pixmap"); - assert!( - !freed(&backend.calls()), - "FreePixmap must respect a border-only reference" - ); - - // 3. Positive control: B swaps to a solid border, nothing holds the - // tile and the client no longer owns it, so it must be released. - let calls = run_border_request_recording( - &mut state, - 2, - 0, - &border_cwa_body(border_win.0, CWA_BORDER_PIXEL, &[0x0000_00ff]), - ); - assert!( - freed(&calls), - "the fully orphaned host tile must be released, or this test could \ - never observe a free at all" - ); - } - - /// #133: the mirror image of the retention above. A tile kept alive past - /// its `FreePixmap` by a window's border must be RELEASED when that window - /// dies — otherwise nothing is left to notice it: no resource owns it and - /// no window references it. `destroy_window_subtree` collected only - /// background pixmaps, so this leaked the host storage for the rest of the - /// session. - #[test] - fn destroying_a_window_releases_the_border_tile_it_was_keeping_alive() { - const HOST_TILE: u32 = 0x9999_0009; - let host = crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"); - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0031); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - let tile = ResourceId(0x0080_1309); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: tile, - drawable: ROOT_WINDOW, - width: 8, - height: 8, - depth: 24, - }, - ); - assert!(state.resources.set_pixmap_host_xid(tile, host)); - run_border_request( - &mut state, - 2, - 0, - &border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]), - ); - assert_no_error(&read_all_available(&mut peer), "CWA border-pixmap"); - - // The client drops the id; the border reference retains the storage. - let mut backend = RecordingBackend::new(); - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - &free_pixmap_body(tile.0), - ) - .expect("free pixmap"); - assert!( - !backend - .calls() - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))), - "retained while the border holds it" - ); - assert!( - state.resources.host_xid_still_referenced(host), - "the border must be the only thing keeping it alive now" - ); - - // Destroying the window removes that last reference, so the host - // handle has to go with it. - let mut backend = RecordingBackend::new(); - destroy_window_subtree(&mut state, &mut backend, None, win); - assert!( - !state.resources.host_xid_still_referenced(host), - "nothing may reference the tile after the window is destroyed" - ); - assert!( - backend - .calls() - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))), - "destroying the window must release the border tile it was keeping alive" - ); - } - - /// #133 minor: one request replacing BOTH attributes, where both named the - /// same tile, hands the same host handle back twice. Freeing it twice is - /// inert on KMS — the store entry is gone by the second call — but it is a - /// broken backend contract, and a recording or host-X11 backend sees the - /// duplicate. - #[test] - fn replacing_a_shared_background_and_border_frees_the_host_tile_once() { - const HOST_OLD: u32 = 0x9999_000a; - const HOST_NEW: u32 = 0x9999_000b; - const CWA_BACK_PIXMAP: u32 = 0x0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0041); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - - let make_tile = |state: &mut ServerState, id: u32, host: u32| { - let pix = ResourceId(id); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: pix, - drawable: ROOT_WINDOW, - width: 8, - height: 8, - depth: 24, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - pix, - crate::backend::PixmapHandle::from_raw(host).expect("non-zero") - )); - pix - }; - let old = make_tile(&mut state, 0x0080_1310, HOST_OLD); - let new = make_tile(&mut state, 0x0080_1311, HOST_NEW); - - // One tile as BOTH the background and the border. - run_border_request( - &mut state, - 2, - 0, - &border_cwa_body(win.0, CWA_BACK_PIXMAP | CWA_BORDER_PIXMAP, &[old.0, old.0]), - ); - assert_no_error(&read_all_available(&mut peer), "CWA shared tile"); - - // The client drops the id, so only the two attributes hold it and the - // replacement below fully orphans it. - let mut backend = RecordingBackend::new(); - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - &free_pixmap_body(old.0), - ) - .expect("free pixmap"); - - // Replace both in ONE request: `released.background` and - // `released.border` are the same handle. - let calls = run_border_request_recording( - &mut state, - 2, - 0, - &border_cwa_body(win.0, CWA_BACK_PIXMAP | CWA_BORDER_PIXMAP, &[new.0, new.0]), - ); - let frees = calls - .iter() - .filter(|call| matches!(call, RecordedCall::FreePixmap(HOST_OLD))) - .count(); - assert_eq!( - frees, 1, - "the shared host tile must be freed exactly once, got {frees}" - ); - } - - #[test] - fn free_pixmap_retains_host_pixmap_while_gc_tile_still_references_it() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 1, - pixmap: ResourceId(0x3001), - drawable: ROOT_WINDOW, - width: 8, - height: 8, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - ResourceId(0x3001), - crate::backend::PixmapHandle::from_raw(0xbeef).unwrap(), - )); - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(0x2001), - drawable: ROOT_WINDOW, - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: Some(FillStyle::Tiled.protocol_value()), - fill_rule: None, - tile: Some(ResourceId(0x3001)), - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &free_pixmap_body(0x3001), - ) - .expect("free pixmap"); - - let calls = backend.calls.lock().expect("calls"); - assert!( - !calls - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(0xbeef))), - "host pixmap must stay alive while retained by GC tile" - ); - } - - #[test] - fn poly_fill_rectangle_input_only_returns_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 0, - window: ResourceId(0x1100), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 10, - height: 10, - border_width: 0, - class: 2, - visual: ResourceId(0), - ..Default::default() - }, - ); - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(0x2000), - drawable: ROOT_WINDOW, - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - let body = poly_fill_rectangle_body(0x1100, 0x2000); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 70, - data: 0, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - - let bytes = read_all_available(&mut peer); - assert!( - bytes.len() >= 32, - "expected 32-byte error reply, got {} bytes: {:02x?}", - bytes.len(), - bytes - ); - let buf = &bytes[..32]; - assert_eq!(buf[1], x11::error::BAD_MATCH); - assert_eq!(buf[10], 70); - } - - #[test] - fn poly_fill_rectangle_depth_mismatch_returns_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: ResourceId(0x1200), - drawable: ROOT_WINDOW, - width: 4, - height: 4, - depth: 1, - }, - ); - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(0x2000), - drawable: ROOT_WINDOW, - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - let body = poly_fill_rectangle_body(0x1200, 0x2000); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 70, - data: 0, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - None, - ) - .expect("process_request"); - - let bytes = read_all_available(&mut peer); - assert!( - bytes.len() >= 32, - "expected 32-byte error reply, got {} bytes: {:02x?}", - bytes.len(), - bytes - ); - let buf = &bytes[..32]; - assert_eq!(buf[1], x11::error::BAD_MATCH); - assert_eq!(buf[10], 70); - } - - // Reproduces the Cinnamon frame-sync deadlock: muffin arms a SYNC - // alarm on a GTK client's _NET_WM_SYNC_REQUEST_COUNTER and depends - // on AlarmNotify to learn the client finished a frame. Before the - // fix, SetCounter never evaluated alarms and no AlarmNotify was - // ever sent, so muffin never composited and clients froze. - #[test] - fn sync_alarm_fires_alarmnotify_on_watched_counter_crossing() { - let mut state = ServerState::new(); - let mut muffin = install_client(&mut state, 1); - let mut gtk = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - // GTK client (2) creates its frame-sync counter at 0. - handle_sync_request( - &mut state, - &mut backend, - ClientId(2), - SequenceNumber(1), - sync_header(2), // CREATE_COUNTER - &counter_value_body(0x0260_0006, 0), - ) - .unwrap(); - - // muffin (1) arms the alarm. wait_value = counter(0) + 1 = 1, - // so the create-time test (0 >= 1) does not fire. - handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - sync_header(8), // CREATE_ALARM - &muffin_alarm_body(), - ) - .unwrap(); - assert!( - read_all_available(&mut muffin).is_empty(), - "alarm must not fire at creation when wait_value exceeds the counter" - ); - - // GTK client finishes a frame: counter 0 -> 2, crossing 1. - handle_sync_request( - &mut state, - &mut backend, - ClientId(2), - SequenceNumber(2), - sync_header(3), // SET_COUNTER - &counter_value_body(0x0260_0006, 2), - ) - .unwrap(); - - let evt = read_all_available(&mut muffin); - assert_eq!(evt.len(), 32, "exactly one AlarmNotify to the alarm owner"); - assert_eq!(evt[0], 84, "type = SYNC first-event(83) + AlarmNotify(1)"); - assert_eq!(evt[1], 1, "kind = AlarmNotify"); - assert_eq!( - u32::from_le_bytes(evt[4..8].try_into().unwrap()), - 0x01e0_0019, - "alarm id" - ); - assert_eq!( - u32::from_le_bytes(evt[12..16].try_into().unwrap()), - 2, - "counter value carried on the event" - ); - assert_eq!( - u32::from_le_bytes(evt[20..24].try_into().unwrap()), - 1, - "alarm (wait) value that triggered" - ); - assert_eq!(evt[28], 0, "non-zero delta re-arms -> state Active"); - assert!( - read_all_available(&mut gtk).is_empty(), - "AlarmNotify goes to the alarm owner, not the counter setter" - ); - - // Re-arm proof: the next frame (2 -> 4) must fire again. Without - // re-arm the muffin frame loop would stall after one frame. - handle_sync_request( - &mut state, - &mut backend, - ClientId(2), - SequenceNumber(3), - sync_header(3), - &counter_value_body(0x0260_0006, 4), - ) - .unwrap(); - let evt2 = read_all_available(&mut muffin); - assert_eq!( - evt2.len(), - 32, - "second crossing fires again (alarm re-armed)" - ); - assert_eq!( - u32::from_le_bytes(evt2[12..16].try_into().unwrap()), - 4, - "second event carries the new counter value" - ); - } - - #[test] - fn xi_query_version_negotiates_up_to_server_24() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 131, - data: 47, - length_units: 2, - }; - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[2, 0, 4, 0], - ) - .expect("XIQueryVersion 2.4"); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "XIQueryVersion reply size"); - assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2); - assert_eq!(u16::from_le_bytes([wire[10], wire[11]]), 4); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - header, - &[2, 0, 3, 0], - ) - .expect("XIQueryVersion 2.3"); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "XIQueryVersion reply size"); - assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2); - assert_eq!(u16::from_le_bytes([wire[10], wire[11]]), 3); - } - - /// XI1 GetExtensionVersion answers the server's XI version, as Xorg's - /// `ProcXGetExtensionVersion` (Xi/getvers.c: `XIVersion` = 2.4; Xvfb's - /// `xinput --version` reports "XI version on server: 2.4"), with - /// RepType = X_GetExtensionVersion. libXi decides from this reply - /// whether XI 2.2 fields such as a raw event's `sourceid` are valid: - /// the old hard-coded 2.0 made `xinput test-xi2 --root` print every - /// raw key event as `device: 3 (0)` (#173; Xorg: `3 (5)`). A length - /// that doesn't match `nbytes` is BadLength. - #[test] - fn xi_get_extension_version_reports_the_server_version_like_xorg() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let name = b"XInputExtension"; - let mut body = vec![name.len() as u8, 0, 0, 0]; - body.extend_from_slice(name); - body.push(0); - let header = RequestHeader { - opcode: 131, - data: 1, - length_units: 6, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &body, - ) - .expect("GetExtensionVersion"); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "reply size"); - assert_eq!((wire[0], wire[1]), (1, 1), "X_Reply, RepType"); - assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2, "major"); - assert_eq!(u16::from_le_bytes([wire[10], wire[11]]), 4, "minor"); - assert_eq!(wire[12], 1, "present"); - - let short = RequestHeader { - length_units: 5, - ..header - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - short, - &body[..16], - ) - .expect("GetExtensionVersion, wrong length"); - let wire = read_all_available(&mut peer); - assert_eq!((wire[0], wire[1]), (0, x11::error::BAD_LENGTH), "BadLength"); - } - - /// The XI version a client announced is remembered the way Xorg's - /// `ProcXIQueryVersion` stores it, because `FilterRawEvents` reads it. - /// Xvfb capture (probe mon:…:0,2 / 2,0 / 3,2, then a keyboard grab): - /// 2.0 then 2.2 stays 2.0 (still filtered as XI 2.0); 2.2 then 2.0 - /// keeps 2.2 (Xorg answers the 2.0 query with BadValue); 2.3 then 2.2 - /// keeps 2.3; a client that never asks has no version (not filtered). - #[test] - fn xi_query_version_records_client_version_like_xorg() { - let header = RequestHeader { - opcode: 131, - data: 47, - length_units: 2, - }; - let stored_after = |minors: &[u16]| { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - for (i, minor) in minors.iter().enumerate() { - let m = minor.to_le_bytes(); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(u16::try_from(i + 1).unwrap()), - header, - &[2, 0, m[0], m[1]], - ) - .expect("XIQueryVersion"); - } - state.xi2_client_versions.get(&ClientId(1)).copied() - }; - assert_eq!(stored_after(&[]), None); - assert_eq!(stored_after(&[0]), Some((2, 0))); - assert_eq!(stored_after(&[0, 2]), Some((2, 0))); - assert_eq!(stored_after(&[2, 0]), Some((2, 2))); - assert_eq!(stored_after(&[3, 2]), Some((2, 3))); - assert_eq!(stored_after(&[2, 3]), Some((2, 3))); - // Capped at the server's version, as the reply is. - assert_eq!(stored_after(&[9]), Some((2, 4))); - } - - /// XIGrabDevice(keyboard) and an XI2 passive key grab keep the grab's - /// event mask: Xorg delivers an XI2 raw key event to the grab owner - /// only when that mask selects it (DeliverOneGrabbedEvent reads - /// `grab->xi2mask`). - #[test] - fn xi2_keyboard_grabs_keep_their_event_mask() { - const MASK: u32 = (1 << 2) | (1 << 3) | (1 << 13) | (1 << 14); - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = Vec::new(); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); // window - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&3u16.to_le_bytes()); // master keyboard - body.extend_from_slice(&[1, 1, 0, 0]); // async, async, owner_events=0, pad - body.extend_from_slice(&1u16.to_le_bytes()); // mask_len - body.extend_from_slice(&MASK.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 131, - data: 51, - length_units: 7, - }, - &body, - ) - .expect("XIGrabDevice keyboard"); - assert_eq!(state.active_keyboard_grab.map(|g| g.xi2_mask), Some(MASK)); - - let mut body = Vec::new(); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); // grab_window - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&38u32.to_le_bytes()); // detail - body.extend_from_slice(&3u16.to_le_bytes()); // deviceid - body.extend_from_slice(&1u16.to_le_bytes()); // num_modifiers - body.extend_from_slice(&1u16.to_le_bytes()); // mask_len - body.extend_from_slice(&[1, 1, 1, 0]); // Keycode, async, async, owner_events - body.extend_from_slice(&0u16.to_le_bytes()); // pad - body.extend_from_slice(&MASK.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // modifier 0 - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 131, - data: 54, - length_units: 9, - }, - &body, - ) - .expect("XIPassiveGrabDevice keycode"); - assert_eq!(state.key_grabs.last().map(|g| g.xi2_mask), Some(MASK)); - } - - #[test] - fn xi_select_events_on_root_bootstraps_device_changed() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 131, - data: 46, - length_units: 5, - }; - let mut body = Vec::new(); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&1u16.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); // XIAllDevices - body.extend_from_slice(&1u16.to_le_bytes()); // 1 mask word - body.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &body, - ) - .expect("XISelectEvents"); - - let wire = read_all_available(&mut peer); - let event_offset = (0..wire.len().saturating_sub(32)) - .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) - .expect("bootstrap XI_DeviceChanged event"); - assert_eq!(wire[event_offset + 10], 2, "deviceid low byte"); - assert_eq!(wire[event_offset + 16], 7, "num_classes low byte"); - assert_eq!(wire[event_offset + 18], 4, "sourceid low byte"); - } - - // ----------------------------------------------------------------- - // Tier 2 Task 4: device naming from the registry + XI1/XI2 sync - // ----------------------------------------------------------------- - - /// Drive XIQueryDevice (opcode 48) and parse out `(id, name)` for - /// each device in the reply (little-endian fixture clients). - fn query_device_ids_and_names( - state: &mut ServerState, - peer: &mut UnixStream, - ) -> Vec<(u16, String)> { - let mut backend = RecordingBackend::new(); - handle_xi2_request( - state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(48), - &[], - ) - .expect("XIQueryDevice"); - let wire = read_all_available(peer); - let num_devices = u16::from_le_bytes([wire[8], wire[9]]) as usize; - let mut off = 32; - let mut out = Vec::new(); - for _ in 0..num_devices { - let id = u16::from_le_bytes([wire[off], wire[off + 1]]); - let num_classes = u16::from_le_bytes([wire[off + 6], wire[off + 7]]) as usize; - let name_len = u16::from_le_bytes([wire[off + 8], wire[off + 9]]) as usize; - let name_start = off + 12; - let name = String::from_utf8(wire[name_start..name_start + name_len].to_vec()).unwrap(); - // Advance: 12-byte info header + name (padded to 4) + classes. - let mut pos = name_start + name_len; - while !pos.is_multiple_of(4) { - pos += 1; - } - // Walk class blocks by their 4-byte-unit length field (u16 at - // offset +2 of each class header). - for _ in 0..num_classes { - let units = u16::from_le_bytes([wire[pos + 2], wire[pos + 3]]) as usize; - pos += units * 4; - } - out.push((id, name)); - off = pos; - } - out - } - - /// Drive XListInputDevices (XI 1.x, major 131 minor 2) and parse out - /// `(id, name)` for each device. - fn list_input_devices_ids_and_names( - state: &mut ServerState, - peer: &mut UnixStream, - ) -> Vec<(u16, String)> { - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 131, - data: 2, - // ListInputDevices (XI minor 2) is Fixed(1): just the 4-byte - // request header = 1 unit. (Was 0 — pre-dated the length - // gate, now BadLengths before the handler enumerates devices.) - length_units: 1, - }; - handle_xi2_request( - state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[], - ) - .expect("XListInputDevices"); - let wire = read_all_available(peer); - let ndevices = wire[8] as usize; - // Device-info array: 8 bytes each (type ATOM, id, num_classes, - // use, pad). Track ids and per-device class counts. - let mut ids = Vec::new(); - let mut class_counts = Vec::new(); - let mut off = 32; - for _ in 0..ndevices { - ids.push(u16::from(wire[off + 4])); - class_counts.push(wire[off + 5] as usize); - off += 8; - } - // Class-info blocks: walk by the BYTE length field (offset +1). - for &nc in &class_counts { - for _ in 0..nc { - let len = wire[off + 1] as usize; - off += len; - } - } - // STR name list: 1 length byte + bytes, in device order. - let mut out = Vec::new(); - for &id in &ids { - let n = wire[off] as usize; - let name = String::from_utf8(wire[off + 1..off + 1 + n].to_vec()).unwrap(); - out.push((id, name)); - off += 1 + n; - } - out - } - - #[test] - fn xiquerydevice_reports_slave_pointer_registry_name_after_rename() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // Rename device 4 in the registry (simulating a seeded touchpad). - state - .xi_devices - .iter_mut() - .find(|d| d.id == 4) - .unwrap() - .name = "SynPS/2 Synaptics TouchPad".to_owned(); - - let devs = query_device_ids_and_names(&mut state, &mut peer); - let slave = devs.iter().find(|(id, _)| *id == 4).expect("device 4"); - assert_eq!( - slave.1, "SynPS/2 Synaptics TouchPad", - "XIQueryDevice must report device 4's registry name" - ); - } - - #[test] - fn xi1_and_xi2_report_same_device_ids_and_names() { - // Default (no touchpad): both enumerations must agree. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let xi2 = query_device_ids_and_names(&mut state, &mut peer); - let xi1 = list_input_devices_ids_and_names(&mut state, &mut peer); - assert_eq!(xi2, xi1, "XI1 and XI2 must agree on (id, name) by default"); - - // After a touchpad rename, both must STILL agree — this is the - // ListInputDevices fatal-CHECK guard: Chromium/Electron compare - // the two enumerations and crash on any divergence. - state - .xi_devices - .iter_mut() - .find(|d| d.id == 4) - .unwrap() - .name = "ETPS/2 Elantech Touchpad".to_owned(); - let xi2 = query_device_ids_and_names(&mut state, &mut peer); - let xi1 = list_input_devices_ids_and_names(&mut state, &mut peer); - assert_eq!( - xi2, xi1, - "XI1 and XI2 must agree on (id, name) after a touchpad rename" - ); - assert_eq!( - xi2.iter().find(|(id, _)| *id == 4).unwrap().1, - "ETPS/2 Elantech Touchpad", - "both enumerations carry the renamed slave pointer" - ); - } - - /// Drive `XListInputDevices` (XI 1.x, major 131 minor 2) and return - /// the type-atom `u32` for each device in order `[2, 3, 4, 5]`. - /// The atom sits at bytes 0-3 of each 8-byte device-info descriptor - /// immediately after the 32-byte reply header. - fn list_input_devices_type_atoms(state: &mut ServerState, peer: &mut UnixStream) -> [u32; 4] { - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 131, - data: 2, - // ListInputDevices (XI minor 2) is Fixed(1): just the 4-byte - // request header = 1 unit. (Was 0 — pre-dated the length - // gate, now BadLengths before the handler enumerates devices.) - length_units: 1, - }; - handle_xi2_request( - state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &[], - ) - .expect("XListInputDevices"); - let wire = read_all_available(peer); - let ndevices = wire[8] as usize; - assert_eq!(ndevices, 4, "expected 4 devices"); - let mut result = [0u32; 4]; - let mut off = 32; - for r in result.iter_mut().take(ndevices) { - *r = u32::from_le_bytes([wire[off], wire[off + 1], wire[off + 2], wire[off + 3]]); - off += 8; - } - result - } - - /// `XListInputDevices` device-type atoms: before seeding, device 4 - /// (slave pointer) must carry the MOUSE atom; after `xi_seed_touchpad` - /// it must carry the TOUCHPAD atom; after `xi_clear_touchpad` it must - /// revert to MOUSE. Devices 2 (master ptr) and 3/5 (keyboards) are - /// always MOUSE/KEYBOARD respectively. - #[test] - fn list_input_devices_device4_type_atom_matches_touchpad_state() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - // Look up the pre-interned type atoms from the server's atom table. - let mouse_atom = state.atoms.intern(crate::xinput::XI_ATOM_MOUSE, true).0; - let kbd_atom = state.atoms.intern(crate::xinput::XI_ATOM_KEYBOARD, true).0; - let touchpad_atom = state.atoms.intern(crate::xinput::XI_ATOM_TOUCHPAD, true).0; - assert_ne!(mouse_atom, 0, "MOUSE pre-interned"); - assert_ne!(kbd_atom, 0, "KEYBOARD pre-interned"); - assert_ne!(touchpad_atom, 0, "TOUCHPAD pre-interned"); - - // Before seeding: device 4 should be MOUSE. - let types = list_input_devices_type_atoms(&mut state, &mut peer); - assert_eq!(types[0], mouse_atom, "device 2 = MOUSE"); - assert_eq!(types[1], kbd_atom, "device 3 = KEYBOARD"); - assert_eq!( - types[2], mouse_atom, - "device 4 = MOUSE before touchpad seed" - ); - assert_eq!(types[3], kbd_atom, "device 5 = KEYBOARD"); - - // Seed a touchpad onto device 4: type must become TOUCHPAD. - let touchpad_info = crate::core_loop::DeviceInfo { - name: "SynPS/2 Synaptics TouchPad".into(), - device_node: "/dev/input/event4".into(), - sysname: "event4".into(), - vendor_id: 0x046d, - product_id: 0xc52f, - is_touchpad: true, - config: crate::core_loop::message::LibinputConfigSnapshot { - tap: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: false, - }, - natural_scroll: crate::core_loop::message::BoolSetting { - available: true, - current: false, - default: true, - }, - dwt: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: true, - }, - ..Default::default() - }, - }; - state.xi_seed_touchpad(&touchpad_info); - let types = list_input_devices_type_atoms(&mut state, &mut peer); - assert_eq!(types[2], touchpad_atom, "device 4 = TOUCHPAD after seed"); - - // Clear it: device 4 must revert to MOUSE. - state.xi_clear_touchpad("/dev/input/event4"); - let types = list_input_devices_type_atoms(&mut state, &mut peer); - assert_eq!(types[2], mouse_atom, "device 4 = MOUSE after clear"); - } - - /// Drive XIQueryDevice (opcode 48) and return the RAW class-block - /// bytes (and `num_classes`) for device 4 only — the slave pointer. - /// Walks the device-info array exactly like - /// `query_device_ids_and_names` but, for the device whose id is 4, - /// slices out the trailing class bytes rather than just the name. - fn query_device_4_class_block( - state: &mut ServerState, - peer: &mut UnixStream, - ) -> (Vec, u16) { - let mut backend = RecordingBackend::new(); - handle_xi2_request( - state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(48), - &[], - ) - .expect("XIQueryDevice"); - let wire = read_all_available(peer); - let num_devices = u16::from_le_bytes([wire[8], wire[9]]) as usize; - let mut off = 32; - for _ in 0..num_devices { - let id = u16::from_le_bytes([wire[off], wire[off + 1]]); - let num_classes = u16::from_le_bytes([wire[off + 6], wire[off + 7]]); - let name_len = u16::from_le_bytes([wire[off + 8], wire[off + 9]]) as usize; - let mut pos = off + 12 + name_len; - while !pos.is_multiple_of(4) { - pos += 1; - } - let classes_start = pos; - for _ in 0..num_classes { - let units = u16::from_le_bytes([wire[pos + 2], wire[pos + 3]]) as usize; - pos += units * 4; - } - if id == 4 { - return (wire[classes_start..pos].to_vec(), num_classes); - } - off = pos; - } - panic!("device 4 not present in XIQueryDevice reply"); - } - - /// Regression guard: the device-4 class block XIQueryDevice (opcode - /// 48) emits MUST be byte-identical to the block carried by the - /// touchpad-add/remove `XI_DeviceChanged` fanout. Both callers now go - /// through `fanout::build_slave_pointer_class_block`, so they cannot - /// drift; this test parses the real XIQueryDevice wire bytes and - /// compares them against the shared builder's output (the path the - /// fanout uses) to keep that guarantee under test. - #[test] - fn query_device_4_matches_device_changed_block() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let (wire_classes, wire_num) = query_device_4_class_block(&mut state, &mut peer); - let (builder_classes, builder_num) = - crate::core_loop::fanout::build_slave_pointer_class_block(&mut state); - - assert_eq!( - wire_num, builder_num, - "XIQueryDevice device-4 num_classes must match the shared builder" - ); - assert_eq!( - wire_classes, builder_classes, - "XIQueryDevice device-4 class bytes must be byte-identical to the \ - XI_DeviceChanged fanout block (both call build_slave_pointer_class_block)" - ); - - // Also hold under a seeded-touchpad rename: the class shape is - // name-independent, so the two must STILL match byte-for-byte. - state - .xi_devices - .iter_mut() - .find(|d| d.id == 4) - .unwrap() - .name = "SynPS/2 Synaptics TouchPad".to_owned(); - let (wire_classes, _) = query_device_4_class_block(&mut state, &mut peer); - let (builder_classes, _) = - crate::core_loop::fanout::build_slave_pointer_class_block(&mut state); - assert_eq!( - wire_classes, builder_classes, - "device-4 class blocks must stay byte-identical after a touchpad rename" - ); - } - - /// Tier 2b T7 regression: the `XI_DeviceChanged` event emitted by - /// `emit_xi2_device_changed_bootstrap` (driven from XISelectEvents at - /// connect time) must advertise the SAME scroll-class `flags` u32 as - /// XIQueryDevice does, namely `0`. xserver populates both paths from a - /// single `axis->scroll.flags` source (`Xi/xiquerydevice.c:ListScrollInfo` - /// and `dix/eventconvert.c:appendScrollInfo`), so they cannot legitimately - /// differ. yserver's XIQueryDevice site emits `0`; a stale `flags = 1` in - /// the bootstrap path would re-arm the 2026-05-29 Chrome crash-class - /// (NoEmulation declared while still emitting emulated XI_ButtonPress - /// 4..7). - #[test] - fn t7_xi2_device_changed_bootstrap_scroll_flags_match_xiquerydevice() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - emit_xi2_device_changed_bootstrap( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(7), - XI2_MAJOR_OPCODE, - ) - .expect("emit_xi2_device_changed_bootstrap"); - - let wire = read_all_available(&mut peer); - // Locate the XI_DeviceChanged event (opcode 35, evtype 1). - let off = (0..wire.len().saturating_sub(32)) - .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) - .expect("XI_DeviceChanged event in wire"); - assert_eq!(wire[off + 1], XI2_MAJOR_OPCODE, "major opcode = XI2 ext"); - // Header layout (see encode_xi2_device_changed_event): - // 0 u8 35 (GenericEvent) - // 1 u8 major_opcode - // 2..4 u16 sequence - // 4..8 u32 length (classes.len() / 4) - // 8..10 u16 evtype = 1 - // 10..12 u16 deviceid - // 12..16 u32 time - // 16..18 u16 num_classes - // 18..20 u16 sourceid - // 20 u8 reason - // 21..32 pad - // 32.. classes - let num_classes = u16::from_le_bytes([wire[off + 16], wire[off + 17]]); - assert_eq!(num_classes, 7, "Button + 4 Valuators + 2 Scrolls"); - - // Walk past the 32-byte event header and the non-scroll classes. - // Layout matches what `emit_xi2_device_changed_bootstrap` writes: - // - 32 bytes header - // - Button(7): 8 (header) + 4 (state words for 7 buttons) + 4*7 - // = 40 bytes - // - Valuator x4: 11 units * 4 = 44 bytes each, 176 total - // - Scroll x2: 6 units * 4 = 24 bytes each - let classes_start = off + 32; - let mut pos = classes_start; - let mut scroll_offsets = Vec::new(); - for _ in 0..num_classes { - let cls_type = u16::from_le_bytes([wire[pos], wire[pos + 1]]); - let units = u16::from_le_bytes([wire[pos + 2], wire[pos + 3]]) as usize; - if cls_type == 3 { - // Scroll class — `flags` is a u32 at offset 12 within the - // 24-byte class body (after type/length/sourceid/number/ - // scroll_type/pad). - scroll_offsets.push(pos); - } - pos += units * 4; - } - assert_eq!(scroll_offsets.len(), 2, "two scroll classes (V + H)"); - for s_off in scroll_offsets { - let flags = u32::from_le_bytes([ - wire[s_off + 12], - wire[s_off + 13], - wire[s_off + 14], - wire[s_off + 15], - ]); - assert_eq!( - flags, 0, - "XI_DeviceChanged scroll flags must match XIQueryDevice (0); see the \ - XIQueryDevice `write_scroll_class` comment for the 2026-05-29 \ - Chrome crash-class rationale" - ); - } - } - - #[test] - fn device_changed_emitted_to_selecting_client_on_touchpad_add_and_remove() { - use crate::{ - core_loop::fanout::emit_xi2_device_changed_slave_pointer, - xinput::DEVICEID_SLAVE_POINTER, - }; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // Client selects XI_DeviceChanged on the slave pointer (device 4) - // at the root window — the way GDK/Chromium subscribe. - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (ROOT_WINDOW, DEVICEID_SLAVE_POINTER), - u64::from(XI2_DEVICE_CHANGED_MASK), - ); - - // Touchpad add → DeviceChanged for device 4. - let info = crate::core_loop::DeviceInfo { - name: "SynPS/2 Synaptics TouchPad".into(), - device_node: "/dev/input/event4".into(), - sysname: "event4".into(), - vendor_id: 0x046d, - product_id: 0xc52f, - is_touchpad: true, - config: crate::core_loop::message::LibinputConfigSnapshot { - tap: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: false, - }, - natural_scroll: crate::core_loop::message::BoolSetting { - available: true, - current: false, - default: true, - }, - dwt: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: true, - }, - ..Default::default() - }, - }; - state.xi_seed_touchpad(&info); - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - let wire = read_all_available(&mut peer); - let off = (0..wire.len().saturating_sub(32)) - .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) - .expect("XI_DeviceChanged on add"); - assert_eq!(wire[off + 10], 4, "deviceid = slave pointer"); - assert_eq!(wire[off + 18], 4, "sourceid = the device itself"); - assert_eq!(wire[off + 20], 2, "reason = XIDeviceChange"); - assert_eq!(wire[off + 16], 7, "num_classes low byte"); - - // Touchpad remove → DeviceChanged again. - state.xi_clear_touchpad(&info.device_node); - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - let wire = read_all_available(&mut peer); - let off = (0..wire.len().saturating_sub(32)) - .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) - .expect("XI_DeviceChanged on remove"); - assert_eq!(wire[off + 10], 4, "deviceid = slave pointer"); - } - - #[test] - fn device_changed_is_noop_when_no_client_selected() { - use crate::core_loop::fanout::emit_xi2_device_changed_slave_pointer; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // No xi2_masks selection → no event. - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - assert!( - read_all_available(&mut peer).is_empty(), - "no DeviceChanged when nothing selected" - ); - } - - #[test] - fn device_changed_not_sent_for_selection_on_non_root_window() { - // DeviceChanged is a root-window hierarchy event. A client that - // selected it on some unrelated (non-root) window must NOT get it - // — otherwise the fanout spuriously delivers to the wrong window. - use crate::{ - core_loop::fanout::emit_xi2_device_changed_slave_pointer, - xinput::DEVICEID_SLAVE_POINTER, - }; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let non_root = ResourceId(0x4000_0001); - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (non_root, DEVICEID_SLAVE_POINTER), - u64::from(XI2_DEVICE_CHANGED_MASK), - ); - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - assert!( - read_all_available(&mut peer).is_empty(), - "selection on a non-root window must not receive DeviceChanged" - ); - } - - // ----------------------------------------------------------------- - // Tier 2 Task 3: XI2 device-property requests (dispatch-level, wire bytes) - // ----------------------------------------------------------------- - - /// Header for an XI2 (major 131) request with the given minor opcode. - fn xi2_header(minor: u8) -> RequestHeader { - // Declare the spec-correct request length so the dispatcher's - // REQUEST_SIZE_MATCH gate (validate_xi_request_length) doesn't - // BadLength the request before it reaches the handler. These - // fixtures pre-date that XTS-driven length gate and used a - // placeholder length_units=1; for Fixed-size minors the table - // value IS the exact wire length, for variable minors it is the - // spec minimum (payload-carrying variable requests build their - // own header — see xi2_header_for_body). - use yserver_protocol::x11::request_lengths::{LenSpec, xi_request_length}; - let length_units = match xi_request_length(minor) { - Some(LenSpec::Fixed(n) | LenSpec::AtLeast(n)) => n, - None => 1, - }; - RequestHeader { - opcode: 131, - data: minor, - length_units, - } - } - - /// Header for a variable-length XI minor whose body carries a payload - /// (e.g. XIChangeProperty value bytes): the exact-length gate requires - /// `length_units` to match the actual body, so derive it from `body`. - fn xi2_header_for_body(minor: u8, body: &[u8]) -> RequestHeader { - RequestHeader { - opcode: 131, - data: minor, - length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap_or(1), - } - } - - /// Seed the slave-pointer device (id 4) with one INTEGER/8 property - /// keyed by a synthetic atom whose numeric id is supplied by the - /// caller. The atom is registered into `state.atoms` so it passes - /// the T3 BadAtom guard in the property dispatch arms — historical - /// test fixtures pass 100/200, which sit outside the well-known - /// range and would otherwise look "uninterned" to the dispatcher. - fn seed_one_prop(state: &mut ServerState, atom: u32, format: u8, data: Vec) { - state - .atoms - .register_for_test(AtomId(atom), &format!("test-prop-{atom}")); - let dev = state - .xi_devices - .iter_mut() - .find(|d| d.id == 4) - .expect("slave pointer"); - dev.properties.insert( - AtomId(atom), - crate::xinput::XiProperty { - type_atom: crate::xinput::XA_INTEGER, - format, - data, - }, - ); - } - - #[test] - fn xi_list_properties_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - seed_one_prop(&mut state, 200, 8, vec![2]); - - // body: deviceid=4 (u16) + pad(u16). - let body = [4u8, 0, 0, 0]; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(56), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32 + 8, "32 header + 2 atoms"); - assert_eq!(wire[0], 1, "X_Reply"); - assert_eq!( - u32::from_le_bytes(wire[4..8].try_into().unwrap()), - 2, - "length" - ); - assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2, "num_properties"); - assert_eq!(u32::from_le_bytes(wire[32..36].try_into().unwrap()), 100); - assert_eq!(u32::from_le_bytes(wire[36..40].try_into().unwrap()), 200); - } - - #[test] - fn xi_list_properties_bad_device() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = [99u8, 0, 0, 0]; // deviceid 99 — not present - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(7), - xi2_header(56), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error is 32 bytes"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!( - wire[1], XI2_FIRST_ERROR, - "BadDevice = XI2_FIRST_ERROR (157)" - ); - // sequence at bytes 2-3. - assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 7); - } - - #[test] - fn xi_get_property_full_read_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![0xAB]); - - // body: deviceid(2)=4, delete(1)=0, pad(1), property(4)=100, - // type(4)=0(Any), offset(4)=0, len(4)=100. - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(0); // delete - body.push(0); // pad - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(59), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32 + 4, "header + 1 byte padded to 4"); - assert_eq!( - u32::from_le_bytes(wire[8..12].try_into().unwrap()), - 19, - "type=INTEGER" - ); - assert_eq!( - u32::from_le_bytes(wire[12..16].try_into().unwrap()), - 0, - "bytes_after" - ); - assert_eq!( - u32::from_le_bytes(wire[16..20].try_into().unwrap()), - 1, - "num_items" - ); - assert_eq!(wire[20], 8, "format"); - assert_eq!(wire[32], 0xAB, "value byte"); - } - - #[test] - fn xi_get_property_bad_delete_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // device 4 exists; delete = 2 (illegal) → BadValue. - // Pre-register atom 100 so the BadAtom guard (T3) doesn't fire - // before the bad-delete check we're actually exercising. - state.atoms.register_for_test(AtomId(100), "test-prop-100"); - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(2); // delete = 2 (illegal) - body.push(0); - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&1u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(3), - xi2_header(59), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], 2, "BadValue"); - } - - #[test] - fn xi_change_then_get_roundtrip_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Pre-register atom 100 so the T3 BadAtom guard accepts it. - state.atoms.register_for_test(AtomId(100), "test-prop-100"); - - // XIChangeProperty: deviceid(2)=4, mode(1)=Replace, format(1)=8, - // property(4)=100, type(4)=INTEGER(19), num_items(4)=3, data=[7,8,9]+pad. - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(0); // mode Replace - body.push(8); // format - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&19u32.to_le_bytes()); - body.extend_from_slice(&3u32.to_le_bytes()); - body.extend_from_slice(&[7, 8, 9, 0]); // 3 data bytes + 1 pad - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - // ChangeProperty has no reply. - assert!(read_all_available(&mut peer).is_empty()); - - // GetProperty back. - let mut gbody = Vec::new(); - gbody.extend_from_slice(&4u16.to_le_bytes()); - gbody.push(0); - gbody.push(0); - gbody.extend_from_slice(&100u32.to_le_bytes()); - gbody.extend_from_slice(&0u32.to_le_bytes()); - gbody.extend_from_slice(&0u32.to_le_bytes()); - gbody.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(59), - &gbody, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!( - u32::from_le_bytes(wire[16..20].try_into().unwrap()), - 3, - "num_items" - ); - assert_eq!(&wire[32..35], &[7, 8, 9], "value round-trips"); - } - - #[test] - fn xi_change_property_bad_format_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(0); // mode - body.push(7); // format = 7 (illegal) - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&19u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(4), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], 2, "BadValue"); - } - - #[test] - fn xi_change_property_unknown_device_outranks_bad_format() { - // Error-precedence: xserver ProcXIChangeProperty (xiproperty.c:1137) - // does the device lookup before validating mode/format, so an - // unknown device + illegal format must yield BadDevice, not BadValue. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = Vec::new(); - body.extend_from_slice(&99u16.to_le_bytes()); // deviceid 99 — absent - body.push(0); // mode - body.push(7); // format = 7 (illegal) - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&19u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(5), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], XI2_FIRST_ERROR, "BadDevice outranks BadValue"); - assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 5, "sequence"); - } - - #[test] - fn xi_delete_property_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - - // body: deviceid(2)=4, pad(2), property(4)=100. - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(58), - &body, - ) - .unwrap(); - // No reply for DeleteProperty. - assert!(read_all_available(&mut peer).is_empty()); - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - assert!( - !dev.properties.contains_key(&AtomId(100)), - "property removed" - ); - } - - // ----------------------------------------------------------------- - // XI 1.x device-property dispatch (minors 36/37/38/39) — byte-level. - // These are the path MATE's settings daemon actually uses - // (OpenDevice + GetDeviceProperty), distinct from the XI2 path above. - // ----------------------------------------------------------------- - - /// Build an `xGetDevicePropertyReq` body (bytes after the 4-byte - /// generic header): property(4), type(4), longOffset(4), longLength(4), - /// deviceid(1, CARD8), delete(1), pad(2). - fn xi1_get_property_body( - property: u32, - type_atom: u32, - offset: u32, - len: u32, - deviceid: u8, - delete: u8, - ) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&property.to_le_bytes()); - body.extend_from_slice(&type_atom.to_le_bytes()); - body.extend_from_slice(&offset.to_le_bytes()); - body.extend_from_slice(&len.to_le_bytes()); - body.push(deviceid); - body.push(delete); - body.extend_from_slice(&0u16.to_le_bytes()); - body - } - - #[test] - fn xi1_get_device_property_tapping_enabled_wire() { - // Mirrors MATE's read of "libinput Tapping Enabled" on the - // seeded touchpad (device 4): INTEGER/8/[1], deviceid echoed. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.xi_seed_touchpad(&crate::core_loop::DeviceInfo { - name: "SynPS/2 Synaptics TouchPad".into(), - device_node: "/dev/input/event4".into(), - sysname: "event4".into(), - vendor_id: 0x046d, - product_id: 0xc52f, - is_touchpad: true, - config: crate::core_loop::message::LibinputConfigSnapshot { - tap: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: false, - }, - natural_scroll: crate::core_loop::message::BoolSetting { - available: true, - current: false, - default: true, - }, - dwt: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: true, - }, - ..Default::default() - }, - }); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi1_get_property_body(tap_atom, 0 /* AnyPropertyType */, 0, 100, 4, 0); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(0x1234), - xi2_header(39), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - // 32-byte header + 1 data byte padded to 4 → 36. - assert_eq!(wire.len(), 36); - assert_eq!(wire[0], 1, "X_Reply"); - assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 0x1234, "sequence"); - assert_eq!( - u32::from_le_bytes(wire[4..8].try_into().unwrap()), - 1, - "length = ceil(1/4)" - ); - assert_eq!( - u32::from_le_bytes(wire[8..12].try_into().unwrap()), - integer_atom, - "type = INTEGER" - ); - assert_eq!( - u32::from_le_bytes(wire[12..16].try_into().unwrap()), - 0, - "bytes_after = 0" - ); - assert_eq!( - u32::from_le_bytes(wire[16..20].try_into().unwrap()), - 1, - "num_items = 1" - ); - assert_eq!(wire[20], 8, "format = 8"); - assert_eq!(wire[21], 4, "deviceid echoed (XI1-specific byte)"); - assert!(wire[22..32].iter().all(|&b| b == 0), "pad1..pad3 zero"); - assert_eq!(wire[32], 1, "value = tap enabled"); - assert_eq!(&wire[33..36], &[0, 0, 0], "value padding"); - } - - #[test] - fn xi1_get_device_property_absent_returns_none() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // device 4 exists but has no property at atom 999. The atom - // ITSELF must be valid (T3 BadAtom guard); the test checks the - // distinct case where the atom is interned but the device has - // no value for it. - state.atoms.register_for_test(AtomId(999), "test-prop-999"); - let body = xi1_get_property_body(999, 0, 0, 100, 4, 0); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(3), - xi2_header(39), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "no data for absent property"); - assert_eq!(wire[0], 1, "X_Reply (not error)"); - assert_eq!( - u32::from_le_bytes(wire[8..12].try_into().unwrap()), - 0, - "type = None" - ); - assert_eq!( - u32::from_le_bytes(wire[12..16].try_into().unwrap()), - 0, - "bytes_after = 0" - ); - assert_eq!(wire[20], 0, "format = 0"); - assert_eq!(wire[21], 4, "deviceid still echoed"); - } - - #[test] - fn xi1_get_device_property_type_mismatch_metadata_only() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Seed an INTEGER/8 prop at atom 100, then ask for STRING. - seed_one_prop(&mut state, 100, 8, vec![0xAB]); - let string_atom = crate::xinput::XA_STRING.0; - let body = xi1_get_property_body(100, string_atom, 0, 100, 4, 0); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(4), - xi2_header(39), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "no value bytes on mismatch"); - assert_eq!( - u32::from_le_bytes(wire[8..12].try_into().unwrap()), - crate::xinput::XA_INTEGER.0, - "type = stored INTEGER" - ); - assert_eq!( - u32::from_le_bytes(wire[12..16].try_into().unwrap()), - 1, - "bytes_after = stored item count" - ); - assert_eq!( - u32::from_le_bytes(wire[16..20].try_into().unwrap()), - 0, - "num_items = 0" - ); - assert_eq!(wire[20], 8, "format = stored"); - assert_eq!(wire[21], 4, "deviceid echoed"); - } - - #[test] - fn xi1_get_device_property_bad_device() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Pre-register atom 100 so the BadAtom guard doesn't fire before - // the bad-device check the test is exercising. - state.atoms.register_for_test(AtomId(100), "test-prop-100"); - let body = xi1_get_property_body(100, 0, 0, 100, 99, 0); // device 99 absent - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(9), - xi2_header(39), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error is 32 bytes"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!( - wire[1], XI2_FIRST_ERROR, - "BadDevice = XI2_FIRST_ERROR (157)" - ); - assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 9, "sequence"); - } - - #[test] - fn xi1_get_device_property_bad_delete_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.atoms.register_for_test(AtomId(100), "test-prop-100"); - let body = xi1_get_property_body(100, 0, 0, 1, 4, 2); // delete = 2 (illegal) - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(11), - xi2_header(39), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], 2, "BadValue"); - } - - #[test] - fn xi1_list_device_properties_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - seed_one_prop(&mut state, 200, 8, vec![2]); - - // xListDevicePropertiesReq body: deviceid(1), pad0(1), pad1(2). - let body = [4u8, 0, 0, 0]; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(36), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32 + 8, "32 header + 2 atoms"); - assert_eq!(wire[0], 1, "X_Reply"); - assert_eq!( - u32::from_le_bytes(wire[4..8].try_into().unwrap()), - 2, - "length = nAtoms" - ); - assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2, "nAtoms"); - assert!(wire[10..32].iter().all(|&b| b == 0), "pad zero"); - assert_eq!(u32::from_le_bytes(wire[32..36].try_into().unwrap()), 100); - assert_eq!(u32::from_le_bytes(wire[36..40].try_into().unwrap()), 200); - } - - #[test] - fn xi1_list_device_properties_bad_device() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = [99u8, 0, 0, 0]; // device 99 absent - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(36), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], XI2_FIRST_ERROR, "BadDevice"); - } - - #[test] - fn xi1_change_then_get_roundtrip_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Pre-register atom 100 (T3 BadAtom guard). - state.atoms.register_for_test(AtomId(100), "test-prop-100"); - - // xChangeDevicePropertyReq body: property(4)=100, type(4)=INTEGER, - // deviceid(1)=4, format(1)=8, mode(1)=Replace, pad(1), - // nUnits(4)=3, value=[7,8,9]+pad. - let mut body = Vec::new(); - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&crate::xinput::XA_INTEGER.0.to_le_bytes()); - body.push(4); // deviceid (CARD8) - body.push(8); // format - body.push(crate::xinput::XI_PROP_MODE_REPLACE); // mode - body.push(0); // pad - body.extend_from_slice(&3u32.to_le_bytes()); - body.extend_from_slice(&[7, 8, 9, 0]); // 3 data bytes + 1 pad - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(37), - &body, - ) - .unwrap(); - // ChangeDeviceProperty has no reply. - assert!(read_all_available(&mut peer).is_empty()); - - // Read it back via XI1 GetDeviceProperty. - let gbody = xi1_get_property_body(100, 0, 0, 100, 4, 0); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(39), - &gbody, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!( - u32::from_le_bytes(wire[16..20].try_into().unwrap()), - 3, - "num_items" - ); - assert_eq!(wire[21], 4, "deviceid echoed"); - assert_eq!(&wire[32..35], &[7, 8, 9], "value round-trips"); - } - - #[test] - fn xi1_change_device_property_bad_device_outranks_format() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = Vec::new(); - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&crate::xinput::XA_INTEGER.0.to_le_bytes()); - body.push(99); // deviceid (CARD8) absent - body.push(7); // format 7 (illegal) - body.push(0); // mode - body.push(0); // pad - body.extend_from_slice(&0u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(5), - xi2_header(37), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], XI2_FIRST_ERROR, "BadDevice outranks BadValue"); - } - - #[test] - fn xi1_delete_device_property_wire() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - - // xDeleteDevicePropertyReq body: property(4)=100, deviceid(1)=4, - // pad0(1), pad1(2). - let mut body = Vec::new(); - body.extend_from_slice(&100u32.to_le_bytes()); - body.push(4); // deviceid (CARD8) - body.push(0); - body.extend_from_slice(&0u16.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(38), - &body, - ) - .unwrap(); - assert!(read_all_available(&mut peer).is_empty(), "no reply"); - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - assert!( - !dev.properties.contains_key(&AtomId(100)), - "property removed" - ); - } - - // ----------------------------------------------------------------- - // T3 dispatch: validate→apply→commit + BadAtom/BadAccess/BadValue. - // These exercise the new descriptor-aware path against a seeded - // touchpad; the recording backend's default `apply_device_config` - // returns `Ok(())`, so successful writes commit to the registry. - // ----------------------------------------------------------------- - - /// Build an `xXIChangePropertyReq` body (after the 4-byte generic - /// header): deviceid(2), mode(1), format(1), property(4), type(4), - /// num_items(4), value(num_items * format/8). The caller is - /// responsible for any 4-byte pad on the wire — the body slice we - /// hand to `handle_xi2_request` doesn't need it because each test - /// passes the raw data block directly. - fn xi2_change_property_body( - deviceid: u16, - mode: u8, - format: u8, - property: u32, - type_atom: u32, - data: &[u8], - ) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&deviceid.to_le_bytes()); - body.push(mode); - body.push(format); - body.extend_from_slice(&property.to_le_bytes()); - body.extend_from_slice(&type_atom.to_le_bytes()); - let num_items = data.len() / usize::from(format / 8); - body.extend_from_slice(&(num_items as u32).to_le_bytes()); - body.extend_from_slice(data); - // 4-byte pad on the value tail. - while body.len() % 4 != 0 { - body.push(0); - } - body - } - - /// Seed a touchpad onto device 4 with tap available+current+default. - /// Mirrors the MATE test fixture used elsewhere in this module. - fn seed_touchpad_for_t3(state: &mut ServerState) { - state.xi_seed_touchpad(&crate::core_loop::DeviceInfo { - name: "SynPS/2 Synaptics TouchPad".into(), - device_node: "/dev/input/event4".into(), - sysname: "event4".into(), - vendor_id: 0x046d, - product_id: 0xc52f, - is_touchpad: true, - config: crate::core_loop::message::LibinputConfigSnapshot { - tap: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: false, - }, - natural_scroll: crate::core_loop::message::BoolSetting { - available: true, - current: false, - default: true, - }, - dwt: crate::core_loop::message::BoolSetting { - available: true, - current: true, - default: true, - }, - scroll_method: crate::core_loop::message::OneHot3 { - available_mask: 0b111, - current: Some(0), - default: Some(0), - }, - ..Default::default() - }, - }); - } - - #[test] - fn t3_xi2_change_property_writable_descriptor_commits_to_registry() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - // Write `[0]` (disable tap) to a writable Bool descriptor. - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "successful XIChangeProperty has no reply" - ); - // Registry now holds the new value. - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - let prop = dev.properties.get(&AtomId(tap_atom)).expect("tap stored"); - assert_eq!(prop.format, 8); - assert_eq!(prop.data, vec![0], "tap toggled off"); - } - - // ----------------------------------------------------------------- - // T3 B1 (review round): `dispatch_change_property` must pin the - // request's `format`/`type_atom` to the descriptor's before running - // `validate_value`/`decode_change` — the latter's fixed-width - // decoders (`float32`, `card32`) index the value slice assuming - // `validate_value` already enforced the descriptor's real width. - // Before the fix, a request lying about `format` slipped a - // too-short value past `validate_value` (which derived its expected - // length from the *request's* format) and then panicked on - // out-of-bounds indexing in `decode_change` — a client-reachable - // server crash. These tests drive the real dispatch path (not - // `validate_value` in isolation) so a regression shows up as either - // a wrong error or a test-thread panic. - // ----------------------------------------------------------------- - - /// Build an `xChangeDevicePropertyReq` body (after the 4-byte - /// generic header): property(4), type(4), deviceid(1), format(1), - /// mode(1), pad(1), num_items(4), value(num_items * format/8, - /// padded to 4 bytes) — mirrors `xi2_change_property_body` for the - /// XI1 wire layout (XIproto.h:1462-1473). - fn xi1_change_property_body( - property: u32, - type_atom: u32, - deviceid: u8, - format: u8, - mode: u8, - data: &[u8], - ) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&property.to_le_bytes()); - body.extend_from_slice(&type_atom.to_le_bytes()); - body.push(deviceid); - body.push(format); - body.push(mode); - body.push(0); // pad - let num_items = data.len() / usize::from(format / 8); - body.extend_from_slice(&(num_items as u32).to_le_bytes()); - body.extend_from_slice(data); - while body.len() % 4 != 0 { - body.push(0); - } - body - } - - #[test] - fn b1_xi2_change_property_format8_scalar_float_mismatch_is_badmatch_no_panic() { - // `libinput Accel Speed` is Scalar/Float, descriptor format 32. - // A `format=8, num_items=1` write used to pass `validate_value` - // (which computed its expected length from the request's - // format) and then panic in `decode_change`'s `float32(&[7])` - // (`b[1]` out of bounds). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let accel_speed_atom = state.atoms.intern("libinput Accel Speed", false).0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - accel_speed_atom, - crate::xinput::XA_INTEGER.0, - &[7], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], x11::error::BAD_MATCH, "BadMatch, not a panic"); - } - - #[test] - fn b1_xi2_change_property_format16_scalar_float_mismatch_is_badmatch() { - // Same target, format=16 (still not the descriptor's 32). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let accel_speed_atom = state.atoms.intern("libinput Accel Speed", false).0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 16, - accel_speed_atom, - crate::xinput::XA_INTEGER.0, - &[7, 0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], x11::error::BAD_MATCH, "BadMatch"); - } - - #[test] - fn b1_xi2_change_property_format8_card32_mismatch_is_badmatch_no_panic() { - // `libinput Button Scrolling Button` is Scalar/Card32, - // descriptor format 32. Same crash shape via `card32(&[7])`. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let scroll_button_atom = state - .atoms - .intern("libinput Button Scrolling Button", false) - .0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - scroll_button_atom, - crate::xinput::XA_INTEGER.0, - &[7], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], x11::error::BAD_MATCH, "BadMatch, not a panic"); - } - - /// The short-write relaxation is per-descriptor, not blanket. - /// - /// `xf86-input-libinput` gates every 8-bit multi-slot property on an - /// exact `val->size` except `Accel Profile Enabled`, whose width grew - /// from 2 to 3 with libinput 1.23's custom-accel slot - /// (`LibinputSetPropertyAccelProfile`, xf86libinput.c:4622 — - /// `val->size < 2 || val->size > 3`; compare `ScrollMethods` :4884 - /// `!= 3`, `ClickMethod` :4988 `!= 2`). - /// - /// Accepting a short `Scroll Method Enabled` and zero-padding it - /// would silently commit "two-finger on, edge off, button off" — a - /// configuration the client never expressed, and BadMatch on Xorg. - #[test] - fn short_write_accepted_only_for_the_ranged_accel_profile_descriptor() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let scroll_atom = state - .atoms - .intern("libinput Scroll Method Enabled", false) - .0; - - // Two bytes against a 3-wide exact descriptor → BadValue. - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - scroll_atom, - crate::xinput::XA_INTEGER.0, - &[0, 1], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!( - wire[1], - x11::error::BAD_VALUE, - "short Scroll Method write must not be zero-padded into a real config", - ); - - // The same two-byte shape against Accel Profile Enabled is the - // write mate-settings-daemon emits, and must be accepted. - let accel_atom = state - .atoms - .intern("libinput Accel Profile Enabled", false) - .0; - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - accel_atom, - crate::xinput::XA_INTEGER.0, - &[0, 1], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "two-item accel-profile write must succeed (no error packet)", - ); - } - - #[test] - fn b1_xi1_change_device_property_format_mismatch_is_badmatch_no_panic() { - // Same crash shape, XI1 wire arm (minor 37) — the path MATE's - // settings daemon actually uses. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let accel_speed_atom = state.atoms.intern("libinput Accel Speed", false).0; - - let body = xi1_change_property_body( - accel_speed_atom, - crate::xinput::XA_INTEGER.0, - 4, - 8, - crate::xinput::XI_PROP_MODE_REPLACE, - &[7], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(37), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!(wire[1], x11::error::BAD_MATCH, "BadMatch, not a panic"); - } - - // ----------------------------------------------------------------- - // T3 B2 (review round): merge-then-validate. `Append`/`Prepend` - // must be merged with the existing stored value BEFORE - // `validate_value` runs, or a short *fragment* (legal on its own - // since Task 1) can pass validation, decode to a value the client - // never wrote, and reach `apply_device_config`. The commit must - // also store the *normalised* merged value, not the raw request - // bytes, or a short Replace silently narrows the property's - // advertised width for the next reader. - // ----------------------------------------------------------------- - - #[test] - fn t3_b2_xi2_two_item_accel_profile_write_commits_normalized_three_bytes() { - // The headline vector: msd writes exactly 2 bytes; the merged - // (here: unmerged, since Replace) value must validate, decode - // to AccelProfile(Some(1)) — flat — and the STORED property - // must be normalised to the full 3-byte descriptor width, not - // the 2 raw bytes the client sent. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - let atom = state - .atoms - .intern("libinput Accel Profile Enabled", false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - atom, - integer_atom, - &[0, 1], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "no X error for a short write" - ); - assert_eq!( - backend.applied_device_configs, - vec![( - "/dev/input/event4".to_string(), - crate::xinput::libinput_props::DeviceConfigChange::AccelProfile(Some(1)), - )], - "reaches the backend as AccelProfile(Some(1)) — flat" - ); - - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - let prop = dev - .properties - .get(&AtomId(atom)) - .expect("accel profile stored"); - assert_eq!( - prop.data, - vec![0, 1, 0], - "stored property is exactly 3 bytes, zero-padded" - ); - } - - #[test] - fn t3_b2_xi1_two_item_accel_profile_write_commits_normalized_three_bytes() { - // Same assertions, XI1 wire arm (minor 37). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - let atom = state - .atoms - .intern("libinput Accel Profile Enabled", false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi1_change_property_body( - atom, - integer_atom, - 4, - 8, - crate::xinput::XI_PROP_MODE_REPLACE, - &[0, 1], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(37), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "no X error for a short write" - ); - assert_eq!( - backend.applied_device_configs, - vec![( - "/dev/input/event4".to_string(), - crate::xinput::libinput_props::DeviceConfigChange::AccelProfile(Some(1)), - )], - "reaches the backend as AccelProfile(Some(1)) — flat" - ); - - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - let prop = dev - .properties - .get(&AtomId(atom)) - .expect("accel profile stored"); - assert_eq!( - prop.data, - vec![0, 1, 0], - "stored property is exactly 3 bytes, zero-padded" - ); - } - - #[test] - fn t3_b2_append_onto_full_width_accel_profile_is_badvalue_and_untouched() { - // Append [1] onto an already-full-width (3-byte) stored value: - // the merged length is 4 > n=3, so this must be BadValue with - // BOTH the stored property and the libinput config untouched — - // in particular, `apply_device_config` must NOT be called a - // second time with the wrong fragment-decoded value. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - let atom = state - .atoms - .intern("libinput Accel Profile Enabled", false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - // Seed a full-width value first (Replace [1, 0, 0] = adaptive). - let seed_body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - atom, - integer_atom, - &[1, 0, 0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &seed_body, - ) - .unwrap(); - assert!(read_all_available(&mut peer).is_empty()); - - // Append [1] → merged length 4 > n=3 → BadValue, untouched. - let append_body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_APPEND, - 8, - atom, - integer_atom, - &[1], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(57), - &append_body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "error packet"); - assert_eq!( - wire[1], - x11::error::BAD_VALUE, - "BadValue: merged length 4 > n" - ); - - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - let prop = dev.properties.get(&AtomId(atom)).unwrap(); - assert_eq!( - prop.data, - vec![1, 0, 0], - "stored property untouched by the rejected append" - ); - assert_eq!( - backend.applied_device_configs.len(), - 1, - "only the seeding Replace reached apply_device_config, not the rejected Append" - ); - } - - #[test] - fn t3_b2_append_onto_absent_accel_profile_behaves_like_replace() { - // Append [0, 1, 0] onto a property that was never seeded (no - // existing value to merge against) behaves exactly like - // Replace and stores exactly 3 bytes. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - let atom = state - .atoms - .intern("libinput Accel Profile Enabled", false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_APPEND, - 8, - atom, - integer_atom, - &[0, 1, 0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "no error: absent property + Append behaves like Replace" - ); - - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - let prop = dev.properties.get(&AtomId(atom)).unwrap(); - assert_eq!(prop.data, vec![0, 1, 0]); - } - - // ----------------------------------------------------------------- - // XI2 XI_PropertyEvent fan-out on change / delete / get(delete=1). - // The dispatch arm must wire `emit_property_change` into all six - // property-write sites so every client that selected - // `XI_PropertyEventMask` on the affected device receives a - // 32-byte XI2 GenericEvent (evtype 12) with the right `what` byte. - // ----------------------------------------------------------------- - - /// Scan a wire buffer for the first XI2 GenericEvent (`type == 35`) - /// of evtype 12 (XI_PropertyEvent) and return the 32-byte slice - /// pointing at the event header. Used by the T5 tests below; we - /// can't anchor at offset 0 because some arms emit a reply (e.g. - /// `XIGetProperty(delete=1)`) before the event. - /// - /// Window: `0..=wire.len()-32` (inclusive) so a 32-byte buffer - /// matches at offset 0. - fn find_xi2_property_event(wire: &[u8]) -> Option<&[u8]> { - let end = wire.len().checked_sub(32)?; - (0..=end).find_map(|i| { - (wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 12) - .then(|| &wire[i..i + 32]) - }) - } - - /// Subscribe `client_id` to `XI_PropertyEventMask` on the slave - /// pointer (device 4) at the root window — the selection MATE / - /// GDK make once they have learned the device id. - fn select_xi2_property_event_on_root(state: &mut ServerState, client_id: u32, deviceid: u16) { - state - .clients - .get_mut(&client_id) - .expect("client installed") - .xi2_masks - .insert((ROOT_WINDOW, deviceid), u64::from(XI2_PROPERTY_EVENT_MASK)); - } - - #[test] - fn t5_xi2_change_property_emits_property_event_modified_to_selecting_client() { - // Selecting client receives an XI2 XI_PropertyEvent with - // what=Modified after a successful XIChangeProperty against an - // already-seeded libinput property ("libinput Tapping Enabled" - // is set by `seed_touchpad`, so the write is a Modify). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - select_xi2_property_event_on_root(&mut state, 1, 4); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - // No reply for XIChangeProperty; the only bytes on the wire - // must be the 32-byte XI_PropertyEvent. - assert_eq!(wire.len(), 32, "exactly one 32-byte event, no reply"); - let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); - assert_eq!(ev[0], 35, "GenericEvent"); - assert_eq!(ev[1], 137, "extension = XInputExtension major"); - assert_eq!(u16::from_le_bytes([ev[8], ev[9]]), 12, "evtype"); - assert_eq!(u16::from_le_bytes([ev[10], ev[11]]), 4, "deviceid"); - assert_eq!( - u32::from_le_bytes([ev[16], ev[17], ev[18], ev[19]]), - tap_atom, - "property atom" - ); - assert_eq!(ev[20], 2, "what = Modified (property already seeded)"); - } - - #[test] - fn t5_xi2_change_property_emits_property_event_created_for_new_atom() { - // Writing a property the device has never carried before - // (atom 0x4242 — a synthetic test atom, no descriptor table - // entry, so the dispatch falls through to the bare commit step) - // reports `Created`. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // No touchpad → the descriptor path is bypassed and any atom - // commits straight into the registry. - state.atoms.register_for_test(AtomId(0x4242), "T5 created"); - select_xi2_property_event_on_root(&mut state, 1, 4); - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - 0x4242, - crate::xinput::XA_INTEGER.0, - &[7], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); - assert_eq!(ev[20], 1, "what = Created"); - assert_eq!( - u32::from_le_bytes([ev[16], ev[17], ev[18], ev[19]]), - 0x4242, - "property atom" - ); - } - - #[test] - fn t5_xi2_delete_property_emits_property_event_deleted() { - // XIDeleteProperty against a seeded property fans out - // what=Deleted. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - select_xi2_property_event_on_root(&mut state, 1, 4); - - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(58), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "exactly one 32-byte event, no reply"); - let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); - assert_eq!(ev[20], 0, "what = Deleted"); - assert_eq!( - u32::from_le_bytes([ev[16], ev[17], ev[18], ev[19]]), - 100, - "property atom" - ); - } - - #[test] - fn t5_xi2_delete_property_absent_is_silent() { - // Redundant delete of an absent property must NOT emit an - // event (mirror of xiproperty.c, which only calls - // `send_property_event` when the registry actually shrank). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Atom must exist for the BadAtom guard, but the property is - // not seeded onto device 4. - state.atoms.register_for_test(AtomId(100), "T5 absent prop"); - select_xi2_property_event_on_root(&mut state, 1, 4); - - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(58), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "no event for a no-op delete" - ); - } - - #[test] - fn t5_xi2_get_property_delete_emits_property_event_deleted() { - // `XIGetProperty(delete=1)` removes the property after a full - // read and the dispatch arm fans out what=Deleted to selecting - // clients. Both the GetProperty reply (36 bytes: 32 header + - // 1 data byte padded to 4) and the 32-byte XI_PropertyEvent - // end up on the same socket — the X protocol leaves the order - // unspecified (clients reorder by sequence), so the test - // searches for the event payload rather than anchoring on its - // wire position. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - select_xi2_property_event_on_root(&mut state, 1, 4); - - // body: deviceid(2)=4, delete(1)=1, pad(1), property(4)=100, - // type(4)=0, offset(4)=0, len(4)=100. - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(1); // delete = true - body.push(0); // pad - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(59), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 36 + 32, "GetProperty reply + PropertyEvent"); - let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); - assert_eq!(ev[20], 0, "what = Deleted"); - // Independently confirm the reply is somewhere in the buffer. - // The reply starts with X_Reply = 1, which the 32-byte event - // (starts with GenericEvent = 35) can't impersonate. - assert!(wire.contains(&1), "GetProperty reply is on the wire"); - // The registry must have actually shrunk. - let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); - assert!( - !dev.properties.contains_key(&AtomId(100)), - "delete=1 consumed the property" - ); - } - - #[test] - fn t5_xi2_get_property_no_delete_does_not_emit() { - // The non-deleting read path must not emit anything. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - select_xi2_property_event_on_root(&mut state, 1, 4); - - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(0); // delete = false - body.push(0); // pad - body.extend_from_slice(&100u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(59), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert!( - find_xi2_property_event(&wire).is_none(), - "no XI_PropertyEvent on a non-deleting read" - ); - } - - #[test] - fn t5_xi2_change_property_not_selected_client_gets_nothing() { - // A client that did NOT select `XI_PropertyEventMask` for - // device 4 must not receive the event, even if it has other - // XI2 selections on the same window. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Selecting `XI_DeviceChanged` only — the - // `XI2_PROPERTY_EVENT_MASK` bit is NOT set, so this client - // must be skipped. - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (ROOT_WINDOW, 4), - u64::from(crate::xinput::XI2_DEVICE_CHANGED_MASK), - ); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "client without the property-event bit gets nothing" - ); - } - - #[test] - fn t5_xi2_change_property_other_device_does_not_match() { - // Selecting `XI_PropertyEvent` for device 3 (master keyboard) - // must NOT route a device-4 property change to that client. - // The wildcards `XIAllDevices(0)` / `XIAllMasterDevices(1)` are - // followed by `xi2mask_isset` (xserver dix/inpututils.c:1153), - // but device 3 is neither, so this client stays unselected. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Client subscribes to property events on device 3, not 4. - state - .clients - .get_mut(&1) - .unwrap() - .xi2_masks - .insert((ROOT_WINDOW, 3), u64::from(XI2_PROPERTY_EVENT_MASK)); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "device-3 selection must not see device-4 events" - ); - } - - #[test] - fn t5_xi2_change_property_xi_all_devices_wildcard_matches() { - // Regression for the bug `xinput watch-props 4` exposed on - // M1/Asahi: every realworld client (xinput, MATE, etc.) calls - // XISelectEvents with `deviceid = XIAllDevices = 0`, not the - // specific slave id. xserver's `xi2mask_isset` - // (dix/inpututils.c:1153) ORs the wildcard mask with the - // specific mask; without that OR the client silently received - // nothing. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Select on the wildcard, NOT on device 4 directly. - state - .clients - .get_mut(&1) - .unwrap() - .xi2_masks - .insert((ROOT_WINDOW, 0), u64::from(XI2_PROPERTY_EVENT_MASK)); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - let ev = find_xi2_property_event(&wire) - .expect("XIAllDevices selection must receive the property event"); - assert_eq!(ev[20], 2, "what byte = Modified"); - } - - #[test] - fn t5_xi1_change_device_property_also_emits_xi2_property_event() { - // The XI1 write path (minor 37) must trigger the same XI2 - // fan-out — xserver's `send_property_event` fires from both - // protocol paths so an XI2-listening client sees its tap - // toggle even when an XI1 caller (e.g. an older xset variant) - // wrote the property. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - select_xi2_property_event_on_root(&mut state, 1, 4); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - // xChangeDevicePropertyReq body layout (XIproto.h:1467-1479): - // property(4), type(4), deviceid(1), format(1), mode(1), pad(1), - // num_items(4), value(num_items * format/8 padded to 4). - let mut body = Vec::new(); - body.extend_from_slice(&tap_atom.to_le_bytes()); - body.extend_from_slice(&integer_atom.to_le_bytes()); - body.push(4); // deviceid - body.push(8); // format - body.push(crate::xinput::XI_PROP_MODE_REPLACE); - body.push(0); // pad - body.extend_from_slice(&1u32.to_le_bytes()); // num_items = 1 - body.extend_from_slice(&[0u8, 0, 0, 0]); // value=[0] + 3 pad - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(37), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - let ev = - find_xi2_property_event(&wire).expect("XI1 write must also fan-out XI_PropertyEvent"); - assert_eq!(ev[20], 2, "what = Modified"); - } - - #[test] - fn t5_property_event_selected_on_any_window_still_delivers() { - // SendEventToAllWindows: a client that selected - // `XI_PropertyEvent` for the device on ANY window (here a - // synthetic non-root xid) must still receive the event. The - // event has no event-window field, so per-window distinctions - // only affect delivery. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Subscribe via a non-root window — anything keyed by the - // device id wins. - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (ResourceId(0xdead_beef), 4), - u64::from(XI2_PROPERTY_EVENT_MASK), - ); - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert!( - find_xi2_property_event(&wire).is_some(), - "non-root selection must still deliver" - ); - } - - // ----------------------------------------------------------------- - // XI 1.x `SelectExtensionEvent` + `DevicePropertyNotify` fan-out. - // ----------------------------------------------------------------- - - /// XI1 device-property event code is 16; with `XI_FIRST_EVENT = 66` - /// the wire type byte is 82. The XEventClass packs - /// `(deviceid << 8) | event_code`, so for the slave pointer - /// (deviceid 4) the class is `(4 << 8) | 82 = 0x0452`. - const XI1_DEV_PROP_CLASS_DEV4: u32 = (4 << 8) | 82; - - /// Build an `xSelectExtensionEventReq` body (the bytes after the - /// 4-byte X request header) for a single XEventClass list. - fn xi1_select_extension_event_body(window: u32, classes: &[u32]) -> Vec { - let mut body = Vec::with_capacity(8 + classes.len() * 4); - body.extend_from_slice(&window.to_le_bytes()); // window - #[allow(clippy::cast_possible_truncation)] - let count = classes.len() as u16; - body.extend_from_slice(&count.to_le_bytes()); // count - body.extend_from_slice(&0u16.to_le_bytes()); // pad - for c in classes { - body.extend_from_slice(&c.to_le_bytes()); - } - body - } - - /// Scan a wire buffer for the first XI1 `DevicePropertyNotify` - /// (type byte == 82) and return the 32-byte slice. T5's - /// `find_xi2_property_event` keyed off GenericEvent + evtype 12; - /// XI1 is a sequential event code so a single-byte type match is - /// enough — and it explicitly cannot collide with the XI2 - /// `GenericEvent` (35) or other extension events in our range. - fn find_xi1_device_property_notify(wire: &[u8]) -> Option<&[u8]> { - let end = wire.len().checked_sub(32)?; - (0..=end).find_map(|i| (wire[i] == 82).then(|| &wire[i..i + 32])) - } - - #[test] - fn xi1_query_device_state_reports_real_classes() { - // QueryDeviceState (minor 30) on the slave pointer must report - // ButtonState (7 buttons, down-bitmask) + ValuatorState (4 - // axes, sprite position) — not the old num_classes=0 stub. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - { - let entry = state.xi1_device_input_state.entry(4).or_default(); - entry.buttons_down[0] = 0b0000_0010; // button 1 down - entry.valuators = [120, 45, 0, 0]; // axes as of last motion - } - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(30), - &[4, 0, 0, 0], // deviceid + pad - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!( - wire.len(), - 32 + 36 + 20, - "reply + xButtonState + xValuatorState" - ); - assert_eq!(wire[8], 2, "num_classes"); - let bs = &wire[32..68]; - assert_eq!((bs[0], bs[1], bs[2]), (1, 36, 7), "ButtonClass/len/count"); - assert_eq!(bs[4], 0b0000_0010, "button 1 down bit"); - let vs = &wire[68..]; - assert_eq!( - (vs[0], vs[1], vs[2], vs[3]), - (2, 20, 4, 0), - "ValuatorClass/len/axes/mode" - ); - assert_eq!(i32::from_le_bytes(vs[4..8].try_into().unwrap()), 120); - assert_eq!(i32::from_le_bytes(vs[8..12].try_into().unwrap()), 45); - } - - #[test] - fn t6_xi1_select_extension_event_populates_client_class_set() { - // Selecting a DevicePropertyNotify class for device 4 stores - // the exact wire-form class in `xi1_event_classes`. Classes the - // server does not yet implement (e.g. a hypothetical XI1 - // motion-event class 0x04XX with the wrong low byte) are - // silently dropped — Xorg's behaviour. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Body: window=ROOT, count=2, [DevicePropertyNotify(dev4), - // motion-event(dev4)]. The motion-event class has low byte - // != 82 so must be dropped. - let unknown_class: u32 = (4 << 8) | 70; // bogus event code 4 → DeviceMotion - let body = xi1_select_extension_event_body( - ROOT_WINDOW.0, - &[XI1_DEV_PROP_CLASS_DEV4, unknown_class], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - let client = state.clients.get(&1).expect("client installed"); - assert!( - client.xi1_event_classes.contains(&XI1_DEV_PROP_CLASS_DEV4), - "DevicePropertyNotify class stored verbatim" - ); - assert!( - !client.xi1_event_classes.contains(&unknown_class), - "unsupported XI1 event classes dropped" - ); - assert_eq!( - client.xi1_event_classes.len(), - 1, - "exactly one class accepted" - ); - } - - #[test] - fn t6_xi1_select_extension_event_replaces_classes_for_device() { - // Xorg's SelectExtensionEvent REPLACES the prior selection for - // every deviceid mentioned in the request. So a follow-up call - // with an empty class list for the same device drops the entry. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Step 1: select DevicePropertyNotify for device 4. - let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - assert!( - state - .clients - .get(&1) - .unwrap() - .xi1_event_classes - .contains(&XI1_DEV_PROP_CLASS_DEV4) - ); - // Step 2: re-select with a class list that names device 4 but - // requests a class we don't handle. The replacement must clear - // the prior device-4 entry. - let unknown_class_dev4: u32 = (4 << 8) | 70; - let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[unknown_class_dev4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - let client = state.clients.get(&1).unwrap(); - assert!( - client.xi1_event_classes.is_empty(), - "replacement with no supported classes clears device-4 selection" - ); - } - - #[test] - fn t6_xi1_select_extension_event_other_device_preserved() { - // Replacement is scoped to the deviceids mentioned in the new - // request. Pre-select dev4 + dev5; re-select only dev4. The - // dev5 entry must survive (Xorg's per-device replace). - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let class_dev5: u32 = (5 << 8) | 82; - // Seed via the dispatch — two classes, two devices. - let body = - xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4, class_dev5]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - // Re-select only dev4 (with the supported class). The dev5 - // entry must remain — its deviceid wasn't named in this call. - let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - let client = state.clients.get(&1).unwrap(); - assert!( - client.xi1_event_classes.contains(&XI1_DEV_PROP_CLASS_DEV4), - "device-4 selection re-installed" - ); - assert!( - client.xi1_event_classes.contains(&class_dev5), - "device-5 selection untouched" - ); - } - - #[test] - fn xi1_get_selected_extension_events_reports_this_and_all_clients() { - let mut state = ServerState::new(); - let mut peer1 = install_client(&mut state, 1); - let _peer2 = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - let motion_dev4: u32 = (4 << 8) | 70; - let property_dev5: u32 = (5 << 8) | 82; - - let body = - xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4, motion_dev4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[property_dev5]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(2), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - - let body = ROOT_WINDOW.0.to_le_bytes(); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header_for_body(7, &body), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer1); - assert_eq!(wire.len(), 32 + 5 * 4); - assert_eq!(wire[1], 7, "XI1 reply subtype"); - assert_eq!(u32::from_le_bytes(wire[4..8].try_into().unwrap()), 5); - assert_eq!(u16::from_le_bytes(wire[8..10].try_into().unwrap()), 2); - assert_eq!(u16::from_le_bytes(wire[10..12].try_into().unwrap()), 3); - let classes: Vec = wire[32..] - .chunks_exact(4) - .map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap())) - .collect(); - assert_eq!( - classes, - vec![ - motion_dev4, - XI1_DEV_PROP_CLASS_DEV4, - motion_dev4, - XI1_DEV_PROP_CLASS_DEV4, - property_dev5, - ], - "this-client list precedes the all-clients list" - ); - } - - #[test] - fn t6_xi1_change_property_delivers_device_property_notify() { - // End-to-end: a client SelectExtensionEvent(DevicePropertyNotify - // for dev4), then someone (here, the same client via XI2 - // XIChangeProperty minor 57) writes a property. The 32-byte - // XI1 event must land on the selecting client with the right - // type byte, atom, and deviceid. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Subscribe via SelectExtensionEvent only (no XI2 mask), so the - // ONLY event on the wire is the XI1 one. - let select_body = - xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &select_body), - &select_body, - ) - .unwrap(); - // Drain anything the select produced (must be empty — minor 6 - // is event-only, no reply). - assert!( - read_all_available(&mut peer).is_empty(), - "SelectExtensionEvent emits no reply" - ); - - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "exactly one 32-byte XI1 event"); - let ev = find_xi1_device_property_notify(&wire).expect("XI1 event present"); - assert_eq!(ev[0], 82, "type = XI_FIRST_EVENT(66) + 16"); - assert_eq!(ev[1], 0, "state = PropertyNewValue"); - assert_eq!( - u32::from_le_bytes([ev[8], ev[9], ev[10], ev[11]]), - tap_atom, - "atom" - ); - assert_eq!(ev[31], 4, "deviceid (last byte)"); - } - - #[test] - fn t6_xi1_delete_property_delivers_event_with_state_one() { - // The delete path (XI2 minor 58) must also fan out an XI1 - // event, with `state = 1` (PropertyDelete). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_one_prop(&mut state, 100, 8, vec![1]); - let select_body = - xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &select_body), - &select_body, - ) - .unwrap(); - let _ = read_all_available(&mut peer); - - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(58), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "exactly one 32-byte XI1 event"); - let ev = find_xi1_device_property_notify(&wire).expect("XI1 event present"); - assert_eq!(ev[1], 1, "state = PropertyDelete"); - assert_eq!( - u32::from_le_bytes([ev[8], ev[9], ev[10], ev[11]]), - 100, - "atom" - ); - assert_eq!(ev[31], 4, "deviceid"); - } - - #[test] - fn t6_xi1_unselected_client_gets_nothing() { - // A client that did NOT call SelectExtensionEvent must not - // receive an XI1 DevicePropertyNotify — even if the property - // change happens on the device it cares about. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // No SelectExtensionEvent, no XI2 mask. - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "unselected client receives nothing" - ); - } - - #[test] - fn t6_xi1_wrong_device_class_does_not_match() { - // Selecting DevicePropertyNotify for device 5 must NOT route a - // device-4 property change to that client (parallel to the - // XI2 same-property-different-device test in T5). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - let class_dev5: u32 = (5 << 8) | 82; - let select_body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[class_dev5]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &select_body), - &select_body, - ) - .unwrap(); - let _ = read_all_available(&mut peer); - - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(57), - &body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "device-5 selection must not see device-4 events" - ); - } - - #[test] - fn t6_xi1_select_extension_event_short_body_bad_length() { - // A body shorter than the 8-byte fixed header must yield - // BadLength. The error reply uses minor=6 and major=137. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Only 4 bytes — missing the count/pad portion. - let body = vec![0u8; 4]; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "single 32-byte X error reply"); - assert_eq!(wire[0], 0, "X error opcode"); - assert_eq!(wire[1], 16, "BadLength code"); - } - - #[test] - fn t6_xi1_select_extension_event_truncated_class_list_bad_length() { - // count = 2 but only one class on the wire → BadLength. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = Vec::new(); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); // count = 2 - body.extend_from_slice(&0u16.to_le_bytes()); // pad - body.extend_from_slice(&XI1_DEV_PROP_CLASS_DEV4.to_le_bytes()); // only one class - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &body), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire[0], 0, "X error opcode"); - assert_eq!(wire[1], 16, "BadLength"); - } - - #[test] - fn t6_xi1_and_xi2_dual_selection_delivers_one_event_per_path() { - // A client that selected `XI_PropertyEvent` via XI2's - // `xi2_masks` AND a `DevicePropertyNotify` class via XI1's - // `SelectExtensionEvent` receives TWO independent events from - // a single property write — one per protocol path. The fan-outs - // do not deduplicate across paths because a client may be - // running adapter code that bridges both (e.g. a GTK app that - // uses XI2 directly plus a legacy libXi consumer in the same - // process). Pins the no-cross-path-dedup invariant. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // XI2 selection. - select_xi2_property_event_on_root(&mut state, 1, 4); - // XI1 selection. - let select_body = - xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_DEV4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi2_header_for_body(6, &select_body), - &select_body, - ) - .unwrap(); - assert!( - read_all_available(&mut peer).is_empty(), - "SelectExtensionEvent emits no reply" - ); - - let tap_atom = state - .atoms - .intern(crate::xinput::PROP_TAPPING_ENABLED, false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - tap_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 64, "two 32-byte events (XI2 + XI1)"); - // Both events must be present — anchor by type byte. - let xi2 = find_xi2_property_event(&wire).expect("XI2 GenericEvent present"); - assert_eq!(xi2[0], 35, "GenericEvent"); - assert_eq!(u16::from_le_bytes([xi2[8], xi2[9]]), 12, "evtype = 12"); - assert_eq!(u16::from_le_bytes([xi2[10], xi2[11]]), 4, "deviceid"); - let xi1 = find_xi1_device_property_notify(&wire).expect("XI1 event present"); - assert_eq!(xi1[0], 82, "XI_FIRST_EVENT + 16"); - assert_eq!(xi1[31], 4, "XI1 deviceid (last byte)"); - } - - #[test] - fn t3_xi2_change_property_readonly_descriptor_yields_bad_access() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // `…Enabled Default` is the ReadOnly companion (Access::ReadOnly). - let default_atom = state - .atoms - .intern("libinput Tapping Enabled Default", false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - - // Capture the seeded value so we can confirm the write was - // rejected and the registry was not mutated. - let before = state - .xi_devices - .iter() - .find(|d| d.id == 4) - .unwrap() - .properties - .get(&AtomId(default_atom)) - .cloned() - .expect("default seeded"); - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - default_atom, - integer_atom, - &[0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "X_Error"); - assert_eq!(wire[1], 10, "BadAccess"); - - let after = state - .xi_devices - .iter() - .find(|d| d.id == 4) - .unwrap() - .properties - .get(&AtomId(default_atom)) - .cloned() - .expect("default still present"); - assert_eq!(before.data, after.data, "read-only value unchanged"); - } - - // ----------------------------------------------------------------- - // XI 1.x `SendExtensionEvent` (minor 31) — dispatch + specials. - // ----------------------------------------------------------------- - - /// Build an `xSendExtensionEventReq` body (the bytes after the - /// 4-byte X request header) for a single 32-byte event payload and - /// a single XEventClass. - fn xi1_send_extension_event_body( - destination: u32, - deviceid: u8, - propagate: bool, - event: &[u8; 32], - classes: &[u32], - ) -> Vec { - let mut body = Vec::with_capacity(12 + 32 + classes.len() * 4); - body.extend_from_slice(&destination.to_le_bytes()); // 0..4 destination - body.push(deviceid); // 4 deviceid - body.push(u8::from(propagate)); // 5 propagate - #[allow(clippy::cast_possible_truncation)] - let count = classes.len() as u16; - body.extend_from_slice(&count.to_le_bytes()); // 6..8 count - body.push(1); // 8 num_events - body.extend_from_slice(&[0u8; 3]); // 9..12 pad - body.extend_from_slice(event); // 12..44 one xEvent - for c in classes { - body.extend_from_slice(&c.to_le_bytes()); - } - body - } - - /// `length_units` covering the 4-byte X header + the body produced - /// by [`xi1_send_extension_event_body`] for a single 32-byte event: - /// `4 + 8*num_events + class_count` = `4 + 8 + classes.len()`. - #[allow(clippy::cast_possible_truncation)] - fn xi1_send_extension_event_header(class_count: usize) -> RequestHeader { - RequestHeader { - opcode: 131, - data: 31, - length_units: 12 + class_count as u32, - } - } - - /// 32-byte XI1 DeviceKeyPress wire template — only the type byte - /// matters for these tests; everything else is zero. - fn xi1_device_key_press_event(first_event: u8) -> [u8; 32] { - let mut ev = [0u8; 32]; - ev[0] = first_event + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; - ev - } - - /// XI1 _noExtensionEvent code (9) — see /usr/include/X11/extensions/XI.h. - /// `noextensioneventclass = (deviceid << 8) | 9` is the sentinel - /// Xlib's `NoExtensionEvent` macro produces. Xorg - /// `CreateMaskFromList` maps it to a per-device mask of 0, which - /// short-circuits `DeliverToWindowOwner`'s filter check - /// (`filter == CantBeFiltered`) and so the destination window's - /// CREATOR receives the event regardless of any selection. - const XI1_NO_EXTENSION_EVENT_OFFSET: u8 = 9; - - fn seed_test_window(state: &mut ServerState, owner: u32, xid: u32) { - state.resources.create_window( - ClientId(owner), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - - #[test] - fn xi1_send_extension_event_with_noextensioneventclass_delivers_to_window_creator() { - // XSendExtensionEvent test 1 (xts5 XI/SendExtensionEvent.m:124): - // a client creates a window and SendExtensionEvent's an XI1 - // event to it with `event_list = &noextensioneventclass`. The - // expected behaviour mirrors Xorg `Xi/sendexev.c::SendEvent` → - // `dix/events.c::DeliverToWindowOwner`: when the per-device - // mask is empty (i.e. `noextensioneventclass`), the owner - // receives the event unconditionally. Without this path xts5 - // SendExtensionEvent 1–4 / 11 / 12 / 14 / 16 all fail with - // "Expected event (DeviceKeyPress) not received". - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let win_xid = 0x4000_0001u32; - seed_test_window(&mut state, 1, win_xid); - - let no_class = (4u32 << 8) | u32::from(XI1_NO_EXTENSION_EVENT_OFFSET); - let event = xi1_device_key_press_event(crate::server::XI_FIRST_EVENT); - let body = xi1_send_extension_event_body(win_xid, 4, false, &event, &[no_class]); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi1_send_extension_event_header(1), - &body, - ) - .unwrap(); - - let wire = read_all_available(&mut peer); - assert_eq!( - wire.len(), - 32, - "exactly one 32-byte XI1 event delivered to creator" - ); - assert_eq!( - wire[0], - (crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET) | 0x80, - "type byte is DeviceKeyPress with send_event (0x80) bit set" - ); - } - - #[test] - fn xi1_send_extension_event_pointer_window_resolves_to_sprite() { - // dest = 0 (PointerWindow) must resolve to the window currently - // containing the sprite (Xorg SendEvent:2915 — `pWin = spriteWin`). - // With the sprite at (0,0) on the root and a 100x100 child - // window covering the origin, the child's creator gets the - // event when noextensioneventclass is used. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let win_xid = 0x4000_0002u32; - seed_test_window(&mut state, 1, win_xid); - // Map the window so `direct_child_at` finds it. - if let Some(w) = state.resources.window_mut(ResourceId(win_xid)) { - w.map_state = crate::resources::MapState::Viewable; - } - state.pointer_root = (10, 10); - - let no_class = (4u32 << 8) | u32::from(XI1_NO_EXTENSION_EVENT_OFFSET); - let event = xi1_device_key_press_event(crate::server::XI_FIRST_EVENT); - let body = xi1_send_extension_event_body(0, 4, false, &event, &[no_class]); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi1_send_extension_event_header(1), - &body, - ) - .unwrap(); - - let wire = read_all_available(&mut peer); - assert_eq!( - wire.len(), - 32, - "PointerWindow special resolves to sprite, creator gets event" - ); - } - - #[test] - fn xi1_send_extension_event_input_focus_resolves_to_device_focus() { - // dest = 1 (InputFocus) must resolve to the device's focus - // window when the focus is a real window (not PointerRoot / - // None) — Xorg SendEvent:2917-2942. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let win_xid = 0x4000_0003u32; - seed_test_window(&mut state, 1, win_xid); - state.xi1_device_focus.insert( - 4, - crate::server::Xi1DeviceFocus { - focus: win_xid, - revert_to: 0, - time: 0, - }, - ); - - let no_class = (4u32 << 8) | u32::from(XI1_NO_EXTENSION_EVENT_OFFSET); - let event = xi1_device_key_press_event(crate::server::XI_FIRST_EVENT); - let body = xi1_send_extension_event_body(1, 4, false, &event, &[no_class]); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi1_send_extension_event_header(1), - &body, - ) - .unwrap(); - - let wire = read_all_available(&mut peer); - assert_eq!( - wire.len(), - 32, - "InputFocus special resolves to device-focus window, creator gets event" - ); - } - - #[test] - fn xi1_send_extension_event_propagate_walks_to_selecting_ancestor() { - // xts5 XI/SendExtensionEvent purpose 11: 3-level window - // hierarchy, only the top has a selection for `dbpc`, send - // to bottom with propagate=True. Walk must reach the top. - // Mirrors Xorg SendEvent's `for (; pWin; pWin = pWin->parent)` - // loop (xserver.git Xi/exevents.c:2952-2962). - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let grandparent_xid = 0x4000_0010u32; - let parent_xid = 0x4000_0011u32; - let child_xid = 0x4000_0012u32; - seed_test_window(&mut state, 2, grandparent_xid); - state.resources.create_window( - ClientId(2), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(parent_xid), - parent: ResourceId(grandparent_xid), - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(2), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(child_xid), - parent: ResourceId(parent_xid), - x: 0, - y: 0, - width: 25, - height: 25, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - // Client 1 selects DeviceButtonPress (offset 3) on the - // GRANDPARENT only. Neither parent nor child have any - // selectors. With propagate=True, the dispatch must reach - // grandparent. - let dbpc = (4u32 << 8) - | u32::from( - crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, - ); - if let Some(c) = state.clients.get_mut(&1) { - c.xi1_window_event_classes - .entry(ResourceId(grandparent_xid)) - .or_default() - .insert(dbpc); - } - - let mut event = [0u8; 32]; - event[0] = crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; - let body = xi1_send_extension_event_body(child_xid, 4, true, &event, &[dbpc]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - xi1_send_extension_event_header(1), - &body, - ) - .unwrap(); - - let wire = read_all_available(&mut peer); - assert_eq!( - wire.len(), - 32, - "propagate=True walks ancestors, grandparent selector receives event" - ); - assert_eq!( - wire[0], - (crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET) | 0x80, - "type byte is DeviceButtonPress + send_event" - ); - } - - #[test] - fn t3_xi2_get_property_uninterned_atom_yields_bad_atom() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Atom 0xdeadbeef has never been interned → BadAtom. - let bogus_atom = 0xdead_beefu32; - assert!(!state.atoms.exists(AtomId(bogus_atom)), "precondition"); - // XIGetProperty body: deviceid(2)=4, delete(1)=0, pad(1), - // property(4), type(4)=0, offset(4)=0, len(4)=100. - let mut body = Vec::new(); - body.extend_from_slice(&4u16.to_le_bytes()); - body.push(0); // delete - body.push(0); // pad - body.extend_from_slice(&bogus_atom.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&100u32.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(3), - xi2_header(59), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "X_Error"); - assert_eq!(wire[1], 5, "BadAtom"); - // The error's bad-value field should echo the offending atom. - assert_eq!( - u32::from_le_bytes(wire[4..8].try_into().unwrap()), - bogus_atom, - "BadAtom echoes property" - ); - } - - #[test] - fn t3_xi2_change_property_invalid_value_yields_bad_value_without_mutation() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_touchpad_for_t3(&mut state); - // Scroll Method Enabled is `OneHotOrNone { n: 3 }` — two bits set is illegal. - let scroll_atom = state - .atoms - .intern("libinput Scroll Method Enabled", false) - .0; - let integer_atom = crate::xinput::XA_INTEGER.0; - let before = state - .xi_devices - .iter() - .find(|d| d.id == 4) - .unwrap() - .properties - .get(&AtomId(scroll_atom)) - .cloned() - .expect("scroll method seeded"); - - let body = xi2_change_property_body( - 4, - crate::xinput::XI_PROP_MODE_REPLACE, - 8, - scroll_atom, - integer_atom, - &[1, 1, 0], - ); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(4), - xi2_header(57), - &body, - ) - .unwrap(); - let wire = read_all_available(&mut peer); - assert_eq!(wire.len(), 32, "error packet"); - assert_eq!(wire[0], 0, "X_Error"); - assert_eq!(wire[1], 2, "BadValue"); - - let after = state - .xi_devices - .iter() - .find(|d| d.id == 4) - .unwrap() - .properties - .get(&AtomId(scroll_atom)) - .cloned() - .expect("scroll method still present"); - assert_eq!( - before.data, after.data, - "registry untouched when validation rejects the value" - ); - } - - #[test] - fn no_operation_returns_handled() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(7), - RequestHeader { - opcode: 127, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - } - - #[test] - fn get_input_focus_writes_reply_through_client_io() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - RequestHeader { - opcode: 43, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - // Reply opcode is 1 (Reply), sequence in bytes 2..4 little-endian. - assert_eq!(buf[0], 1); - assert_eq!(u16::from_le_bytes([buf[2], buf[3]]), 3); - } - - /// Regression (codex review #1): a grab/ungrab focus transition - /// whose grab window is ALREADY the focus (from == to) must still - /// emit FocusOut+FocusIn(NotifyNonlinear, NotifyGrab) on that - /// window. Xorg DoFocusEvents only short-circuits same-window - /// moves for NON-grab modes (dix/enterleave.c:1557); pre-fix - /// yserver dropped these whenever the grab window held the focus. - #[test] - fn same_window_grab_focus_emits_nonlinear_pair() { - use yserver_protocol::x11::CreateWindowRequest; - - const CLIENT: u32 = 71; - const WIN: u32 = 0x0370_0006; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT); - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .clients - .get_mut(&CLIENT) - .unwrap() - .event_masks - .insert(ResourceId(WIN), FOCUS_CHANGE_MASK); - state.core_focus.raw = WIN; - - // GrabKeyboard on WIN while WIN is already the focus → mode 1. - emit_core_focus_transition(&mut state, WIN, WIN, 1); - - let bytes = read_all_available(&mut peer); - assert!( - bytes.len() >= 64, - "expected FocusOut + FocusIn (got {} bytes)", - bytes.len() - ); - assert_eq!(bytes[0], 10, "first event FocusOut"); - assert_eq!(bytes[1], 3, "FocusOut detail NotifyNonlinear"); - assert_eq!(bytes[8], 1, "FocusOut mode NotifyGrab"); - assert_eq!(bytes[32], 9, "second event FocusIn"); - assert_eq!(bytes[33], 3, "FocusIn detail NotifyNonlinear"); - assert_eq!(bytes[40], 1, "FocusIn mode NotifyGrab"); - } - - /// GH #59 regression: a core SetInputFocus issued WHILE a keyboard - /// grab is active must report the focus transition as - /// NotifyWhileGrabbed (mode 3), not NotifyNormal (0) — Xorg - /// dix/events.c:4923. bspwm focuses a newly-mapped window while - /// sxhkd's synchronous passive key grab is still active; emitting - /// NotifyNormal there made GLFW/kitty believe it had genuinely taken - /// focus mid-grab and then ignore every typed key (the KeyPress - /// events still routed correctly to its window). Mirrors the gate - /// already present in `revert_core_focus_from`. - #[test] - fn set_input_focus_during_keyboard_grab_is_notify_while_grabbed() { - use crate::server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}; - use yserver_protocol::x11::CreateWindowRequest; - - const CLIENT: u32 = 71; - const WIN_A: u32 = 0x0071_0001; // currently focused - const WIN_B: u32 = 0x0071_0002; // focus target - - let make = |state: &mut ServerState, win: u32| { - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - }; - - // mode 3 (NotifyWhileGrabbed) when a keyboard grab is active, - // mode 0 (NotifyNormal) otherwise — run both in one test. - for (grab_active, want_mode) in [(true, 3u8), (false, 0u8)] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT); - make(&mut state, WIN_A); - make(&mut state, WIN_B); - assert!( - state - .resources - .map_window(ResourceId(WIN_B)) - .mapping_changed - ); - { - let c = state.clients.get_mut(&CLIENT).unwrap(); - c.event_masks.insert(ResourceId(WIN_A), FOCUS_CHANGE_MASK); - c.event_masks.insert(ResourceId(WIN_B), FOCUS_CHANGE_MASK); - } - state.core_focus.raw = WIN_A; - if grab_active { - state.active_keyboard_grab = Some(ActiveKeyboardGrab { - owner: ClientId(CLIENT), - grab_window: ROOT_WINDOW, - owner_events: false, - source: ActiveKeyboardGrabSource::PassiveKey { keycode: 36 }, - via_xi2: false, - xi2_mask: 0, - }); - } - - let header = yserver_protocol::x11::RequestHeader { - opcode: 42, - data: 2, // RevertToParent - length_units: 3, - }; - let mut body = Vec::new(); - body.extend_from_slice(&WIN_B.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime - handle_set_input_focus( - &mut state, - ClientId(CLIENT), - SequenceNumber(1), - header, - &body, - ) - .expect("set input focus"); - - let bytes = read_all_available(&mut peer); - assert!( - bytes.len() >= 32, - "expected focus events (grab_active={grab_active}), got {} bytes", - bytes.len() - ); - // First event is the FocusOut on WIN_A; mode is byte 8. - assert_eq!(bytes[0] & 0x7f, 10, "first event must be FocusOut"); - assert_eq!( - bytes[8], want_mode, - "SetInputFocus with grab_active={grab_active} must emit mode {want_mode}" - ); - } - } - - #[test] - fn focus_move_to_child_uses_inferior_detail_for_parent_focus_out() { - use yserver_protocol::x11::CreateWindowRequest; - - const CLIENT: u32 = 52; - const TOP: u32 = 0x0350_0006; - const CHILD: u32 = 0x0350_0007; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(TOP), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD), - parent: ResourceId(TOP), - x: 10, - y: 10, - width: 100, - height: 40, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let client = state.clients.get_mut(&CLIENT).expect("client"); - client - .event_masks - .insert(ResourceId(TOP), FOCUS_CHANGE_MASK); - client - .event_masks - .insert(ResourceId(CHILD), FOCUS_CHANGE_MASK); - client - .xi2_masks - .insert((ResourceId(TOP), 3), (1 << 9) | (1 << 10)); - client - .xi2_masks - .insert((ResourceId(CHILD), 3), (1 << 9) | (1 << 10)); - - state.core_focus = crate::server::CoreFocus { - raw: TOP, - revert_to: 0, - time: 0, - }; - emit_core_focus_transition(&mut state, TOP, CHILD, 0); - state.core_focus.raw = CHILD; - let bytes = read_all_available(&mut peer); - - assert_eq!(bytes.len(), 216, "expected core + XI2 focus out/in"); - assert_eq!(bytes[0], 10, "first event should be core FocusOut"); - assert_eq!(bytes[1], 2, "parent FocusOut should be NotifyInferior"); - assert_eq!( - u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), - TOP - ); - assert_eq!(bytes[32], 35, "second event should be XI2 GenericEvent"); - assert_eq!( - u16::from_le_bytes([bytes[40], bytes[41]]), - 10, - "XI2 FocusOut evtype" - ); - assert_eq!(bytes[51], 2, "XI2 parent FocusOut should be NotifyInferior"); - assert_eq!( - u32::from_le_bytes([bytes[56], bytes[57], bytes[58], bytes[59]]), - TOP - ); - assert_eq!(bytes[108], 9, "third event should be core FocusIn"); - assert_eq!(bytes[109], 0, "child FocusIn should be NotifyAncestor"); - assert_eq!( - u32::from_le_bytes([bytes[112], bytes[113], bytes[114], bytes[115]]), - CHILD - ); - assert_eq!(bytes[140], 35, "fourth event should be XI2 GenericEvent"); - assert_eq!( - u16::from_le_bytes([bytes[148], bytes[149]]), - 9, - "XI2 FocusIn evtype" - ); - assert_eq!(bytes[159], 0, "XI2 child FocusIn should be NotifyAncestor"); - assert_eq!( - u32::from_le_bytes([bytes[164], bytes[165], bytes[166], bytes[167]]), - CHILD - ); - assert_eq!( - state.core_focus.raw, CHILD, - "keyboard focus should track child" - ); - } - - #[test] - fn window_host_xid_prefers_resolved_host_mapping() { - use crate::backend::WindowHandle; - use yserver_protocol::x11::CreateWindowRequest; - - const CLIENT: u32 = 55; - const WIN: u32 = 0x0360_0008; - const HOST: u32 = 0x0400_1234; - - let mut state = ServerState::new(); - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 64, - height: 64, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(WIN)) - .unwrap() - .host_xid = WindowHandle::from_raw(HOST); - - assert_eq!(window_host_xid(&state, ResourceId(WIN)), HOST); - } - - #[test] - fn grab_server_tracks_owner_until_owner_ungrabs() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 36, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert_eq!(state.server_grab_owner, Some(ClientId(1))); - - // A direct non-owner call cannot steal or release the grab. In the - // real loop these requests are parked before dispatch. - handle_grab_server(&mut state, ClientId(2), SequenceNumber(3)).unwrap(); - handle_ungrab_server(&mut state, ClientId(2), SequenceNumber(4)).unwrap(); - assert_eq!(state.server_grab_owner, Some(ClientId(1))); - - handle_ungrab_server(&mut state, ClientId(1), SequenceNumber(5)).unwrap(); - assert_eq!(state.server_grab_owner, None); - } - - #[test] - fn get_motion_events_filters_and_translates_history() { - let request = |window: ResourceId, start: u32, stop: u32| { - let mut body = vec![0u8; 12]; - body[0..4].copy_from_slice(&window.0.to_le_bytes()); - body[4..8].copy_from_slice(&start.to_le_bytes()); - body[8..12].copy_from_slice(&stop.to_le_bytes()); - body - }; - - let mut state = ServerState::new(); - state.start_instant = std::time::Instant::now() - std::time::Duration::from_secs(1); - state.pointer_motion_history.extend([ - crate::server::PointerMotionRecord { - time: 500, - root_x: 100, - root_y: 50, - }, - crate::server::PointerMotionRecord { - time: 550, - root_x: 900, - root_y: 50, - }, - ]); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(8), - RequestHeader { - opcode: 39, - data: 0, - length_units: 4, - }, - &request(ROOT_WINDOW, 400, 600), - None, - ) - .unwrap(); - let mut reply = [0u8; 40]; - peer.read_exact(&mut reply).unwrap(); - assert_eq!(reply[0], 1); - assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), 1); - assert_eq!(u32::from_le_bytes(reply[32..36].try_into().unwrap()), 500); - assert_eq!(i16::from_le_bytes(reply[36..38].try_into().unwrap()), 100); - assert_eq!(i16::from_le_bytes(reply[38..40].try_into().unwrap()), 50); - - let missing = ResourceId(0x00ff_1234); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(9), - RequestHeader { - opcode: 39, - data: 0, - length_units: 4, - }, - &request(missing, 400, 600), - None, - ) - .unwrap(); - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[1], x11::error::BAD_WINDOW); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - missing.0 - ); - assert_eq!(error[10], 39); - } - - #[test] - fn xtest_compare_cursor_uses_window_and_current_cursor_state() { - const CURSOR_A: ResourceId = ResourceId(0x0010_1000); - const CURSOR_B: ResourceId = ResourceId(0x0010_1001); - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.resources.create_cursor(ClientId(1), CURSOR_A); - state.resources.create_cursor(ClientId(1), CURSOR_B); - state.resources.window_mut(ROOT_WINDOW).unwrap().cursor = Some(CURSOR_A); - let mut backend = RecordingBackend::new(); - let request = |cursor: ResourceId| { - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&cursor.0.to_le_bytes()); - body - }; - let header = RequestHeader { - opcode: 146, - data: yserver_protocol::x11::xtest::COMPARE_CURSOR, - length_units: 3, - }; - - for (sequence, cursor, expected) in [ - (1, CURSOR_A, true), - (2, CURSOR_B, false), - (3, ResourceId(1), true), // XTestCurrentCursor - ] { - handle_xtest_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(sequence), - header, - &request(cursor), - ) - .unwrap(); - let reply = read_all_available(&mut peer); - assert_eq!(reply[0], 1); - assert_eq!(reply[1], u8::from(expected)); - } - - let missing = ResourceId(0x0010_dead); - handle_xtest_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(4), - header, - &request(missing), - ) - .unwrap(); - let error = read_all_available(&mut peer); - assert_eq!(error[1], x11::error::BAD_CURSOR); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - missing.0 - ); - } - - #[test] - fn recolor_cursor_rejects_unknown_cursor() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let missing = ResourceId(0x00cc_1234); - let mut body = vec![0u8; 16]; - body[0..4].copy_from_slice(&missing.0.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(10), - RequestHeader { - opcode: 96, - data: 0, - length_units: 5, - }, - &body, - None, - ) - .unwrap(); - - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[1], x11::error::BAD_CURSOR); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - missing.0 - ); - assert_eq!(error[10], 96); - } - - #[test] - fn recolor_cursor_forwards_colors_to_backend() { - const CURSOR: u32 = 0x0010_1234; - const HOST_CURSOR: u32 = 0x00ab_cdef; - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - state - .resources - .create_cursor(ClientId(1), ResourceId(CURSOR)); - state.resources.set_cursor_host_xid( - ResourceId(CURSOR), - crate::backend::CursorHandle::from_raw_panicking(HOST_CURSOR), - ); - let mut backend = RecordingBackend::new(); - let fore: (u16, u16, u16) = (0x1122, 0x3344, 0x5566); - let back: (u16, u16, u16) = (0x7788, 0x99aa, 0xbbcc); - let mut body = vec![0u8; 16]; - body[0..4].copy_from_slice(&CURSOR.to_le_bytes()); - for (offset, value) in [fore.0, fore.1, fore.2, back.0, back.1, back.2] - .into_iter() - .enumerate() - { - let start = 4 + offset * 2; - body[start..start + 2].copy_from_slice(&value.to_le_bytes()); - } - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(11), - RequestHeader { - opcode: 96, - data: 0, - length_units: 5, - }, - &body, - None, - ) - .unwrap(); - - assert_eq!( - backend.calls.lock().unwrap().as_slice(), - [RecordedCall::RecolorCursor { - host_xid: HOST_CURSOR, - fore, - back, - }] - ); - } - - #[test] - fn list_hosts_writes_reply() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(11), - RequestHeader { - opcode: 110, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!(buf[0], 1, "Reply opcode"); - assert_eq!(u16::from_le_bytes([buf[2], buf[3]]), 11); - } - - #[test] - fn dri3_hidden_when_caps_unsupported() { - // Default RecordingBackend returns Dri3Caps::unsupported() - // (version (0, 0)), so DRI3 must not appear in QueryExtension / - // ListExtensions output. KmsBackend overrides - // dri3_capabilities() and the Phase 4.2 vng smoke covers the - // advertised path. - let mut backend = RecordingBackend::new(); - assert!(extension_query_reply("DRI3", &mut backend).is_none()); - let names = advertised_extension_names(&mut backend); - assert!( - !names.contains(&"DRI3"), - "DRI3 should be hidden when caps unsupported, got: {names:?}" - ); - } - - #[test] - fn sync_create_trigger_query_fence_round_trip() { - let mut state = ServerState::new(); - let peer_a = install_client(&mut state, 1); - let mut peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - // Client A: CreateFence(fence=0x42, initially_triggered=false). - let mut create_body = vec![0u8; 12]; - create_body[0..4].copy_from_slice(&0u32.to_le_bytes()); // drawable=0 - create_body[4..8].copy_from_slice(&0x42u32.to_le_bytes()); - create_body[8] = 0; - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 142, - data: 14, // CREATE_FENCE - length_units: 4, - }, - &create_body, - None, - ) - .unwrap(); - - // Client B: QueryFence -> triggered=false initially. - let mut q_body = vec![0u8; 4]; - q_body[0..4].copy_from_slice(&0x42u32.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(2), - SequenceNumber(1), - RequestHeader { - opcode: 142, - data: 18, // QUERY_FENCE - length_units: 2, - }, - &q_body, - None, - ) - .unwrap(); - peer_b.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer_b.read_exact(&mut buf).unwrap(); - assert_eq!(buf[0], 1); // Reply - assert_eq!(buf[8], 0, "fence not yet triggered"); - - // Client A: TriggerFence. - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 142, - data: 15, // TRIGGER_FENCE - length_units: 2, - }, - &q_body, - None, - ) - .unwrap(); - - // Client B: QueryFence -> triggered=true now. - process_request( - &mut state, - &mut backend, - ClientId(2), - SequenceNumber(2), - RequestHeader { - opcode: 142, - data: 18, // QUERY_FENCE - length_units: 2, - }, - &q_body, - None, - ) - .unwrap(); - let mut buf2 = [0u8; 32]; - peer_b.read_exact(&mut buf2).unwrap(); - assert_eq!(buf2[8], 1, "fence triggered after Client A's trigger"); - - // Stash peer_a so it doesn't drop and close the writer mid-test. - let _ = peer_a; - } - - /// Build an ImportSyncobj request body: syncobj(4) + drawable(4), fd via - /// SCM_RIGHTS (attached_fd). - fn import_syncobj_body(syncobj: u32, drawable: u32) -> Vec { - let mut body = vec![0u8; 8]; - body[0..4].copy_from_slice(&syncobj.to_le_bytes()); - body[4..8].copy_from_slice(&drawable.to_le_bytes()); - body - } - - fn read_error(buf: &[u8]) -> u8 { - // X error: type=0, error-code at byte 1. - assert_eq!(buf[0], 0, "expected an X error, got type {}", buf[0]); - buf[1] - } - - /// RecordingBackend with a DRI3 1.4 / `syncobj: true` surface so the - /// IMPORT_SYNCOBJ / FREE_SYNCOBJ handlers pass their `caps.syncobj` gate. - /// Kept as a per-test opt-in: the DEFAULT backend must stay - /// `Dri3Caps::unsupported()` for the existing - /// `dri3_hidden_when_caps_unsupported` test (process_request.rs:37076). - fn syncobj_cap_backend() -> RecordingBackend { - let mut backend = RecordingBackend::new(); - backend.dri3_caps = crate::backend::Dri3Caps { - version: (1, 4), - modifiers: false, - fence_fd: false, - syncobj: true, - }; - backend - } - - #[test] - fn import_syncobj_in_use_xid_is_bad_id_choice() { - use yserver_protocol::x11::{CreatePixmapRequest, ResourceId}; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - - // install_client (process_request.rs:29047) gives every test client - // base=0/mask=u32::MAX — "every xid is in range" — so the - // xid_out_of_client_range half of the LEGAL_NEW_RESOURCE gate is - // unreachable in this fixture. Exercise the OTHER half: name a - // pixmap with the xid, then ImportSyncobj with the same xid -> - // resources.xid_in_use fires. - const XID: u32 = 0x0040_0001; - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(XID), - drawable: ROOT_WINDOW, - width: 1, - height: 1, - }, - ); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 10, // IMPORT_SYNCOBJ - length_units: 3, - }, - // drawable=0 is fine here: the xid check (Xorg LEGAL_NEW_RESOURCE) - // fires before the drawable check. - &import_syncobj_body(XID, 0), - None, // no SCM_RIGHTS fd - ) - .unwrap(); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_ID_CHOICE, - "an in-use xid must be rejected as BadIDChoice (Xorg LEGAL_NEW_RESOURCE)", - ); - } - - #[test] - fn import_syncobj_bad_drawable_is_bad_drawable() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - - // A legal syncobj xid (never used, so no xid_in_use) naming a drawable - // that does not exist -> the Xorg drawable check (dixLookupDrawable) - // must fire with BadDrawable. It runs AFTER the xid check and BEFORE - // the fd check. - const SYNCOBJ: u32 = 0x0010_0001; - const MISSING_DRAWABLE: u32 = 0x0050_0001; - assert!( - state - .resources - .window(ResourceId(MISSING_DRAWABLE)) - .is_none() - && state - .resources - .pixmap(ResourceId(MISSING_DRAWABLE)) - .is_none(), - "fixture: MISSING_DRAWABLE must not exist" - ); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 10, // IMPORT_SYNCOBJ - length_units: 3, - }, - &import_syncobj_body(SYNCOBJ, MISSING_DRAWABLE), - None, // no SCM_RIGHTS fd - ) - .unwrap(); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_DRAWABLE, - "ImportSyncobj naming a nonexistent drawable must be BadDrawable", - ); - // The bad drawable must abort the request: nothing imported. - assert!(!backend.dri3_syncobj_owners.contains_key(&SYNCOBJ)); - } - - #[test] - fn import_syncobj_missing_fd_is_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 10, // IMPORT_SYNCOBJ - length_units: 3, - }, - // legal xid; install_client is range-permissive. drawable=ROOT_WINDOW - // (0x100) exists in the default ResourceTable, so the request passes - // the xid + drawable checks and lands on the fd check (Xorg: - // ReadFdFromClient < 0 -> BadValue). - &import_syncobj_body(0x0010_0001, ROOT_WINDOW.0), - None, // no fd attached - ) - .unwrap(); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_VALUE, - "ImportSyncobj without an fd must be BadValue (Xorg ReadFdFromClient)", - ); - } - - #[test] - fn free_syncobj_unknown_is_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&0x0040_9999u32.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 11, // FREE_SYNCOBJ - length_units: 2, - }, - &body, - None, - ) - .unwrap(); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_VALUE, - "FreeSyncobj of an unknown xid must be BadValue", - ); - } - - #[test] - fn free_syncobj_of_another_client_is_bad_access() { - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 1); - let mut peer_b = install_client(&mut state, 2); - let mut backend = syncobj_cap_backend(); - - // Client A imports 0x0010_0001 (a legal xid for client 1 — the - // handler now validates range). drawable=ROOT_WINDOW exists, so the - // request passes the xid + drawable checks. RecordingBackend ignores - // the fd's payload, only ownership is recorded. - let fd = std::fs::File::open("/dev/null") - .expect("open /dev/null") - .into(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 10, - length_units: 3, - }, - &import_syncobj_body(0x0010_0001, ROOT_WINDOW.0), - Some(fd), - ) - .unwrap(); - - // Client B frees A's syncobj. FreeSyncobj has no range check (it is - // not a new-resource request), so B can name A's xid — the ownership - // check is what must reject it. Xorg's dixLookupResourceByType with - // DixWriteAccess maps a foreign owner to BadAccess. - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&0x0010_0001u32.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(2), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 11, - length_units: 2, - }, - &body, - None, - ) - .unwrap(); - peer_b.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer_b.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_ACCESS, - "FreeSyncobj of another client's syncobj must be BadAccess", - ); - - // A still owns it (ImportSyncobj is a void request — nothing to read - // on A's socket; the ownership assertion is the whole check). - assert!(backend.dri3_syncobj_owners.contains_key(&0x0010_0001)); - } - - /// PresentPixmapSynced 84-byte fixed prefix. Offsets per the :40644 - /// test's comment: window(0) pixmap(4) serial(8) valid(12) update(16) - /// x_off(20) y_off(22) target_crtc(24) acquire_syncobj(28) - /// release_syncobj(32) acquire_point(36) release_point(44) options(52) - /// pad(56) target_msc(60) divisor(68) remainder(76). - fn pixmap_synced_body( - window: u32, - pixmap: u32, - acquire_syncobj: u32, - release_syncobj: u32, - acquire_point: u64, - release_point: u64, - ) -> Vec { - let mut body = vec![0u8; 84]; - body[0..4].copy_from_slice(&window.to_le_bytes()); - body[4..8].copy_from_slice(&pixmap.to_le_bytes()); - body[28..32].copy_from_slice(&acquire_syncobj.to_le_bytes()); - body[32..36].copy_from_slice(&release_syncobj.to_le_bytes()); - body[36..44].copy_from_slice(&acquire_point.to_le_bytes()); - body[44..52].copy_from_slice(&release_point.to_le_bytes()); - body - } - - fn pixmap_body(window: u32, pixmap: u32) -> Vec { - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&window.to_le_bytes()); - body[4..8].copy_from_slice(&pixmap.to_le_bytes()); - body - } - - fn dispatch_present_body( - state: &mut ServerState, - backend: &mut RecordingBackend, - client_id: ClientId, - sequence: u16, - minor: u8, - body: &[u8], - ) { - process_request( - state, - backend, - client_id, - SequenceNumber(sequence), - RequestHeader { - opcode: 145, - data: minor, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - body, - None, - ) - .unwrap(); - } - - fn assert_present_error(peer: &mut UnixStream, expected_code: u8, expected_value: u32) { - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(read_error(&error), expected_code); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - expected_value - ); - } - - fn dispatch_pixmap_synced( - state: &mut ServerState, - backend: &mut RecordingBackend, - client_id: yserver_protocol::x11::ClientId, - body: &[u8], - ) { - process_request( - state, - backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP_SYNCED, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - body, - None, - ) - .unwrap(); - } - - #[test] - fn present_pixmap_common_validation_order_and_card32_remainder() { - const PIXMAP: u32 = 0x0010_2001; - const VALID: u32 = 0x0010_2002; - const UPDATE: u32 = 0x0010_2003; - const BAD_CRTC: u32 = 0x0010_2004; - const WAIT_FENCE: u32 = 0x0010_2005; - const IDLE_FENCE: u32 = 0x0010_2006; - const BAD_OPTIONS: u32 = 0x8000_001f; - const LARGE_REMAINDER: u64 = 0x1_9abc_def0; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP), - drawable: ROOT_WINDOW, - width: 16, - height: 16, - }, - ); - - let mut body = pixmap_body(ROOT_WINDOW.0, PIXMAP); - body[12..16].copy_from_slice(&VALID.to_le_bytes()); - body[16..20].copy_from_slice(&UPDATE.to_le_bytes()); - body[24..28].copy_from_slice(&BAD_CRTC.to_le_bytes()); - body[28..32].copy_from_slice(&WAIT_FENCE.to_le_bytes()); - body[32..36].copy_from_slice(&IDLE_FENCE.to_le_bytes()); - body[36..40].copy_from_slice(&BAD_OPTIONS.to_le_bytes()); - body[60..68].copy_from_slice(&LARGE_REMAINDER.to_le_bytes()); - - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, XFIXES_BAD_REGION, VALID); - - state.xfixes_regions.insert( - VALID, - crate::server::XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, XFIXES_BAD_REGION, UPDATE); - - state.xfixes_regions.insert( - UPDATE, - crate::server::XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 3, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, RANDR_BAD_CRTC, BAD_CRTC); - - body[24..28].copy_from_slice(&0u32.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 4, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, SYNC_BAD_FENCE, WAIT_FENCE); - - state.sync_fences.insert( - WAIT_FENCE, - crate::server::SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 5, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, SYNC_BAD_FENCE, IDLE_FENCE); - - state.sync_fences.insert( - IDLE_FENCE, - crate::server::SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 6, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_OPTIONS); - - body[36..40].copy_from_slice(&0u32.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 7, - yserver_protocol::x11::present::PIXMAP, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, LARGE_REMAINDER as u32); - assert!(!state.present_window_msc.contains_key(&ROOT_WINDOW.0)); - } - - #[test] - fn present_pixmap_synced_validation_order_and_card32_remainder() { - const PIXMAP: u32 = 0x0010_2101; - const ACQUIRE: u32 = 0x0010_2102; - const RELEASE: u32 = 0x0010_2103; - const BAD_ACQUIRE: u32 = 0x0010_21a2; - const BAD_RELEASE: u32 = 0x0010_21a3; - const VALID: u32 = 0x0010_2104; - const UPDATE: u32 = 0x0010_2105; - const BAD_CRTC: u32 = 0x0010_2106; - const BAD_OPTIONS: u32 = 0x4000_001f; - const LARGE_REMAINDER: u64 = 0x1_7654_3210; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(1)); - backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(1)); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP), - drawable: ROOT_WINDOW, - width: 16, - height: 16, - }, - ); - - let mut body = pixmap_synced_body(ROOT_WINDOW.0, PIXMAP, BAD_ACQUIRE, RELEASE, 1, 2); - body[12..16].copy_from_slice(&VALID.to_le_bytes()); - body[16..20].copy_from_slice(&UPDATE.to_le_bytes()); - body[24..28].copy_from_slice(&BAD_CRTC.to_le_bytes()); - body[52..56].copy_from_slice(&BAD_OPTIONS.to_le_bytes()); - body[76..84].copy_from_slice(&LARGE_REMAINDER.to_le_bytes()); - - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_ACQUIRE); - - body[28..32].copy_from_slice(&ACQUIRE.to_le_bytes()); - body[32..36].copy_from_slice(&BAD_RELEASE.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_RELEASE); - - body[32..36].copy_from_slice(&RELEASE.to_le_bytes()); - body[36..44].copy_from_slice(&0u64.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 3, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, 0); - - body[36..44].copy_from_slice(&1u64.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 4, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, XFIXES_BAD_REGION, VALID); - - state.xfixes_regions.insert( - VALID, - crate::server::XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 5, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, XFIXES_BAD_REGION, UPDATE); - - state.xfixes_regions.insert( - UPDATE, - crate::server::XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 6, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, RANDR_BAD_CRTC, BAD_CRTC); - - body[24..28].copy_from_slice(&0u32.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 7, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_OPTIONS); - - body[52..56].copy_from_slice(&0u32.to_le_bytes()); - dispatch_present_body( - &mut state, - &mut backend, - ClientId(1), - 8, - yserver_protocol::x11::present::PIXMAP_SYNCED, - &body, - ); - assert_present_error(&mut peer, x11::error::BAD_VALUE, LARGE_REMAINDER as u32); - assert!(!state.present_window_msc.contains_key(&ROOT_WINDOW.0)); - } - - #[test] - fn present_pixmap_synced_unknown_acquire_syncobj_is_bad_value() { - use yserver_protocol::x11::{ClientId, CreatePixmapRequest, CreateWindowRequest}; - const WINDOW_XID: u32 = 0x00e0_0403; - const PIXMAP_XID: u32 = 0x00e0_0404; - const ACQUIRE_SYNCOBJ: u32 = 0x00e0_0bad; // never imported - const RELEASE_SYNCOBJ: u32 = 0x00e0_0408; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 17); - let mut backend = RecordingBackend::new(); - // The release syncobj is a valid, imported resource; the acquire is - // NOT. Row 4: an unknown acquire xid must produce a Value error, not - // a silent no-reply hang. - backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(17)); - - state.resources.create_window( - ClientId(17), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0x400403); - } - state.resources.create_pixmap( - ClientId(17), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(0x400404).expect("valid host pixmap"), - ); - - let mut body = pixmap_synced_body( - WINDOW_XID, - PIXMAP_XID, - ACQUIRE_SYNCOBJ, - RELEASE_SYNCOBJ, - 1, - 1, - ); - body[76..84].copy_from_slice(&1u64.to_le_bytes()); - dispatch_pixmap_synced(&mut state, &mut backend, ClientId(17), &body); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_VALUE, - "unknown acquire syncobj must be BadValue, not a silent no-reply wait", - ); - // X error: bytes 4-7 are the bad-value argument. It must carry the - // offending xid, mirroring Xorg's VERIFY_DRI3_SYNCOBJ - // (client->errorValue = id). - assert_eq!( - u32::from_le_bytes(buf[4..8].try_into().unwrap()), - ACQUIRE_SYNCOBJ, - "BadValue must carry the offending syncobj xid", - ); - } - - #[test] - fn rejected_synced_depth_mismatch_does_not_change_remembered_crtc() { - const CLIENT: u32 = 17; - const WINDOW: u32 = 0x00e0_0451; - const PIXMAP: u32 = 0x00e0_0452; - const ACQUIRE: u32 = 0x00e0_0453; - const RELEASE: u32 = 0x00e0_0454; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![ - present_test_output(1, 11, 0, 0, 100, 100, true), - present_test_output(2, 22, 100, 0, 100, 100, true), - ], - ); - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 64, - height: 64, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(WINDOW)) - .unwrap() - .host_xid = crate::backend::WindowHandle::from_raw(0x0040_0451); - state.resources.create_pixmap( - ClientId(CLIENT), - CreatePixmapRequest { - depth: 32, - pixmap: ResourceId(PIXMAP), - drawable: ResourceId(WINDOW), - width: 64, - height: 64, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP), - crate::backend::PixmapHandle::from_raw(0x0040_0452).unwrap(), - ); - let mut backend = RecordingBackend::new(); - backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(CLIENT)); - backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(CLIENT)); - let original = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); - - let mut body = pixmap_synced_body(WINDOW, PIXMAP, ACQUIRE, RELEASE, 1, 1); - body[24..28].copy_from_slice(&22u32.to_le_bytes()); - dispatch_pixmap_synced(&mut state, &mut backend, ClientId(CLIENT), &body); - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[1], x11::error::BAD_MATCH); - let remembered = state.present_window_msc[&WINDOW]; - assert_eq!(remembered.last_crtc, original.crtc_id); - assert_eq!(remembered.last_crtc_epoch, original.crtc_epoch); - assert!(!state.present_window_generations.contains_key(&WINDOW)); - } - - #[test] - fn present_pixmap_synced_zero_point_is_bad_value() { - use yserver_protocol::x11::ClientId; - const WINDOW_XID: u32 = 0x00e0_0403; - const PIXMAP_XID: u32 = 0x00e0_0404; - const SYNCOBJ: u32 = 0x00e0_0407; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 17); - let mut backend = RecordingBackend::new(); - backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(17)); - - // Both syncobjs imported; acquire_point == 0 is the violation. - dispatch_pixmap_synced( - &mut state, - &mut backend, - ClientId(17), - &pixmap_synced_body(WINDOW_XID, PIXMAP_XID, SYNCOBJ, SYNCOBJ, 0, 2), - ); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_VALUE, - "acquire_point 0 must be BadValue" - ); - } - - #[test] - fn present_pixmap_synced_acquire_gte_release_is_bad_value() { - use yserver_protocol::x11::ClientId; - const WINDOW_XID: u32 = 0x00e0_0403; - const PIXMAP_XID: u32 = 0x00e0_0404; - const SYNCOBJ: u32 = 0x00e0_0407; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 17); - let mut backend = RecordingBackend::new(); - backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(17)); - - // Same syncobj for acquire and release: acquire_value >= - // release_value is the violation. - dispatch_pixmap_synced( - &mut state, - &mut backend, - ClientId(17), - &pixmap_synced_body(WINDOW_XID, PIXMAP_XID, SYNCOBJ, SYNCOBJ, 5, 5), - ); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_VALUE, - "acquire_value >= release_value on the same syncobj must be BadValue", - ); - } - - #[test] - fn import_syncobj_duplicate_xid_is_bad_id_choice() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - - const XID: u32 = 0x0010_0001; - let fd1: std::os::fd::OwnedFd = std::fs::File::open("/dev/null") - .expect("open /dev/null") - .into(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 10, // IMPORT_SYNCOBJ - length_units: 3, - }, - &import_syncobj_body(XID, ROOT_WINDOW.0), - Some(fd1), - ) - .unwrap(); - - // Re-import of the SAME xid is rejected by the core X resource - // registry before the backend is touched, matching Xorg's - // LEGAL_NEW_RESOURCE gate. - let fd2: std::os::fd::OwnedFd = std::fs::File::open("/dev/null") - .expect("open /dev/null") - .into(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 147, - data: 10, // IMPORT_SYNCOBJ - length_units: 3, - }, - &import_syncobj_body(XID, ROOT_WINDOW.0), - Some(fd2), - ) - .unwrap(); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_ID_CHOICE, - "re-importing a live syncobj XID must be BadIDChoice", - ); - } - - #[test] - fn live_syncobj_xid_cannot_be_reused_for_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = syncobj_cap_backend(); - const XID: u32 = 0x0010_0001; - - let fd: std::os::fd::OwnedFd = std::fs::File::open("/dev/null") - .expect("open /dev/null") - .into(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 147, - data: 10, - length_units: 3, - }, - &import_syncobj_body(XID, ROOT_WINDOW.0), - Some(fd), - ) - .unwrap(); - assert!(state.resources.xid_in_use(ResourceId(XID))); - - let mut body = vec![0u8; 12]; - body[0..4].copy_from_slice(&XID.to_le_bytes()); - body[4..8].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body[8..10].copy_from_slice(&1u16.to_le_bytes()); - body[10..12].copy_from_slice(&1u16.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 53, // CreatePixmap - data: 24, - length_units: 4, - }, - &body, - None, - ) - .unwrap(); - - peer.set_nonblocking(true).unwrap(); - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(read_error(&error), x11::error::BAD_ID_CHOICE); - } - - #[test] - fn kill_client_by_retained_syncobj_xid_destroys_zombie_resources() { - const SYNCOBJ: u32 = 0x0070_0094; - let mut state = ServerState::new(); - let _killer_peer = install_client(&mut state, 1); - let _owner_peer = install_client(&mut state, 7); - let mut backend = RecordingBackend::new(); - state.close_down_modes.insert(7, 1); // RetainPermanent - assert!( - state - .resources - .register_dri3_syncobj(ResourceId(SYNCOBJ), ClientId(7)) - ); - backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(7)); - super::super::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(7)); - assert_eq!(state.zombie_clients.get(&7), Some(&1)); - - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 113, // KillClient - data: 0, - length_units: 2, - }, - &SYNCOBJ.to_le_bytes(), - None, - ) - .unwrap(); - - assert!(matches!(outcome, RequestOutcome::Handled)); - assert!(!state.resources.xid_in_use(ResourceId(SYNCOBJ))); - assert!(!backend.dri3_syncobj_owners.contains_key(&SYNCOBJ)); - assert!(!state.zombie_clients.contains_key(&7)); - } - - #[test] - fn kill_client_all_temporary_destroys_retained_syncobj() { - const SYNCOBJ: u32 = 0x0070_0095; - let mut state = ServerState::new(); - let _killer_peer = install_client(&mut state, 1); - let _owner_peer = install_client(&mut state, 7); - let mut backend = RecordingBackend::new(); - state.close_down_modes.insert(7, 2); // RetainTemporary - assert!( - state - .resources - .register_dri3_syncobj(ResourceId(SYNCOBJ), ClientId(7)) - ); - backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(7)); - super::super::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(7)); - assert_eq!(state.zombie_clients.get(&7), Some(&2)); - - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 113, // KillClient - data: 0, - length_units: 2, - }, - &0u32.to_le_bytes(), // AllTemporary - None, - ) - .unwrap(); - - assert!(matches!(outcome, RequestOutcome::Handled)); - assert!(!state.resources.xid_in_use(ResourceId(SYNCOBJ))); - assert!(!backend.dri3_syncobj_owners.contains_key(&SYNCOBJ)); - assert!(!state.zombie_clients.contains_key(&7)); - } - - #[test] - fn present_pixmap_synced_another_clients_acquire_syncobj_is_bad_value() { - use yserver_protocol::x11::{ClientId, CreatePixmapRequest, CreateWindowRequest}; - const WINDOW_XID: u32 = 0x00e0_0403; - const PIXMAP_XID: u32 = 0x00e0_0404; - const ACQUIRE_SYNCOBJ: u32 = 0x00e0_0bad; // owned by client A (17) - const RELEASE_SYNCOBJ: u32 = 0x00e0_0408; // owned by client B (18) - - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 17); - let mut peer_b = install_client(&mut state, 18); - let mut backend = RecordingBackend::new(); - backend.seed_dri3_syncobj_for_test(ACQUIRE_SYNCOBJ, ClientId(17)); - backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(18)); - - state.resources.create_window( - ClientId(17), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0x400403); - } - state.resources.create_pixmap( - ClientId(17), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(0x400404).expect("valid host pixmap"), - ); - - // B presents using A's acquire syncobj. Xorg's VERIFY_DRI3_SYNCOBJ is - // client-scoped, so the ownership check must reject B as BadValue — - // otherwise B could advance A's timeline on completion and corrupt A's - // buffer reuse. - dispatch_pixmap_synced( - &mut state, - &mut backend, - ClientId(18), - &pixmap_synced_body( - WINDOW_XID, - PIXMAP_XID, - ACQUIRE_SYNCOBJ, - RELEASE_SYNCOBJ, - 1, - 1, - ), - ); - - peer_b.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer_b.read_exact(&mut buf).unwrap(); - assert_eq!( - read_error(&buf), - x11::error::BAD_VALUE, - "B must not be able to present against A's acquire syncobj", - ); - // X error: bytes 4-7 are the bad-value argument — the offending - // acquire xid, mirroring Xorg's VERIFY_DRI3_SYNCOBJ. - assert_eq!( - u32::from_le_bytes(buf[4..8].try_into().unwrap()), - ACQUIRE_SYNCOBJ, - "BadValue must carry the offending acquire xid", - ); - } - - #[test] - fn dri3_get_supported_modifiers_default_window_subset_screen() { - // Default Backend::dri3_supported_modifiers returns - // ([LINEAR], [LINEAR]); the window list must always be a - // subset of the screen list per design §3.2. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = vec![0u8; 8]; - body[0..4].copy_from_slice(&0xCAFEu32.to_le_bytes()); // window - body[4] = 24; - body[5] = 32; - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(11), - RequestHeader { - opcode: 147, - data: 6, // GET_SUPPORTED_MODIFIERS - length_units: 3, - }, - &body, - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - peer.set_nonblocking(true).unwrap(); - // Reply: 32-byte header + 8*nwin + 8*nscr; nwin=nscr=1. - let mut buf = [0u8; 48]; - peer.read_exact(&mut buf).expect("reply bytes delivered"); - assert_eq!(buf[0], 1, "expected Reply, got opcode {}", buf[0]); - let nwin = u32::from_le_bytes(buf[8..12].try_into().unwrap()); - let nscr = u32::from_le_bytes(buf[12..16].try_into().unwrap()); - assert!(nwin <= nscr, "window-list must be subset: {nwin} > {nscr}"); - assert_eq!(nwin, 1); - assert_eq!(nscr, 1); - let m_win = u64::from_le_bytes(buf[32..40].try_into().unwrap()); - let m_scr = u64::from_le_bytes(buf[40..48].try_into().unwrap()); - assert_eq!(m_win, 0); // LINEAR - assert_eq!(m_scr, 0); - } - - #[test] - fn dri3_pixmap_from_buffers_rejects_multi_plane() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // 60-byte body with num_buffers=2 (multi-plane). Phase 4.2 - // accepts only num_buffers==1; everything else returns - // BadAlloc per design "single-plane RGB only" scope. - let mut body = vec![0u8; 60]; - body[0..4].copy_from_slice(&0xAAAA_AAAAu32.to_le_bytes()); // pixmap xid - body[4..8].copy_from_slice(&0xBBBB_BBBBu32.to_le_bytes()); // window xid - body[8] = 2; // num_buffers - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(5), - RequestHeader { - opcode: 147, - data: 7, // PIXMAP_FROM_BUFFERS - length_units: 16, - }, - &body, - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error bytes delivered"); - assert_eq!(buf[0], 0, "expected Error, got opcode {}", buf[0]); - assert_eq!(buf[1], 11, "expected BadAlloc (11), got {}", buf[1]); - } - - #[test] - fn dri3_open_emits_bad_alloc_when_backend_unsupported() { - // RecordingBackend's default Backend::dri3_open returns Err - // (DRI3 unsupported). The dispatcher must convert that to a - // BadAlloc error event, not a successful reply. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let mut body = vec![0u8; 8]; - body[0..4].copy_from_slice(&0xCAFEu32.to_le_bytes()); // drawable - body[4..8].copy_from_slice(&0u32.to_le_bytes()); // provider - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - RequestHeader { - opcode: 147, - data: 1, // OPEN - length_units: 3, - }, - &body, - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - // Read 32 bytes from the peer end of the client's UnixStream: - // X errors are 32-byte fixed-size messages with opcode 0 in - // byte 0 and the error code in byte 1. - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("error bytes delivered to peer"); - assert_eq!(buf[0], 0, "expected Error (opcode 0), got {}", buf[0]); - assert_eq!(buf[1], 11, "expected BadAlloc (11), got {}", buf[1]); - } - - #[test] - fn unknown_major_opcodes_return_bad_request() { - // Xorg's ProcVector routes reserved core opcodes 120-126 and - // unregistered extension slots to ProcBadRequest. Opcode 127 remains - // NoOperation and the registered extension slots are matched above. - for opcode in [120, 126, 255] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(0x1234), - RequestHeader { - opcode, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[0], 0, "wire packet must be an X11 error"); - assert_eq!(error[1], x11::error::BAD_REQUEST); - assert_eq!(u16::from_le_bytes([error[2], error[3]]), 0x1234); - assert_eq!( - error[10], opcode, - "error must identify the unknown major opcode" - ); - assert_eq!(u16::from_le_bytes([error[8], error[9]]), 0); - } - } - - #[test] - fn no_operation_remains_a_successful_noop() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(7), - RequestHeader { - opcode: 127, - data: 0, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled)); - - peer.set_nonblocking(true).unwrap(); - let mut byte = [0u8; 1]; - assert_eq!( - peer.read(&mut byte).unwrap_err().kind(), - io::ErrorKind::WouldBlock - ); - } - - #[test] - fn unknown_extension_minors_return_bad_request() { - // Each locally-dispatched extension below has an Xorg dispatcher that - // returns core BadRequest when the minor is outside its request table. - // GLX is intentionally absent: its dispatcher uses GLXBadRequest and - // has separate coverage for that extension-specific error. - let extensions = [ - (128, "RANDR"), - (130, "MIT-SHM"), - (133, "RENDER"), - (134, "DPMS"), - (135, "BIG-REQUESTS"), - (136, "XKEYBOARD"), - (137, "XInputExtension"), - (138, "Generic Event Extension"), - (140, "XFIXES"), - (141, "SHAPE"), - (142, "SYNC"), - (143, "DAMAGE"), - (144, "Composite"), - (145, "Present"), - (146, "XTEST"), - (147, "DRI3"), - (149, "X-Resource"), - (150, "MIT-SCREEN-SAVER"), - (151, "XINERAMA"), - (152, "XC-MISC"), - (153, "XFree86-VidModeExtension"), - ]; - - for (opcode, name) in extensions { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(0x4321), - RequestHeader { - opcode, - data: u8::MAX, - length_units: 1, - }, - &[], - None, - ) - .unwrap(); - assert!(matches!(outcome, RequestOutcome::Handled), "{name}"); - - let mut error = [0u8; 32]; - peer.read_exact(&mut error) - .unwrap_or_else(|e| panic!("{name}: missing error: {e}")); - assert_eq!(error[0], 0, "{name}: packet must be an X11 error"); - assert_eq!(error[1], x11::error::BAD_REQUEST, "{name}"); - assert_eq!( - u16::from_le_bytes([error[2], error[3]]), - 0x4321, - "{name}: sequence" - ); - assert_eq!( - u16::from_le_bytes([error[8], error[9]]), - u16::from(u8::MAX), - "{name}: minor opcode" - ); - assert_eq!(error[10], opcode, "{name}: major opcode"); - } - } - - #[test] - fn xf86vidmode_v2_mode_line_round_trips_current_randr_timing() { - use crate::randr::{ModeTiming, RandrOutput, RandrState}; - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs( - 1, - vec![RandrOutput { - name: "DP-1".to_string(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 2560, - height: 1440, - vrefresh: 60, - timing: Some(ModeTiming { - clock_khz: 241_500, - hsync_start: 2608, - hsync_end: 2640, - htotal: 2720, - vsync_start: 1443, - vsync_end: 1448, - vtotal: 1481, - mode_flags: 5, - }), - mm_width: 600, - mm_height: 340, - mode_ids: vec![3], - num_preferred: 1, - }], - ); - let expected = current_vidmode_mode_line(&state).expect("active RandR mode"); - assert_eq!( - expected, - x11vm::ModeLine { - dot_clock: 241_500, - hdisplay: 2560, - hsync_start: 2608, - hsync_end: 2640, - htotal: 2720, - hskew: 0, - vdisplay: 1440, - vsync_start: 1443, - vsync_end: 1448, - vtotal: 1481, - flags: 5, - } - ); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::QUERY_VERSION, - length_units: 1, - }, - &[], - None, - ) - .expect("QueryVersion"); - let version = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(version.len(), 32); - assert_eq!(&version[8..12], &[2, 0, 2, 0]); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::SET_CLIENT_VERSION, - length_units: 2, - }, - &[2, 0, 2, 0], - None, - ) - .expect("SetClientVersion"); - assert!(read_all_or_buffered(&mut state, 1, &mut peer).is_empty()); - assert_eq!( - state.vidmode_client_versions.get(&ClientId(1)), - Some(&(2, 2)) - ); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::GET_MODE_LINE, - length_units: 2, - }, - &[0; 4], - None, - ) - .expect("GetModeLine"); - let mode = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(mode.len(), 52); - assert_eq!(u32::from_le_bytes(mode[4..8].try_into().unwrap()), 5); - assert_eq!( - u32::from_le_bytes(mode[8..12].try_into().unwrap()), - expected.dot_clock - ); - assert_eq!( - u16::from_le_bytes(mode[12..14].try_into().unwrap()), - expected.hdisplay - ); - assert_eq!( - u16::from_le_bytes(mode[18..20].try_into().unwrap()), - expected.htotal - ); - assert_eq!( - u16::from_le_bytes(mode[22..24].try_into().unwrap()), - expected.vdisplay - ); - assert_eq!( - u16::from_le_bytes(mode[28..30].try_into().unwrap()), - expected.vtotal - ); - assert_eq!( - u32::from_le_bytes(mode[32..36].try_into().unwrap()), - expected.flags - ); - assert_eq!(&mode[36..52], &[0; 16]); - } - - #[test] - fn xf86vidmode_defaults_to_legacy_reply_and_rejects_unknown_screen() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::GET_MODE_LINE, - length_units: 2, - }, - &[0; 4], - None, - ) - .expect("legacy GetModeLine"); - let legacy = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(legacy.len(), 36); - assert_eq!(u32::from_le_bytes(legacy[4..8].try_into().unwrap()), 1); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::GET_MODE_LINE, - length_units: 2, - }, - &[1, 0, 0, 0], - None, - ) - .expect("bad-screen GetModeLine"); - let error = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!(error.len(), 32); - assert_eq!(error[0], 0); - assert_eq!(error[1], x11::error::BAD_VALUE); - assert_eq!(u32::from_le_bytes(error[4..8].try_into().unwrap()), 1); - assert_eq!( - u16::from_le_bytes(error[8..10].try_into().unwrap()), - u16::from(x11vm::GET_MODE_LINE) - ); - assert_eq!(error[10], crate::nested::XF86VIDMODE_MAJOR_OPCODE); - } - - /// Drive one VidMode request and return whatever went back to the client. - fn dispatch_vidmode( - state: &mut ServerState, - peer: &mut UnixStream, - sequence: u16, - minor: u8, - body: &[u8], - ) -> Vec { - let mut backend = RecordingBackend::new(); - dispatch_vidmode_with_backend(state, &mut backend, peer, sequence, minor, body) - } - - fn dispatch_vidmode_with_backend( - state: &mut ServerState, - backend: &mut dyn Backend, - peer: &mut UnixStream, - sequence: u16, - minor: u8, - body: &[u8], - ) -> Vec { - let length_units = u32::try_from(4 + body.len()).expect("test body") / 4; - process_request( - state, - backend, - ClientId(1), - SequenceNumber(sequence), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: minor, - length_units, - }, - body, - None, - ) - .expect("vidmode dispatch"); - read_all_or_buffered(state, 1, peer) - } - - fn assert_vidmode_error(reply: &[u8], code: u8, minor: u8) { - assert_eq!(reply.len(), 32, "X errors are always 32 bytes"); - assert_eq!(reply[0], 0, "error, not a reply"); - assert_eq!(reply[1], code); - assert_eq!( - u16::from_le_bytes(reply[8..10].try_into().unwrap()), - u16::from(minor) - ); - assert_eq!(reply[10], crate::nested::XF86VIDMODE_MAJOR_OPCODE); - } - - fn validate_mode_line_body( - mode: yserver_protocol::x11::xf86vidmode::ModeLine, - version_2: bool, - byte_order: ClientByteOrder, - ) -> Vec { - fn put_u16(body: &mut [u8], offset: usize, value: u16, order: ClientByteOrder) { - let bytes = match order { - ClientByteOrder::LittleEndian => value.to_le_bytes(), - ClientByteOrder::BigEndian => value.to_be_bytes(), - }; - body[offset..offset + 2].copy_from_slice(&bytes); - } - - fn put_u32(body: &mut [u8], offset: usize, value: u32, order: ClientByteOrder) { - let bytes = match order { - ClientByteOrder::LittleEndian => value.to_le_bytes(), - ClientByteOrder::BigEndian => value.to_be_bytes(), - }; - body[offset..offset + 4].copy_from_slice(&bytes); - } - - let mut body = vec![0; if version_2 { 48 } else { 32 }]; - put_u32(&mut body, 4, mode.dot_clock, byte_order); - put_u16(&mut body, 8, mode.hdisplay, byte_order); - put_u16(&mut body, 10, mode.hsync_start, byte_order); - put_u16(&mut body, 12, mode.hsync_end, byte_order); - put_u16(&mut body, 14, mode.htotal, byte_order); - if version_2 { - put_u16(&mut body, 16, mode.hskew, byte_order); - put_u16(&mut body, 18, mode.vdisplay, byte_order); - put_u16(&mut body, 20, mode.vsync_start, byte_order); - put_u16(&mut body, 22, mode.vsync_end, byte_order); - put_u16(&mut body, 24, mode.vtotal, byte_order); - put_u32(&mut body, 28, mode.flags, byte_order); - } else { - put_u16(&mut body, 16, mode.vdisplay, byte_order); - put_u16(&mut body, 18, mode.vsync_start, byte_order); - put_u16(&mut body, 20, mode.vsync_end, byte_order); - put_u16(&mut body, 22, mode.vtotal, byte_order); - put_u32(&mut body, 24, mode.flags, byte_order); - } - body - } - - /// Known writes must use the same Xorg non-local branch advertised by - /// GetPermissions; truly unknown minors remain BadRequest. - #[test] - fn xf86vidmode_rejects_writes_with_client_not_local() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").is_local = false; - - for (seq, minor) in [2u8, 3, 5, 7, 8, 10, 12, 15, 18].into_iter().enumerate() { - #[allow(clippy::cast_possible_truncation)] - let seq = seq as u16 + 1; - // The locality gate runs before per-request length parsing in Xorg. - let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[]); - assert_vidmode_error( - &reply, - crate::nested::XF86VIDMODE_FIRST_ERROR - + yserver_protocol::x11::xf86vidmode::CLIENT_NOT_LOCAL, - minor, - ); - } - - for (seq, minor) in [21u8, 255].into_iter().enumerate() { - #[allow(clippy::cast_possible_truncation)] - let seq = seq as u16 + 20; - let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[]); - assert_vidmode_error(&reply, x11::error::BAD_REQUEST, minor); - } - } - - #[test] - fn xf86vidmode_permissions_follow_client_locality() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - let local = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_PERMISSIONS, &[0; 4]); - assert_eq!(local[0], 1); - assert_eq!( - u32::from_le_bytes(local[8..12].try_into().unwrap()), - x11vm::PERMISSION_READ | 2, - "local clients receive XF86VM_WRITE_PERMISSION" - ); - - state.clients.get_mut(&1).expect("test client").is_local = false; - let remote = dispatch_vidmode(&mut state, &mut peer, 2, x11vm::GET_PERMISSIONS, &[0; 4]); - assert_eq!(remote[0], 1); - assert_eq!( - u32::from_le_bytes(remote[8..12].try_into().unwrap()), - x11vm::PERMISSION_READ, - "remote clients remain read-only" - ); - } - - #[test] - fn xf86vidmode_rejects_malformed_bodies_with_bad_length() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").is_local = false; - - // QueryVersion takes no body at all. - let reply = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::QUERY_VERSION, &[0; 4]); - assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::QUERY_VERSION); - - // The screen-scoped requests need exactly `screen + pad`. - for (seq, minor) in [ - x11vm::GET_MODE_LINE, - x11vm::GET_MONITOR, - x11vm::GET_ALL_MODE_LINES, - x11vm::GET_VIEW_PORT, - x11vm::GET_DOT_CLOCKS, - x11vm::GET_GAMMA_RAMP_SIZE, - x11vm::GET_PERMISSIONS, - ] - .into_iter() - .enumerate() - { - #[allow(clippy::cast_possible_truncation)] - let seq = seq as u16 + 2; - let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[0; 8]); - assert_vidmode_error(&reply, x11::error::BAD_LENGTH, minor); - } - - // The legacy gamma scalar request is padded to 32 bytes total. - let reply = dispatch_vidmode(&mut state, &mut peer, 12, x11vm::GET_GAMMA, &[0; 4]); - assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::GET_GAMMA); - - // GetGammaRamp carries exactly screen + requested size. - let reply = dispatch_vidmode(&mut state, &mut peer, 13, x11vm::GET_GAMMA_RAMP, &[0; 8]); - assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::GET_GAMMA_RAMP); - - // A legacy ValidateModeLine body is 32 bytes after the X header. - let reply = dispatch_vidmode( - &mut state, - &mut peer, - 14, - x11vm::VALIDATE_MODE_LINE, - &[0; 4], - ); - assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::VALIDATE_MODE_LINE); - - // SetClientVersion needs exactly `major + minor`. - let reply = dispatch_vidmode( - &mut state, - &mut peer, - 15, - x11vm::SET_CLIENT_VERSION, - &[2, 0], - ); - assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::SET_CLIENT_VERSION); - assert!( - !state.vidmode_client_versions.contains_key(&ClientId(1)), - "a rejected SetClientVersion must not record a version" - ); - } - - #[test] - fn xf86vidmode_gamma_matches_selected_randr_crtc() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let crtc = current_vidmode_output(&state) - .expect("active output") - .crtc_id; - let mut backend = RecordingBackend::new(); - - let mut red = vec![0u16; 256]; - let mut green = vec![0u16; 256]; - let mut blue = vec![0u16; 256]; - red[0] = 0x1111; - green[0] = 0x2222; - blue[0] = 0x3333; - red[255] = 0xaaaa; - green[255] = 0xbbbb; - blue[255] = 0xcccc; - backend - .set_crtc_gamma(crtc, &red, &green, &blue) - .expect("seed selected CRTC gamma"); - - let perms = dispatch_vidmode_with_backend( - &mut state, - &mut backend, - &mut peer, - 1, - x11vm::GET_PERMISSIONS, - &[0; 4], - ); - assert_eq!(perms.len(), 32); - assert_eq!(perms[0], 1, "reply, not an error"); - assert_eq!( - u32::from_le_bytes(perms[8..12].try_into().unwrap()), - x11vm::PERMISSION_READ | x11vm::PERMISSION_WRITE, - "local clients receive Xorg's WRITE permission" - ); - - let size = dispatch_vidmode_with_backend( - &mut state, - &mut backend, - &mut peer, - 2, - x11vm::GET_GAMMA_RAMP_SIZE, - &[0; 4], - ); - assert_eq!(size.len(), 32); - assert_eq!(size[0], 1); - assert_eq!(u16::from_le_bytes(size[8..10].try_into().unwrap()), 256); - - let gamma = dispatch_vidmode_with_backend( - &mut state, - &mut backend, - &mut peer, - 3, - x11vm::GET_GAMMA, - &[0; 28], - ); - assert_eq!(gamma.len(), 32); - for offset in [8usize, 12, 16] { - assert_eq!( - u32::from_le_bytes(gamma[offset..offset + 4].try_into().unwrap()), - 10_000, - "GetGamma is the independent per-screen 1.0 scalar" - ); - } - - let ramp = dispatch_vidmode_with_backend( - &mut state, - &mut backend, - &mut peer, - 4, - x11vm::GET_GAMMA_RAMP, - &[0, 0, 0, 1], // screen=0, size=256 - ); - assert_eq!(ramp.len(), 32 + 256 * 3 * 2); - assert_eq!( - u32::from_le_bytes(ramp[4..8].try_into().unwrap()), - 256 * 3 * 2 / 4 - ); - assert_eq!(u16::from_le_bytes(ramp[8..10].try_into().unwrap()), 256); - assert_eq!(u16::from_le_bytes(ramp[32..34].try_into().unwrap()), 0x1111); - assert_eq!( - u16::from_le_bytes(ramp[544..546].try_into().unwrap()), - 0x2222 - ); - assert_eq!( - u16::from_le_bytes(ramp[1056..1058].try_into().unwrap()), - 0x3333 - ); - - let wrong_size = dispatch_vidmode_with_backend( - &mut state, - &mut backend, - &mut peer, - 5, - x11vm::GET_GAMMA_RAMP, - &[0, 0, 128, 0], - ); - assert_vidmode_error(&wrong_size, x11::error::BAD_VALUE, x11vm::GET_GAMMA_RAMP); - } - - #[test] - fn xf86vidmode_monitor_viewport_dotclocks_and_validation_are_readable() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let current = current_vidmode_output(&state).expect("active output"); - let connector = current.connector.clone(); - let mut peer = install_client(&mut state, 1); - - let monitor = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_MONITOR, &[0; 4]); - assert_eq!(monitor[0], 1); - assert_eq!(monitor[8], 0, "no synthetic EDID vendor"); - assert_eq!(usize::from(monitor[9]), connector.len()); - assert_eq!(monitor[10], 1, "one active hsync range"); - assert_eq!(monitor[11], 1, "one active vsync range"); - assert_eq!(&monitor[40..40 + connector.len()], connector.as_bytes()); - - let viewport = dispatch_vidmode(&mut state, &mut peer, 2, x11vm::GET_VIEW_PORT, &[0; 4]); - assert_eq!(viewport.len(), 32); - assert_eq!(&viewport[8..16], &[0; 8]); - - let clocks = dispatch_vidmode(&mut state, &mut peer, 3, x11vm::GET_DOT_CLOCKS, &[0; 4]); - assert_eq!(clocks.len(), 32); - assert_eq!( - u32::from_le_bytes(clocks[8..12].try_into().unwrap()), - x11vm::CLOCK_FLAG_PROGRAMMABLE - ); - assert_eq!(u32::from_le_bytes(clocks[12..16].try_into().unwrap()), 0); - assert_eq!( - u32::from_le_bytes(clocks[16..20].try_into().unwrap()), - x11vm::MAX_CLOCKS - ); - - let legacy_body = - validate_mode_line_body(current.mode, false, ClientByteOrder::LittleEndian); - let legacy_validate = dispatch_vidmode( - &mut state, - &mut peer, - 4, - x11vm::VALIDATE_MODE_LINE, - &legacy_body, - ); - assert_eq!(legacy_validate.len(), 32); - assert_eq!( - u32::from_le_bytes(legacy_validate[8..12].try_into().unwrap()), - x11vm::MODE_OK - ); - - let invalid_validate = dispatch_vidmode( - &mut state, - &mut peer, - 5, - x11vm::VALIDATE_MODE_LINE, - &[0; 32], - ); - assert_eq!( - u32::from_le_bytes(invalid_validate[8..12].try_into().unwrap()), - x11vm::MODE_BAD - ); - - let mut inverted_mode = current.mode; - inverted_mode.hsync_start = inverted_mode.hdisplay - 1; - let inverted_body = - validate_mode_line_body(inverted_mode, false, ClientByteOrder::LittleEndian); - let inverted_validate = dispatch_vidmode( - &mut state, - &mut peer, - 6, - x11vm::VALIDATE_MODE_LINE, - &inverted_body, - ); - assert_eq!( - u32::from_le_bytes(inverted_validate[8..12].try_into().unwrap()), - x11vm::MODE_BAD - ); - - dispatch_vidmode( - &mut state, - &mut peer, - 7, - x11vm::SET_CLIENT_VERSION, - &[2, 0, 2, 0], - ); - let v2_body = validate_mode_line_body(current.mode, true, ClientByteOrder::LittleEndian); - let v2_validate = dispatch_vidmode( - &mut state, - &mut peer, - 8, - x11vm::VALIDATE_MODE_LINE, - &v2_body, - ); - assert_eq!(v2_validate.len(), 32); - assert_eq!( - u32::from_le_bytes(v2_validate[8..12].try_into().unwrap()), - x11vm::MODE_OK - ); - - let mut other_mode = current.mode; - other_mode.dot_clock += 1; - let other_body = validate_mode_line_body(other_mode, true, ClientByteOrder::LittleEndian); - let other_validate = dispatch_vidmode( - &mut state, - &mut peer, - 9, - x11vm::VALIDATE_MODE_LINE, - &other_body, - ); - assert_eq!( - u32::from_le_bytes(other_validate[8..12].try_into().unwrap()), - x11vm::MODE_BAD - ); - } - - #[test] - fn xf86vidmode_dotclocks_reports_programmable_clock_when_headless() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - state.randr.outputs.clear(); - let mut peer = install_client(&mut state, 1); - - // Xorg's modesetting driver advertises a programmable clock even - // without an active output; the active dot clock belongs to - // GetModeLine rather than the legacy fixed-clock table. - let clocks = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_DOT_CLOCKS, &[0; 4]); - assert_eq!(clocks.len(), 32); - assert_eq!( - u32::from_le_bytes(clocks[8..12].try_into().unwrap()), - x11vm::CLOCK_FLAG_PROGRAMMABLE - ); - assert_eq!(u32::from_le_bytes(clocks[12..16].try_into().unwrap()), 0); - assert_eq!( - u32::from_le_bytes(clocks[16..20].try_into().unwrap()), - x11vm::MAX_CLOCKS - ); - } - - #[test] - fn xf86vidmode_monitor_identity_decodes_edid_and_falls_back_to_connector() { - let mut edid = vec![0u8; 128]; - // DEL manufacturer code: D=4, E=5, L=12. - edid[8..10].copy_from_slice(&0x10ac_u16.to_be_bytes()); - edid[54..59].copy_from_slice(&[0, 0, 0, 0xfc, 0]); - edid[59..72].copy_from_slice(b"U2723QE\n "); - assert_eq!( - vidmode_monitor_identity(&edid, "DP-1"), - (b"DEL".to_vec(), b"U2723QE".to_vec()) - ); - assert_eq!( - vidmode_monitor_identity(&[], "Virtual-1"), - (Vec::new(), b"Virtual-1".to_vec()) - ); - } - - #[test] - fn xf86vidmode_get_all_mode_lines_reports_only_the_active_mode() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - // Legacy client: 32-byte header + one 28-byte xXF86OldVidModeModeInfo. - let legacy = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_ALL_MODE_LINES, &[0; 4]); - assert_eq!(legacy.len(), 60); - assert_eq!(u32::from_le_bytes(legacy[8..12].try_into().unwrap()), 1); - - dispatch_vidmode( - &mut state, - &mut peer, - 2, - x11vm::SET_CLIENT_VERSION, - &[2, 0, 2, 0], - ); - - // v2 client: 32-byte header + one 48-byte xXF86VidModeModeInfo. - let v2 = dispatch_vidmode(&mut state, &mut peer, 3, x11vm::GET_ALL_MODE_LINES, &[0; 4]); - assert_eq!(v2.len(), 80); - assert_eq!(u32::from_le_bytes(v2[4..8].try_into().unwrap()), 12); - assert_eq!(u32::from_le_bytes(v2[8..12].try_into().unwrap()), 1); - // Same active mode GetModeLine reports. - let expected = current_vidmode_mode_line(&state).expect("active mode"); - assert_eq!( - u32::from_le_bytes(v2[32..36].try_into().unwrap()), - expected.dot_clock - ); - assert_eq!( - u16::from_le_bytes(v2[42..44].try_into().unwrap()), - expected.htotal - ); - } - - #[test] - fn xf86vidmode_v2_mode_list_keeps_the_core_stream_aligned() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::SET_CLIENT_VERSION, - length_units: 2, - }, - &[2, 0, 2, 0], - None, - ) - .expect("SetClientVersion"); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, - data: x11vm::GET_ALL_MODE_LINES, - length_units: 2, - }, - &[0; 4], - None, - ) - .expect("GetAllModeLines"); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - RequestHeader { - opcode: 43, // GetInputFocus - data: 0, - length_units: 1, - }, - &[], - None, - ) - .expect("GetInputFocus"); - - let stream = read_all_or_buffered(&mut state, 1, &mut peer); - assert_eq!( - stream.len(), - 80 + 32, - "complete VidMode reply followed by core reply" - ); - - assert_eq!(stream[0], 1); - assert_eq!(u16::from_le_bytes(stream[2..4].try_into().unwrap()), 2); - assert_eq!(u32::from_le_bytes(stream[4..8].try_into().unwrap()), 12); - assert_eq!(u32::from_le_bytes(stream[8..12].try_into().unwrap()), 1); - - let focus = &stream[80..]; - assert_eq!(focus[0], 1); - assert_eq!(u16::from_le_bytes(focus[2..4].try_into().unwrap()), 3); - assert_eq!(u32::from_le_bytes(focus[4..8].try_into().unwrap()), 0); - } - - /// `client_reader` swaps ordinary request bodies before dispatch. - /// ValidateModeLine remains in original client order for its - /// version-dependent parser; replies and errors always use client order. - #[test] - fn xf86vidmode_big_endian_client_gets_a_byte_swapped_reply() { - use yserver_protocol::x11::xf86vidmode as x11vm; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.clients.get_mut(&1).expect("test client").byte_order = ClientByteOrder::BigEndian; - - // Bodies arrive already in host order — as `swap_request_body` left - // them — so this is still a little-endian `2.2`. - dispatch_vidmode( - &mut state, - &mut peer, - 1, - x11vm::SET_CLIENT_VERSION, - &[2, 0, 2, 0], - ); - assert_eq!( - state.vidmode_client_versions.get(&ClientId(1)), - Some(&(2, 2)), - "the swapped body must parse as 2.2, not 512.512" - ); - - let expected = current_vidmode_mode_line(&state).expect("active mode"); - let reply = dispatch_vidmode(&mut state, &mut peer, 0x1234, x11vm::GET_MODE_LINE, &[0; 4]); - assert_eq!(reply.len(), 52); - assert_eq!(&reply[2..4], &0x1234_u16.to_be_bytes()); - assert_eq!(&reply[4..8], &5_u32.to_be_bytes()); - assert_eq!(&reply[8..12], &expected.dot_clock.to_be_bytes()); - assert_eq!(&reply[18..20], &expected.htotal.to_be_bytes()); - assert_eq!(&reply[28..30], &expected.vtotal.to_be_bytes()); - - // Errors follow the client's byte order too. `screen = 1` is still - // spelled little-endian in the already-swapped body. - let error = dispatch_vidmode( - &mut state, - &mut peer, - 5, - x11vm::GET_MODE_LINE, - &[1, 0, 0, 0], - ); - assert_eq!(error[0], 0); - assert_eq!(error[1], x11::error::BAD_VALUE); - assert_eq!(&error[4..8], &1_u32.to_be_bytes()); - - let validate = validate_mode_line_body(expected, true, ClientByteOrder::BigEndian); - let validated = dispatch_vidmode( - &mut state, - &mut peer, - 6, - x11vm::VALIDATE_MODE_LINE, - &validate, - ); - assert_eq!(validated.len(), 32); - assert_eq!(&validated[2..4], &6u16.to_be_bytes()); - assert_eq!(&validated[8..12], &x11vm::MODE_OK.to_be_bytes()); - } - - /// The VidMode mode line and RANDR's `ModeInfo` describe the same - /// hardware mode; they must agree on blanking, and their pixel clocks - /// must agree once RANDR's Hz is reduced to VidMode's kHz. - #[test] - fn xf86vidmode_mode_line_agrees_with_randr_mode_info() { - let state = ServerState::new(); - let mode = current_vidmode_mode_line(&state).expect("active mode"); - let resources = state.randr.screen_resources_current(); - let info = resources - .modes - .iter() - .find(|m| m.width == mode.hdisplay && m.height == mode.vdisplay) - .expect("matching RANDR mode"); - - assert_eq!(mode.htotal, info.htotal); - assert_eq!(mode.vtotal, info.vtotal); - assert_eq!(mode.hsync_start, info.hsync_start); - assert_eq!(mode.hsync_end, info.hsync_end); - assert_eq!(mode.vsync_start, info.vsync_start); - assert_eq!(mode.vsync_end, info.vsync_end); - assert_eq!(mode.flags, info.mode_flags); - assert_eq!(mode.dot_clock, (info.dot_clock + 500) / 1000); - } - - // ---- L2 plan B.1: COMPOSITE redirect dispatch policy -------- - - fn composite_redirect_request_body(window: u32, mode: u8) -> Vec { - let mut body = vec![0u8; 8]; - body[0..4].copy_from_slice(&window.to_le_bytes()); - body[4] = mode; - body - } - - fn dispatch_composite_redirect( - state: &mut ServerState, - backend: &mut dyn crate::backend::Backend, - client_id: ClientId, - window: u32, - mode: u8, - ) -> RequestOutcome { - let body = composite_redirect_request_body(window, mode); - process_request( - state, - backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 144, - data: 1, // REDIRECT_WINDOW - length_units: 3, - }, - &body, - None, - ) - .unwrap() - } - - #[test] - fn redirect_window_conflict_from_different_client_returns_bad_access() { - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 1); - let mut peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - // Client A redirects window 0xCAFE first (succeeds). - dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0xCAFE, 0); - // Client B tries the same redirect — must get BadAccess. - dispatch_composite_redirect(&mut state, &mut backend, ClientId(2), 0xCAFE, 0); - peer_b.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer_b.read_exact(&mut buf).expect("error delivered to B"); - assert_eq!(buf[0], 0, "expected X11 Error, got opcode {}", buf[0]); - // BAD_ACCESS = 10 - assert_eq!(buf[1], 10, "expected BadAccess (10), got {}", buf[1]); - } - - #[test] - fn redirect_window_same_client_idempotent() { - let mut state = ServerState::new(); - let mut peer_a = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Two REDIRECT_WINDOW from the same client on the same window: - // both should succeed with no error event written. - dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0xBEEF, 0); - dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0xBEEF, 0); - peer_a.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - let n = peer_a.read(&mut buf).unwrap_or(0); - assert_eq!(n, 0, "no error bytes expected, got {n} bytes: {buf:02x?}"); - assert_eq!(state.composite_redirects.len(), 1); - } - - #[test] - fn redirect_manual_mode_is_accepted() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // compositeproto: update=1 → Manual. xfwm4, picom, xcompmgr, - // and mate-panel's notification-area-applet all request Manual. - dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0xDEAD, 1); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - let n = peer.read(&mut buf).unwrap_or(0); - assert_eq!(n, 0, "no error bytes expected, got {n} bytes: {buf:02x?}"); - assert_eq!(state.composite_redirects.len(), 1); - } - - #[test] - fn redirect_window_manual_conflicts_with_inherited_manual() { - use crate::server::{CompositeRedirectMode, RedirectRecord}; - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let window = ResourceId(0x0100_0042); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window, - parent: ROOT_WINDOW, - width: 100, - height: 100, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.composite_redirects.insert( - (ROOT_WINDOW, true), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); - - // Muffin issues this redundant request for a root child that - // already inherited root RedirectSubwindows(Manual). Xorg's - // compRedirectWindow rejects it even for the same client. - dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), window.0, 1); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("BadAccess delivered"); - assert_eq!(buf[0], 0); - assert_eq!(buf[1], x11::error::BAD_ACCESS); - assert!( - !state.composite_redirects.contains_key(&(window, false)), - "rejected probe must not install a persistent direct redirect", - ); - } - - #[test] - fn redirect_window_cow_is_success_noop() { - // RedirectWindow(COW) must succeed silently (no X error on the wire) - // and must NOT install a redirect — matching Xorg compalloc.c:145-147. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - dispatch_composite_redirect( - &mut state, - &mut backend, - ClientId(1), - crate::resources::COMPOSITE_OVERLAY_WINDOW.0, - 1, // Manual - ); - - // No X11 error should have been queued to the client. - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - let n = peer.read(&mut buf).unwrap_or(0); - assert_eq!(n, 0, "no error bytes expected, got {n} bytes: {buf:02x?}"); - - // The COW must not be marked redirected: no redirect record exists. - assert!( - state.composite_redirects.is_empty(), - "RedirectWindow(COW) is a Success no-op, COW stays unredirected" - ); - } - - #[test] - fn present_default_crtc_uses_overlap_primary_tie_and_stable_order() { - const WINDOW: u32 = 0x0001_1001; - let mut state = ServerState::new(); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![ - present_test_output(2, 22, 0, 0, 100, 100, true), - present_test_output(1, 11, 100, 0, 100, 100, true), - ], - ); - state.randr.primary_output = 1; - create_present_test_window(&mut state, WINDOW, 50, 0, 100, 50); - - assert_eq!( - default_present_crtc_for_window(&state, ResourceId(WINDOW)), - 11, - "the primary output wins an equal-area overlap" - ); - state.randr.primary_output = 999; - assert_eq!( - default_present_crtc_for_window(&state, ResourceId(WINDOW)), - 22, - "without a primary tie, stable output enumeration wins" - ); - let window = state.resources.window_mut(ResourceId(WINDOW)).unwrap(); - window.x = 10; - window.width = 70; - assert_eq!( - default_present_crtc_for_window(&state, ResourceId(WINDOW)), - 22, - "greatest intersection wins before tie-breaking" - ); - - for output in &mut state.randr.outputs { - output.mode_id = 0; - } - assert_eq!( - default_present_crtc_for_window(&state, ResourceId(WINDOW)), - 0, - "zero enabled outputs use the synthetic headless domain" - ); - } - - #[test] - fn explicit_off_crtc_is_valid_but_unpaced() { - const CRTC: u32 = 55; - const WINDOW: u32 = 0x0001_1051; - const PIXMAP: u32 = 0x0001_1052; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![present_test_output(5, CRTC, 0, 0, 1920, 1080, false)], - ); - create_present_test_window(&mut state, WINDOW, 0, 0, 64, 64); - { - let window = state.resources.window_mut(ResourceId(WINDOW)).unwrap(); - window.host_xid = crate::backend::WindowHandle::from_raw(0x0040_1051); - // A Present to an unviewable window copies nothing (Xorg micopy.c:157). - window.map_state = crate::resources::MapState::Viewable; - } - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP), - drawable: ResourceId(WINDOW), - width: 64, - height: 64, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP), - crate::backend::PixmapHandle::from_raw(0x0040_1052).unwrap(), - ); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc_by_crtc.insert(CRTC, (999, 0x1234)); - - let domain = select_present_domain(&mut state, &mut backend, ROOT_WINDOW.0, CRTC, false) - .expect("a valid-but-Off RANDR CRTC is accepted"); - assert_eq!((domain.crtc_id, domain.crtc_epoch), (CRTC, 0)); - assert_eq!((domain.raw_msc, domain.raw_ust), (0, 0)); - assert_eq!( - effective_present_target_raw(domain, 500, 7, 3, 0), - None, - "Off CRTCs degrade to immediate/unpaced operation" - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP.to_le_bytes()); - body[24..28].copy_from_slice(&CRTC.to_le_bytes()); - body[44..52].copy_from_slice(&500u64.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: 18, - }, - &body, - None, - ) - .unwrap(); - assert!(state.present_pending_exec.is_empty()); - assert!(state.present_complete_gate.is_empty()); - assert!(backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: 0x0040_1052, - dst_host_xid: 0x0040_1051, - .. - } - ))); - assert!(read_all_available(&mut peer).is_empty(), "no X error"); - } - - #[test] - fn clocked_async_present_keeps_xorg_current_msc_target_identity() { - let domain = PresentDomainSelection { - crtc_id: 55, - crtc_epoch: 7, - msc_offset: 0, - raw_msc: 500, - raw_ust: 50_000, - }; - - assert_eq!( - effective_present_target_raw( - domain, - 0, - 0, - 0, - crate::present_scheduler::PRESENT_OPTION_ASYNC, - ), - Some(500), - "Xorg retains the current CRTC MSC as the target identity for an immediate async Present", - ); - } - - #[test] - fn invalid_explicit_present_crtc_is_bad_crtc_with_error_value() { - const PIXMAP: u32 = 0x0001_1101; - const BAD_CRTC: u32 = 0xdead_beef; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP), - drawable: ROOT_WINDOW, - width: 16, - height: 16, - }, - ); - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP.to_le_bytes()); - body[24..28].copy_from_slice(&BAD_CRTC.to_le_bytes()); - body[60..68].copy_from_slice(&1u64.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: 18, - }, - &body, - None, - ) - .unwrap(); - - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[0], 0); - assert_eq!(error[1], RANDR_BAD_CRTC); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - BAD_CRTC - ); - assert!( - !state.present_window_msc.contains_key(&ROOT_WINDOW.0), - "a rejected request must not bind the window domain" - ); - } - - #[test] - fn notify_msc_reuses_last_present_domain_while_pixmap_reselects() { - const WINDOW: u32 = 0x0001_1201; - let mut state = ServerState::new(); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![ - present_test_output(1, 11, 0, 0, 100, 100, true), - present_test_output(2, 22, 100, 0, 100, 100, true), - ], - ); - create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); - let mut backend = RecordingBackend::new(); - - let explicit = select_present_domain(&mut state, &mut backend, WINDOW, 22, false).unwrap(); - assert_eq!(explicit.crtc_id, 22); - let notify = select_present_domain(&mut state, &mut backend, WINDOW, 0, true).unwrap(); - assert_eq!(notify.crtc_id, 22, "NotifyMSC reuses the remembered CRTC"); - let pixmap = select_present_domain(&mut state, &mut backend, WINDOW, 0, false).unwrap(); - assert_eq!(pixmap.crtc_id, 11, "Pixmap reselects from current coverage"); - } - - #[test] - fn domain_switch_preserves_window_msc_and_unshifted_remainder_snapshot() { - const WINDOW: u32 = 0x0001_1301; - let mut state = ServerState::new(); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![ - present_test_output(1, 11, 0, 0, 100, 100, true), - present_test_output(2, 22, 100, 0, 100, 100, true), - ], - ); - create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); - let mut backend = RecordingBackend::new(); - backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); - backend.present_crtc_clock_epoch_by_crtc.insert(22, 7); - backend.present_ust_msc_by_crtc.insert(11, (100, 1)); - backend.present_ust_msc_by_crtc.insert(22, (1_007, 2)); - - let first = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); - assert_eq!(first.raw_msc.wrapping_sub(first.msc_offset), 100); - backend.present_ust_msc_by_crtc.insert(11, (120, 3)); - let switched = select_present_domain(&mut state, &mut backend, WINDOW, 22, false).unwrap(); - assert_eq!(switched.msc_offset, 887); - assert_eq!(switched.raw_msc.wrapping_sub(switched.msc_offset), 120); - - let effective = effective_present_target_raw(switched, 100, 10, 3, 0).unwrap(); - assert_eq!(effective, 1_013); - assert_eq!( - effective % 10, - 3, - "the wire remainder is not offset-shifted" - ); - - let mut pending = - present_pending_entry_with(700, WINDOW, 0x0040_1302, Some(effective), true).pending; - pending.crtc_id = switched.crtc_id; - pending.crtc_epoch = switched.crtc_epoch; - pending.msc_offset = switched.msc_offset; - let event = completed_event_for_pending(&pending); - backend.present_ust_msc_by_crtc.insert(11, (200, 4)); - let _later = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); - assert_eq!( - event.msc_offset, 887, - "in-flight events retain their offset snapshot" - ); - assert_eq!( - present_wire_clock( - crate::backend::PresentClockSample { - msc: effective, - ust: 5, - source: crate::backend::PresentClockSource::PageFlip, - }, - event.msc_offset, - ) - .msc, - 126 - ); - } - - #[test] - fn notify_msc_reaches_wrapped_raw_target_after_domain_switch() { - const WINDOW: u32 = 0x0001_1351; - let mut state = ServerState::new(); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![ - present_test_output(1, 11, 0, 0, 100, 100, true), - present_test_output(2, 22, 100, 0, 100, 100, true), - ], - ); - create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); - let mut backend = RecordingBackend::new(); - backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); - backend.present_crtc_clock_epoch_by_crtc.insert(22, 1); - backend.present_ust_msc_by_crtc.insert(11, (20, 1)); - backend.present_ust_msc_by_crtc.insert(22, (10, 2)); - let _ = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); - let switched = select_present_domain(&mut state, &mut backend, WINDOW, 22, false).unwrap(); - assert_eq!(switched.msc_offset, u64::MAX - 9); - let raw_target = 9u64.wrapping_add(switched.msc_offset); - assert_eq!(raw_target, u64::MAX); - state - .present_pending_msc - .push(crate::server::PendingNotifyMsc { - owner: ClientId(1), - window: WINDOW, - crtc_id: 22, - crtc_epoch: 1, - msc_offset: switched.msc_offset, - serial: 1, - target_msc: raw_target, - divisor: 0, - remainder: 0, - byte_order: ClientByteOrder::LittleEndian, - }); - - fire_due_present_notify_msc_for_domain(&mut state, 22, 1, 1, 3, false); - assert!( - state.present_pending_msc.is_empty(), - "raw MSC 1 is after wrapped target u64::MAX" - ); - } - - #[test] - fn same_crtc_new_epoch_rebases_from_cached_old_raw_clock() { - const WINDOW: u32 = 0x0001_1401; - const CRTC: u32 = 11; - let mut state = ServerState::new(); - state.randr = crate::randr::RandrState::from_outputs( - 1, - vec![present_test_output(1, CRTC, 0, 0, 100, 100, true)], - ); - create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); - let mut backend = RecordingBackend::new(); - backend.present_crtc_clock_epoch_by_crtc.insert(CRTC, 1); - backend.present_ust_msc_by_crtc.insert(CRTC, (100, 1)); - let _ = select_present_domain(&mut state, &mut backend, WINDOW, CRTC, false).unwrap(); - backend.present_ust_msc_by_crtc.insert(CRTC, (120, 2)); - refresh_present_crtc_general_clock(&mut state, &mut backend, CRTC, 1); - - backend.present_crtc_clock_epoch_by_crtc.insert(CRTC, 2); - backend.present_ust_msc_by_crtc.insert(CRTC, (1_000, 3)); - let rebound = select_present_domain(&mut state, &mut backend, WINDOW, CRTC, false).unwrap(); - assert_eq!(rebound.msc_offset, 880); - assert_eq!(rebound.raw_msc.wrapping_sub(rebound.msc_offset), 120); - assert!(state.present_crtc_clocks.contains_key(&(CRTC, 1))); - assert!(state.present_crtc_clocks.contains_key(&(CRTC, 2))); - } - - #[test] - fn exact_completion_sample_does_not_regress_domain_due_clock() { - let mut state = ServerState::new(); - seed_present_domain_clock(&mut state, 11, 1, 200, 2); - let older = crate::backend::PresentClockSample { - msc: 150, - ust: 1, - source: crate::backend::PresentClockSource::PageFlip, - }; - let mut backend = RecordingBackend::new(); - let returned = - refresh_present_crtc_completion_clock(&mut state, &mut backend, 11, 1, Some(older)); - assert_eq!(returned.msc, 150, "the event retains its exact stamp"); - assert_eq!( - state.present_crtc_clocks[&(11, 1)].completion.msc, - 200, - "the shared due clock never regresses" - ); - fire_due_present_completions_for_domain(&mut state, &mut backend, 11, 1, older); - assert_eq!(state.present_crtc_clocks[&(11, 1)].completion.msc, 200); - } - - #[test] - fn older_exact_sample_stamps_event_but_domain_clock_decides_due() { - const WINDOW: u32 = 0x0001_1451; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - 0x0001_14e1, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW), - event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - seed_present_domain_clock(&mut state, 11, 1, 120, 12); - let mut pending = due_pending_complete( - WINDOW, - 750, - 100, - yserver_protocol::x11::present::COMPLETE_MODE_COPY, - false, - ); - pending.event.crtc_id = 11; - pending.event.crtc_epoch = 1; - pending.event.completion_clock = Some(crate::backend::PresentClockSample { - msc: 90, - ust: 9, - source: crate::backend::PresentClockSource::PageFlip, - }); - state.present_pending_complete.push(pending); - let mut backend = RecordingBackend::new(); - backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); - - fire_due_present_completions_for_domain( - &mut state, - &mut backend, - 11, - 1, - crate::backend::PresentClockSample { - msc: 120, - ust: 12, - source: crate::backend::PresentClockSource::PageFlip, - }, - ); - assert!( - state.present_pending_complete.is_empty(), - "cached domain MSC 120 releases target 100 despite exact stamp 90" - ); - let mut event = [0u8; 40]; - peer.read_exact(&mut event).unwrap(); - assert_eq!( - u64::from_le_bytes(event[32..40].try_into().unwrap()), - 90, - "the grouped-direct reference sample remains the wire timestamp" - ); - } - - #[test] - fn supersession_never_crosses_crtc_or_epoch_domains() { - const WINDOW: u32 = 0x0001_1501; - const PREDECESSOR: u64 = 800; - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut predecessor = - present_pending_entry_with(PREDECESSOR, WINDOW, 0x0040_1502, Some(500), true); - predecessor.pending.crtc_id = 11; - predecessor.pending.crtc_epoch = 1; - state.present_pending_exec.insert(PREDECESSOR, predecessor); - - let mut successor = - present_pending_entry_with(801, WINDOW, 0x0040_1503, Some(500), true).pending; - successor.crtc_id = 22; - successor.crtc_epoch = 1; - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - assert!(state.present_pending_exec.contains_key(&PREDECESSOR)); - successor.crtc_id = 11; - successor.crtc_epoch = 2; - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - assert!(state.present_pending_exec.contains_key(&PREDECESSOR)); - successor.crtc_epoch = 1; - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - assert!( - !state.present_pending_exec.contains_key(&PREDECESSOR), - "the control case scraps only inside the identical raw clock domain" - ); - } - - #[test] - fn epoch_mismatch_is_not_rearmed_and_fails_open_unpaced() { - const PRESENT_ID: u64 = 900; - let mut state = ServerState::new(); - let mut entry = - present_pending_entry_with(PRESENT_ID, 0x0001_1601, 0x0040_1602, Some(1_000), true); - entry.pending.crtc_id = 11; - entry.pending.crtc_epoch = 1; - state.present_pending_exec.insert(PRESENT_ID, entry); - seed_present_domain_clock(&mut state, 11, 1, 10, 1); - let mut backend = RecordingBackend::new(); - backend.present_crtc_clock_epoch_by_crtc.insert(11, 2); - backend.present_absolute_vblank_arm_supported = true; - - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - assert!(backend.armed_absolute_vblank_targets.is_empty()); - assert!(state.present_pending_exec.contains_key(&PRESENT_ID)); - drain_due_present_pending_exec(&mut state, &mut backend); - assert!(state.present_pending_exec.is_empty()); - assert!(backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: 0x0040_1602, - .. - } - ))); - } - - #[test] - fn destroyed_window_generation_suppresses_hidden_direct_events_after_xid_reuse() { - const WINDOW: u32 = 0x0001_1701; - const DIRECT_ID: u64 = 901; - const ABSENT_COPY_ID: u64 = 902; - const REUSED_COPY_ID: u64 = 903; - const PURGED_COPY_ID: u64 = 904; - const ABSENT_FENCE: u32 = 0x0001_17f1; - const REUSED_FENCE: u32 = 0x0001_17f2; - const PURGED_FENCE: u32 = 0x0001_17f3; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); - let old_generation = state.present_window_generation(WINDOW); - state.present_event_selections.insert( - 0x0001_17e1, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW), - event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - state.present_complete_gate.insert( - DIRECT_ID, - crate::server::PresentCompleteGate { - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: 1, - owner: ClientId(1), - dst_window_xid: WINDOW, - }, - ); - let event = crate::backend::CompletedPresentEvent { - client_id: ClientId(1), - serial: 1, - host_xid: 0x0001_1702, - dst_host_xid: WINDOW, - options: 0, - present_id: DIRECT_ID, - window_generation: old_generation, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - completion_clock: None, - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_FLIP, - emit_idle: false, - }; - let absent_copy = crate::backend::CompletedPresentEvent { - present_id: ABSENT_COPY_ID, - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: ABSENT_FENCE, - }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - ..event.clone() - }; - let reused_copy = crate::backend::CompletedPresentEvent { - present_id: REUSED_COPY_ID, - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: REUSED_FENCE, - }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - ..event.clone() - }; - let purged_copy = crate::backend::CompletedPresentEvent { - present_id: PURGED_COPY_ID, - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: PURGED_FENCE, - }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - ..event.clone() - }; - for fence in [ABSENT_FENCE, REUSED_FENCE, PURGED_FENCE] { - state.sync_fences.insert( - fence, - crate::server::SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - } - state - .present_pending_complete - .push(crate::server::PendingPresentComplete { - event: purged_copy, - effective_target_msc: 1, - mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }); - let mut backend = RecordingBackend::new(); - - destroy_window_subtree(&mut state, &mut backend, None, ResourceId(WINDOW)); - assert!(!state.present_window_generations.contains_key(&WINDOW)); - assert!(state.present_complete_gate.is_empty()); - assert!(state.present_event_selections.is_empty()); - assert_eq!(backend.signalled_present_wakes, vec![PURGED_COPY_ID]); - assert!(state.sync_fences[&PURGED_FENCE].triggered); - - backend.completed_present_events_to_drain.push(absent_copy); - let _ = read_all_available(&mut peer); - crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); - assert_eq!( - backend.signalled_present_wakes, - vec![PURGED_COPY_ID, ABSENT_COPY_ID], - "a stale hidden Copy releases exactly when its GPU completion drains" - ); - assert!(state.sync_fences[&ABSENT_FENCE].triggered); - assert!(read_all_available(&mut peer).is_empty()); - - create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); - let new_generation = state.present_window_generation(WINDOW); - assert_ne!(new_generation, old_generation); - state.present_event_selections.insert( - 0x0001_17e2, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW), - event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - backend - .completed_present_events_to_drain - .push(event.clone()); - backend.completed_present_events_to_drain.push(reused_copy); - let _ = read_all_available(&mut peer); - crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); - assert!(read_all_available(&mut peer).is_empty()); - assert_eq!( - backend.signalled_present_wakes, - vec![PURGED_COPY_ID, ABSENT_COPY_ID, REUSED_COPY_ID], - "stale Copy releases, but stale direct Complete does not idle early" - ); - assert!(state.sync_fences[&REUSED_FENCE].triggered); - - backend.retired_present_idle_events_to_drain.push(event); - crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); - assert_eq!( - backend.signalled_present_wakes, - vec![PURGED_COPY_ID, ABSENT_COPY_ID, REUSED_COPY_ID, DIRECT_ID] - ); - assert!(read_all_available(&mut peer).is_empty()); - } - - #[test] - fn run_loop_groups_all_present_arm_sites_by_crtc_epoch() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); - backend.present_crtc_clock_epoch_by_crtc.insert(22, 2); - state.present_pending_msc.extend([ - crate::server::PendingNotifyMsc { - owner: ClientId(1), - window: 1, - crtc_id: 11, - crtc_epoch: 1, - msc_offset: 0, - serial: 1, - target_msc: 101, - divisor: 0, - remainder: 0, - byte_order: ClientByteOrder::LittleEndian, - }, - crate::server::PendingNotifyMsc { - owner: ClientId(1), - window: 2, - crtc_id: 11, - crtc_epoch: 1, - msc_offset: 0, - serial: 2, - target_msc: 102, - divisor: 0, - remainder: 0, - byte_order: ClientByteOrder::LittleEndian, - }, - crate::server::PendingNotifyMsc { - owner: ClientId(1), - window: 3, - crtc_id: 22, - crtc_epoch: 2, - msc_offset: 0, - serial: 3, - target_msc: 201, - divisor: 0, - remainder: 0, - byte_order: ClientByteOrder::LittleEndian, - }, - ]); - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - assert_eq!( - backend.armed_idle_vblank_targets, - vec![(11, vec![101, 102]), (22, vec![201])] - ); - - state.present_pending_msc.clear(); - let mut c1 = due_pending_complete(10, 1, 111, 0, true); - c1.event.crtc_id = 11; - c1.event.crtc_epoch = 1; - let mut c2 = due_pending_complete(20, 2, 222, 0, true); - c2.event.crtc_id = 22; - c2.event.crtc_epoch = 2; - state.present_pending_complete.extend([c1, c2]); - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - assert_eq!( - backend.armed_completion_idle_vblank_targets, - vec![(11, vec![111]), (22, vec![222])] - ); - - state.present_pending_complete.clear(); - let mut e1 = present_pending_entry_with(3, 30, 31, Some(110), true); - e1.pending.crtc_id = 11; - e1.pending.crtc_epoch = 1; - let mut e2 = present_pending_entry_with(4, 40, 41, Some(220), true); - e2.pending.crtc_id = 22; - e2.pending.crtc_epoch = 2; - state.present_pending_exec.insert(3, e1); - state.present_pending_exec.insert(4, e2); - seed_present_domain_clock(&mut state, 11, 1, 100, 1); - seed_present_domain_clock(&mut state, 22, 2, 200, 2); - backend.present_absolute_vblank_arm_supported = true; - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - assert_eq!(backend.armed_absolute_vblank_crtcs, vec![11, 22]); - assert_eq!( - backend.armed_absolute_vblank_targets, - vec![vec![109], vec![219]] - ); - } - - #[test] - fn headless_notify_msc_completes_without_parking() { - let mut state = ServerState::new(); - state.randr = crate::randr::RandrState::from_outputs(1, Vec::new()); - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - 1, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ROOT_WINDOW, - event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let mut body = vec![0u8; 36]; - body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body[4..8].copy_from_slice(&1u32.to_le_bytes()); - body[12..20].copy_from_slice(&500u64.to_le_bytes()); - let mut backend = RecordingBackend::new(); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::NOTIFY_MSC, - length_units: 10, - }, - &body, - None, - ) - .unwrap(); - assert!(state.present_pending_msc.is_empty()); - assert_eq!(state.present_window_msc[&ROOT_WINDOW.0].last_crtc, 0); - let mut event = [0u8; 40]; - peer.read_exact(&mut event).unwrap(); - assert_eq!(u64::from_le_bytes(event[32..40].try_into().unwrap()), 0); - } - - #[test] - fn present_notify_msc_parks_then_fires_on_vblank_advance() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - const WINDOW: u32 = 0x100; - const EID: u32 = 0x0100_0001; - const SERIAL: u32 = 0x0100_0002; - const COMPLETE_NOTIFY_MASK: u32 = 0x2; - - let mut select_body = Vec::new(); - select_body.extend_from_slice(&EID.to_le_bytes()); - select_body.extend_from_slice(&WINDOW.to_le_bytes()); - select_body.extend_from_slice(&COMPLETE_NOTIFY_MASK.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::SELECT_INPUT, - length_units: 4, - }, - &select_body, - None, - ) - .expect("Present SelectInput"); - - let mut notify_body = Vec::new(); - notify_body.extend_from_slice(&WINDOW.to_le_bytes()); - notify_body.extend_from_slice(&SERIAL.to_le_bytes()); - notify_body.extend_from_slice(&0_u32.to_le_bytes()); // pad - notify_body.extend_from_slice(&0_u64.to_le_bytes()); // target_msc - notify_body.extend_from_slice(&0_u64.to_le_bytes()); // divisor - notify_body.extend_from_slice(&0_u64.to_le_bytes()); // remainder - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::NOTIFY_MSC, - length_units: 10, - }, - ¬ify_body, - None, - ) - .expect("Present NotifyMSC"); - - // Vblank-paced clock: with no pageflip yet (present_kernel_msc == 0) - // the request is PARKED rather than completed immediately — emitting - // ust=0 would be rejected by a `present`-scheduler compositor (picom). - assert_eq!( - state.present_pending_msc.len(), - 1, - "NotifyMSC parks until a real (msc, ust) is available" - ); - - // Simulate a pageflip / armed-vblank advancing the kernel clock. This - // is what `drain_present_completions` does after the backend reports a - // retirement; it drains every parked request whose target is satisfied. - const FIRED_MSC: u64 = 100; - const FIRED_UST: u64 = 0x1234_5678; - fire_due_present_notify_msc(&mut state, FIRED_MSC, FIRED_UST); - assert!( - state.present_pending_msc.is_empty(), - "satisfied parked request is removed after firing" - ); - - let mut event = [0u8; 40]; - peer.read_exact(&mut event).expect("CompleteNotify event"); - assert_eq!(event[0], 35, "GenericEvent"); - assert_eq!(event[1], 145, "Present extension major opcode"); - assert_eq!( - u16::from_le_bytes([event[8], event[9]]), - u16::from(yserver_protocol::x11::present::EVENT_COMPLETE_NOTIFY) - ); - assert_eq!( - event[10], - yserver_protocol::x11::present::COMPLETE_KIND_NOTIFY_MSC - ); - assert_eq!( - u32::from_le_bytes([event[12], event[13], event[14], event[15]]), - EID - ); - assert_eq!( - u32::from_le_bytes([event[16], event[17], event[18], event[19]]), - WINDOW - ); - assert_eq!( - u32::from_le_bytes([event[20], event[21], event[22], event[23]]), - SERIAL - ); - // UST (offset 24) and MSC (offset 32) carry the real kernel values. - assert_eq!( - u64::from_le_bytes([ - event[24], event[25], event[26], event[27], event[28], event[29], event[30], - event[31], - ]), - FIRED_UST, - "CompleteNotify reports the real UST from the vblank advance" - ); - assert_eq!( - u64::from_le_bytes([ - event[32], event[33], event[34], event[35], event[36], event[37], event[38], - event[39], - ]), - FIRED_MSC, - "CompleteNotify reports the real MSC from the vblank advance" - ); - } - - #[test] - fn notify_msc_resource_precedence_and_card32_remainder_error_value() { - const UNKNOWN_WINDOW: u32 = 0x00ff_aa01; - const LARGE_REMAINDER: u64 = 0x1_0000_0001; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 36]; - body[0..4].copy_from_slice(&UNKNOWN_WINDOW.to_le_bytes()); - body[28..36].copy_from_slice(&LARGE_REMAINDER.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::NOTIFY_MSC, - length_units: 10, - }, - &body, - None, - ) - .unwrap(); - let mut error = [0u8; 32]; - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[1], x11::error::BAD_WINDOW); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - UNKNOWN_WINDOW - ); - - body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::NOTIFY_MSC, - length_units: 10, - }, - &body, - None, - ) - .unwrap(); - peer.read_exact(&mut error).unwrap(); - assert_eq!(error[1], x11::error::BAD_VALUE); - assert_eq!( - u32::from_le_bytes(error[4..8].try_into().unwrap()), - 1, - "Xorg stores remainder in CARD32 errorValue (low-32 truncation)" - ); - assert!(!state.present_window_msc.contains_key(&ROOT_WINDOW.0)); - } - - #[test] - fn present_notify_msc_remainder_ge_divisor_is_rejected_not_parked() { - // Xorg rejects remainder >= divisor with BadValue. Pre-fix, such a - // request parked forever: current_msc % divisor is always < divisor, so - // it could never equal a remainder >= divisor, growing the parked list - // unbounded and re-scanning it every vblank. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - const WINDOW: u32 = 0x100; - - let mut notify_body = Vec::new(); - notify_body.extend_from_slice(&WINDOW.to_le_bytes()); - notify_body.extend_from_slice(&1_u32.to_le_bytes()); // serial - notify_body.extend_from_slice(&0_u32.to_le_bytes()); // pad - notify_body.extend_from_slice(&0_u64.to_le_bytes()); // target_msc - notify_body.extend_from_slice(&2_u64.to_le_bytes()); // divisor - notify_body.extend_from_slice(&5_u64.to_le_bytes()); // remainder >= divisor - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::NOTIFY_MSC, - length_units: 10, - }, - ¬ify_body, - None, - ) - .expect("Present NotifyMSC (invalid divisor/remainder)"); - - assert!( - state.present_pending_msc.is_empty(), - "remainder >= divisor must be rejected, not parked forever" - ); - } - - #[test] - fn present_pending_msc_purged_on_client_disconnect() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - const WINDOW: u32 = 0x100; - - // Park a NotifyMSC (present_kernel_msc == 0 → always parks). - let mut notify_body = Vec::new(); - notify_body.extend_from_slice(&WINDOW.to_le_bytes()); - notify_body.extend_from_slice(&1_u32.to_le_bytes()); // serial - notify_body.extend_from_slice(&0_u32.to_le_bytes()); // pad - notify_body.extend_from_slice(&1_u64.to_le_bytes()); // target_msc - notify_body.extend_from_slice(&0_u64.to_le_bytes()); // divisor - notify_body.extend_from_slice(&0_u64.to_le_bytes()); // remainder - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::NOTIFY_MSC, - length_units: 10, - }, - ¬ify_body, - None, - ) - .expect("Present NotifyMSC"); - assert_eq!(state.present_pending_msc.len(), 1, "request parked"); - - // Client disconnects → its parked requests must be purged, else they - // are re-scanned every vblank forever with no client to satisfy them. - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - assert!( - state.present_pending_msc.is_empty(), - "parked NotifyMSC purged when its owning client disconnects" - ); - } - - #[test] - fn deferred_present_pixmap_copies_only_after_source_readiness() { - use crate::server::{PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest}; - use yserver_protocol::x11::present::PixmapRequest; - - const WAIT_ID: u64 = 7; - const PRESENT_ID: u64 = 42; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let pending = PendingPresentPixmap { - origin: None, - client_id: ClientId(1), - request: PendingPresentRequest::Pixmap(PixmapRequest { - window: 0x101, - pixmap: 0x102, - serial: 3, - valid: 0, - update: 0, - x_off: 4, - y_off: 5, - target_crtc: 0, - wait_fence: 0, - idle_fence: 0, - options: 0, - target_msc: 0, - divisor: 0, - remainder: 0, - notifies: Vec::new(), - }), - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - masked_options: 0, - src_host_xid: 0x400102, - paint_dst_host_xid: 0x400101, - completion_dst_host_xid: 0x400101, - src_width: 800, - src_height: 600, - update_rects: None, - present_id: PRESENT_ID, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: None, - }; - state.present_wait_to_id.insert(WAIT_ID, PRESENT_ID); - state.present_pending_exec.insert( - PRESENT_ID, - PendingPresentEntry { - pending, - source_ready: false, - wait_id: Some(WAIT_ID), - pin: Some(999), - }, - ); - - drain_ready_present_pixmaps(&mut state, &mut backend); - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })) - ); - - backend.ready_present_source_waits.push(WAIT_ID); - drain_ready_present_pixmaps(&mut state, &mut backend); - assert!(backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: 0x400102, - dst_host_xid: 0x400101, - dst_x: 4, - dst_y: 5, - width: 800, - height: 600, - .. - } - ))); - // The WAIT pin (finish_present_source_wait) and the ENTRY pin - // (release_present_source) are distinct releases — both fire - // exactly once for this one parked entry. - assert_eq!(backend.finished_present_source_waits, vec![WAIT_ID]); - assert_eq!(backend.released_present_sources, vec![999]); - assert!(state.present_pending_exec.is_empty()); - assert!(state.present_wait_to_id.is_empty()); - } - - #[test] - fn destroyed_window_purges_parked_present_wait_before_producer_ready() { - // Task 8 Step 1b (extended for Task 5's unified store): a - // PresentPixmap still parked on its async source wait when its - // destination window is destroyed must be purged so it can never - // execute against a dead drawable. The idle fence is released - // by-xid (client still alive), the WAIT pin - // (`finish_present_source_wait`) and the distinct ENTRY pin - // (`release_present_source`) each drop exactly once, the side map - // row is cleaned up, and a later producer-ready drain then creates - // NO copy and NO gate. - use crate::server::{ - PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest, SyncFence, - }; - use yserver_protocol::x11::{CreateWindowRequest, present::PixmapRequest}; - - const CLIENT: u32 = 1; - const WINDOW_XID: u32 = 0x0000_0101; - const IDLE_FENCE: u32 = 0x0000_0555; - const WAIT_ID: u64 = 7; - const PRESENT_ID: u64 = 4242; - const PIN_ID: u64 = 8181; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.sync_fences.insert( - IDLE_FENCE, - SyncFence { - owner: ClientId(CLIENT), - triggered: false, - }, - ); - - let pending = PendingPresentPixmap { - origin: None, - client_id: ClientId(CLIENT), - request: PendingPresentRequest::Pixmap(PixmapRequest { - window: WINDOW_XID, - pixmap: 0x102, - serial: 3, - valid: 0, - update: 0, - x_off: 4, - y_off: 5, - target_crtc: 0, - wait_fence: 0, - idle_fence: IDLE_FENCE, - options: 0, - target_msc: 0, - divisor: 0, - remainder: 0, - notifies: Vec::new(), - }), - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: IDLE_FENCE, - }, - masked_options: 0, - src_host_xid: 0x400102, - paint_dst_host_xid: 0x400101, - completion_dst_host_xid: 0x400101, - src_width: 800, - src_height: 600, - update_rects: None, - present_id: PRESENT_ID, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: None, - }; - state.present_wait_to_id.insert(WAIT_ID, PRESENT_ID); - state.present_pending_exec.insert( - PRESENT_ID, - PendingPresentEntry { - pending, - source_ready: false, - wait_id: Some(WAIT_ID), - pin: Some(PIN_ID), - }, - ); - - destroy_window_subtree(&mut state, &mut backend, None, ResourceId(WINDOW_XID)); - - // (a) the parked entry and its side-map row are removed, - assert!( - state.present_pending_exec.is_empty(), - "parked PresentPixmap purged when its destination window is destroyed" - ); - assert!( - state.present_wait_to_id.is_empty(), - "wait_id -> present_id side map row dropped alongside the entry" - ); - // (b) its idle fence was triggered by-xid (client alive), and both - // the WAIT pin and the distinct ENTRY pin dropped exactly once, - assert_eq!( - backend.triggered_dri3_fences, - vec![IDLE_FENCE], - "idle fence released exactly once on window-destroy teardown" - ); - assert!( - state.sync_fences[&IDLE_FENCE].triggered, - "QueryFence mirror must agree with the released idle fence" - ); - assert_eq!( - backend.finished_present_source_waits, - vec![WAIT_ID], - "wait pin dropped exactly once on window-destroy teardown" - ); - assert_eq!( - backend.released_present_sources, - vec![PIN_ID], - "entry pin dropped exactly once on window-destroy teardown" - ); - - // (c) a later producer-ready drain creates no orphan copy + no gate. - let calls_before = backend.calls().len(); - backend.ready_present_source_waits.push(WAIT_ID); - drain_ready_present_pixmaps(&mut state, &mut backend); - assert!( - backend.calls()[calls_before..] - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "no copy is issued for a present whose window was destroyed" - ); - assert!( - state.present_complete_gate.is_empty(), - "no completion gate is inserted for a purged present" - ); - // The later drain reports an unknown wait_id (the entry was - // already purged) — must not double-release either pin. - assert_eq!( - backend.finished_present_source_waits, - vec![WAIT_ID, WAIT_ID], - "backend's own unknown-wait_id report is a no-op guard at the caller, \ - but finish_present_source_wait is still invoked once per drain call" - ); - assert_eq!( - backend.released_present_sources, - vec![PIN_ID], - "entry pin must not be released a second time by the later drain" - ); - } - - /// A minimal `PendingPresentEntry` for `present_pending_exec`, only - /// carrying what the Task 6 hold-back tests below need: which window - /// it targets. Everything else is inert filler. - fn stub_pending_present_entry( - window: u32, - present_id: u64, - ) -> crate::server::PendingPresentEntry { - use crate::server::{PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest}; - use yserver_protocol::x11::present::PixmapRequest; - - PendingPresentEntry { - pending: PendingPresentPixmap { - origin: None, - client_id: ClientId(1), - request: PendingPresentRequest::Pixmap(PixmapRequest { - window, - pixmap: 0x1, - serial: 1, - valid: 0, - update: 0, - x_off: 0, - y_off: 0, - target_crtc: 0, - wait_fence: 0, - idle_fence: 0, - options: 0, - target_msc: 0, - divisor: 0, - remainder: 0, - notifies: Vec::new(), - }), - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - masked_options: 0, - src_host_xid: 0x2, - // Deliberately DISTINCT from `window` (the client-visible - // XID the blocked-check keys on via `request.window()`): - // if a future edit mistakenly keyed the hold-back off a - // host-xid field instead, these tests must fail rather - // than pass by accident on identical values. - paint_dst_host_xid: window | 0x0040_0000, - completion_dst_host_xid: window | 0x0040_0000, - src_width: 1, - src_height: 1, - update_rects: None, - present_id, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: None, - }, - source_ready: false, - wait_id: None, - pin: None, - } - } - - fn due_pending_complete( - window: u32, - present_id: u64, - effective_target_msc: u64, - mode: u8, - emit_idle: bool, - ) -> crate::server::PendingPresentComplete { - use crate::backend::{CompletedPresentEvent, PresentWake}; - - crate::server::PendingPresentComplete { - event: CompletedPresentEvent { - client_id: ClientId(1), - serial: 1, - host_xid: window, - dst_host_xid: window, - options: 0, - present_id, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - completion_clock: None, - wake: PresentWake::Pixmap { idle_fence_xid: 0 }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }, - effective_target_msc, - mode, - emit_idle, - } - } - - /// Round-3 inversion vector (spec §"Ordered completion delivery - /// (per-window `present_id` order)", blocked-check state 2: - /// executed-but-undrained). P1 executed already (its GPU copy is - /// done) but its completion event has not drained yet — it still sits - /// in `present_complete_gate`. P3 (not modelled — Task 8 doesn't - /// exist on this branch yet) scrapped P2 and parked `Skip(P2)` - /// directly into `present_pending_complete`, already due. Pre-fix, - /// `fire_due_present_completions` swept the queue in raw order and - /// had no notion of the gate at all, so it would deliver the due - /// Skip(P2) immediately — a backward serial, since P1 < P2 for the - /// same window. The per-window hold-back must block Skip(P2) until - /// P1 resolves, then deliver Copy(P1) before Skip(P2). - #[test] - fn due_skip_is_held_back_behind_a_smaller_id_undrained_gate_entry() { - use crate::server::PresentCompleteGate; - use yserver_protocol::x11::present as x11present; - - const WINDOW_XID: u32 = 0x0000_0101; - const PRESENT_EID: u32 = 0x0010_0011; - const P1: u64 = 10; - const P2: u64 = 11; - const TARGET_MSC: u64 = 100; - let clock = crate::backend::PresentClockSample { - msc: TARGET_MSC, - ust: 0x1000, - source: crate::backend::PresentClockSource::PageFlip, - }; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // COMPLETE_NOTIFY_MASK only, so `complete_notify_modes` doesn't - // have to skate around IdleNotify sizes/interleaving. - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW_XID), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - let mut backend = RecordingBackend::new(); - - state.present_complete_gate.insert( - P1, - PresentCompleteGate { - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: TARGET_MSC, - owner: ClientId(1), - dst_window_xid: WINDOW_XID, - }, - ); - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - P2, - TARGET_MSC, - x11present::COMPLETE_MODE_SKIP, - false, - )); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert!( - backend.signalled_present_wakes.is_empty(), - "Skip(P2) must not deliver while P1 (smaller present_id) is \ - still undrained in present_complete_gate — pre-fix this fires" - ); - assert_eq!( - state.present_pending_complete.len(), - 1, - "Skip(P2) stays parked, held back" - ); - assert!( - read_all_available(&mut peer).is_empty(), - "no CompleteNotify reaches the client while held back" - ); - - // P1 resolves (its fence retires late): the gate empties and its - // own completion joins the queue, due, same as Skip(P2). - state.present_complete_gate.remove(&P1); - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - P1, - TARGET_MSC, - x11present::COMPLETE_MODE_COPY, - true, - )); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert!( - state.present_pending_complete.is_empty(), - "both entries deliver once P1 is no longer blocking" - ); - assert_eq!( - backend.signalled_present_wakes, - vec![P1], - "Copy(P1) signals its wake; Skip(P2)'s emit_idle=false gates \ - signal_present_wake off (fix 3 — its wake was already \ - released at scrap)" - ); - // Order proof independent of the (now Skip-gated) wake log: the - // wire itself must read Copy(P1) then Skip(P2). - assert_eq!( - complete_notify_modes(&read_all_available(&mut peer)), - vec![ - x11present::COMPLETE_MODE_COPY, - x11present::COMPLETE_MODE_SKIP - ], - "Copy(P1) delivers before Skip(P2): per-window present_id order" - ); - } - - /// Blocked-check state 1: msc-parked-unexecuted (`present_pending_exec`). - /// Entry A (smaller present_id) is still parked, unexecuted, in the - /// store for window W; Skip(B) (larger present_id) is already due in - /// the queue. B must be held back until A leaves the store, then both - /// deliver in id order. - #[test] - fn due_skip_is_held_back_behind_a_smaller_id_unexecuted_store_entry() { - use yserver_protocol::x11::present as x11present; - - const WINDOW_XID: u32 = 0x0000_0202; - const PRESENT_EID: u32 = 0x0010_0022; - const A: u64 = 20; - const B: u64 = 21; - const TARGET_MSC: u64 = 50; - let clock = crate::backend::PresentClockSample { - msc: TARGET_MSC, - ust: 0x2000, - source: crate::backend::PresentClockSource::PageFlip, - }; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW_XID), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - let mut backend = RecordingBackend::new(); - - state - .present_pending_exec - .insert(A, stub_pending_present_entry(WINDOW_XID, A)); - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - B, - TARGET_MSC, - x11present::COMPLETE_MODE_SKIP, - false, - )); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert!( - backend.signalled_present_wakes.is_empty(), - "Skip(B) held back while A (smaller present_id) is still \ - unexecuted in present_pending_exec" - ); - - // A executes and completes. - state.present_pending_exec.remove(&A); - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - A, - TARGET_MSC, - x11present::COMPLETE_MODE_COPY, - true, - )); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert_eq!( - backend.signalled_present_wakes, - vec![A], - "Copy(A) signals its wake; Skip(B)'s emit_idle=false gates it off" - ); - assert_eq!( - complete_notify_modes(&read_all_available(&mut peer)), - vec![ - x11present::COMPLETE_MODE_COPY, - x11present::COMPLETE_MODE_SKIP - ], - "both deliver in arrival (present_id) order once A clears the store" - ); - } - - /// Per-window isolation: window X's stalled completion must not delay - /// window Y's due completion in the same sweep. - #[test] - fn per_window_hold_back_does_not_cross_windows() { - use crate::server::PresentCompleteGate; - use yserver_protocol::x11::present as x11present; - - const WINDOW_X: u32 = 0x0000_0303; - const WINDOW_Y: u32 = 0x0000_0404; - const X_SMALL: u64 = 30; - const X_SKIP: u64 = 31; - const Y_ID: u64 = 32; - const TARGET_MSC: u64 = 70; - let clock = crate::backend::PresentClockSample { - msc: TARGET_MSC, - ust: 0x3000, - source: crate::backend::PresentClockSource::PageFlip, - }; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - state.present_complete_gate.insert( - X_SMALL, - PresentCompleteGate { - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: TARGET_MSC, - owner: ClientId(1), - dst_window_xid: WINDOW_X, - }, - ); - state.present_pending_complete.push(due_pending_complete( - WINDOW_X, - X_SKIP, - TARGET_MSC, - x11present::COMPLETE_MODE_SKIP, - false, - )); - state.present_pending_complete.push(due_pending_complete( - WINDOW_Y, - Y_ID, - TARGET_MSC, - x11present::COMPLETE_MODE_COPY, - true, - )); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert_eq!( - backend.signalled_present_wakes, - vec![Y_ID], - "window Y's due completion delivers even though window X is stalled" - ); - assert_eq!( - state.present_pending_complete.len(), - 1, - "window X's Skip stays held back" - ); - assert_eq!(state.present_pending_complete[0].event.present_id, X_SKIP); - } - - /// Blocked-check state 3: parked-not-yet-due, i.e. an earlier entry - /// in the very same queue group. id=5 (smaller, Copy) has a FUTURE - /// target; id=7 (larger, Skip) is due right now. Even though id=7 is - /// individually due, it must not be delivered ahead of id=5 — the - /// per-window walk has to stop (not skip past) the first blocked - /// entry it meets. Reworded as a mutation check: a `break`→`continue` - /// slip in the sweep's inner loop would let id=7 slide through on the - /// first pass while id=5 stays parked — this test's first-pass - /// assertion (nothing delivered) catches exactly that; verified by - /// hand-applying the mutation locally (see report). - #[test] - fn future_smaller_id_blocks_due_larger_id_in_same_queue_group() { - use yserver_protocol::x11::present as x11present; - - const WINDOW_XID: u32 = 0x0000_0707; - const PRESENT_EID: u32 = 0x0010_0077; - const SMALLER_FUTURE: u64 = 5; - const LARGER_DUE: u64 = 7; - const FUTURE_MSC: u64 = 1_000; - const DUE_MSC: u64 = 10; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW_XID), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - let mut backend = RecordingBackend::new(); - - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - SMALLER_FUTURE, - FUTURE_MSC, - x11present::COMPLETE_MODE_COPY, - true, - )); - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - LARGER_DUE, - DUE_MSC, - x11present::COMPLETE_MODE_SKIP, - false, - )); - - // First sweep: clock is past id=7's target but nowhere near - // id=5's. Nothing for this window may deliver. - let clock_mid = crate::backend::PresentClockSample { - msc: 50, - ust: 0x7000, - source: crate::backend::PresentClockSource::PageFlip, - }; - fire_due_present_completions(&mut state, &mut backend, clock_mid); - assert!( - backend.signalled_present_wakes.is_empty(), - "neither entry delivers: id=7 is due but held behind id=5's \ - still-future target (state 3 — parked-not-yet-due)" - ); - assert_eq!( - state.present_pending_complete.len(), - 2, - "both entries retained" - ); - assert!( - read_all_available(&mut peer).is_empty(), - "no CompleteNotify reaches the client on the blocked first sweep" - ); - - // Second sweep: clock passes both targets — both deliver, in order. - let clock_late = crate::backend::PresentClockSample { - msc: FUTURE_MSC + 1, - ust: 0x7001, - source: crate::backend::PresentClockSource::PageFlip, - }; - fire_due_present_completions(&mut state, &mut backend, clock_late); - assert!(state.present_pending_complete.is_empty()); - assert_eq!( - complete_notify_modes(&read_all_available(&mut peer)), - vec![ - x11present::COMPLETE_MODE_COPY, - x11present::COMPLETE_MODE_SKIP - ], - "Copy(5) then Skip(7), once both are due" - ); - } - - /// A parked Skip (supersession scrap) must emit no second IdleNotify - /// and touch no fence mirror at delivery — both were already handled - /// at scrap time (spec §"Ordered completion delivery" item 1). Only - /// the CompleteNotify goes out, with mode byte `COMPLETE_MODE_SKIP`. - #[test] - fn parked_skip_delivery_emits_only_complete_notify_mode_skip() { - use crate::{backend::CompletedPresentEvent, server::SyncFence}; - use yserver_protocol::x11::present as x11present; - - const WINDOW_XID: u32 = 0x0000_0505; - const PRESENT_EID: u32 = 0x0010_0099; - const IDLE_FENCE: u32 = 0x0000_0777; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW_XID), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY - | x11present::EVENT_MASK_IDLE_NOTIFY, - }, - ); - // A live fence the scrap path already triggered; delivery must - // not touch it (it's already `true`, but the *write* itself must - // not happen — a real regression would re-trigger a fence a - // client has since reused for a fresh present, per the spec). - state.sync_fences.insert( - IDLE_FENCE, - SyncFence { - owner: ClientId(1), - triggered: true, - }, - ); - let _ = read_all_available(&mut peer); - - let mut backend = RecordingBackend::new(); - let event = CompletedPresentEvent { - client_id: ClientId(1), - serial: 5, - host_xid: WINDOW_XID, - dst_host_xid: WINDOW_XID, - options: 0, - present_id: 99, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - completion_clock: None, - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: IDLE_FENCE, - }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }; - let clock = crate::backend::PresentClockSample { - msc: 42, - ust: 0x9999, - source: crate::backend::PresentClockSource::PageFlip, - }; - complete_present_with_clock( - &mut state, - &mut backend, - &event, - clock, - x11present::COMPLETE_MODE_SKIP, - false, - ); - - let bytes = read_all_available(&mut peer); - assert_eq!( - bytes.len(), - 40, - "exactly one event (CompleteNotify only, no IdleNotify): got {} bytes", - bytes.len() - ); - assert_eq!(bytes[0], 35, "GenericEvent"); - assert_eq!(bytes[1], 145, "PRESENT major opcode"); - assert_eq!( - u16::from_le_bytes(bytes[8..10].try_into().unwrap()), - u16::from(x11present::EVENT_COMPLETE_NOTIFY), - ); - assert_eq!(bytes[11], x11present::COMPLETE_MODE_SKIP); - assert!( - state.sync_fences[&IDLE_FENCE].triggered, - "fence mirror must still read triggered=true (scrap set it) — \ - this only proves delivery didn't touch it; a fresh false->false \ - would look identical, so this test also relies on \ - `complete_present_with_clock`'s emit_idle=false code path \ - skipping the write entirely (see source)" - ); - } - - #[test] - fn direct_flip_completion_and_buffer_idle_are_separate_retirements() { - use crate::{backend::CompletedPresentEvent, server::SyncFence}; - use yserver_protocol::x11::present as x11present; - - const WINDOW_XID: u32 = 0x0000_0606; - const PIXMAP_XID: u32 = 0x0000_0607; - const PRESENT_EID: u32 = 0x0010_00aa; - const IDLE_FENCE: u32 = 0x0000_0888; - const PRESENT_ID: u64 = 123; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW_XID), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY - | x11present::EVENT_MASK_IDLE_NOTIFY, - }, - ); - state.sync_fences.insert( - IDLE_FENCE, - SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - let _ = read_all_available(&mut peer); - - let event = CompletedPresentEvent { - client_id: ClientId(1), - serial: 7, - host_xid: PIXMAP_XID, - dst_host_xid: WINDOW_XID, - options: 0, - present_id: PRESENT_ID, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - completion_clock: None, - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: IDLE_FENCE, - }, - completion_mode: x11present::COMPLETE_MODE_FLIP, - emit_idle: false, - }; - let clock = crate::backend::PresentClockSample { - msc: 55, - ust: 66, - source: crate::backend::PresentClockSource::PageFlip, - }; - let mut backend = RecordingBackend::new(); - - complete_present_with_clock( - &mut state, - &mut backend, - &event, - clock, - event.completion_mode, - event.emit_idle, - ); - let complete = read_all_available(&mut peer); - assert_eq!(complete.len(), 40, "flip retirement emits one event"); - assert_eq!( - u16::from_le_bytes(complete[8..10].try_into().unwrap()), - u16::from(x11present::EVENT_COMPLETE_NOTIFY) - ); - assert_eq!(complete[11], x11present::COMPLETE_MODE_FLIP); - assert!(!state.sync_fences[&IDLE_FENCE].triggered); - assert!(backend.signalled_present_wakes.is_empty()); - - retire_present_idle(&mut state, &mut backend, &event); - let idle = read_all_available(&mut peer); - assert_eq!(idle.len(), 32, "replacement retirement emits one event"); - assert_eq!( - u16::from_le_bytes(idle[8..10].try_into().unwrap()), - u16::from(x11present::EVENT_IDLE_NOTIFY) - ); - assert!(state.sync_fences[&IDLE_FENCE].triggered); - assert_eq!(backend.signalled_present_wakes, vec![PRESENT_ID]); - } - - #[test] - fn free_pixmap_between_park_and_drain_still_executes_the_pinned_copy() { - // Task 5 TDD (iii): `FreePixmap` on the *source* pixmap is legal - // immediately after `PresentPixmap` — Xorg refs the vblank's - // pixmap for exactly this reason. The entry pin exists so a copy - // still parked on its producer-fence wait at that point keeps - // targeting the pinned drawable rather than a dead xid. Drive the - // real Deferred arm through `process_request` (not a manually - // constructed entry) so the pin comes from the production code - // path, `FreePixmap` the source in between, then verify the drain - // still issues the copy and releases the entry pin exactly once. - use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; - - const CLIENT: u32 = 21; - const WINDOW_XID: u32 = 0x00e0_2103; - const PIXMAP_XID: u32 = 0x00e0_2104; - const WINDOW_HOST_XID: u32 = 0x0040_2103; - const PIXMAP_HOST_XID: u32 = 0x0040_2104; - const WAIT_ID: u64 = 33; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - backend.present_source_wait = crate::backend::PresentSourceWait::Deferred(WAIT_ID); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST_XID); - } - state.resources.create_pixmap( - ClientId(CLIENT), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(PIXMAP_HOST_XID).expect("valid host pixmap"), - ); - - // PresentPixmap (opcode 1) fixed prefix, mirroring the 68-byte - // body other tests in this module build: window pixmap serial - // valid update x_off y_off ... (only window/pixmap set here — a - // full-pixmap copy, no update region). - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert_eq!( - state.present_pending_exec.len(), - 1, - "the source wait parks exactly one entry" - ); - let pin = state - .present_pending_exec - .values() - .next() - .unwrap() - .pin - .expect("Deferred arm takes an entry pin"); - - // FreePixmap the source in between park and drain. - handle_free_pixmap( - &mut state, - &mut backend, - None, - ClientId(CLIENT), - SequenceNumber(2), - &free_pixmap_body(PIXMAP_XID), - ) - .expect("free pixmap"); - assert!( - backend - .calls() - .iter() - .any(|call| matches!(call, RecordedCall::FreePixmap(PIXMAP_HOST_XID))), - "FreePixmap on the source must still free the host pixmap" - ); - - let calls_before = backend.calls().len(); - backend.ready_present_source_waits.push(WAIT_ID); - drain_ready_present_pixmaps(&mut state, &mut backend); - - assert!( - backend.calls()[calls_before..].iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - dst_host_xid: WINDOW_HOST_XID, - .. - } - )), - "the drain still executes the copy against the pinned source xid, \ - not a dropped/dead one" - ); - assert_eq!( - backend.released_present_sources, - vec![pin], - "the entry pin is released exactly once, at execution" - ); - assert!(state.present_pending_exec.is_empty()); - assert!(state.present_wait_to_id.is_empty()); - } - - // ──────────────────────────────────────────────────────────────── - // Task 7 Step 4: msc-due classification + deferral. - // ──────────────────────────────────────────────────────────────── - - /// (i) A future-target present must not copy or damage anything until - /// it becomes due. Drives `drain_due_present_pending_exec` directly - /// against a manually parked (source-ready) entry — the due-pass is - /// the sole place a still-parked future-target entry can execute. - #[test] - fn future_target_present_produces_no_copy_until_due() { - const PRESENT_ID: u64 = 500; - const WINDOW_HOST_XID: u32 = 0x0040_0601; - const PIXMAP_HOST_XID: u32 = 0x0040_0602; - const EFF: u64 = 105; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); // clock=100, eff(105) > 101: future. - seed_present_clock(&mut state, 100, 0x1000); - // Isolate the plain clock-driven due rule from the idle-display - // fallback (RecordingBackend defaults `present_display_idle` to - // `true`, matching "no backend ever composes" — which would - // otherwise execute this future-target entry immediately via - // that separate fallback rung, not the one this test pins). - backend.present_display_idle = false; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(EFF), - true, // source_ready - ), - ); - - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "no copy while the target is still in the future" - ); - assert_eq!( - state.present_pending_exec.len(), - 1, - "the entry stays parked" - ); - - // Clock catches up to the target: now due. - backend.present_ust_msc = (EFF, 0x2000); - seed_present_clock(&mut state, EFF, 0x2000); - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - dst_host_xid: WINDOW_HOST_XID, - .. - } - )), - "the copy executes once the clock reaches the target" - ); - assert!(state.present_pending_exec.is_empty()); - } - - /// Review fix (test addition b): the due-pass must RE-PARK an - /// immediate-target entry when `flip_in_flight` is STILL true at - /// drain time — the previously-covered vector only pinned the park - /// decision at ARRIVAL, not the due-pass's own re-evaluation using a - /// freshly sampled `flip_in_flight`. - #[test] - fn due_pass_reparks_immediate_target_when_flip_still_in_flight() { - const PRESENT_ID: u64 = 509; - const WINDOW_HOST_XID: u32 = 0x0040_0f01; - const PIXMAP_HOST_XID: u32 = 0x0040_0f02; - const CLOCK: u64 = 300; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (CLOCK, 0x1000); - backend.present_flip_in_flight = true; // still in flight at drain time. - // Isolate the plain due-pass decision from the fallback rungs. - backend.present_display_idle = false; - backend.present_absolute_vblank_arm_supported = false; - backend.present_scanout_blackout = false; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(CLOCK + 1), // immediate target. - true, - ), - ); - - drain_due_present_pending_exec(&mut state, &mut backend); - - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "an immediate target must stay parked while a flip is still in \ - flight at the due-pass's own re-evaluation, not just at arrival" - ); - assert_eq!(state.present_pending_exec.len(), 1, "entry stays parked"); - } - - /// Builds a minimal `PendingPresentEntry` for the msc-due tests below — - /// deliberately distinct host xids for source/dest (window_host_xid | - /// 0 stays the "destination", pixmap_host_xid the "source") so a - /// `CopyArea` assertion can't pass by coincidence. - fn present_pending_entry_with( - present_id: u64, - window_host_xid: u32, - pixmap_host_xid: u32, - effective_target_msc: Option, - source_ready: bool, - ) -> crate::server::PendingPresentEntry { - use crate::server::{PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest}; - use yserver_protocol::x11::present::PixmapRequest; - - PendingPresentEntry { - pending: PendingPresentPixmap { - origin: None, - client_id: ClientId(1), - request: PendingPresentRequest::Pixmap(PixmapRequest { - window: window_host_xid, - pixmap: pixmap_host_xid, - serial: 1, - valid: 0, - update: 0, - x_off: 0, - y_off: 0, - target_crtc: 0, - wait_fence: 0, - idle_fence: 0, - options: 0, - target_msc: 0, - divisor: 0, - remainder: 0, - notifies: Vec::new(), - }), - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - masked_options: 0, - src_host_xid: pixmap_host_xid, - paint_dst_host_xid: window_host_xid, - completion_dst_host_xid: window_host_xid, - src_width: 4, - src_height: 4, - update_rects: None, - present_id, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc, - }, - source_ready, - wait_id: None, - pin: Some(present_id), // distinct-ish pin id for release assertions - } - } - - /// (ii) Immediate-target arrival: executes with no flip in flight, - /// parks with one — driven end-to-end through `process_request` so - /// the arrival evaluation (not just the pure classifier) is pinned. - #[test] - fn immediate_target_present_executes_at_arrival_without_flip_in_flight() { - const CLIENT: u32 = 30; - const WINDOW_XID: u32 = 0x00e0_3001; - const PIXMAP_XID: u32 = 0x00e0_3002; - const WINDOW_HOST_XID: u32 = 0x0040_3001; - const PIXMAP_HOST_XID: u32 = 0x0040_3002; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (10, 0x1000); // eff will land at clock+1 = 11. - backend.present_flip_in_flight = false; - - setup_present_pixmap_source_and_dest( - &mut state, - CLIENT, - WINDOW_XID, - PIXMAP_XID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - dst_host_xid: WINDOW_HOST_XID, - .. - } - )), - "immediate target with no flip in flight executes at arrival" - ); - assert!(state.present_pending_exec.is_empty()); - } - - #[test] - fn immediate_target_present_parks_at_arrival_with_flip_in_flight() { - const CLIENT: u32 = 31; - const WINDOW_XID: u32 = 0x00e0_3101; - const PIXMAP_XID: u32 = 0x00e0_3102; - const WINDOW_HOST_XID: u32 = 0x0040_3101; - const PIXMAP_HOST_XID: u32 = 0x0040_3102; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (10, 0x1000); - backend.present_flip_in_flight = true; - - setup_present_pixmap_source_and_dest( - &mut state, - CLIENT, - WINDOW_XID, - PIXMAP_XID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "immediate target with a flip in flight must not copy at arrival" - ); - assert_eq!( - state.present_pending_exec.len(), - 1, - "the present parks instead" - ); - assert!( - state - .present_pending_exec - .values() - .next() - .unwrap() - .source_ready, - "parked-for-msc entries are source_ready (only the clock is blocking)" - ); - } - - #[test] - fn clocked_async_present_executes_during_in_flight_flip() { - const CLIENT: u32 = 32; - const WINDOW_XID: u32 = 0x00e0_3201; - const PIXMAP_XID: u32 = 0x00e0_3202; - const WINDOW_HOST_XID: u32 = 0x0040_3201; - const PIXMAP_HOST_XID: u32 = 0x0040_3202; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (10, 0x1000); - backend.present_flip_in_flight = true; - - setup_present_pixmap_source_and_dest( - &mut state, - CLIENT, - WINDOW_XID, - PIXMAP_XID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - body[36..40].copy_from_slice(&crate::present_scheduler::PRESENT_OPTION_ASYNC.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - dst_host_xid: WINDOW_HOST_XID, - .. - } - )), - "a clocked immediate async Present must reach the backend successor path instead of parking behind the current flip", - ); - assert!( - state.present_pending_exec.is_empty(), - "the core scheduler must not retain the async successor until vblank", - ); - assert_eq!( - state - .present_complete_gate - .values() - .next() - .map(|gate| gate.effective_target_msc), - Some(10), - "the Xorg current-MSC identity must survive through backend completion gating", - ); - } - - /// Shared window+pixmap setup for the arrival-evaluation tests above. - fn setup_present_pixmap_source_and_dest( - state: &mut ServerState, - client: u32, - window_xid: u32, - pixmap_xid: u32, - window_host_xid: u32, - pixmap_host_xid: u32, - ) { - use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; - - state.resources.create_window( - ClientId(client), - CreateWindowRequest { - depth: 24, - window: ResourceId(window_xid), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(window_xid)); - if let Some(w) = state.resources.window_mut(ResourceId(window_xid)) { - w.host_xid = crate::backend::WindowHandle::from_raw(window_host_xid); - } - state.resources.create_pixmap( - ClientId(client), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(pixmap_xid), - drawable: ResourceId(window_xid), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(pixmap_xid), - crate::backend::PixmapHandle::from_raw(pixmap_host_xid).expect("valid host pixmap"), - ); - } - - /// (iii) A parked immediate-target entry executes on the flip- - /// retirement wakeup, and its `mark_dirty` precedes `maybe_composite` - /// in the SAME `run_iteration_tail` call — reusing Task 4's call-order - /// instrumentation, now exercised via the msc-due path (source_ready, - /// no wait_id) rather than the source-wait path. - #[test] - fn parked_immediate_target_executes_and_marks_dirty_before_compose_in_same_tail() { - use crate::backend::recording::RecordedCall; - - const PRESENT_ID: u64 = 0x9001; - const WINDOW_HOST_XID: u32 = 0x0040_9001; - const PIXMAP_HOST_XID: u32 = 0x0040_9002; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - // The entry parked earlier because a flip was in flight; that - // flip has now retired (this iteration's fresh sample) and the - // clock has caught up so the target is due. - backend.present_ust_msc = (200, 0x3000); - backend.present_flip_in_flight = false; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(200), // eff <= clock: due now. - true, - ), - ); - - crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); - - let calls = backend.calls(); - let mark_dirty_idx = calls - .iter() - .position(|c| matches!(c, RecordedCall::MarkDirty)) - .expect("due entry executed and marked dirty"); - let composite_idx = calls - .iter() - .position(|c| matches!(c, RecordedCall::MaybeComposite)) - .expect("maybe_composite invoked"); - assert!( - mark_dirty_idx < composite_idx, - "due-pass mark_dirty ({mark_dirty_idx}) must precede maybe_composite ({composite_idx})" - ); - assert!(state.present_pending_exec.is_empty()); - } - - /// (iv) Idle-display fallback: only on `!present_absolute_vblank_arm_supported()` - /// backends, and only when `present_display_idle()` is true, does a - /// still-parked source-ready entry execute early. - #[test] - fn idle_display_fallback_executes_parked_entry_when_display_idle() { - const PRESENT_ID: u64 = 501; - const WINDOW_HOST_XID: u32 = 0x0040_0701; - const PIXMAP_HOST_XID: u32 = 0x0040_0702; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); - backend.present_absolute_vblank_arm_supported = false; - backend.present_display_idle = true; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(200), // far future — never due by clock alone here. - true, - ), - ); - - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - .. - } - )), - "an idle display with no absolute-arm support must execute the parked entry" - ); - assert!(state.present_pending_exec.is_empty()); - } - - #[test] - fn idle_display_fallback_does_not_fire_when_display_not_idle() { - const PRESENT_ID: u64 = 502; - const WINDOW_HOST_XID: u32 = 0x0040_0801; - const PIXMAP_HOST_XID: u32 = 0x0040_0802; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); - backend.present_absolute_vblank_arm_supported = false; - backend.present_display_idle = false; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(200), - true, - ), - ); - - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "not-idle display must not trigger the idle fallback" - ); - assert_eq!(state.present_pending_exec.len(), 1, "entry stays parked"); - } - - #[test] - fn idle_display_fallback_does_not_apply_when_arm_supported() { - // Spec §msc-due: the idle-display fallback applies ONLY on - // `!present_absolute_vblank_arm_supported()` drivers — even with - // `present_display_idle() == true`, an arm-capable driver must not - // take this shortcut (it would reintroduce the early-frame bug - // for mpv on sequence-capable drivers). - const PRESENT_ID: u64 = 503; - const WINDOW_HOST_XID: u32 = 0x0040_0901; - const PIXMAP_HOST_XID: u32 = 0x0040_0902; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); - backend.present_absolute_vblank_arm_supported = true; - backend.present_display_idle = true; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(200), - true, - ), - ); - - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "arm-supported backends never take the idle-display shortcut" - ); - assert_eq!(state.present_pending_exec.len(), 1); - } - - /// (v) Blackout: parked entries execute AND queued completions deliver - /// with the frozen clock, independent of clock advance. - #[test] - fn blackout_flushes_parked_entries_and_queued_completions() { - use yserver_protocol::x11::present as x11present; - - const PRESENT_ID: u64 = 504; - const WINDOW_HOST_XID: u32 = 0x0040_0a01; - const PIXMAP_HOST_XID: u32 = 0x0040_0a02; - const QUEUED_ID: u64 = 900; - const WINDOW_XID: u32 = 0x0000_0a03; // dst_host_xid key for the queued completion - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); // frozen: never advances during blackout. - backend.present_scanout_blackout = true; - backend.present_absolute_vblank_arm_supported = false; - backend.present_display_idle = false; // prove blackout fires independent of idle. - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(5_000), // far future — would never be due by clock or idle alone. - true, - ), - ); - // A queued completion whose target is also far in the future — - // must still flush, stamped with the frozen clock. - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - QUEUED_ID, - 5_000, - x11present::COMPLETE_MODE_COPY, - true, - )); - - drain_due_present_pending_exec(&mut state, &mut backend); - - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - .. - } - )), - "blackout must force-execute the parked msc-due entry" - ); - assert!(state.present_pending_exec.is_empty()); - assert!( - state.present_pending_complete.is_empty(), - "the queued completion must flush too, not just the parked entry" - ); - assert_eq!( - backend.signalled_present_wakes, - vec![QUEUED_ID], - "the queued completion delivers despite its target being far in the future" - ); - } - - /// Review fix (blocker): blackout must flush queued completions even - /// when `present_pending_exec` is completely EMPTY — the DPMS-off - /// case where flips keep retiring normally (so every arrival - /// classifies `ExecuteNow` and the store never accumulates an entry) - /// but `present_pending_complete` still carries an entry gated - /// against a frozen completion clock. Pre-fix, `drain_due_present_pending_exec`'s - /// leading `present_pending_exec.is_empty()` check returned before - /// ever reaching the blackout branch (the sole caller of - /// `fire_all_present_completions_now`), so this entry would park - /// forever. - #[test] - fn blackout_flushes_queued_completions_even_with_empty_exec_store() { - use yserver_protocol::x11::present as x11present; - - const QUEUED_ID: u64 = 901; - const WINDOW_XID: u32 = 0x0000_0a04; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); - backend.present_scanout_blackout = true; - - assert!( - state.present_pending_exec.is_empty(), - "precondition: the msc-due store is empty — this is the DPMS-off \ - case where flips keep retiring so nothing ever msc-parks" - ); - state.present_pending_complete.push(due_pending_complete( - WINDOW_XID, - QUEUED_ID, - 5_000, // far future — would never be due by clock alone. - x11present::COMPLETE_MODE_COPY, - true, - )); - - drain_due_present_pending_exec(&mut state, &mut backend); - - assert!( - state.present_pending_complete.is_empty(), - "the queued completion must flush during blackout even with an \ - empty present_pending_exec store" - ); - assert_eq!(backend.signalled_present_wakes, vec![QUEUED_ID]); - } - - /// Review fix: pin the residual blackout hold-back case documented on - /// `fire_all_present_completions_now` — `drain_due_present_pending_exec`'s - /// blackout branch force-executes only `source_ready` entries, so a - /// `source_ready:false` entry (still waiting on its own producer - /// fence — e.g. an uncovered sliver the successor gate declined to - /// scrap) keeps its window's parked completions held back through - /// the flush, even with blackout on. Once the producer fence signals - /// (`source_ready` flips true), the next due-pass + flush drains - /// both. - #[test] - fn blackout_holds_back_completions_behind_a_not_source_ready_entry_until_it_resolves() { - use yserver_protocol::x11::present as x11present; - - const WINDOW_HOST_XID: u32 = 0x0040_0a05; - const PIXMAP_HOST_XID: u32 = 0x0040_0a06; - const BLOCKER_ID: u64 = 1; - const QUEUED_ID: u64 = 2; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); - backend.present_scanout_blackout = true; - - // `effective_target_msc: None` for the no-clock blocker so its own - // execution delivers inline with no `present_complete_gate` row - // (the no-target arm at `execute_present_pixmap_copy`'s - // gate insert — `if let Some(eff) = ... `) — otherwise resolving - // it would additionally require draining the gate (a distinct, - // already-covered mechanism), which would muddy this test's - // narrow point: every execution filter here (`due`, idle - // fallback, blackout) is gated on `source_ready` alone, so this - // entry is blocked purely by that flag regardless of clock/eff. - state.present_pending_exec.insert( - BLOCKER_ID, - present_pending_entry_with( - BLOCKER_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - None, - false, // still waiting on its own producer fence - ), - ); - state.present_pending_complete.push(due_pending_complete( - WINDOW_HOST_XID, - QUEUED_ID, - 5_000, // far future — only "due" via the blackout force. - x11present::COMPLETE_MODE_COPY, - true, - )); - - drain_due_present_pending_exec(&mut state, &mut backend); - - assert_eq!( - state.present_pending_exec.len(), - 1, - "blackout must NOT force-execute a source_ready:false entry" - ); - assert_eq!( - state.present_pending_complete.len(), - 1, - "the due completion for the same window must stay held back behind \ - the unresolved blocker, even during blackout" - ); - assert!(backend.signalled_present_wakes.is_empty()); - - // The blocker's own producer fence signals. - state - .present_pending_exec - .get_mut(&BLOCKER_ID) - .unwrap() - .source_ready = true; - - drain_due_present_pending_exec(&mut state, &mut backend); - - assert!( - state.present_pending_exec.is_empty(), - "the next blackout pass must force-execute the now-source_ready blocker" - ); - assert!( - state.present_pending_complete.is_empty(), - "and the queue drains: the held-back completion delivers in the same pass" - ); - assert_eq!(backend.signalled_present_wakes, vec![QUEUED_ID]); - } - - /// (vi) Arm failure / `Ok(0)`: entries execute immediately in the - /// same pass (the third arming call site, `run::arm_present_idle_vblanks`). - #[test] - fn absolute_arm_ok_zero_executes_parked_entries_immediately() { - const PRESENT_ID: u64 = 505; - const WINDOW_HOST_XID: u32 = 0x0040_0b01; - const PIXMAP_HOST_XID: u32 = 0x0040_0b02; - const CLOCK: u64 = 100; - const EFF: u64 = 110; // future: eff - 1 = 109 is what should be armed. - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (CLOCK, 0x1000); - seed_present_clock(&mut state, CLOCK, 0x1000); - backend.present_absolute_vblank_arm_supported = true; - backend.arm_present_absolute_vblank_result = Some(Ok(0)); - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(EFF), - true, - ), - ); - - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - - assert_eq!( - backend.armed_absolute_vblank_targets, - vec![vec![EFF - 1]], - "the arm is called with eff - 1 (the -1 is core-side)" - ); - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - .. - } - )), - "Ok(0) (nothing covered) must execute the entry immediately" - ); - assert!(state.present_pending_exec.is_empty()); - } - - #[test] - fn absolute_arm_err_executes_parked_entries_immediately() { - const PRESENT_ID: u64 = 506; - const WINDOW_HOST_XID: u32 = 0x0040_0c01; - const PIXMAP_HOST_XID: u32 = 0x0040_0c02; - const CLOCK: u64 = 100; - const EFF: u64 = 110; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (CLOCK, 0x1000); - seed_present_clock(&mut state, CLOCK, 0x1000); - backend.present_absolute_vblank_arm_supported = true; - backend.arm_present_absolute_vblank_result = Some(Err(std::io::ErrorKind::Other)); - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(EFF), - true, - ), - ); - - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - .. - } - )), - "Err must execute the entry immediately, same as Ok(0)" - ); - assert!(state.present_pending_exec.is_empty()); - } - - #[test] - fn absolute_arm_success_leaves_entry_parked() { - const PRESENT_ID: u64 = 507; - const WINDOW_HOST_XID: u32 = 0x0040_0d01; - const PIXMAP_HOST_XID: u32 = 0x0040_0d02; - const CLOCK: u64 = 100; - const EFF: u64 = 110; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (CLOCK, 0x1000); - seed_present_clock(&mut state, CLOCK, 0x1000); - backend.present_absolute_vblank_arm_supported = true; - // Default (None) result mimics a real always-succeeds arm. - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(EFF), - true, - ), - ); - - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "a successful arm must not execute — the entry stays parked, awaiting the arm's event" - ); - assert_eq!(state.present_pending_exec.len(), 1); - } - - /// Review fix (minor): the arm target is `eff.wrapping_sub(1)`, not a - /// plain `eff - 1` — with a wrapped clock, `eff` can legitimately be - /// `0` (the vblank right after `u64::MAX`), and a plain subtraction - /// would debug-panic. Picks a clock/eff pair where `eff == 0` is - /// genuinely future-target (`msc_is_after(0, clock_msc + 1)` wraps - /// true) and asserts the arm receives `u64::MAX`, not a panic. - #[test] - fn absolute_arm_target_wraps_instead_of_panicking() { - const PRESENT_ID: u64 = 508; - const WINDOW_HOST_XID: u32 = 0x0040_0e01; - const PIXMAP_HOST_XID: u32 = 0x0040_0e02; - // clock_msc + 1 = u64::MAX - 1; eff = 0 is strictly after that in - // wrapped MSC order (msc_is_after(0, u64::MAX - 1) is true), so it - // classifies as a genuine future target whose arm target - // (eff - 1, wrapped) is u64::MAX. - const CLOCK: u64 = u64::MAX - 2; - const EFF: u64 = 0; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (CLOCK, 0x1000); - seed_present_clock(&mut state, CLOCK, 0x1000); - backend.present_absolute_vblank_arm_supported = true; - - state.present_pending_exec.insert( - PRESENT_ID, - present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(EFF), - true, - ), - ); - - crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); - - assert_eq!( - backend.armed_absolute_vblank_targets, - vec![vec![u64::MAX]], - "eff=0 wraps to u64::MAX when subtracting 1, not a panic" - ); - assert_eq!( - state.present_pending_exec.len(), - 1, - "the (default, always-covers) arm succeeds, so the entry stays parked" - ); - } - - /// (vii) One-clock contract / no-reclassification: a present arriving - /// when the GENERAL clock is ahead of the (deliberately stale) - /// completion clock must classify against the general clock alone — - /// eff == general + 1 reads as immediate-target, never future. - #[test] - fn arrival_classifies_against_general_clock_not_completion_clock() { - const CLIENT: u32 = 32; - const WINDOW_XID: u32 = 0x00e0_3201; - const PIXMAP_XID: u32 = 0x00e0_3202; - const WINDOW_HOST_XID: u32 = 0x0040_3201; - const PIXMAP_HOST_XID: u32 = 0x0040_3202; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - // General clock (used for eff + msc-due) is well ahead of the - // completion clock (used only for stamping/gate release — - // untouched by this path). If the arrival evaluation mistakenly - // read the completion clock, eff (general_clock + 1 = 101) would - // be far past completion_clock + 1 (11) and misclassify as - // future-target, parking instead of executing. - backend.present_ust_msc = (100, 0x1000); - backend.present_completion_clock = Some(crate::backend::PresentClockSample { - msc: 10, - ust: 0x0010, - source: crate::backend::PresentClockSource::PageFlip, - }); - backend.present_flip_in_flight = false; - - setup_present_pixmap_source_and_dest( - &mut state, - CLIENT, - WINDOW_XID, - PIXMAP_XID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - .. - } - )), - "eff == general_clock + 1 must classify as immediate-target (execute at arrival), \ - not future-target — a completion-clock-driven misclassification would park instead" - ); - assert!(state.present_pending_exec.is_empty()); - } - - /// (viii) Combined source-wait + msc-due: the source wait signals - /// (source_ready becomes true) but msc-due says Park — the entry - /// stays parked with no copy; only once the clock catches up does the - /// due-pass execute it. - #[test] - fn source_wait_resolution_reclassifies_and_stays_parked_until_due() { - const WAIT_ID: u64 = 44; - const PRESENT_ID: u64 = 600; - const WINDOW_HOST_XID: u32 = 0x0040_0e01; - const PIXMAP_HOST_XID: u32 = 0x0040_0e02; - const EFF: u64 = 205; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (100, 0x1000); // eff(205) is far future at wait-resolution time. - - let mut entry = present_pending_entry_with( - PRESENT_ID, - WINDOW_HOST_XID, - PIXMAP_HOST_XID, - Some(EFF), - false, - ); - entry.wait_id = Some(WAIT_ID); - state.present_wait_to_id.insert(WAIT_ID, PRESENT_ID); - state.present_pending_exec.insert(PRESENT_ID, entry); - - backend.ready_present_source_waits.push(WAIT_ID); - drain_ready_present_pixmaps(&mut state, &mut backend); - - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "source signalled but msc-due says Park: no copy yet" - ); - assert_eq!( - state.present_pending_exec.len(), - 1, - "the entry stays parked, now purely on msc-due" - ); - let reclassified = state.present_pending_exec.get(&PRESENT_ID).unwrap(); - assert!( - reclassified.source_ready, - "wait resolution still marks source_ready = true" - ); - assert!( - reclassified.wait_id.is_none(), - "the wait_id clears — this entry no longer waits on the source" - ); - assert_eq!( - backend.finished_present_source_waits, - vec![WAIT_ID], - "the WAIT pin still drops at wait resolution regardless of the msc-due outcome" - ); - assert!( - backend.released_present_sources.is_empty(), - "the ENTRY pin must NOT be released yet — the entry is still parked" - ); - - // Clock catches up: the due-pass executes it. - backend.present_ust_msc = (EFF, 0x2000); - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_host_xid: PIXMAP_HOST_XID, - .. - } - )), - "once due, the due-pass executes the copy" - ); - assert!(state.present_pending_exec.is_empty()); - } - - #[test] - fn present_pixmap_update_region_emits_damage_on_destination_window() { - use crate::server::DamageObject; - use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, xfixes::RegionRect}; - - const CLIENT: u32 = 14; - const WINDOW_XID: u32 = 0x00e0_0103; - const PIXMAP_XID: u32 = 0x00e0_0104; - const DAMAGE_XID: u32 = 0x00e0_0105; - const UPDATE_REGION_XID: u32 = 0x00e0_0106; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0x400103); - } - - state.resources.create_pixmap( - ClientId(CLIENT), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(0x400104).expect("valid host pixmap"), - ); - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(CLIENT), - drawable: ResourceId(WINDOW_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - state.xfixes_regions.insert( - UPDATE_REGION_XID, - crate::server::XFixesRegion { - owner: ClientId(CLIENT), - rects: vec![ - RegionRect { - x: 100, - y: 120, - width: 80, - height: 40, - }, - RegionRect { - x: 220, - y: 260, - width: 25, - height: 35, - }, - ], - }, - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - body[16..20].copy_from_slice(&UPDATE_REGION_XID.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - let damage = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object"); - assert_eq!( - damage.rects, state.xfixes_regions[&UPDATE_REGION_XID].rects, - "PresentPixmap must feed its update region into DAMAGE on the destination window", - ); - } - - #[test] - fn present_pixmap_synced_update_region_emits_damage_on_destination_window() { - // Regression: the explicit-sync (v1.4) PixmapSynced path copied - // the client pixmap into the window but never reported X11 damage, - // unlike the v1.0 Pixmap path. Under an external compositor - // (fastcompmgr) the missing DamageNotify meant the window never - // recomposited — vkcube froze until a drag forced a repaint. - use crate::server::DamageObject; - use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, xfixes::RegionRect}; - - const CLIENT: u32 = 17; - const WINDOW_XID: u32 = 0x00e0_0403; - const PIXMAP_XID: u32 = 0x00e0_0404; - const DAMAGE_XID: u32 = 0x00e0_0405; - const UPDATE_REGION_XID: u32 = 0x00e0_0406; - const ACQUIRE_SYNCOBJ: u32 = 0x00e0_0407; - const ACQUIRE_VALUE: u64 = 42; - const RELEASE_SYNCOBJ: u32 = 0x00e0_0408; - const RELEASE_VALUE: u64 = 43; - const WAIT_ID: u64 = 77; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - backend.present_syncobj_wait = crate::backend::PresentSourceWait::Deferred(WAIT_ID); - // Task 3: PresentPixmapSynced now validates both syncobjs per - // presentproto 1.4 — an unregistered xid (or a None release syncobj) - // is a Value error before any arm. Register both as imported so this - // test exercises the copy/damage path, not the new rejection. - backend.seed_dri3_syncobj_for_test(ACQUIRE_SYNCOBJ, ClientId(CLIENT)); - let original_release = - backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(CLIENT)); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0x400403); - } - - state.resources.create_pixmap( - ClientId(CLIENT), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(0x400404).expect("valid host pixmap"), - ); - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(CLIENT), - drawable: ResourceId(WINDOW_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - state.xfixes_regions.insert( - UPDATE_REGION_XID, - crate::server::XFixesRegion { - owner: ClientId(CLIENT), - rects: vec![ - RegionRect { - x: 100, - y: 120, - width: 80, - height: 40, - }, - RegionRect { - x: 220, - y: 260, - width: 25, - height: 35, - }, - ], - }, - ); - - // PixmapSynced (opcode 5) fixed prefix = 84 bytes: - // window(4) pixmap(4) serial(4) valid(4) update(4) x_off(2) - // y_off(2) target_crtc(4) acquire_syncobj(4) release_syncobj(4) - // acquire_point(8) release_point(8) options(4) pad(4) - // target_msc(8) divisor(8) remainder(8). - let mut body = vec![0u8; 84]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - body[16..20].copy_from_slice(&UPDATE_REGION_XID.to_le_bytes()); - body[28..32].copy_from_slice(&ACQUIRE_SYNCOBJ.to_le_bytes()); - body[32..36].copy_from_slice(&RELEASE_SYNCOBJ.to_le_bytes()); - body[36..44].copy_from_slice(&ACQUIRE_VALUE.to_le_bytes()); - body[44..52].copy_from_slice(&RELEASE_VALUE.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP_SYNCED, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert_eq!( - backend.armed_present_syncobj_waits, - vec![(0x400404, ACQUIRE_SYNCOBJ, ACQUIRE_VALUE)], - "PixmapSynced must arm its explicit acquire timeline point", - ); - assert!( - state.damage_objects[&DAMAGE_XID].rects.is_empty(), - "the destination must not be copied or damaged before acquire signals", - ); - assert_eq!(state.present_pending_exec.len(), 1); - backend - .dri3_free_syncobj(ClientId(CLIENT), RELEASE_SYNCOBJ) - .expect("free original release syncobj"); - let replacement = backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(CLIENT)); - let parked_release = match &state - .present_pending_exec - .values() - .next() - .expect("parked synced Present") - .pending - .wake - { - crate::backend::PresentWake::PixmapSynced { release, .. } => release, - crate::backend::PresentWake::Pixmap { .. } => panic!("expected synced wake"), - }; - assert!( - std::sync::Arc::ptr_eq(parked_release, &original_release), - "accepted Present must retain the original release object" - ); - assert!( - !std::sync::Arc::ptr_eq(parked_release, &replacement), - "reusing the XID must not retarget the parked Present" - ); - parked_release - .signal(RELEASE_VALUE) - .expect("pinned release remains usable after FreeSyncobj"); - assert_eq!( - *backend.signalled_dri3_syncobjs.lock().unwrap(), - vec![(RELEASE_SYNCOBJ, RELEASE_VALUE)] - ); - assert_eq!( - state.present_pending_exec.values().next().unwrap().pin, - Some(1), - "the Deferred arm takes an entry pin on the source drawable" - ); - - backend.ready_present_source_waits.push(WAIT_ID); - drain_ready_present_pixmaps(&mut state, &mut backend); - - let damage = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object"); - assert_eq!( - damage.rects, state.xfixes_regions[&UPDATE_REGION_XID].rects, - "PresentPixmapSynced must feed its update region into DAMAGE on the destination window", - ); - } - - #[test] - fn present_pixmap_copy_uses_update_region_rects_as_copy_clips() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, xfixes::RegionRect}; - - const CLIENT: u32 = 15; - const WINDOW_XID: u32 = 0x00e0_0203; - const PIXMAP_XID: u32 = 0x00e0_0204; - const UPDATE_REGION_XID: u32 = 0x00e0_0206; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0x400203); - } - - state.resources.create_pixmap( - ClientId(CLIENT), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 800, - height: 600, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(0x400204).expect("valid host pixmap"), - ); - - state.xfixes_regions.insert( - UPDATE_REGION_XID, - crate::server::XFixesRegion { - owner: ClientId(CLIENT), - rects: vec![ - RegionRect { - x: 100, - y: 120, - width: 80, - height: 40, - }, - RegionRect { - x: 220, - y: 260, - width: 25, - height: 35, - }, - ], - }, - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - body[16..20].copy_from_slice(&UPDATE_REGION_XID.to_le_bytes()); - body[20..22].copy_from_slice(&7_i16.to_le_bytes()); - body[22..24].copy_from_slice(&11_i16.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - let copies: Vec<_> = backend - .calls() - .into_iter() - .filter_map(|call| match call { - RecordedCall::CopyArea { - src_host_xid, - dst_host_xid, - src_x, - src_y, - dst_x, - dst_y, - width, - height, - } => Some(( - src_host_xid, - dst_host_xid, - src_x, - src_y, - dst_x, - dst_y, - width, - height, - )), - _ => None, - }) - .collect(); - - assert_eq!( - copies, - vec![ - (0x400204, 0x400203, 100, 120, 107, 131, 80, 40), - (0x400204, 0x400203, 220, 260, 227, 271, 25, 35), - ], - "PresentPixmap Copy must copy only the update rects, offset into the destination by x_off/y_off", - ); - } - - #[test] - fn present_pixmap_copy_to_redirected_window_preserves_window_destination() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; - - const CLIENT: u32 = 16; - const WINDOW_XID: u32 = 0x00e0_0303; - const PIXMAP_XID: u32 = 0x00e0_0304; - const BACKING_XID: u32 = 0x0040_03ff; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 640, - height: 480, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0x400303); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(BACKING_XID), - width: 640, - height: 480, - depth: 24, - }); - } - - state.resources.create_pixmap( - ClientId(CLIENT), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 640, - height: 480, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP_XID), - crate::backend::PixmapHandle::from_raw(0x400304).expect("valid host pixmap"), - ); - - let mut body = vec![0u8; 68]; - body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); - body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); - body[20..22].copy_from_slice(&13_i16.to_le_bytes()); - body[22..24].copy_from_slice(&17_i16.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: 145, - data: yserver_protocol::x11::present::PIXMAP, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - let copies: Vec<_> = backend - .calls() - .into_iter() - .filter_map(|call| match call { - RecordedCall::CopyArea { - src_host_xid, - dst_host_xid, - src_x, - src_y, - dst_x, - dst_y, - width, - height, - } => Some(( - src_host_xid, - dst_host_xid, - src_x, - src_y, - dst_x, - dst_y, - width, - height, - )), - _ => None, - }) - .collect(); - - assert_eq!( - copies, - vec![(0x400304, 0x400303, 0, 0, 13, 17, 640, 480)], - "PresentPixmap must paint through the destination window xid, not its redirected backing xid, so the backend can retain ClipByChildren and hierarchy stacking while resolving that window to the backing", - ); - } - - // ===================================================================== - // Task 8: supersession (coverage-gated scrap + parked Skip) and the - // copy-failure reroute. Spec §Supersession + §"Ordered completion - // delivery"; plan `docs/superpowers/plans/ - // 2026-08-01-present-deferred-execution-supersession.md` Task 8. - // ===================================================================== - - use yserver_protocol::x11::xfixes; - - /// Full-control `PendingPresentPixmap`/`PendingPresentEntry` builder - /// for the Task 8 tests below — unlike `stub_pending_present_entry` - /// (window/present_id only) and `present_pending_entry_with` - /// (window/pixmap host xids/eff/source_ready only), these tests need - /// to vary geometry, update region, and wake identity (`Pixmap` - /// idle_fence vs `PixmapSynced` release syncobj). - #[derive(Clone)] - struct SupersessionFixture { - present_id: u64, - window: u32, - effective_target_msc: Option, - x_off: i16, - y_off: i16, - src_width: u16, - src_height: u16, - update_rects: Option>, - /// The wire `update` field (an XFixes region XID or 0) — - /// independent of `update_rects` (the server-resolved rects, or - /// `None` when the region was unresolvable). Task 13: needed to - /// exercise `execute_present_pixmap_copy`'s damage arm with - /// `update != 0` + `update_rects == None` (unresolvable region). - update: u32, - idle_fence: u32, - synced_release: Option<(u32, u64)>, - } - - impl SupersessionFixture { - fn new(present_id: u64, window: u32) -> Self { - Self { - present_id, - window, - effective_target_msc: Some(100), - x_off: 0, - y_off: 0, - src_width: 100, - src_height: 100, - update_rects: None, - update: 0, - idle_fence: 0, - synced_release: None, - } - } - - fn eff(mut self, eff: Option) -> Self { - self.effective_target_msc = eff; - self - } - - fn geometry(mut self, x_off: i16, y_off: i16, src_width: u16, src_height: u16) -> Self { - self.x_off = x_off; - self.y_off = y_off; - self.src_width = src_width; - self.src_height = src_height; - self - } - - fn update_rects(mut self, rects: Option>) -> Self { - self.update_rects = rects; - self - } - - fn update(mut self, update: u32) -> Self { - self.update = update; - self - } - - fn idle_fence(mut self, fence: u32) -> Self { - self.idle_fence = fence; - self - } - - fn synced_release(mut self, release_syncobj: u32, release_value: u64) -> Self { - self.synced_release = Some((release_syncobj, release_value)); - self - } - - fn pending(&self) -> crate::server::PendingPresentPixmap { - use crate::server::{PendingPresentPixmap, PendingPresentRequest}; - use yserver_protocol::x11::present::{PixmapRequest, PixmapSyncedRequest}; - - let request = if let Some((release_syncobj, release_value)) = self.synced_release { - PendingPresentRequest::PixmapSynced(PixmapSyncedRequest { - window: self.window, - pixmap: 0x1, - serial: 1, - valid: 0, - update: self.update, - x_off: self.x_off, - y_off: self.y_off, - target_crtc: 0, - acquire_syncobj: 0, - release_syncobj, - acquire_value: 0, - release_value, - options: 0, - target_msc: 0, - divisor: 0, - remainder: 0, - notifies: Vec::new(), - }) - } else { - PendingPresentRequest::Pixmap(PixmapRequest { - window: self.window, - pixmap: 0x1, - serial: 1, - valid: 0, - update: self.update, - x_off: self.x_off, - y_off: self.y_off, - target_crtc: 0, - wait_fence: 0, - idle_fence: self.idle_fence, - options: 0, - target_msc: 0, - divisor: 0, - remainder: 0, - notifies: Vec::new(), - }) - }; - - PendingPresentPixmap { - origin: None, - client_id: ClientId(1), - request, - wake: crate::backend::PresentWake::Pixmap { - idle_fence_xid: self.idle_fence, - }, - masked_options: 0, - src_host_xid: 0x2, - paint_dst_host_xid: self.window | 0x0040_0000, - completion_dst_host_xid: self.window | 0x0040_0000, - src_width: self.src_width, - src_height: self.src_height, - update_rects: self.update_rects.clone(), - present_id: self.present_id, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - effective_target_msc: self.effective_target_msc, - } - } - - fn entry(&self) -> crate::server::PendingPresentEntry { - crate::server::PendingPresentEntry { - pending: self.pending(), - source_ready: true, - wait_id: None, - pin: None, - } - } - } - - // ---------------- Step 1: present_supersession_covers ---------------- - - #[test] - fn coverage_full_predecessor_under_full_successor_is_covered() { - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - assert!(present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_sliver_predecessor_under_full_successor_is_covered() { - // Xorg semantics (verification item (d)): a full-frame successor - // scraps a sliver predecessor — the successor gate cares only - // about ITS OWN update region, not the predecessor's. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 10, - y: 10, - width: 5, - height: 5, - }])) - .pending(); - assert!( - present_supersession_covers(&successor, &predecessor), - "a full-frame successor covers a thin sliver predecessor" - ); - } - - #[test] - fn coverage_partial_region_successor_never_scraps_regardless_of_coverage() { - // Xorg gate (present_scmd.c:802), amended (Task 13, spec - // §"Amendment 2026-08-01"): a successor carrying a PARTIAL update - // region — one that does not clear `successor_presents_full_extent` - // — never scraps, even when its rects would geometrically cover - // the predecessor. This is what protects marco/picom's - // drag-sliver presents from scrapping each other. (NOT a - // full-extent fixture: the successor's rect is a genuine sliver - // of its 100x100 source, distinct from the full-extent case - // covered by `coverage_single_rect_full_extent_region_scraps_like_none`.) - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 10, - y: 10, - width: 5, - height: 5, - }])) - .pending(); - // Predecessor's footprint sits exactly inside the successor's - // rect — geometrically "coverable" — yet the gate still declines - // because the successor's region isn't full-extent. - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(10, 10, 5, 5) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_negative_offsets_fitting_is_covered() { - // Offsets are i16 and may be negative (a window partially - // off-screen) — the arithmetic must not saturate. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(-50, -50, 200, 200) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(-40, -40, 50, 50) - .pending(); - assert!(present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_negative_offsets_not_fitting_is_not_covered() { - let successor = SupersessionFixture::new(2, 0x100) - .geometry(-50, -50, 100, 100) - .pending(); - // Predecessor's left edge (-60) is outside the successor's rect - // (starts at -50). - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(-60, -50, 20, 20) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_full_frame_successor_from_smaller_resize_source_does_not_cover_larger_predecessor() - { - // Mid-resize: Mesa reallocated a smaller swapchain pixmap for the - // successor, but a larger predecessor from before the resize is - // still parked. The successor's full-extent rect is - // SOURCE-pixmap-bounded, so it must NOT cover a predecessor - // extending beyond it — yserver's strictly conservative extra on - // top of Xorg's geometry-blind scrap. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 50, 50) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_zero_pixel_successor_never_scraps() { - // The documented zero-pixel present: `update_rects = Some(empty)` - // still satisfies the successor gate's `is_some()` check, so it - // never scraps — regardless of how trivially "coverable" the - // predecessor is. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(Vec::new())) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 1, 1) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_zero_pixel_predecessor_is_trivially_covered() { - // A predecessor with `Some(empty)` has no content, so it is - // covered by any (gate-passing) successor — falls out of - // `.all()` on an empty iterator. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(Vec::new())) - .pending(); - assert!(present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_near_i16_max_rect_offset_saturates_like_the_real_copy() { - // Review fix: the predicate must judge coverage at exactly the - // position the real copy lands, not at an unsaturated `i32` sum. - // Predecessor `x_off=32000` with rect `r.x=1000` sums to an - // unsaturated `i32` 33000, but `execute_present_pixmap_copy` - // computes the dest x as `x_off.saturating_add(rect.x)` in `i16`, - // which clamps to `i16::MAX` (32767) — the real copy never draws - // past that. The successor's extent below ends exactly at 32767 - // (`x_off` is itself `i16`-bounded, so its extent can only reach - // i16::MAX from below, never past it), so the saturated dest - // (32767 + rect width 100 = 32867) overruns the successor's real - // right edge by exactly 100px and must NOT be judged covered — a - // covered-but-not-actually-copied verdict here would lose that - // sliver. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(32700, 0, 67, 100) // extent x in [32700, 32767) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(32000, 0, 1000, 1000) - .update_rects(Some(vec![xfixes::RegionRect { - x: 1000, - y: 0, - width: 100, - height: 100, - }])) - .pending(); - assert!( - !present_supersession_covers(&successor, &predecessor), - "the real copy saturates the dest x to i16::MAX = 32767, and \ - 32767 + rect width 100 = 32867 overruns the successor's real \ - right edge (32767) by 100px — must not be judged covered" - ); - } - - // ---------------- Task 13: successor-gate relaxation (spec - // §"Amendment 2026-08-01 — successor-gate relaxation") ---------------- - - #[test] - fn coverage_single_rect_full_extent_region_scraps_like_none() { - // The NVIDIA-WSI shape from the CS2 capture: a single rect that - // exactly equals the source extent. Must scrap exactly like - // `update_rects == None`. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 50, 50) - .pending(); - assert!( - present_supersession_covers(&successor, &predecessor), - "a single-rect full-extent update region scraps exactly like None" - ); - } - - #[test] - fn coverage_over_large_rect_passes() { - // A rect with negative origin and an extent past the source - // bounds still provably contains the full extent. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: -10, - y: -10, - width: 300, - height: 300, - }])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - assert!(present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_superset_region_passes_via_containing_rect() { - // `rects = [full-extent rect, extra sliver]` passes via the - // containing rect — the executed copy writes the union, a - // superset of the extent (spec amendment's "superset region" - // paragraph). - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![ - xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }, - xfixes::RegionRect { - x: 150, - y: 150, - width: 10, - height: 10, - }, - ])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - assert!(present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_multirect_union_but_no_single_rect_covers_declines() { - // Two rects whose UNION covers the full extent, but neither rect - // alone does — union coverage is deliberately not computed, so - // this declines (the documented conservative bound). This also - // bites harder on yserver than Xorg: yserver's y-band region - // normalization doesn't re-coalesce vertically/horizontally - // adjacent identical bands. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![ - xfixes::RegionRect { - x: 0, - y: 0, - width: 50, - height: 100, - }, - xfixes::RegionRect { - x: 50, - y: 0, - width: 50, - height: 100, - }, - ])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 10, 10) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_marco_style_multirect_sliver_declines() { - // A realistic marco/picom drag-update shape: two thin horizontal - // strips (top + bottom), whose union does NOT even cover the - // full extent. Never scraps. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![ - xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 10, - }, - xfixes::RegionRect { - x: 0, - y: 90, - width: 100, - height: 10, - }, - ])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 100, 100) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_region_full_extent_one_axis_only_declines() { - // Padded / mid-resize shape: the rect is full-extent in width but - // not in height, on a source taller than the rect. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 50, - }])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 10, 10) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn coverage_zero_area_rect_declines() { - // `Some([zero-area rect])` — reachable via the - // `CREATE_REGION_FROM_GC` path, which inserts parsed rects raw, - // bypassing `normalize_region_rects`. A zero-area rect can never - // satisfy both `>=` conditions. - let successor = SupersessionFixture::new(2, 0x100) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 0, - y: 0, - width: 0, - height: 100, - }])) - .pending(); - let predecessor = SupersessionFixture::new(1, 0x100) - .geometry(0, 0, 1, 1) - .pending(); - assert!(!present_supersession_covers(&successor, &predecessor)); - } - - #[test] - fn supersede_single_rect_full_extent_region_scraps_like_none() { - // End-to-end: `supersede_covered_pending_presents` scraps a - // covered victim behind a successor carrying the NVIDIA-WSI - // full-extent single-rect shape. - const WINDOW: u32 = 0x0001_0009; - const VICTIM_ID: u64 = 90; - const SUCCESSOR_ID: u64 = 91; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 50, 50) - .entry(); - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }])) - .update(1) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert!( - state.present_pending_exec.is_empty(), - "a full-extent single-rect successor must scrap a covered victim" - ); - } - - // ---------------- Task 13: damage-arm fix (spec §"Amendment - // 2026-08-01" — damage-arm dependency) ---------------- - - #[test] - fn damage_full_extent_region_present_with_offset_translates_position() { - // Failing test first (plan Task 13 Step 3): a full-extent-region - // present with `x_off`/`y_off != 0` accumulates damage at the - // TRANSLATED position, matching the copy arm's - // `x_off.saturating_add(rect.x)`. - use crate::{backend::recording::RecordedCall, server::DamageObject}; - - const WINDOW: u32 = 0x0002_0001; - const DAMAGE_XID: u32 = 0x0002_0002; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(WINDOW), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let pending = SupersessionFixture::new(1, WINDOW) - .geometry(20, 30, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }])) - .update(1) - .pending(); - - execute_present_pixmap_copy(&mut state, &mut backend, pending) - .expect("copy succeeds against RecordingBackend"); - - assert!( - backend.calls().iter().any(|call| matches!( - call, - RecordedCall::CopyArea { - src_x: 0, - src_y: 0, - dst_x: 20, - dst_y: 30, - width: 100, - height: 100, - .. - } - )), - "the copy arm translates by x_off/y_off: {:?}", - backend.calls() - ); - let damage = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object"); - assert_eq!( - damage.rects, - vec![xfixes::RegionRect { - x: 20, - y: 30, - width: 100, - height: 100, - }], - "the damage arm must translate per-rect damage by x_off/y_off \ - exactly like the copy arm" - ); - } - - #[test] - fn direct_present_success_bypasses_copy_and_keeps_completion_gate() { - use crate::backend::recording::RecordedCall; - - const WINDOW: u32 = 0x0002_0011; - const PRESENT_ID: u64 = 0x44; - const TARGET_MSC: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_direct_result = true; - let pending = SupersessionFixture::new(PRESENT_ID, WINDOW) - .eff(Some(TARGET_MSC)) - .geometry(0, 0, 100, 100) - .pending(); - - execute_present_pixmap_copy(&mut state, &mut backend, pending) - .expect("direct ownership succeeds"); - - assert_eq!(backend.present_direct_candidates.len(), 1); - assert!( - backend - .calls() - .iter() - .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), - "M2b success must not record the normal source-to-COW Copy" - ); - let gate = state - .present_complete_gate - .get(&PRESENT_ID) - .expect("direct completion gate installed before ownership handoff"); - assert_eq!(gate.effective_target_msc, TARGET_MSC); - } - - /// Xorg: the flip check fails on the empty clipList (present_scmd.c:122), - /// the Copy to an unrealized window is a no-op (micopy.c:157), and idle - /// plus CompleteModeCopy are still sent (present_execute.c:137-156). - #[test] - fn present_to_unviewable_window_skips_copy_and_damage_but_completes() { - use crate::{backend::recording::RecordedCall, resources::MapState, server::DamageObject}; - - const PARENT: u32 = 0x0002_0021; - const WINDOW: u32 = 0x0002_0022; - const DAMAGE_XID: u32 = 0x0002_0023; - const PRESENT_ID: u64 = 0x45; - const TARGET_MSC: u64 = 600; - - for (parent_state, window_state, hidden) in [ - (MapState::Viewable, MapState::Unmapped, true), - (MapState::Unmapped, MapState::Unviewable, true), - (MapState::Viewable, MapState::Viewable, false), - ] { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_direct_result = true; - for (xid, parent, map_state) in [ - (PARENT, ROOT_WINDOW, parent_state), - (WINDOW, ResourceId(PARENT), window_state), - ] { - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent, - width: 100, - height: 100, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(xid)) - .expect("window") - .map_state = map_state; - } - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(WINDOW), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - let pending = SupersessionFixture::new(PRESENT_ID, WINDOW) - .eff(Some(TARGET_MSC)) - .geometry(0, 0, 100, 100) - .pending(); - - execute_present_pixmap_copy(&mut state, &mut backend, pending).expect("present"); - - let copies = backend - .calls() - .iter() - .filter(|call| matches!(call, RecordedCall::CopyArea { .. })) - .count(); - let damaged = !state.damage_objects[&DAMAGE_XID].rects.is_empty(); - let gate = state.present_complete_gate.get(&PRESENT_ID).expect("gate"); - assert_eq!(gate.effective_target_msc, TARGET_MSC); - if hidden { - assert!( - backend.present_direct_candidates.is_empty(), - "{window_state:?}: no direct attempt" - ); - assert_eq!(copies, 0, "{window_state:?}: no copy"); - assert!(!damaged, "{window_state:?}: no damage"); - assert_eq!(backend.enqueued_present_completions.len(), 1); - let (event, _) = &backend.enqueued_present_completions[0]; - assert_eq!( - event.completion_mode, - yserver_protocol::x11::present::COMPLETE_MODE_COPY - ); - assert!(event.emit_idle, "{window_state:?}: idle still sent"); - assert_eq!(event.present_id, PRESENT_ID); - } else { - // Viewable control: direct path taken as before. - assert_eq!(backend.present_direct_candidates.len(), 1); - assert!(damaged); - assert!(backend.enqueued_present_completions.is_empty()); - } - } - } - - #[test] - fn damage_unresolvable_region_with_update_flag_accumulates_full_extent() { - // Failing test first (plan Task 13 Step 3): an `update != 0` + - // unresolvable-region (`update_rects == None`) present - // accumulates FULL-EXTENT damage, not nothing — the branch is - // re-keyed off `update_rects.is_none()`, not the raw `update` - // xid, so this can no longer silently drop all damage. - use crate::server::DamageObject; - - const WINDOW: u32 = 0x0002_0003; - const DAMAGE_XID: u32 = 0x0002_0004; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(WINDOW), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let pending = SupersessionFixture::new(1, WINDOW) - .geometry(5, 7, 60, 40) - .update_rects(None) - .update(1) - .pending(); - - execute_present_pixmap_copy(&mut state, &mut backend, pending) - .expect("copy succeeds against RecordingBackend"); - - let damage = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object"); - assert_eq!( - damage.rects, - vec![xfixes::RegionRect { - x: 5, - y: 7, - width: 60, - height: 40, - }], - "update != 0 with an unresolvable region must still damage \ - full-extent, not nothing" - ); - } - - // ---------------- Step 2: supersede_covered_pending_presents ---------------- - - /// Seed one `Present` event selection for `window` with the given - /// mask, draining the connection setup traffic first. Tests that - /// decode the wire with `complete_notify_modes` (fixed 40-byte - /// chunks) pass `EVENT_MASK_COMPLETE_NOTIFY` alone — mixing in - /// `EVENT_MASK_IDLE_NOTIFY` would interleave 32-byte `IdleNotify` - /// events into that fixed-width chunking (Task 6's - /// `due_skip_is_held_back_behind_a_smaller_id_undrained_gate_entry` - /// makes the same choice for the same reason). - fn seed_present_selection( - state: &mut ServerState, - peer: &mut UnixStream, - eid: u32, - window: u32, - mask: u32, - ) { - state.present_event_selections.insert( - eid, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(window), - event_mask: mask, - }, - ); - let _ = read_all_available(peer); - } - - #[test] - fn supersede_scraps_covered_same_window_same_target_entry() { - const WINDOW: u32 = 0x0001_0001; - const PRESENT_EID: u32 = 0x0020_1001; - const VICTIM_ID: u64 = 10; - const SUCCESSOR_ID: u64 = 11; - const TARGET: u64 = 500; - const IDLE_FENCE: u32 = 0x0030_1001; - const WAIT_ID: u64 = 777; - const PIN_ID: u64 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_present_selection( - &mut state, - &mut peer, - PRESENT_EID, - WINDOW, - yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY - | yserver_protocol::x11::present::EVENT_MASK_IDLE_NOTIFY, - ); - let mut backend = RecordingBackend::new(); - - state.sync_fences.insert( - IDLE_FENCE, - crate::server::SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - - let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 50, 50) - .idle_fence(IDLE_FENCE) - .entry(); - victim.wait_id = Some(WAIT_ID); - victim.pin = Some(PIN_ID); - state.present_pending_exec.insert(VICTIM_ID, victim); - state.present_wait_to_id.insert(WAIT_ID, VICTIM_ID); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert!( - state.present_pending_exec.is_empty(), - "the covered victim must be removed from the store" - ); - assert!( - state.present_wait_to_id.is_empty(), - "the side-map row must be dropped with the entry" - ); - assert_eq!( - backend.finished_present_source_waits, - vec![WAIT_ID], - "the armed source wait must be cancelled" - ); - assert_eq!( - backend.released_present_sources, - vec![PIN_ID], - "the entry pin must be released" - ); - assert_eq!( - backend.triggered_dri3_fences, - vec![IDLE_FENCE], - "the idle fence must be triggered by XID, immediately" - ); - assert!( - state.sync_fences[&IDLE_FENCE].triggered, - "the X11 fence mirror must be set at scrap time" - ); - assert_eq!( - state.present_pending_complete.len(), - 1, - "a Skip completion must be parked for ordered delivery" - ); - let parked = &state.present_pending_complete[0]; - assert_eq!(parked.event.present_id, VICTIM_ID); - assert_eq!(parked.effective_target_msc, TARGET); - assert_eq!( - parked.mode, - yserver_protocol::x11::present::COMPLETE_MODE_SKIP - ); - assert!(!parked.emit_idle, "IdleNotify already fired at scrap"); - - // Review fix (5a): actually decode the IdleNotify wire bytes - // (layout per `encode_idle_notify`), not just count them — - // pins event type, eid, window, pixmap xid, and fence xid. - let idle_bytes = read_all_available(&mut peer); - assert_eq!( - idle_bytes.len(), - 32, - "exactly one IdleNotify (32 bytes) must be delivered on the wire right \ - now, at scrap time — no CompleteNotify yet" - ); - assert_eq!(idle_bytes[0], 35, "GenericEvent"); - assert_eq!(idle_bytes[1], 145, "PRESENT major opcode"); - assert_eq!( - idle_bytes[8], - yserver_protocol::x11::present::EVENT_IDLE_NOTIFY, - "evtype must be IdleNotify" - ); - assert_eq!( - u32::from_le_bytes(idle_bytes[12..16].try_into().unwrap()), - PRESENT_EID, - "eid must be the selection that requested IdleNotify" - ); - assert_eq!( - u32::from_le_bytes(idle_bytes[16..20].try_into().unwrap()), - WINDOW, - "window xid" - ); - assert_eq!( - u32::from_le_bytes(idle_bytes[24..28].try_into().unwrap()), - 0x1, - "pixmap xid — the victim's own client-visible pixmap (SupersessionFixture \ - hardcodes 0x1)" - ); - assert_eq!( - u32::from_le_bytes(idle_bytes[28..32].try_into().unwrap()), - IDLE_FENCE, - "fence xid" - ); - } - - #[test] - fn supersede_note_present_skip_once_per_scrapped_victim() { - // Task 10 telemetry: `Backend::note_present_skip` must fire exactly - // once per victim actually scrapped by supersession — not once per - // call, not for a survivor, and not double-counted. - const WINDOW: u32 = 0x0001_1002; - const VICTIM_A: u64 = 200; - const VICTIM_B: u64 = 201; - const SUCCESSOR_ID: u64 = 202; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let victim_a = SupersessionFixture::new(VICTIM_A, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 10, 10) - .entry(); - let victim_b = SupersessionFixture::new(VICTIM_B, WINDOW) - .eff(Some(TARGET)) - .geometry(20, 20, 10, 10) - .entry(); - state.present_pending_exec.insert(VICTIM_A, victim_a); - state.present_pending_exec.insert(VICTIM_B, victim_b); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert!( - state.present_pending_exec.is_empty(), - "both covered victims must be scrapped" - ); - assert_eq!( - backend.present_skip_count, 2, - "note_present_skip must fire exactly once per scrapped victim" - ); - } - - #[test] - fn supersede_leaves_entry_with_different_effective_target_msc() { - const WINDOW: u32 = 0x0001_0002; - const VICTIM_ID: u64 = 20; - const SUCCESSOR_ID: u64 = 21; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(500)) - .geometry(0, 0, 50, 50) - .entry(); - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(600)) // different target - .geometry(0, 0, 100, 100) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert_eq!( - state.present_pending_exec.len(), - 1, - "an entry targeting a different effective MSC must survive" - ); - assert!(state.present_pending_complete.is_empty()); - } - - #[test] - fn supersede_leaves_entry_in_different_window() { - const WINDOW_A: u32 = 0x0001_0003; - const WINDOW_B: u32 = 0x0001_0004; - const VICTIM_ID: u64 = 30; - const SUCCESSOR_ID: u64 = 31; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let victim = SupersessionFixture::new(VICTIM_ID, WINDOW_A) - .eff(Some(TARGET)) - .geometry(0, 0, 50, 50) - .entry(); - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW_B) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert_eq!( - state.present_pending_exec.len(), - 1, - "an entry in a different window must survive" - ); - assert!(state.present_pending_complete.is_empty()); - } - - #[test] - fn supersede_partial_region_successor_with_update_rects_never_scraps() { - // Task 13 refit (spec §"Amendment 2026-08-01"): the fixture's - // successor rect is a genuine sliver of its 100x100 source, not - // an accidentally-full-extent one — post-amendment a full-extent - // single rect WOULD clear the gate (see - // `coverage_single_rect_full_extent_region_scraps_like_none`), - // so this test's coverage of "a partial-region successor never - // scraps" depends on the rect staying genuinely partial. - const WINDOW: u32 = 0x0001_0005; - const VICTIM_ID: u64 = 40; - const SUCCESSOR_ID: u64 = 41; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - // Victim's footprint sits exactly inside the successor's rect — - // geometrically "coverable" — yet the gate still declines because - // the successor's region isn't full-extent. - let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(10, 10, 5, 5) - .entry(); - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 10, - y: 10, - width: 5, - height: 5, - }])) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert_eq!( - state.present_pending_exec.len(), - 1, - "a successor carrying a partial update region must never scrap" - ); - assert!(state.present_pending_complete.is_empty()); - } - - #[test] - fn supersede_successor_with_no_effective_target_never_scraps() { - // With `eff = None`, equivalence with any pending request is unknown. - const WINDOW: u32 = 0x0001_0006; - const VICTIM_ID: u64 = 50; - const SUCCESSOR_ID: u64 = 51; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(500)) - .geometry(0, 0, 50, 50) - .entry(); - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(None) // no effective target: no shared Some target to scrap on - .geometry(0, 0, 100, 100) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert_eq!( - state.present_pending_exec.len(), - 1, - "a successor with no effective target never scraps" - ); - assert!(state.present_pending_complete.is_empty()); - } - - #[test] - fn async_requests_with_same_effective_target_supersede() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut pred_entry = - present_pending_entry_with(1, 0x00e0_3001, 0x00e0_3002, Some(500), true); - pred_entry.pending.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; - let pred = pred_entry.pending.clone(); - state.present_pending_exec.insert(1, pred_entry); - let succ = crate::server::PendingPresentPixmap { - present_id: 2, - effective_target_msc: Some(500), - masked_options: crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS, - ..pred - }; - supersede_covered_pending_presents(&mut state, &mut backend, &succ); - assert!( - !state.present_pending_exec.contains_key(&1), - "async requests with the same known effective target must supersede" - ); - assert_eq!(backend.present_skip_count, 1); - assert_eq!( - state.present_pending_complete.len(), - 1, - "Skip parked for ordered delivery" - ); - } - - #[test] - fn async_requests_with_unknown_effective_targets_do_not_supersede() { - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut pred_entry = present_pending_entry_with(1, 0x00e0_3001, 0x00e0_3002, None, true); - pred_entry.pending.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; - let pred = pred_entry.pending.clone(); - state.present_pending_exec.insert(1, pred_entry); - let succ = crate::server::PendingPresentPixmap { - present_id: 2, - effective_target_msc: None, - masked_options: crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS, - ..pred - }; - supersede_covered_pending_presents(&mut state, &mut backend, &succ); - assert!( - state.present_pending_exec.contains_key(&1), - "None does not establish target equivalence, even for two async requests" - ); - assert_eq!(backend.present_skip_count, 0); - } - - #[test] - fn supersede_pixmap_synced_victim_releases_via_syncobj() { - const WINDOW: u32 = 0x0001_0007; - const VICTIM_ID: u64 = 60; - const SUCCESSOR_ID: u64 = 61; - const TARGET: u64 = 500; - const RELEASE_SYNCOBJ: u32 = 0x0030_1007; - const RELEASE_VALUE: u64 = 42; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let release = backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(1)); - let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 50, 50) - .synced_release(RELEASE_SYNCOBJ, RELEASE_VALUE) - .entry(); - victim.pending.wake = crate::backend::PresentWake::PixmapSynced { - release, - release_syncobj: RELEASE_SYNCOBJ, - release_value: RELEASE_VALUE, - }; - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert!(state.present_pending_exec.is_empty()); - assert_eq!( - *backend.signalled_dri3_syncobjs.lock().unwrap(), - vec![(RELEASE_SYNCOBJ, RELEASE_VALUE)], - "a PixmapSynced victim releases via dri3_signal_syncobj, not dri3_trigger_fence" - ); - assert!(backend.triggered_dri3_fences.is_empty()); - assert_eq!(state.present_pending_complete.len(), 1); - } - - #[test] - fn arm_before_scrap_syncobj_failure_leaves_covered_victim_untouched() { - // Regression for the adversarial-review blocker: the successor's - // own `arm_present_syncobj_wait` is client-reachably fallible - // (e.g. an unknown acquire syncobj). If supersession scrapped - // covered victims BEFORE that arm, a failed arm would unwind via - // `?` with the victim already destroyed and nothing committed to - // replace it — leaving the window with no frame at the target - // MSC where Xorg would still have shown the victim. This drives - // the real `arm_present_pixmap_synced_source_then_supersede` - // helper — the exact arm+scrap sequence the PixmapSynced handler - // calls — rather than invoking - // `supersede_covered_pending_presents` directly, so it actually - // exercises production ordering rather than hand-waving it. - const WINDOW: u32 = 0x0001_0008; - const VICTIM_ID: u64 = 62; - const SUCCESSOR_ID: u64 = 63; - const TARGET: u64 = 500; - const IDLE_FENCE: u32 = 0x0030_1008; - const WAIT_ID: u64 = 778; - const PIN_ID: u64 = 2; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.arm_present_syncobj_wait_result = Some(std::io::ErrorKind::InvalidInput); - - state.sync_fences.insert( - IDLE_FENCE, - crate::server::SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - - let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 50, 50) - .idle_fence(IDLE_FENCE) - .entry(); - victim.wait_id = Some(WAIT_ID); - victim.pin = Some(PIN_ID); - state.present_pending_exec.insert(VICTIM_ID, victim); - state.present_wait_to_id.insert(WAIT_ID, VICTIM_ID); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - - let result = arm_present_pixmap_synced_source_then_supersede( - &mut state, - &mut backend, - 0, - 0, - &successor, - ); - - assert!( - result.is_err(), - "the canned arm failure must propagate as Err" - ); - assert_eq!( - state.present_pending_exec.len(), - 1, - "the covered victim must still be in present_pending_exec — scrap must \ - not run ahead of a failed arm" - ); - assert!( - state.present_pending_exec.contains_key(&VICTIM_ID), - "specifically the victim, untouched" - ); - assert!( - state.present_wait_to_id.contains_key(&WAIT_ID), - "the victim's wait side-map row must survive too" - ); - assert!( - backend.finished_present_source_waits.is_empty(), - "the victim's wait must not be cancelled" - ); - assert!( - backend.released_present_sources.is_empty(), - "the victim's pin must not be released" - ); - assert!( - backend.triggered_dri3_fences.is_empty(), - "the victim's idle fence must NOT be triggered" - ); - assert!( - !state.sync_fences[&IDLE_FENCE].triggered, - "the X11 fence mirror must NOT be set — the victim's fence never fired" - ); - assert!( - state.present_pending_complete.is_empty(), - "no Skip completion may be parked for a victim that was never scrapped" - ); - } - - // ---------------- Step 3: copy-failure reroute ---------------- - - #[test] - fn failing_copy_at_arrival_parks_ordered_copy_completion_and_preserves_window_order() { - const WINDOW: u32 = 0x0001_0101; - const PRESENT_EID: u32 = 0x0020_1101; - const BLOCKER_ID: u64 = 70; - const FAILING_ID: u64 = 71; - const TARGET: u64 = 500; - const IDLE_FENCE: u32 = 0x0030_1101; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // Review fix (5b): also select IdleNotify, so this test can pin - // that exactly one fires — at failure time, with the right fence - // — and none at delivery. - seed_present_selection( - &mut state, - &mut peer, - PRESENT_EID, - WINDOW, - yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY - | yserver_protocol::x11::present::EVENT_MASK_IDLE_NOTIFY, - ); - let mut backend = RecordingBackend::new(); - backend.fail_copy_area = true; - - state.sync_fences.insert( - IDLE_FENCE, - crate::server::SyncFence { - owner: ClientId(1), - triggered: false, - }, - ); - - // An earlier same-window present is still unresolved (msc-parked) - // — the failing present's completion must be held back behind it. - state - .present_pending_exec - .insert(BLOCKER_ID, stub_pending_present_entry(WINDOW, BLOCKER_ID)); - - let failing = SupersessionFixture::new(FAILING_ID, WINDOW) - .eff(Some(TARGET)) - .idle_fence(IDLE_FENCE) - .pending(); - - let ok = execute_present_pixmap_copy_or_reroute(&mut state, &mut backend, failing); - assert!(!ok, "a failing copy_area must report failure"); - - assert!( - backend - .calls() - .iter() - .any(|c| matches!(c, crate::backend::recording::RecordedCall::CopyArea { .. })), - "the copy must actually be attempted" - ); - assert!( - state.present_complete_gate.is_empty(), - "a failed copy runs before the gate insert — no gate row must exist" - ); - assert_eq!( - backend.triggered_dri3_fences, - vec![IDLE_FENCE], - "the buffer must be released by XID immediately, like scrap" - ); - assert!(state.sync_fences[&IDLE_FENCE].triggered); - - // Exactly one IdleNotify must be on the wire NOW, at failure time - // — the reroute's by-XID release fires it immediately, same as - // scrap (Fix 5a's decode pattern). - let idle_bytes = read_all_available(&mut peer); - assert_eq!( - idle_bytes.len(), - 32, - "exactly one IdleNotify (32 bytes) must fire at failure time" - ); - assert_eq!(idle_bytes[0], 35, "GenericEvent"); - assert_eq!(idle_bytes[1], 145, "PRESENT major opcode"); - assert_eq!( - idle_bytes[8], - yserver_protocol::x11::present::EVENT_IDLE_NOTIFY, - "evtype must be IdleNotify" - ); - assert_eq!( - u32::from_le_bytes(idle_bytes[28..32].try_into().unwrap()), - IDLE_FENCE, - "fence xid" - ); - - assert_eq!(state.present_pending_complete.len(), 1); - let parked = &state.present_pending_complete[0]; - assert_eq!(parked.event.present_id, FAILING_ID); - assert_eq!(parked.effective_target_msc, TARGET); - assert_eq!( - parked.mode, - yserver_protocol::x11::present::COMPLETE_MODE_COPY - ); - assert!(!parked.emit_idle); - - let clock = crate::backend::PresentClockSample { - msc: TARGET, - ust: 0x1000, - source: crate::backend::PresentClockSource::PageFlip, - }; - fire_due_present_completions(&mut state, &mut backend, clock); - assert_eq!( - state.present_pending_complete.len(), - 1, - "the parked Copy completion stays held back behind the still-\ - unexecuted blocker in present_pending_exec" - ); - - // The blocker resolves. - state.present_pending_exec.remove(&BLOCKER_ID); - fire_due_present_completions(&mut state, &mut backend, clock); - assert!( - state.present_pending_complete.is_empty(), - "the rerouted Copy completion delivers once the blocker clears" - ); - assert!( - backend.signalled_present_wakes.is_empty(), - "emit_idle=false must not signal the (already-released) wake a second time" - ); - // No second IdleNotify at delivery: `complete_notify_modes` chunks - // strictly by 40 bytes and asserts each chunk is a well-formed - // CompleteNotify, so a stray 32-byte IdleNotify here would - // misalign the chunking and fail loudly rather than pass - // silently. - let wire = read_all_available(&mut peer); - assert_eq!( - complete_notify_modes(&wire), - vec![yserver_protocol::x11::present::COMPLETE_MODE_COPY] - ); - } - - #[test] - fn failing_copy_without_clock_delivers_complete_notify_inline() { - const WINDOW: u32 = 0x0001_0102; - const PRESENT_EID: u32 = 0x0020_1102; - const FAILING_ID: u64 = 72; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_present_selection( - &mut state, - &mut peer, - PRESENT_EID, - WINDOW, - yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - ); - let mut backend = RecordingBackend::new(); - backend.fail_copy_area = true; - seed_present_clock(&mut state, 100, 0x2000); - - let failing = SupersessionFixture::new(FAILING_ID, WINDOW) - .eff(None) // no usable CRTC clock - .pending(); - - let ok = execute_present_pixmap_copy_or_reroute(&mut state, &mut backend, failing); - assert!(!ok); - - assert!( - state.present_pending_complete.is_empty(), - "a no-clock (eff=None) failing copy must deliver inline, not park" - ); - assert!( - backend.signalled_present_wakes.is_empty(), - "emit_idle=false: no wake is signalled" - ); - let wire = read_all_available(&mut peer); - assert_eq!( - complete_notify_modes(&wire), - vec![yserver_protocol::x11::present::COMPLETE_MODE_COPY], - "the completion delivers immediately with mode Copy" - ); - } - - #[test] - fn failing_copy_in_due_pass_releases_entry_pin_exactly_once() { - const WINDOW: u32 = 0x0001_0103; - const FAILING_ID: u64 = 73; - const PIN_ID: u64 = 9; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.fail_copy_area = true; - - let mut entry = SupersessionFixture::new(FAILING_ID, WINDOW) - .eff(Some(TARGET)) - .entry(); - entry.pin = Some(PIN_ID); - state.present_pending_exec.insert(FAILING_ID, entry); - - execute_parked_present_ids(&mut state, &mut backend, &[FAILING_ID], "drain"); - - assert!(state.present_pending_exec.is_empty()); - assert_eq!( - backend.released_present_sources, - vec![PIN_ID], - "the entry pin must be released exactly once, even on copy failure" - ); - assert!( - backend - .calls() - .iter() - .all(|c| !matches!(c, crate::backend::recording::RecordedCall::MarkDirty)), - "mark_dirty must not fire when the copy failed" - ); - assert_eq!(state.present_pending_complete.len(), 1); - } - - // ---------------- Step 4: end-to-end vectors ---------------- - - /// Round-3 inversion vector, now driven by REAL scrap (Task 6's - /// version at `due_skip_is_held_back_behind_a_smaller_id_undrained_gate_entry` - /// inserted the Skip row by hand): P1 executes at arrival (no flip in - /// flight), P2 parks (a flip is in flight), P3 arrives full-frame at - /// the same effective target and scraps P2 via - /// `supersede_covered_pending_presents`. Skip(P2) must not deliver - /// before Copy(P1) even though it was parked first (at P3's arrival, - /// before P1's GPU fence retired). - #[test] - fn supersession_e2e_p1_executes_p2_parks_p3_scraps_p2_delivery_order_preserved() { - use yserver_protocol::x11::present as x11present; - - const WINDOW: u32 = 0x0001_0201; - const PRESENT_EID: u32 = 0x0020_1201; - const P1_ID: u64 = 80; - const P2_ID: u64 = 81; - const P3_ID: u64 = 82; - const CLOCK: u64 = 10; - const TARGET: u64 = CLOCK + 1; // eff for target_msc=0/divisor=0/remainder=0 - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (CLOCK, 0x1000); // held fixed across all three arrivals - seed_present_clock(&mut state, CLOCK, 0x1000); - - // P1: no flip in flight -> ExecuteNow. - backend.present_flip_in_flight = false; - let p1 = SupersessionFixture::new(P1_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - supersede_covered_pending_presents(&mut state, &mut backend, &p1); - arrival_execute_or_park_present_pixmap(&mut state, &mut backend, P1_ID, p1); - assert!( - state.present_complete_gate.contains_key(&P1_ID), - "P1 executed at arrival and inserted its completion gate" - ); - - // P2: a flip is now in flight -> Park. - backend.present_flip_in_flight = true; - let p2 = SupersessionFixture::new(P2_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - supersede_covered_pending_presents(&mut state, &mut backend, &p2); - arrival_execute_or_park_present_pixmap(&mut state, &mut backend, P2_ID, p2); - assert!(state.present_pending_exec.contains_key(&P2_ID)); - - // P3: full-frame, same effective target -> scraps P2, then parks - // itself (flip still in flight). - let p3 = SupersessionFixture::new(P3_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - supersede_covered_pending_presents(&mut state, &mut backend, &p3); - assert!( - !state.present_pending_exec.contains_key(&P2_ID), - "P3 scrapped P2" - ); - arrival_execute_or_park_present_pixmap(&mut state, &mut backend, P3_ID, p3); - assert!(state.present_pending_exec.contains_key(&P3_ID)); - - assert_eq!( - state.present_pending_complete.len(), - 1, - "Skip(P2) is parked" - ); - assert_eq!(state.present_pending_complete[0].event.present_id, P2_ID); - - // Wire up the completion-notify subscriber now that the store - // setup above is done, and drain its connection setup traffic. - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - - let clock = crate::backend::PresentClockSample { - msc: TARGET, - ust: 0x2000, - source: crate::backend::PresentClockSource::PageFlip, - }; - fire_due_present_completions(&mut state, &mut backend, clock); - assert_eq!( - state.present_pending_complete.len(), - 1, - "Skip(P2) held back behind P1's still-undrained completion gate" - ); - - // P1's fence retires late: the gate empties and its completion - // joins the queue, as run.rs's Some(gate) arm does. - state.present_complete_gate.remove(&P1_ID); - state - .present_pending_complete - .push(crate::server::PendingPresentComplete { - event: crate::backend::CompletedPresentEvent { - client_id: ClientId(1), - serial: 1, - host_xid: 0x1, - dst_host_xid: WINDOW, - options: 0, - present_id: P1_ID, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - completion_clock: None, - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }, - effective_target_msc: TARGET, - mode: x11present::COMPLETE_MODE_COPY, - emit_idle: true, - }); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert!(state.present_pending_complete.is_empty()); - assert_eq!( - complete_notify_modes(&read_all_available(&mut peer)), - vec![ - x11present::COMPLETE_MODE_COPY, - x11present::COMPLETE_MODE_SKIP - ], - "Copy(P1) must deliver before Skip(P2) — never inverted" - ); - } - - /// Uncovered survivor (spec vector (ii)): A carries a sliver update - /// region NOT covered by successor C's extent, so C's scrap declines - /// it; B is full-frame and covered, so C scraps it. A later executes - /// via the due-pass; Skip(B) must not deliver before Copy(A) even - /// though B has the larger present_id and was scrapped (queued) - /// first. - #[test] - fn supersede_declined_uncovered_survivor_holds_back_covered_scrap_skip() { - use yserver_protocol::x11::present as x11present; - - const WINDOW: u32 = 0x0001_0202; - const PRESENT_EID: u32 = 0x0020_1202; - const A_ID: u64 = 90; - const B_ID: u64 = 91; - const C_ID: u64 = 92; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (TARGET, 0x1000); // due at TARGET. - - // A: sliver update region far outside C's extent (declines). - let a = SupersessionFixture::new(A_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .update_rects(Some(vec![xfixes::RegionRect { - x: 200, - y: 200, - width: 5, - height: 5, - }])) - .entry(); - state.present_pending_exec.insert(A_ID, a); - - // B: full-frame, covered. - let b = SupersessionFixture::new(B_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .entry(); - state.present_pending_exec.insert(B_ID, b); - - let c = SupersessionFixture::new(C_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - supersede_covered_pending_presents(&mut state, &mut backend, &c); - - assert!( - state.present_pending_exec.contains_key(&A_ID), - "A's sliver update region is not covered by C's extent — declined" - ); - assert!( - !state.present_pending_exec.contains_key(&B_ID), - "B is full-frame and covered — scrapped" - ); - assert_eq!(state.present_pending_complete.len(), 1); - assert_eq!(state.present_pending_complete[0].event.present_id, B_ID); - - let mut peer = install_client(&mut state, 1); - state.present_event_selections.insert( - PRESENT_EID, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: ResourceId(WINDOW), - event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - - drain_due_present_pending_exec(&mut state, &mut backend); - assert!( - state.present_pending_exec.is_empty(), - "A executes in the due-pass" - ); - assert!( - state.present_complete_gate.contains_key(&A_ID), - "A's execute_present_pixmap_copy inserted its completion gate" - ); - - let clock = crate::backend::PresentClockSample { - msc: TARGET, - ust: 0x1000, - source: crate::backend::PresentClockSource::PageFlip, - }; - fire_due_present_completions(&mut state, &mut backend, clock); - assert_eq!( - state.present_pending_complete.len(), - 1, - "Skip(B) held back behind A's still-undrained completion gate" - ); - - // A's fence retires: the gate empties and its completion joins - // the queue, as run.rs's Some(gate) arm does. - state.present_complete_gate.remove(&A_ID); - state - .present_pending_complete - .push(crate::server::PendingPresentComplete { - event: crate::backend::CompletedPresentEvent { - client_id: ClientId(1), - serial: 1, - host_xid: 0x1, - dst_host_xid: WINDOW, - options: 0, - present_id: A_ID, - window_generation: 0, - crtc_id: 0, - crtc_epoch: 0, - msc_offset: 0, - completion_clock: None, - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }, - effective_target_msc: TARGET, - mode: x11present::COMPLETE_MODE_COPY, - emit_idle: true, - }); - - fire_due_present_completions(&mut state, &mut backend, clock); - assert!(state.present_pending_complete.is_empty()); - assert_eq!( - complete_notify_modes(&read_all_available(&mut peer)), - vec![ - x11present::COMPLETE_MODE_COPY, - x11present::COMPLETE_MODE_SKIP - ], - "Copy(A) must deliver before Skip(B): A < B for the same window" - ); - } - - /// Same-target entries whose successor declines (or never arrives) - /// all execute at their due point in arrival (`present_id`) order. - #[test] - fn uncovered_same_target_entries_execute_in_arrival_order() { - use crate::backend::recording::RecordedCall; - - const WINDOW: u32 = 0x0001_0203; - const A_ID: u64 = 100; - const B_ID: u64 = 101; - const TARGET: u64 = 500; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.present_ust_msc = (TARGET, 0x1000); - - // Both carry a sliver update region, so a would-be successor - // would decline both — but here we just prove arrival order - // survives when nothing scraps at all (present_id insertion - // order == BTreeMap iteration order). - let a = SupersessionFixture::new(A_ID, WINDOW) - .eff(Some(TARGET)) - .update_rects(Some(vec![xfixes::RegionRect { - x: 0, - y: 0, - width: 10, - height: 10, - }])) - .entry(); - state.present_pending_exec.insert(A_ID, a); - let b = SupersessionFixture::new(B_ID, WINDOW) - .eff(Some(TARGET)) - .update_rects(Some(vec![xfixes::RegionRect { - x: 20, - y: 20, - width: 10, - height: 10, - }])) - .entry(); - state.present_pending_exec.insert(B_ID, b); - - drain_due_present_pending_exec(&mut state, &mut backend); - - let order: Vec = backend - .calls() - .iter() - .filter_map(|c| match c { - RecordedCall::CopyArea { dst_x, .. } => Some(*dst_x), - _ => None, - }) - .collect(); - // dst_x mirrors the rect's x (0 for A, 20 for B) — arrival order. - assert_eq!(order, vec![0, 20], "A executes before B: arrival order"); - assert!(state.present_pending_exec.is_empty()); - } - - #[test] - fn distinct_effective_targets_never_supersede() { - const WINDOW: u32 = 0x0001_0204; - const A_ID: u64 = 110; - const C_ID: u64 = 111; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - - let mut a = SupersessionFixture::new(A_ID, WINDOW) - .eff(Some(500)) - .geometry(0, 0, 100, 100) - .entry(); - a.pending.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; - state.present_pending_exec.insert(A_ID, a); - - let mut c = SupersessionFixture::new(C_ID, WINDOW) - .eff(Some(600)) // distinct target - .geometry(0, 0, 100, 100) - .pending(); - c.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; - supersede_covered_pending_presents(&mut state, &mut backend, &c); - - assert!( - state.present_pending_exec.contains_key(&A_ID), - "a distinct effective target must never supersede" - ); - assert!(state.present_pending_complete.is_empty()); - } - - /// Scrap × window-destroy race: a present is scrapped first (fence - /// triggered, entry pin released, Skip parked), then the - /// window-destroy purge runs for the same window. The purge must not - /// find the (already-removed) entry again — no double fence trigger, - /// no double pin release. The purge's `signal_present_wake` on the - /// now-parked Skip row (a completion, not a pending-exec entry) is a - /// separate, harmless no-op backend-side; not exercised here. - #[test] - fn scrap_then_window_destroy_purge_releases_exactly_once() { - const WINDOW: u32 = 0x0001_0205; - const VICTIM_ID: u64 = 120; - const SUCCESSOR_ID: u64 = 121; - const TARGET: u64 = 500; - const IDLE_FENCE: u32 = 0x0030_1205; - const PIN_ID: u64 = 5; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 50, 50) - .idle_fence(IDLE_FENCE) - .entry(); - victim.pin = Some(PIN_ID); - state.present_pending_exec.insert(VICTIM_ID, victim); - - let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) - .eff(Some(TARGET)) - .geometry(0, 0, 100, 100) - .pending(); - supersede_covered_pending_presents(&mut state, &mut backend, &successor); - - assert_eq!(backend.triggered_dri3_fences, vec![IDLE_FENCE]); - assert_eq!(backend.released_present_sources, vec![PIN_ID]); - assert!(state.present_pending_exec.is_empty()); - - // Now destroy the window: the by-XID purge scans - // `present_pending_exec` for this window and finds nothing (the - // entry is already gone), so it must not touch the backend again. - destroy_window_subtree(&mut state, &mut backend, None, ResourceId(WINDOW)); - - assert_eq!( - backend.triggered_dri3_fences, - vec![IDLE_FENCE], - "the window-destroy purge must not re-trigger an already-scrapped fence" - ); - assert_eq!( - backend.released_present_sources, - vec![PIN_ID], - "the window-destroy purge must not re-release an already-released pin" - ); - // Review fix (5c): the destroy purge's parked-completions sweep - // (process_request.rs, `destroy_window_subtree`'s - // `present_pending_complete` loop) DOES call `signal_present_wake` - // for every row matching this window — including the Skip row the - // scrap above just parked, since scrap does not remove it from - // `present_pending_complete`. This is a no-op on a real backend - // (the scrapped present_id was never retained as a `PinnedWake` — - // scrap's own by-XID release is what actually signalled the - // client), but `RecordingBackend` records the call regardless, so - // pin the exact expected content: exactly the victim's id, and no - // other wake. - assert_eq!( - backend.signalled_present_wakes, - vec![VICTIM_ID], - "the purge's parked-completion sweep signals the scrapped Skip row's \ - present_id (harmless no-op on a real backend) and nothing else" - ); - } - - // ---------------- extract_shm_zpixmap_region ---------------- - // - // The protocol-level byte-extraction for MIT-SHM PutImage. Until - // 2026-05-15 the handler ignored `total_width` / `src_x` / - // `src_y` and read a tightly-packed `src_width × src_height × - // bpp` block at `offset`. That happens to be correct when the - // client sets `total == src` and `src_xy == 0` (the common - // case), but reads garbage when the client uploads a sub-region - // of a larger shm image. xfdesktop's thumbnail upload pattern - // and any cairo-padded surface trigger the latter, which - // manifests as horizontal-band corruption around the thumbnail. - - #[test] - fn mit_shm_put_image_honors_gc_clip_rectangles() { - const CLIENT: u32 = 1; - const PIXMAP: u32 = 0x0020_0001; - const GC: u32 = 0x0020_0002; - const SHMSEG: u32 = 0x0020_0003; - const HOST_PIXMAP: u32 = 0x0040_0001; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - state.resources.create_pixmap( - ClientId(CLIENT), - x11::CreatePixmapRequest { - depth: 32, - pixmap: ResourceId(PIXMAP), - drawable: ROOT_WINDOW, - width: 4, - height: 4, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - ResourceId(PIXMAP), - crate::backend::PixmapHandle::from_raw(HOST_PIXMAP).expect("non-zero host pixmap"), - )); - state.resources.create_gc( - ClientId(CLIENT), - CreateGcRequest { - gc: ResourceId(GC), - drawable: ResourceId(PIXMAP), - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - let clip = x11::ClipRectangles { - ordering: 0, - x_origin: 0, - y_origin: 0, - rectangles: [ - 0i16.to_le_bytes(), - 1i16.to_le_bytes(), - 4u16.to_le_bytes(), - 1u16.to_le_bytes(), - ] - .concat(), - }; - state.resources.set_clip_rectangles( - ClientId(CLIENT), - x11::SetClipRectanglesRequest { - gc: ResourceId(GC), - clip: clip.clone(), - }, - ); - - let fd = - unsafe { libc::memfd_create(c"mit-shm-put-image-test".as_ptr(), libc::MFD_CLOEXEC) }; - assert!(fd >= 0, "memfd_create failed"); - assert_eq!(unsafe { libc::ftruncate(fd, 64) }, 0, "ftruncate failed"); - let mut segment = crate::server::MitShmSegment::from_fd(ClientId(CLIENT), fd, false) - .expect("map test SHM segment"); - segment - .as_mut_slice() - .expect("writable SHM segment") - .fill(0xff); - state.mit_shm_segments.insert(SHMSEG, segment); - - handle_mit_shm_put_image( - &mut state, - &mut backend, - None, - ClientId(CLIENT), - SequenceNumber(1), - yserver_protocol::x11::mit_shm::PutImageRequest { - drawable: PIXMAP, - gc: GC, - total_width: 4, - total_height: 4, - src_x: 0, - src_y: 0, - src_width: 4, - src_height: 4, - dst_x: 0, - dst_y: 0, - depth: 32, - format: 2, - send_event: false, - shmseg: SHMSEG, - offset: 0, - }, - ) - .expect("MIT-SHM PutImage succeeds"); - - assert!(backend.calls.lock().expect("calls lock").contains( - &crate::backend::recording::RecordedCall::ApplyClipState( - crate::backend::ClipState::Rectangles { - origin: (0, 0), - rects: clip, - }, - ), - )); - } - - fn d32_pixel(b: u8, g: u8, r: u8, a: u8) -> [u8; 4] { - // Wire byte order for a depth-32 ZPixmap is [B, G, R, A] — - // see the comment in `try_vk_put_image`. - [b, g, r, a] - } - - #[test] - fn extract_d32_tight_packing_returns_input() { - // total == src, src_xy == 0 → output is exactly the input. - let mut bytes = Vec::new(); - for y in 0..4u8 { - for x in 0..4u8 { - bytes.extend_from_slice(&d32_pixel(x, y, x ^ y, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 0, 4, 4, 32) - .expect("tight extraction succeeds"); - assert_eq!(out, bytes); - } - - /// 2026-05-28 perf-cliff fix: full-frame extracts MUST return - /// `Cow::Borrowed` (no allocation, no memcpy). On cinnamon the - /// hot-path PutImage of the 28MB compositor stage was spending - /// 8-10ms in the legacy per-row Vec::extend_from_slice loop. - /// Borrowing the SHM slice directly drops it to a bounds-check. - /// Tested both depth=24 and depth=32 at the boundary (full frame, - /// no offset, row_bytes == src_stride) and against a partial / - /// padded case that MUST still allocate. - #[test] - fn extract_full_frame_d32_returns_borrowed_slice() { - // 8×4 full-frame extract, depth 32 → row_bytes == src_stride. - let mut bytes = Vec::new(); - for y in 0..4u8 { - for x in 0..8u8 { - bytes.extend_from_slice(&d32_pixel(x, y, x ^ y, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 8, 4, 0, 0, 8, 4, 32) - .expect("full-frame d32 extraction succeeds"); - assert!( - matches!(out, std::borrow::Cow::Borrowed(_)), - "full-frame extract must zero-copy (Cow::Borrowed)", - ); - assert_eq!(out.as_ref(), bytes.as_slice()); - } - - #[test] - fn extract_full_frame_d24_returns_borrowed_slice() { - // 8×4 full-frame, depth 24 (4 bytes per pixel — same as d32). - let mut bytes = Vec::new(); - for y in 0..4u8 { - for x in 0..8u8 { - bytes.extend_from_slice(&d32_pixel(x, y, x ^ y, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 8, 4, 0, 0, 8, 4, 24) - .expect("full-frame d24 extraction succeeds"); - assert!( - matches!(out, std::borrow::Cow::Borrowed(_)), - "full-frame d24 extract must zero-copy (Cow::Borrowed)", - ); - assert_eq!(out.as_ref(), bytes.as_slice()); - } - - #[test] - fn extract_partial_region_returns_owned_vec() { - // Same data but ask for a sub-region — the borrow fast path - // MUST NOT trigger. - let mut bytes = Vec::new(); - for y in 0..8u8 { - for x in 0..8u8 { - bytes.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 8, 8, 2, 2, 4, 4, 32) - .expect("partial extraction succeeds"); - assert!( - matches!(out, std::borrow::Cow::Owned(_)), - "partial extract must allocate (Cow::Owned)", - ); - } - - #[test] - fn extract_d8_padded_full_frame_does_not_borrow() { - // Depth-8 with src_width=5 → src_stride=8 (pad-to-32-bit). - // row_bytes (5) < src_stride (8) — the borrow fast path's - // `row_bytes == src_stride` precondition excludes this so - // the slow padding path runs. - let bytes: Vec = (0..16).map(|i| i as u8).collect(); - let out = extract_shm_zpixmap_region(&bytes, 0, 5, 2, 0, 0, 5, 2, 8) - .expect("padded d8 extraction succeeds"); - assert!( - matches!(out, std::borrow::Cow::Owned(_)), - "padded full-frame d8 must NOT borrow (per-row padding required)", - ); - } - - #[test] - fn extract_d32_subregion_of_larger_buffer() { - // 8×8 total, take 4×4 at (2, 2). The handler must read row 2 - // bytes 8..24, row 3 bytes 8..24, etc. — NOT 64 contiguous - // bytes from offset 0, which is what the pre-fix handler - // did. - let mut bytes = Vec::new(); - for y in 0..8u8 { - for x in 0..8u8 { - bytes.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 8, 8, 2, 2, 4, 4, 32) - .expect("subregion extraction succeeds"); - // Output must be the (2,2)..(6,6) tile, tightly packed. - let mut want = Vec::new(); - for y in 2..6u8 { - for x in 2..6u8 { - want.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); - } - } - assert_eq!(out, want); - } - - #[test] - fn extract_d32_total_wider_than_src() { - // 16×4 total, take 4×4 at (0, 0). Each src row must skip the - // unused 12 trailing pixels of the total row. - let mut bytes = Vec::new(); - for y in 0..4u8 { - for x in 0..16u8 { - bytes.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 16, 4, 0, 0, 4, 4, 32) - .expect("wide-total extraction succeeds"); - let mut want = Vec::new(); - for y in 0..4u8 { - for x in 0..4u8 { - want.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); - } - } - assert_eq!(out, want); - } - - #[test] - fn extract_honors_offset() { - // Image starts partway into the shm segment. - let mut bytes = vec![0xAAu8; 16]; - for y in 0..2u8 { - for x in 0..2u8 { - bytes.extend_from_slice(&d32_pixel(x, y, 0xFF, 0xFF)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 16, 2, 2, 0, 0, 2, 2, 32) - .expect("offset extraction succeeds"); - assert_eq!(out, &bytes[16..]); - } - - #[test] - fn extract_d8_padding_total_wider_than_src() { - // 6-wide total → 8 bytes/row (padded to 32-bit). Take a 5×2 - // tile. Output stride is `((5 + 3) & ~3) = 8` bytes/row so - // we get 16 bytes; first 5 are image data, next 3 are pad. - let bytes: Vec = (0..16).map(|i| i as u8).collect(); - let out = extract_shm_zpixmap_region(&bytes, 0, 6, 2, 0, 0, 5, 2, 8) - .expect("d8 extraction succeeds"); - assert_eq!(out.len(), 16); - // Row 0 image bytes: 0..5 of the input; row 0 trailing pad: zero. - assert_eq!(&out[..5], &bytes[..5]); - assert_eq!(&out[5..8], &[0, 0, 0]); - // Row 1 image bytes: 8..13 of the input. - assert_eq!(&out[8..13], &bytes[8..13]); - assert_eq!(&out[13..16], &[0, 0, 0]); - } - - #[test] - fn extract_d8_src_x_offset() { - // 8-wide total → 8 bytes/row. Take a 4×1 tile at src_x=2. - let bytes: Vec = (0..8).map(|i| i as u8).collect(); - let out = extract_shm_zpixmap_region(&bytes, 0, 8, 1, 2, 0, 4, 1, 8) - .expect("d8 src_x extraction succeeds"); - // src_width=4 → src_stride=4 (already 32-bit aligned). Output is bytes 2..6. - assert_eq!(out, vec![2u8, 3, 4, 5]); - } - - #[test] - fn extract_rejects_region_outside_total() { - let bytes = vec![0u8; 64]; - // src_x + src_width > total_width - assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 2, 0, 4, 4, 32).is_none()); - // src_y + src_height > total_height - assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 2, 4, 4, 32).is_none()); - } - - #[test] - fn extract_rejects_negative_src_xy() { - let bytes = vec![0u8; 64]; - assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, -1, 0, 4, 4, 32).is_none()); - assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, -1, 4, 4, 32).is_none()); - } - - #[test] - fn extract_rejects_offset_beyond_buffer() { - let bytes = vec![0u8; 16]; - // 4×4 d32 = 64 bytes; only 16 available. - assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 0, 4, 4, 32).is_none()); - } - - #[test] - fn extract_rejects_unsupported_depth() { - let bytes = vec![0u8; 64]; - assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 0, 4, 4, 16).is_none()); - } - - #[test] - fn extract_d24_treats_padding_byte_as_image_data() { - // d24 on the wire is 4 bytes per pixel like d32; the 4th - // byte is undefined but transmitted. Extraction must copy - // all 4 bytes — the put_image backend stamps 0xFF later. - let mut bytes = Vec::new(); - for y in 0..2u8 { - for x in 0..2u8 { - bytes.extend_from_slice(&d32_pixel(x, y, 0xCC, 0x77)); - } - } - let out = extract_shm_zpixmap_region(&bytes, 0, 2, 2, 0, 0, 2, 2, 24) - .expect("d24 extraction succeeds"); - assert_eq!(out, bytes); - } - - // ---------------- end extract_shm_zpixmap_region ---------------- - - #[test] - fn redirect_invalid_mode_returns_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Anything outside {0, 1} is a spec violation → BadValue. - dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0xDEAD, 2); - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error delivered"); - assert_eq!(buf[0], 0); - // BAD_VALUE = 2 - assert_eq!(buf[1], 2, "expected BadValue (2), got {}", buf[1]); - assert!(state.composite_redirects.is_empty()); - } - - // ---------------- Stage 4d gate: COW host_xid wiring ---------------- - // - // Marco-with-compositing uses **pure PRESENT-pixmap onto COW** with zero - // `RedirectSubwindows` / `NameWindowPixmap` calls — it repeatedly emits - // `PRESENT::Pixmap(window=0x103 /* COW */, pixmap=client_offscreen)`. - // - // `process_present_pixmap` resolves both endpoints via - // `state.resources.host_drawable_target(...)`, which returns `None` when - // `window.host_xid` is `None`. Stage 4d allocated COW storage on the - // backend (`KmsBackend.cow_id`) and registered with the scene, but - // left `host_xid` `None` on the yserver-core resource record (seeded - // that way at `ResourceTable::new` since the COW xid pre-exists the - // backend-side allocation). Every `PresentPixmap → COW` therefore - // silently fell through the `if let (Some, Some)` guard at - // `process_request.rs:~4124` and dropped paint. - // - // Fix: on the GET_OVERLAY_WINDOW arm, after the backend hook lands - // successfully, wire `host_xid = Some(0x103)` and copy root dimensions - // onto the COW resource record. On the final RELEASE_OVERLAY_WINDOW, - // destroy the record so the next GET re-wires fresh storage. - // - // These tests use `RecordingBackend`. Which release is final is - // decided by core's claim list (`ServerState::cow_claims`), not by - // the backend — the backend counts nothing. - - fn dispatch_composite_minor( - state: &mut ServerState, - backend: &mut dyn crate::backend::Backend, - client_id: ClientId, - sequence: u16, - minor: u8, - body: &[u8], - ) -> RequestOutcome { - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - process_request( - state, - backend, - client_id, - SequenceNumber(sequence), - RequestHeader { - opcode: 144, // COMPOSITE - data: minor, - length_units, - }, - body, - None, - ) - .unwrap() - } - - #[test] - fn name_window_pixmap_uses_redirected_backing_geometry() { - use crate::{ - backend::{PixmapHandle, WindowHandle}, - resources::RedirectedBacking, - server::{CompositeRedirectMode, RedirectRecord}, - }; - use yserver_protocol::x11::CreateWindowRequest; - - const WINDOW: ResourceId = ResourceId(0x10004a); - const PIXMAP: ResourceId = ResourceId(0x300225); - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new().with_composite_support(); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 32, - window: WINDOW, - parent: ROOT_WINDOW, - width: 646, - height: 501, - border_width: 2, - class: 1, - visual: crate::resources::ARGB_VISUAL, - ..Default::default() - }, - ); - assert!(state.resources.map_window(WINDOW).mapping_changed); - let window = state - .resources - .window_mut(WINDOW) - .expect("window installed"); - window.host_xid = Some(WindowHandle::from_raw_for_test(0x40008a)); - window.redirected_backing = Some(RedirectedBacking { - host_pixmap: PixmapHandle::from_raw_for_test(0x4000d), - width: 650, - height: 505, - depth: 32, - }); - state.composite_redirects.insert( - (WINDOW, false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&WINDOW.0.to_le_bytes()); - body.extend_from_slice(&PIXMAP.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::NAME_WINDOW_PIXMAP, - &body, - ); - - let pixmap = state.resources.pixmap(PIXMAP).expect("named pixmap exists"); - assert_eq!((pixmap.width, pixmap.height), (650, 505)); - let aliases = &state - .resources - .window(WINDOW) - .expect("window remains installed") - .composite_named_pixmaps; - assert_eq!(aliases.len(), 1); - assert_eq!((aliases[0].width, aliases[0].height), (650, 505)); - } - - #[test] - fn get_overlay_window_wires_cow_host_xid() { - // Pre-condition: COW resource record does NOT exist (post-Task-2.1 - // the pre-seed is gone; COW materialises only on GetOverlayWindow). - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .is_none(), - "COW must NOT be pre-seeded; the materialise-on-GET model \ - owns the entire COW lifecycle (Task 2.1 + Task 2.4)", - ); - - // GetOverlayWindow body: window xid (we use root, marco ignores - // the reply's input and just trusts whatever XID we hand back). - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - - // Load-bearing assertion: after GET, host_drawable_target must - // resolve. This is what makes PresentPixmap → COW actually paint. - let target = state - .resources - .host_drawable_target(crate::resources::COMPOSITE_OVERLAY_WINDOW); - match target { - Some(crate::resources::HostDrawableTarget::Window { - nested, - host_xid, - depth, - }) => { - assert_eq!(nested, crate::resources::COMPOSITE_OVERLAY_WINDOW); - assert_eq!( - host_xid.as_raw(), - crate::resources::COMPOSITE_OVERLAY_WINDOW.0, - "COW host_xid must equal its protocol xid (0x103)", - ); - assert_eq!(depth, 24, "COW is depth-24"); - } - other => panic!( - "host_drawable_target(COW) must resolve to Window after \ - GetOverlayWindow — got {other:?}. Pre-fix shape returned \ - None (host_xid still unset on the resource record), which \ - dropped every PresentPixmap → COW.", - ), - } - - // Dimensions: COW should track the root extent (the backend's - // COW storage is screen-extent per the Stage 4d plan). - let cow = state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .expect("COW record"); - let root = state - .resources - .window(crate::resources::ROOT_WINDOW) - .expect("ROOT record"); - assert_eq!(cow.width, root.width, "COW must match root extent"); - assert_eq!(cow.height, root.height, "COW must match root extent"); - } - - #[test] - fn repeated_get_reuses_materialized_host_overlay() { - // A compositor may emit GetOverlayWindow multiple times (e.g. - // re-registration on a window-manager hand-off). What is stable - // across those calls is the identity of the already-materialized - // host overlay: the `host_xid.is_none()` guard prevents repeated - // allocation and host_xid stays wired. - // - // The *request* is deliberately NOT idempotent — each call - // records another claim in `state.cow_claims` (Xorg's N-record - // model) and each needs its own ReleaseOverlayWindow. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - - let cow = state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .expect("COW record"); - assert_eq!( - cow.host_xid.map(crate::backend::WindowHandle::as_raw), - Some(crate::resources::COMPOSITE_OVERLAY_WINDOW.0), - "host_xid stays wired across repeated GETs", - ); - assert_eq!( - state.cow_claims, - vec![ClientId(1), ClientId(1)], - "each GET records its own claim — what moved to the core claim \ - list is exactly what the backend refcount used to count", - ); - } - - #[test] - fn release_overlay_window_destroys_cow_resource_on_final_release() { - // Final release (backend returns Ok(true)) must DESTROY the COW - // resource record entirely (record removed from `windows`, edge - // removed from `root.children`) so a subsequent `GetOverlayWindow` - // re-materialises fresh storage via the 0→1 backend path. The - // pre-Task-2.5 shape merely cleared `host_xid` on the still-existing - // record; that diverged from Xorg (no record between - // release-and-next-claim) and silently retained per-COW state - // (event masks, properties) across the release boundary. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Wire COW via GET first. - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .and_then(|w| w.host_xid) - .is_some(), - ); - let old_generation = - state.present_window_generation(crate::resources::COMPOSITE_OVERLAY_WINDOW.0); - state.present_window_msc.insert( - crate::resources::COMPOSITE_OVERLAY_WINDOW.0, - crate::server::PresentWindowMsc { - last_crtc: 2, - last_crtc_epoch: 1, - msc_offset: 10, - last_raw_msc: 20, - }, - ); - state.present_event_selections.insert( - 0x0001_c0e1, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: crate::resources::COMPOSITE_OVERLAY_WINDOW, - event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - state - .present_pending_msc - .push(crate::server::PendingNotifyMsc { - owner: ClientId(1), - window: crate::resources::COMPOSITE_OVERLAY_WINDOW.0, - crtc_id: 2, - crtc_epoch: 1, - msc_offset: 10, - serial: 1, - target_msc: 30, - divisor: 0, - remainder: 0, - byte_order: ClientByteOrder::LittleEndian, - }); - let stale_event = crate::backend::CompletedPresentEvent { - client_id: ClientId(1), - serial: 1, - host_xid: 0x0001_c002, - dst_host_xid: crate::resources::COMPOSITE_OVERLAY_WINDOW.0, - options: 0, - present_id: 0x_c0, - window_generation: old_generation, - crtc_id: 2, - crtc_epoch: 1, - msc_offset: 10, - completion_clock: None, - wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, - completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, - emit_idle: true, - }; - - // Final release — client 1 holds the only claim. - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .is_none(), - "final release (backend.Ok(true)) must destroy the COW resource \ - record entirely so the next GetOverlayWindow re-materialises \ - fresh storage", - ); - assert!( - !state - .resources - .window(crate::resources::ROOT_WINDOW) - .unwrap() - .children - .contains(&crate::resources::COMPOSITE_OVERLAY_WINDOW), - "final release must remove COW from root.children too", - ); - assert!( - !state - .present_window_generations - .contains_key(&crate::resources::COMPOSITE_OVERLAY_WINDOW.0) - ); - assert!( - !state - .present_window_msc - .contains_key(&crate::resources::COMPOSITE_OVERLAY_WINDOW.0) - ); - assert!(state.present_pending_msc.is_empty()); - assert!(state.present_event_selections.is_empty()); - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 3, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - let new_generation = - state.present_window_generation(crate::resources::COMPOSITE_OVERLAY_WINDOW.0); - assert_ne!(new_generation, old_generation); - state.present_event_selections.insert( - 0x0001_c0e2, - crate::server::PresentEventSelection { - owner: ClientId(1), - window: crate::resources::COMPOSITE_OVERLAY_WINDOW, - event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, - }, - ); - let _ = read_all_available(&mut peer); - backend.completed_present_events_to_drain.push(stale_event); - crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); - assert_eq!(backend.signalled_present_wakes, vec![0x_c0]); - assert!(read_all_available(&mut peer).is_empty()); - } - - #[test] - fn release_overlay_window_keeps_host_xid_on_non_final_release() { - // Non-final release (a claim remains): storage is still live on - // the backend, host_xid must stay wired so any remaining - // compositor's PresentPixmap → COW keeps landing. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let _peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - // A second claimant, so client 2's release below is not the final - // one. Which release is final is core's decision, taken from the - // claim list — the backend has no say and no counter. - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(2), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(2), - 2, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - let cow = state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .expect("COW record"); - assert_eq!( - cow.host_xid.map(crate::backend::WindowHandle::as_raw), - Some(crate::resources::COMPOSITE_OVERLAY_WINDOW.0), - "non-final release must keep host_xid wired — \ - storage is still alive on the backend", - ); - } - - /// Get by A, Release by B ⇒ `BadMatch`, and A's claim survives. - /// Xorg's `ProcCompositeReleaseOverlayWindow` looks the caller up - /// with `compFindOverlayClient` and refuses when it holds no record. - #[test] - fn release_overlay_window_by_non_claimant_is_badmatch() { - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 1); - let mut peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - let _ = read_all_available(&mut peer_b); - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(2), - 1, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - - assert_error_code( - &read_all_available(&mut peer_b), - yserver_protocol::x11::error::BAD_MATCH, - "ReleaseOverlayWindow from a client holding no claim", - ); - assert!( - backend.cow_materialized, - "B's refused release must not tear the overlay out from under A", - ); - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .is_some(), - "A's claim must survive B's refused release", - ); - } - - /// `ReleaseOverlayWindow` from a client that never claimed anything, - /// with no claim outstanding anywhere, is `BadMatch` and changes - /// nothing. Xorg answers the same via `compFindOverlayClient`. - #[test] - fn release_overlay_window_with_no_claim_anywhere_is_badmatch() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - - assert_error_code( - &read_all_available(&mut peer), - yserver_protocol::x11::error::BAD_MATCH, - "unpaired ReleaseOverlayWindow", - ); - assert!(state.cow_claims.is_empty()); - assert!( - !backend.cow_materialized, - "a refused release must not touch the backend at all", - ); - } - - /// N Gets need N Releases: Get and Release pair 1:1, as Xorg's - /// per-Get `CompOverlayClientRec` records do. The overlay survives - /// every release but the last. - #[test] - fn repeated_gets_need_matching_releases() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - for seq in 1..=3 { - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - seq, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - } - assert_eq!(state.cow_claims.len(), 3); - - for seq in 4..=5 { - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - seq, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - } - assert_eq!(state.cow_claims.len(), 1); - assert!( - backend.cow_materialized, - "two of three claims released — the overlay must still be up", - ); - let _ = read_all_available(&mut peer); - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 6, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - assert!(state.cow_claims.is_empty()); - assert!( - !backend.cow_materialized, - "the third release is the final one" - ); - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .is_none(), - ); - - // A fourth release has nothing left to pair with. - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 7, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - assert_error_code( - &read_all_available(&mut peer), - yserver_protocol::x11::error::BAD_MATCH, - "one release too many", - ); - } - - /// Two claimants: the first Release is not the final one, so the - /// backend is not called and the overlay stays up for the other - /// claimant. - #[test] - fn two_claimants_first_release_is_not_final() { - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 1); - let _peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - for client in [1u32, 2] { - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(client), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - } - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - - assert_eq!( - state.cow_claims, - vec![ClientId(2)], - "A released exactly its own claim; B's is untouched", - ); - assert!(backend.cow_materialized); - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(2), - 2, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - assert!(state.cow_claims.is_empty()); - assert!(!backend.cow_materialized); - } - - /// Transactional first Get: if materialization fails, the claim is - /// rolled back and the caller gets `BadAlloc`. A claim recorded - /// against an overlay that does not exist is the desynchronisation - /// this model removes. - #[test] - fn first_get_materialization_failure_records_no_claim() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - backend.cow_materialize_fails = true; - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - - assert_error_code( - &read_all_available(&mut peer), - yserver_protocol::x11::error::BAD_ALLOC, - "GetOverlayWindow whose materialization failed", - ); - assert!( - state.cow_claims.is_empty(), - "the claim must be rolled back — never leave one recorded \ - against an overlay that does not exist", - ); - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .is_none(), - ); - - // And the server is not poisoned: a retry that succeeds works. - backend.cow_materialize_fails = false; - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - assert_eq!(state.cow_claims, vec![ClientId(1)]); - assert!(backend.cow_materialized); - } - - /// The headline case, and the bug at its own level: a compositor - /// takes the overlay and **disconnects without releasing**. Its claim - /// must be gone and the overlay torn down. No reset anywhere in this - /// test. - /// - /// Not to be confused with `scene.root_overlay` / - /// `root_overlay_on_disconnect` (`kms/render/backend.rs`), a - /// different concept with a confusingly similar name that - /// `Backend::client_disconnected` already handles correctly — - /// finding that call is what makes this leak look handled. - #[test] - fn disconnect_releases_overlay_claim_and_tears_down_cow() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - assert_eq!(state.cow_claims, vec![ClientId(1)]); - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - - assert!( - state.cow_claims.is_empty(), - "no claim may outlive its owner", - ); - assert!( - !backend.cow_materialized, - "the departing claimant held the last claim — the backend COW \ - must be torn down", - ); - assert!( - state - .resources - .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) - .is_none(), - "the resources-side COW record must come down with it", - ); - } - - /// Repeated Gets from one client, then it disconnects: all of its - /// claims go, matching Xorg's N-records model where the resource - /// system frees every `CompOverlayClientRec` the client owns. - #[test] - fn disconnect_releases_all_of_a_clients_repeated_overlay_claims() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - for seq in 1..=3 { - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - seq, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - } - assert_eq!(state.cow_claims.len(), 3); - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - - assert!(state.cow_claims.is_empty(), "all three claims must go"); - assert!(!backend.cow_materialized); - } - - /// Two claimants: the overlay survives the first departure and comes - /// down on the second. - #[test] - fn overlay_survives_first_claimants_disconnect_and_dies_with_the_second() { - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 1); - let _peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - for client in [1u32, 2] { - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(client), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - } - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - assert_eq!(state.cow_claims, vec![ClientId(2)]); - assert!( - backend.cow_materialized, - "B still holds a claim — the overlay must survive A's departure", - ); - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(2), - ); - assert!(state.cow_claims.is_empty()); - assert!(!backend.cow_materialized); - } - - /// `KillClient` on another client's resource calls - /// `process_disconnect` inline, bypassing - /// `disconnect_with_pending_cleanup`. That is exactly why the claim - /// release lives in `process_disconnect` and not in the funnel. - #[test] - fn kill_client_releases_the_victims_overlay_claim() { - let mut state = ServerState::new(); - let _peer_a = install_client(&mut state, 1); - let _peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - // Client 2 owns a window, so client 1 can name it in KillClient. - let victim_window = ResourceId(0x2000_0001); - state.resources.create_window( - ClientId(2), - CreateWindowRequest { - depth: 24, - window: victim_window, - parent: ROOT_WINDOW, - width: 64, - height: 64, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(2), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - assert_eq!(state.cow_claims, vec![ClientId(2)]); - - handle_kill_client( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - &victim_window.0.to_le_bytes(), - ) - .expect("KillClient"); - - assert!( - !state.clients.contains_key(&2), - "precondition: the victim was force-disconnected", - ); - assert!( - state.cow_claims.is_empty(), - "the killed compositor's claim must go with it — KillClient \ - bypasses disconnect_with_pending_cleanup, so the release has \ - to live in process_disconnect", - ); - assert!(!backend.cow_materialized); - } - - /// A `RetainPermanent` claimant's overlay claims are released anyway - /// when its connection goes. The overlay is a screen-wide singleton; - /// a zombie holding it would block every future compositor. - #[test] - fn retained_clients_overlay_claims_are_released_anyway() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // RetainPermanent. - state.close_down_modes.insert(1, 1); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - - assert!( - state.zombie_clients.contains_key(&1), - "precondition: the client was retained, not destroyed", - ); - assert!( - state.cow_claims.is_empty(), - "a claim is not a retainable resource", - ); - assert!(!backend.cow_materialized); - } - - /// Protocol path, final release, teardown fails: `BadAlloc`, and the - /// caller **keeps** its claim — the release did not happen, so a - /// compositor can retry. Xorg maps allocation failure in this - /// extension to `BadAlloc` (`composite/compext.c:216,220,263,297`), - /// and a shadow-buffer allocation failing is exactly that. - /// - /// The pre-fix handler swallowed the backend `Err` into `false` and - /// reported protocol success for a teardown that did not occur. - #[test] - fn final_release_teardown_failure_is_badalloc_and_keeps_the_claim() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - let _ = read_all_available(&mut peer); - backend.cow_teardown_fails = true; - - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - - assert_error_code( - &read_all_available(&mut peer), - yserver_protocol::x11::error::BAD_ALLOC, - "ReleaseOverlayWindow whose teardown failed", - ); - assert_eq!( - state.cow_claims, - vec![ClientId(1)], - "the caller keeps its claim — the claim is what keeps the \ - overlay alive, so dropping it here is precisely the leak", - ); - assert!(backend.cow_materialized, "the overlay is still up"); - assert!( - !state.cow_teardown_failed, - "the protocol path is retryable: no session-fatal state", - ); - - // And the retry works. - backend.cow_teardown_fails = false; - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 3, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &[], - ); - assert!(state.cow_claims.is_empty()); - assert!(!backend.cow_materialized); - } - - /// Disconnect path, final release, teardown fails: the claims are - /// released **and** `cow_teardown_failed` is set. The two are not - /// alternatives — a leftover claim would be indistinguishable from a - /// live one and the next compositor would wait on a dead client. - /// - /// A later `GetOverlayWindow` from a fresh client is then `BadAlloc`: - /// whatever it would receive is inherited from a session that could - /// not be torn down. - #[test] - fn disconnect_teardown_failure_sets_cow_teardown_failed() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - backend.cow_teardown_fails = true; - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - - assert!( - state.cow_claims.is_empty(), - "no claim outlives its owner, teardown failure or not", - ); - assert!( - state.cow_teardown_failed, - "the orphaned overlay needs an owner that is not a claim", - ); - assert!( - backend.cow_materialized, - "the overlay really is still up — that is the whole problem", - ); - - let _ = read_all_available(&mut peer_b); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(2), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - assert_error_code( - &read_all_available(&mut peer_b), - yserver_protocol::x11::error::BAD_ALLOC, - "GetOverlayWindow under cow_teardown_failed", - ); - assert!( - state.cow_claims.is_empty(), - "the refused Get records no claim", - ); - } - - // ---------------- rotate_redirected_backing_on_resize ---------------- - // - // Marco-with-compositing resizes the top mate-panel from 25 → 28 px - // tall after `RedirectSubwindows(root, Manual)`. The subsequent - // `NameWindowPixmap(panel)` must succeed against fresh storage at - // the new size. Pre-fix v2 returned `NotFound` because the rotate - // path allocated-then-released against an idempotent - // `host_window_to_backing[W]` cache and freed the very pixmap it - // had just chosen to keep. This test pins release-then-allocate - // ORDER — flipping it back would regress the hardware smoke bug. - #[test] - fn rotate_redirected_backing_on_resize_releases_old_then_allocates_new() { - use crate::backend::recording::RecordedCall; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - const OLD_BACKING: u32 = 0x0050_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Install a top-level child of root, then prime it with a - // pretend-existing redirected backing (the state we'd be in - // after `RedirectSubwindows` + activation but before the - // resize). 100x50 → resize target 100x75. - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 32, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), - width: 100, - height: 50, - depth: 32, - }); - } - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - 100, - 75, - false, - 0, - ); - - let calls = backend.calls(); - // RetainBackingStorage comes first to keep OLD's storage - // alive across the release→copy gap (see - // `rotate_redirected_backing_retains_old_storage_across_release_then_drops_after_copy`). - // Release must then precede Allocate so the backend's - // idempotent `host_window_to_backing[W]` lookup misses on - // the subsequent allocate. - assert_eq!( - calls[0], - RecordedCall::RetainBackingStorage(OLD_BACKING), - "step 1 must be RetainBackingStorage on OLD — keeps storage \ - alive across the release→copy gap so the no-alias case \ - doesn't drop the rotate copy", - ); - assert_eq!( - calls[1], - RecordedCall::ReleaseRedirectedBacking(OLD_BACKING), - "step 2 must be ReleaseRedirectedBacking on the OLD backing — \ - release-before-allocate is load-bearing (see fn doc-comment)", - ); - assert_eq!( - calls[2], - RecordedCall::AllocateRedirectedBacking { - host_window: HOST_XID, - width: 100, - height: 75, - depth: 32, - }, - "step 3 must be AllocateRedirectedBacking at the NEW size", - ); - - // Window resource now points at the freshly-allocated backing - // (RecordingBackend hands back fresh handles per allocate). - let backing = state - .resources - .window(ResourceId(WINDOW_XID)) - .and_then(|w| w.redirected_backing) - .expect("redirected_backing repointed after rotate"); - assert_ne!( - backing.host_pixmap.as_raw(), - OLD_BACKING, - "redirected_backing must point at the NEW pixmap, not the old one", - ); - assert_eq!(backing.width, 100); - assert_eq!(backing.height, 75); - assert_eq!(backing.depth, 32); - } - - /// How a GLX-TFP compositor lets go of a named, resized window. - #[derive(Clone, Copy, Debug)] - enum GlxTeardown { - DestroyGlxThenFree, - FreeThenDestroyGlx, - DestroyWindowFirst, - Disconnect, - } - - fn drive( - state: &mut ServerState, - backend: &mut RecordingBackend, - opcode: u8, - data: u8, - body: &[u8], - ) { - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - process_request( - state, - backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode, - data, - length_units, - }, - body, - None, - ) - .expect("process_request"); - } - - /// picom-glx under a WM: NameWindowPixmap + glXCreatePixmap, `resizes` resizes, then teardown. - fn glx_export_ref_after_resizes(resizes: u16, teardown: GlxTeardown) -> RecordingBackend { - use yserver_protocol::x11::glx as x11glx; - const WIN: u32 = 0x0077_0001; - const PIX: u32 = 0x0077_0002; - const GLXPIX: u32 = 0x0077_0003; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new() - .with_composite_support() - .with_redirect_activation(); - let mut cw = Vec::new(); - cw.extend_from_slice(&WIN.to_le_bytes()); - cw.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - cw.extend_from_slice(&[0, 0, 0, 0]); // x, y - cw.extend_from_slice(&100u16.to_le_bytes()); - cw.extend_from_slice(&50u16.to_le_bytes()); - cw.extend_from_slice(&0u16.to_le_bytes()); // border - cw.extend_from_slice(&1u16.to_le_bytes()); // InputOutput - cw.extend_from_slice(&0u32.to_le_bytes()); // CopyFromParent visual - cw.extend_from_slice(&0u32.to_le_bytes()); // no values - drive(&mut state, &mut backend, 1, 0, &cw); - let mut redirect = ROOT_WINDOW.0.to_le_bytes().to_vec(); - redirect.extend_from_slice(&[1, 0, 0, 0]); // Manual - drive( - &mut state, - &mut backend, - 144, - yserver_protocol::x11::composite::REDIRECT_SUBWINDOWS, - &redirect, - ); - drive(&mut state, &mut backend, 8, 0, &WIN.to_le_bytes()); - let mut name = WIN.to_le_bytes().to_vec(); - name.extend_from_slice(&PIX.to_le_bytes()); - drive( - &mut state, - &mut backend, - 144, - yserver_protocol::x11::composite::NAME_WINDOW_PIXMAP, - &name, - ); - let mut glx = Vec::new(); - glx.extend_from_slice(&0u32.to_le_bytes()); // screen - glx.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig - glx.extend_from_slice(&PIX.to_le_bytes()); - glx.extend_from_slice(&GLXPIX.to_le_bytes()); - drive(&mut state, &mut backend, 148, x11glx::CREATE_PIXMAP, &glx); - let first = state - .resources - .pixmap(ResourceId(PIX)) - .and_then(|p| p.host_xid) - .expect("named pixmap") - .as_raw(); - assert_eq!( - backend.glx_pixmap_exports.get(&first), - Some(&1), - "glXCreatePixmap holds one export ref on the named backing", - ); - - for i in 1..=resizes { - let mut cfg = WIN.to_le_bytes().to_vec(); - cfg.extend_from_slice(&0x0cu16.to_le_bytes()); - cfg.extend_from_slice(&0u16.to_le_bytes()); - cfg.extend_from_slice(&u32::from(100 + 10 * i).to_le_bytes()); - cfg.extend_from_slice(&u32::from(50 + 10 * i).to_le_bytes()); - drive(&mut state, &mut backend, 12, 0, &cfg); - let current = state - .resources - .window(ResourceId(WIN)) - .and_then(|w| w.redirected_backing) - .expect("redirected backing") - .host_pixmap - .as_raw(); - assert_ne!(current, first, "resize {i} rotated the backing"); - assert_eq!( - state - .glx_drawables - .get(&GLXPIX) - .and_then(|d| d.glx_export_host_xid), - Some(current), - "resize {i}: the GLX pixmap follows the retargeted alias", - ); - assert_eq!( - backend - .glx_pixmap_exports - .clone() - .into_iter() - .collect::>(), - vec![(current, 1)], - "resize {i}: the export ref lives on the backing the GLX pixmap names", - ); - } - - let destroy_glx = |state: &mut ServerState, backend: &mut RecordingBackend| { - drive( - state, - backend, - 148, - x11glx::DESTROY_PIXMAP, - &GLXPIX.to_le_bytes(), - ); - }; - let free = |state: &mut ServerState, backend: &mut RecordingBackend| { - drive(state, backend, 54, 0, &PIX.to_le_bytes()); - }; - let destroy_win = |state: &mut ServerState, backend: &mut RecordingBackend| { - drive(state, backend, 4, 0, &WIN.to_le_bytes()); - }; - match teardown { - GlxTeardown::DestroyGlxThenFree => { - destroy_glx(&mut state, &mut backend); - free(&mut state, &mut backend); - destroy_win(&mut state, &mut backend); - } - GlxTeardown::FreeThenDestroyGlx => { - free(&mut state, &mut backend); - destroy_glx(&mut state, &mut backend); - destroy_win(&mut state, &mut backend); - } - GlxTeardown::DestroyWindowFirst => { - destroy_win(&mut state, &mut backend); - destroy_glx(&mut state, &mut backend); - free(&mut state, &mut backend); - } - GlxTeardown::Disconnect => { - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(1), - ); - } - } - backend - } - - /// A resize retargets picom's GLX pixmap; the export ref must move with it, or OLD leaks. - #[test] - fn glx_pixmap_export_ref_follows_the_resize_retarget() { - for resizes in [0, 1, 2] { - for teardown in [ - GlxTeardown::DestroyGlxThenFree, - GlxTeardown::FreeThenDestroyGlx, - GlxTeardown::DestroyWindowFirst, - GlxTeardown::Disconnect, - ] { - let backend = glx_export_ref_after_resizes(resizes, teardown); - assert!( - backend.glx_pixmap_exports.is_empty(), - "resizes={resizes} {teardown:?}: export refs left behind: {:?}", - backend.glx_pixmap_exports, - ); - } - } - } - - // compCopyWindow analog: when a redirected window resizes, the - // pre-existing backing's contents must be carried over into the new - // backing for the overlap region — otherwise any compositor that - // re-Names the post-resize backing (marco on mate-panel-top during - // the 25→28-px grow, etc.) samples an empty buffer and the panel - // renders without the icons that were already painted into the old - // backing. Xorg lands this via `compReallocPixmap` (save old - // pixmap) + `compCopyWindow` (copy_area old→new). See - // /home/jos/Projects/xserver/composite/compalloc.c:680-712 and - // compwindow.c:376-388. - #[test] - fn rotate_redirected_backing_on_resize_copies_old_contents_to_new() { - use crate::backend::recording::RecordedCall; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - const OLD_BACKING: u32 = 0x0050_0001; - const OLD_W: u16 = 100; - const OLD_H: u16 = 50; - const NEW_W: u16 = 100; - const NEW_H: u16 = 75; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 32, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: OLD_W, - height: OLD_H, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), - width: OLD_W, - height: OLD_H, - depth: 32, - }); - } - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - NEW_W, - NEW_H, - false, - 0, - ); - - // NEW handle is whatever the RecordingBackend's allocate - // handed back; pull it from the resource state. - let new_backing = state - .resources - .window(ResourceId(WINDOW_XID)) - .and_then(|w| w.redirected_backing) - .expect("redirected_backing repointed after rotate"); - let new_raw = new_backing.host_pixmap.as_raw(); - - let calls = backend.calls(); - // Expected overlap = min(old, new) per dimension. - let expected_w = OLD_W.min(NEW_W); - let expected_h = OLD_H.min(NEW_H); - let copy = calls.iter().find(|c| { - matches!( - c, - RecordedCall::CopyArea { - src_host_xid, - dst_host_xid, - src_x: 0, - src_y: 0, - dst_x: 0, - dst_y: 0, - width, - height, - } if *src_host_xid == OLD_BACKING - && *dst_host_xid == new_raw - && *width == expected_w - && *height == expected_h - ) - }); - assert!( - copy.is_some(), - "expected CopyArea(OLD=0x{OLD_BACKING:x} → NEW=0x{new_raw:x}, \ - src=(0,0), dst=(0,0), {expected_w}x{expected_h}) — \ - missing the compCopyWindow analog that carries pre-resize \ - contents into the freshly-allocated backing. Calls: {calls:?}", - ); - } - - // #143 (rendering half) — a SHRINK must rotate exactly like a grow. - // - // Measured under awesome+picom: switching tiling layout shrank a - // mate-terminal frame (`bw = 2`) from 1278x704 to 1276x704 and the - // render module logged NOTHING — `redirected_backing_can_fit` was a - // high-water-mark test, so the 1282x708 backing was kept and only its - // metadata was rewritten. The backing's ring stayed laid out for the - // OLD 1278-px content (2-px ring at columns 1280..1281) and nothing - // re-seeded it, leaving an alpha-0 band where content should be. - // - // Xorg reallocates on inequality in EITHER direction: - // `compReallocPixmap` (../xserver/composite/compalloc.c:698), whose - // replacement is always freshly seeded from the parent - // (`compNewPixmap`, compalloc.c:539-605). - // - // The backend predicate is where the fix lives (its own unit test is - // `redirected_backing_reuse_requires_the_exact_storage_extent`); - // what this test pins is the core half — that the realloc path - // allocates at the NEW bordered extent and carries only the CONTENT - // overlap, leaving the freshly painted ring of NEW alone. - #[test] - fn rotate_redirected_backing_on_shrink_allocates_the_new_bordered_extent() { - use crate::backend::recording::RecordedCall; - - const BW: u16 = 2; - // Content 1278x704 → backing 1282x708 (the pre-switch state). - const OLD_BACKING_W: u16 = 1282; - const OLD_BACKING_H: u16 = 708; - // Shrink to content 1276x704 → backing 1280x708. - const NEW_CONTENT_W: u16 = 1276; - const NEW_CONTENT_H: u16 = 704; - - let (mut state, mut backend, old_backing) = - redirected_window_fixture(OLD_BACKING_W, OLD_BACKING_H, BW); - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(ROTATE_WINDOW_XID), - NEW_CONTENT_W, - NEW_CONTENT_H, - false, - BW, - ); - - let new_backing = state - .resources - .window(ResourceId(ROTATE_WINDOW_XID)) - .and_then(|w| w.redirected_backing) - .expect("redirected_backing repointed after the shrink rotate"); - assert_ne!( - new_backing.host_pixmap.as_raw(), - old_backing, - "a shrink must rotate onto a FRESH backing, not keep the oversized one", - ); - assert_eq!( - (new_backing.width, new_backing.height), - (1280, 708), - "the new backing is the new BORDERED extent (1276 + 2*2, 704 + 2*2)", - ); - - let calls = backend.calls(); - assert!( - calls.contains(&RecordedCall::AllocateRedirectedBacking { - host_window: ROTATE_HOST_XID, - width: 1280, - height: 708, - depth: 32, - }), - "the shrink must allocate storage at the new bordered extent \ - 1280x708, not keep 1282x708. Calls: {calls:?}", - ); - - // Content-only copy: both backings hold content at `(bw, bw)`, - // and the overlap is min(1278, 1276) x min(704, 704). - let new_raw = new_backing.host_pixmap.as_raw(); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::CopyArea { - src_host_xid, - dst_host_xid, - src_x: 2, - src_y: 2, - dst_x: 2, - dst_y: 2, - width: 1276, - height: 704, - } if *src_host_xid == old_backing && *dst_host_xid == new_raw - )), - "the rotate copy must carry the CONTENT overlap inset by the \ - border width — a full-extent copy would repaint NEW's \ - right/bottom ring columns with OLD's interior pixels. \ - Calls: {calls:?}", - ); - } - - // The over-correction guard for the test above: a bordered GROW must - // keep rotating the way it always did, and its copy is inset the same - // way (the ring of NEW is painted by `allocate_redirected_backing`; - // Xorg repaints it too, via the `compRepaintBorder` work proc queued - // from `compSetPixmap`, ../xserver/composite/compwindow.c:137-139). - #[test] - fn rotate_redirected_backing_on_bordered_grow_still_rotates_and_copies_content() { - use crate::backend::recording::RecordedCall; - - const BW: u16 = 2; - // Content 1276x704 → backing 1280x708, growing to content - // 1278x704 → backing 1282x708. - const OLD_BACKING_W: u16 = 1280; - const OLD_BACKING_H: u16 = 708; - const NEW_CONTENT_W: u16 = 1278; - const NEW_CONTENT_H: u16 = 704; - - let (mut state, mut backend, old_backing) = - redirected_window_fixture(OLD_BACKING_W, OLD_BACKING_H, BW); - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(ROTATE_WINDOW_XID), - NEW_CONTENT_W, - NEW_CONTENT_H, - false, - BW, - ); - - let new_backing = state - .resources - .window(ResourceId(ROTATE_WINDOW_XID)) - .and_then(|w| w.redirected_backing) - .expect("redirected_backing repointed after the grow rotate"); - assert_eq!((new_backing.width, new_backing.height), (1282, 708)); - - let calls = backend.calls(); - assert!( - calls.contains(&RecordedCall::AllocateRedirectedBacking { - host_window: ROTATE_HOST_XID, - width: 1282, - height: 708, - depth: 32, - }), - "the grow must allocate at the new bordered extent. Calls: {calls:?}", - ); - let new_raw = new_backing.host_pixmap.as_raw(); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::CopyArea { - src_host_xid, - dst_host_xid, - src_x: 2, - src_y: 2, - dst_x: 2, - dst_y: 2, - width: 1276, - height: 704, - } if *src_host_xid == old_backing && *dst_host_xid == new_raw - )), - "the grow copy carries the same content overlap, inset by the \ - border width. Calls: {calls:?}", - ); - } - - const ROTATE_WINDOW_XID: u32 = 0x0010_0001; - const ROTATE_HOST_XID: u32 = 0x0040_0001; - - /// A root child already redirected, with a backing whose recorded - /// extent is `(backing_w, backing_h)` — i.e. the post-activation - /// state, before the resize under test. Returns the OLD backing's - /// raw xid alongside the fixture. - fn redirected_window_fixture( - backing_w: u16, - backing_h: u16, - border_width: u16, - ) -> (ServerState, RecordingBackend, u32) { - const OLD_BACKING: u32 = 0x0050_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 32, - window: ResourceId(ROTATE_WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: backing_w.saturating_sub(border_width.saturating_mul(2)), - height: backing_h.saturating_sub(border_width.saturating_mul(2)), - border_width, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(ROTATE_WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - ROTATE_HOST_XID, - )); - w.border_width = border_width; - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), - width: backing_w, - height: backing_h, - depth: 32, - }); - } - (state, backend, OLD_BACKING) - } - - // Storage-alive invariant for the rotate copy. Observed in HW - // smoke (yserver-hw-mate.log 17:28:10Z) that the rotate path - // dropped tiny 1×1 CopyAreas with `copy_area dropped — src - // unknown` whenever OLD had no `NameWindowPixmap` aliases: the - // existing `release_redirected_backing` decref'd alias_registry - // to 0 → `free_pixmap` → store entry gone → `store.lookup(OLD)` - // returned None at the copy site → silent drop. - // - // Fix shape: take a rotate-scoped retain on OLD's storage - // BEFORE the release (so release's decref doesn't hit 0), drop - // it AFTER the copy (frees storage only if no other aliases - // hold it). This test pins the call ordering on - // RecordingBackend; the v2-side alias_registry incref/decref - // semantics are exercised by the v2 backend's own tests. - #[test] - fn rotate_redirected_backing_retains_old_storage_across_release_then_drops_after_copy() { - use crate::backend::recording::RecordedCall; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - const OLD_BACKING: u32 = 0x0050_0001; - const OLD_W: u16 = 1; - const OLD_H: u16 = 1; - const NEW_W: u16 = 1; - const NEW_H: u16 = 1; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 32, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: OLD_W, - height: OLD_H, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), - width: OLD_W, - height: OLD_H, - depth: 32, - }); - } - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - NEW_W, - NEW_H, - true, - 0, - ); - - let calls = backend.calls(); - let retain_idx = calls - .iter() - .position(|c| matches!(c, RecordedCall::RetainBackingStorage(x) if *x == OLD_BACKING)); - let release_idx = calls.iter().position( - |c| matches!(c, RecordedCall::ReleaseRedirectedBacking(x) if *x == OLD_BACKING), - ); - let allocate_idx = calls.iter().position(|c| { - matches!(c, RecordedCall::AllocateRedirectedBacking { host_window, .. } if *host_window == HOST_XID) - }); - let copy_idx = calls.iter().position(|c| { - matches!(c, RecordedCall::CopyArea { src_host_xid, .. } if *src_host_xid == OLD_BACKING) - }); - let drop_idx = calls - .iter() - .position(|c| matches!(c, RecordedCall::DropBackingStorage(x) if *x == OLD_BACKING)); - - let r = retain_idx.expect( - "rotate must retain OLD storage before releasing — otherwise the no-alias \ - case frees storage before copy_area can read it (observed as `copy_area dropped \ - — src unknown` in HW smoke)", - ); - let rel = release_idx.expect("rotate must still release OLD's W→B map slot"); - let a = allocate_idx.expect("rotate must allocate NEW"); - let c = copy_idx.expect("rotate must copy OLD→NEW"); - let d = drop_idx.expect( - "rotate must drop the retain after copy — leaving storage alive forever \ - would leak the backing across every resize", - ); - - assert!( - r < rel, - "Retain(idx={r}) must precede Release(idx={rel}) — release's decref would \ - otherwise hit refcount=0 and free OLD's storage before copy. Calls: {calls:?}", - ); - assert!( - rel < a, - "Release(idx={rel}) must precede Allocate(idx={a}) — host_window_to_backing[W] \ - idempotency would otherwise return OLD instead of allocating fresh. Calls: {calls:?}", - ); - assert!( - a < c, - "Allocate(idx={a}) must precede Copy(idx={c}) — copy needs NEW as destination. \ - Calls: {calls:?}", - ); - assert!( - c < d, - "Copy(idx={c}) must precede Drop(idx={d}) — dropping the retain before the copy \ - defeats the purpose of taking it. Calls: {calls:?}", - ); - } - - #[test] - fn rotate_redirected_backing_on_move_forces_reallocate_even_when_size_matches() { - use crate::backend::recording::RecordedCall; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - const OLD_BACKING: u32 = 0x0050_0001; - const W: u16 = 100; - const H: u16 = 50; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 32, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: W, - height: H, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), - width: W, - height: H, - depth: 32, - }); - } - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - W, - H, - true, - 0, - ); - - let calls = backend.calls(); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::ReleaseRedirectedBacking(x) if *x == OLD_BACKING - )), - "forced move-rotate must release OLD even when size matches; got {calls:?}", - ); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::AllocateRedirectedBacking { - host_window, - width, - height, - depth: 32, - } if *host_window == HOST_XID && *width == W && *height == H - )), - "forced move-rotate must allocate a fresh backing at the same size; got {calls:?}", - ); - let new_backing = state - .resources - .window(ResourceId(WINDOW_XID)) - .and_then(|w| w.redirected_backing) - .expect("redirected_backing repointed after forced rotate"); - assert_ne!( - new_backing.host_pixmap.as_raw(), - OLD_BACKING, - "forced move-rotate must repoint to a fresh backing even at identical size", - ); - } - - /// Manual-mode redirect removes W from the normal scene and keeps - /// B as an off-screen compositor source. B must not become a scene - /// participant, or the scene path can double-present redirected - /// client content behind/above the compositor's output surface. - #[test] - fn manual_redirect_keeps_window_out_of_scene() { - use crate::backend::recording::RecordedCall; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Install a top-level child of root (the soon-to-be-Manual- - // redirected window). Use real CreateWindow flow so the - // resource record carries width/height/depth that - // `activate_redirect_backing_for` snapshots. - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - // Viewable: Xorg allocates a redirect backing only for a realized window. - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - state.composite_redirects.insert( - (ResourceId(WINDOW_XID), false), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: yserver_protocol::x11::ClientId(1), - }, - ); - - activate_redirect_backing_for( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - crate::server::CompositeRedirectMode::Manual, - ); - - // Window participation: Manual → false (the external - // compositor owns the window's presentation). The paired - // assertion that B *is* scene-participating lives in - // `manual_redirect_marks_backing_scene_participating_so_paints_emit_damage`. - let calls = backend.calls(); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::SetWindowSceneParticipation { - host_window, - participating: false, - } if *host_window == HOST_XID - )), - "expected SetWindowSceneParticipation(W, false) for Manual mode; got {calls:?}", - ); - // Positive control for the COW guard - // (`activate_redirect_on_cow_is_never_applied`): a NORMAL window - // DOES receive a redirect backing. This proves the COW guard is - // overlay-window-specific, not a blanket disable of - // `activate_redirect_backing_for`. - assert!( - state - .resources - .window(ResourceId(WINDOW_XID)) - .expect("window exists") - .redirected_backing - .is_some(), - "a normal window must receive a redirect backing", - ); - } - - /// Xorg `compCheckRedirect` (`composite/compwindow.c:156-170`) forces - /// `should = FALSE` for `pWin == cs->pOverlayWin`: the overlay window - /// is NEVER actually redirected, regardless of trigger. Since Phase 2 - /// made the COW a real child of root, a compositor's - /// `CompositeRedirectSubwindows(root, Manual)` (mutter / cinnamon-mutter - /// all issue it) drives `activate_redirect_backing_for` once per root - /// child — including the COW. Without the guard the COW gets a Manual - /// backing + `scene_participating=false`, and the Phase 3 Manual-skip - /// drops the whole composited desktop from scanout (blank desktop, - /// observed bee/cinnamon-mutter 2026-06-09). The COW must keep its - /// `redirected_backing` empty and its scene participation untouched. - #[test] - fn activate_redirect_on_cow_is_never_applied() { - use crate::backend::recording::RecordedCall; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Materialize the COW exactly as the `GetOverlayWindow` 0->1 - // claim does (host xid == COMPOSITE_OVERLAY_WINDOW.0 for the - // RecordingBackend / v2 path, per the dispatch handler). - let cow_host = crate::backend::WindowHandle::from_raw_panicking(COMPOSITE_OVERLAY_WINDOW.0); - state.resources.materialize_cow_resource(cow_host); - - // This is the call `RedirectSubwindows(root, Manual)`'s child - // loop makes for every child of root — the COW included. - activate_redirect_backing_for( - &mut state, - &mut backend, - None, - COMPOSITE_OVERLAY_WINDOW, - crate::server::CompositeRedirectMode::Manual, - ); - - let cow = state - .resources - .window(COMPOSITE_OVERLAY_WINDOW) - .expect("COW exists"); - assert!( - cow.redirected_backing.is_none(), - "COW must never receive a redirect backing \ - (compCheckRedirect: should=FALSE for pOverlayWin)", - ); - // And no scene-participation flip was recorded for the COW host — - // the Phase 3 Manual-skip is driven off this flag. - let calls = backend.calls(); - assert!( - !calls.iter().any(|c| matches!( - c, - RecordedCall::SetWindowSceneParticipation { host_window, .. } - if *host_window == COMPOSITE_OVERLAY_WINDOW.0 - )), - "COW scene participation must not be flipped by redirect activation; got {calls:?}", - ); - } - - /// Manual-redirected backing must have scene_participating=true so - /// the v2 scene's damage harvest sees paints into it. - /// - /// Post-`6ffd370` the scene walk emits the Manual-redirected window - /// at its own coords but samples storage from the backing via - /// `redirected_target` indirection. `store.damage()` is gated on - /// the *target's* `scene_participating` — if the backing is marked - /// non-participating, every paint into it silently drops its scene - /// damage. Buffer-age clipped compose then never repaints the - /// affected region, and the BO retains whatever was in it the last - /// time it was flipped. Symptom: window content invisible except - /// where cursor damage happens to overlap the window's rect. - #[test] - fn manual_redirect_marks_backing_scene_participating_so_paints_emit_damage() { - use crate::backend::recording::RecordedCall; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - // Viewable: Xorg allocates a redirect backing only for a realized window. - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - state.composite_redirects.insert( - (ResourceId(WINDOW_XID), false), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: yserver_protocol::x11::ClientId(1), - }, - ); - - activate_redirect_backing_for( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - crate::server::CompositeRedirectMode::Manual, - ); - - let calls = backend.calls(); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::SetBackingSceneParticipation { - participating: true, - .. - } - )), - "expected SetBackingSceneParticipation(B, true) for Manual mode so the \ - scene's redirected_target damage-peek sees paints; got {calls:?}", - ); - } - - /// Redirecting an already-mapped window must emit one initial full - /// DamageNotify wakeup so a compositor that subscribes after map - /// can pull the seeded backing into the COW immediately. Without - /// this, the backing contains the correct pixels but the COW keeps - /// showing the root/background until some unrelated later event - /// (click, move, resize) dirties the window. - #[test] - fn activate_redirect_on_mapped_window_emits_initial_damage() { - use crate::server::{DamageObject, RedirectRecord}; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0010; - const HOST_XID: u32 = 0x0040_0010; - const DAMAGE_XID: u32 = 0x0010_0011; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - state.composite_redirects.insert( - (ResourceId(WINDOW_XID), false), - RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: yserver_protocol::x11::ClientId(CLIENT_ID), - }, - ); - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(CLIENT_ID), - drawable: ResourceId(WINDOW_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - activate_redirect_backing_for( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - crate::server::CompositeRedirectMode::Manual, - ); - - let damage = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object after redirect activation"); - assert!( - !damage.rects.is_empty(), - "redirect activation on an already-mapped window must emit an initial \ - full damage wakeup so compositors pull the seeded backing immediately", - ); - } - - /// A compositor subscribes to DAMAGE on the `NameWindowPixmap` - /// pixmap, not the original window. That pixmap must receive the - /// same initial seed as a plain viewable window, otherwise the - /// first composite after redirect can stay blank until some later - /// client paint lands. - #[test] - fn damage_create_on_named_pixmap_alias_seeds_initial_damage() { - use yserver_protocol::x11::damage as x11damage; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0012; - const HOST_WINDOW_XID: u32 = 0x0040_0012; - const PIXMAP_XID: u32 = 0x0020_0012; - const DAMAGE_ID: u32 = 0x0080_0012; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - HOST_WINDOW_XID, - )); - w.map_state = crate::resources::MapState::Viewable; - } - activate_redirect_backing_for( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - crate::server::CompositeRedirectMode::Manual, - ); - let host_pixmap = state - .resources - .window(ResourceId(WINDOW_XID)) - .and_then(|w| w.redirected_backing.as_ref()) - .map(|b| b.host_pixmap) - .expect("redirected backing"); - state.resources.create_pixmap( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreatePixmapRequest { - pixmap: ResourceId(PIXMAP_XID), - drawable: ResourceId(WINDOW_XID), - width: 100, - height: 50, - depth: 24, - }, - ); - let _ = state - .resources - .set_pixmap_host_xid(ResourceId(PIXMAP_XID), host_pixmap); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.composite_named_pixmaps - .push(crate::resources::NamedCompositePixmap { - client_pixmap: ResourceId(PIXMAP_XID), - host_pixmap, - width: 100, - height: 50, - }); - } - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&DAMAGE_ID.to_le_bytes()); - body.extend_from_slice(&PIXMAP_XID.to_le_bytes()); - body.push(x11damage::report_level::NON_EMPTY); - body.extend_from_slice(&[0, 0, 0]); - - let header = RequestHeader { - opcode: 0, - data: x11damage::CREATE, - length_units: 0, - }; - handle_damage_request( - &mut state, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("damage create handled"); - - let damage = state - .damage_objects - .get(&DAMAGE_ID) - .expect("damage object created"); - assert!( - !damage.rects.is_empty(), - "creating DAMAGE on a named pixmap alias of a viewable window must seed \ - initial damage so picom sees the current backing immediately", - ); - } - - /// Mapping a Manual-redirected window must not leave it visible - /// in the normal scene. The map path temporarily flips the - /// storage on, then the redirect-mode reapply must force it back - /// off. - #[test] - fn map_window_reapplies_manual_redirect_scene_participation() { - use crate::backend::recording::RecordedCall; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0002; - const HOST_XID: u32 = 0x0040_0002; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - state.composite_redirects.insert( - (ResourceId(WINDOW_XID), false), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: yserver_protocol::x11::ClientId(CLIENT_ID), - }, - ); - - activate_redirect_backing_for( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - crate::server::CompositeRedirectMode::Manual, - ); - let before = backend.calls().len(); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window"); - - let calls = &backend.calls()[before..]; - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::SetWindowSceneParticipation { - host_window, - participating: false, - } if *host_window == HOST_XID - )), - "mapping a Manual-redirected window must reassert scene_participating=false; got {calls:?}", - ); - assert!( - !calls.iter().any(|c| matches!( - c, - RecordedCall::SetWindowSceneParticipation { - host_window, - participating: true, - } if *host_window == HOST_XID - )), - "mapping a Manual-redirected window must not leave it scene_participating=true; got {calls:?}", - ); - } - - /// Audit #11 regression — when a window maps, server-background - /// paint fills the window's storage but no `DamageNotify` fires - /// for the affected region. Compositors that subscribe to - /// `XDamageCreate(window)` (marco-with-compositing, picom) miss - /// the first frame and the window stays invisible on COW until - /// the next paint into it. Symptom: override-redirect popup - /// menus, mate-panel system-tray icons (`nm-applet`) don't show - /// when a compositor is active and v2 routes the visible output - /// through `Present::Pixmap → COW`. - /// - /// Oracle: a `DamageObject` subscribed to a freshly-created - /// window must accumulate damage rects covering the window's - /// full extent after `handle_map_window` returns. - #[test] - fn map_window_emits_damage_on_window_extent() { - use crate::server::DamageObject; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0010; - const HOST_XID: u32 = 0x0040_0010; - const DAMAGE_ID: u32 = 0x0080_0010; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - - // Compositor subscribes via `XDamageCreate(window)`. Pin the - // pre-state explicitly: no rects accumulated yet. - state.damage_objects.insert( - DAMAGE_ID, - DamageObject { - owner: ClientId(CLIENT_ID), - drawable: ResourceId(WINDOW_XID), - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window"); - - let damage = state - .damage_objects - .get(&DAMAGE_ID) - .expect("damage_object survived map"); - assert!( - !damage.rects.is_empty(), - "MapWindow must fire damage on the window's extent so a \ - subscribed compositor repaints the new region into its \ - offscreen — pre-fix this is empty and the compositor \ - never sees the newly-mapped popup / tray icon / window", - ); - } - - /// Per X11 protocol spec: "If the window is already mapped, this - /// request has no effect." brisk-menu (Ubuntu MATE's standalone - /// applications popup) pounds `MapWindow` at ~50 Hz on its - /// already-viewable override-redirect popup via GTK3's - /// `gtk_window_present`/`XMapRaised` loop. Pre-fix every redundant - /// MapWindow re-emitted MapNotify → Expose → full-extent damage, - /// triggering Marco to issue `COMPOSITE::NameWindowPixmap` and a - /// full recomposite of the popup ~50× per second — visible as - /// menu flicker on the COW-authoritative KMS scene path. - #[test] - fn map_window_on_already_mapped_window_is_no_op() { - use crate::server::DamageObject; - use std::io::Read; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0014; - const HOST_XID: u32 = 0x0040_0014; - const DAMAGE_ID: u32 = 0x0080_0014; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - - // Marco-like subscriber: SubstructureNotify on root + - // XDamageCreate on the new window. - state - .clients - .get_mut(&CLIENT_ID) - .unwrap() - .event_masks - .insert(ROOT_WINDOW, 0x0008_0000); - state.damage_objects.insert( - DAMAGE_ID, - DamageObject { - owner: ClientId(CLIENT_ID), - drawable: ResourceId(WINDOW_XID), - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - - // First map: genuine transition Unmapped → Viewable. Should - // emit MapNotify + accumulate damage. - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window first"); - - peer.set_nonblocking(true).unwrap(); - let mut tmp = [0u8; 1024]; - let mut first_wire = Vec::new(); - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => first_wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - let first_map_notifies = first_wire - .chunks_exact(32) - .filter(|chunk| chunk[0] & 0x7f == 19) - .count(); - assert!( - first_map_notifies >= 1, - "first MapWindow on an unmapped window must emit MapNotify", - ); - let first_rect_count = state - .damage_objects - .get(&DAMAGE_ID) - .expect("damage object") - .rects - .len(); - assert!( - first_rect_count > 0, - "first MapWindow must accumulate damage on the window extent", - ); - - // Second map on the now-already-Viewable window. Per spec this - // is a no-op: no MapNotify, no extra damage rects. - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(2), - &body, - ) - .expect("handle_map_window second"); - - let mut second_wire = Vec::new(); - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => second_wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - let second_map_notifies = second_wire - .chunks_exact(32) - .filter(|chunk| chunk[0] & 0x7f == 19) - .count(); - assert_eq!( - second_map_notifies, 0, - "MapWindow on an already-mapped window must NOT re-emit \ - MapNotify — repeated MapNotifies cause Marco to re-issue \ - COMPOSITE::NameWindowPixmap and full recomposite on every \ - redundant map (visible as brisk-menu flicker on KMS).", - ); - let second_rect_count = state - .damage_objects - .get(&DAMAGE_ID) - .expect("damage object") - .rects - .len(); - assert_eq!( - second_rect_count, first_rect_count, - "MapWindow on an already-mapped window must NOT accumulate \ - additional damage — full-extent damage on every redundant \ - call is what drives the recompositing flicker storm.", - ); - } - - /// Per X11 protocol (Xorg `dix/window.c:2661`): `if (pWin->mapped) - /// return Success;` — `MapWindow` on an already-mapped window is a - /// no-op BEFORE any MapRequest dispatch. The root window is always - /// mapped (initialised `Viewable` at `resources.rs:204`) AND in - /// yserver root's `parent` field points to itself - /// (`resources.rs:194`), so a client calling `MapWindow(root)` - /// pre-fix matched the SubstructureRedirect-on-parent path: the - /// requester wasn't the WM, marco had SubstructureRedirect - /// (`0x0010_0000`) on root, so yserver dispatched a phantom - /// MapRequest event with `parent=root, window=root` to marco. - /// Marco's response (seen on hardware via xtrace seq `0x35e5a` - /// during a mate-screensaver activation): GrabServer → - /// ChangeWindowAttributes(root, event_mask=...) DROPPING - /// SubstructureNotify+SubstructureRedirect → UngrabServer. After - /// that marco no longer receives MapNotify for new top-levels → - /// no `COMPOSITE::NameWindowPixmap` → newly-mapped windows - /// (mate-screensaver overlay, dialogs) are invisible while the - /// cursor still moves. Match Xorg: hoist the "already mapped" - /// short-circuit above the MapRequest emission. - #[test] - fn map_window_on_root_does_not_emit_phantom_map_request() { - use std::io::Read; - - const WM_ID: u32 = 1; - const SAVER_ID: u32 = 2; - - let mut state = ServerState::new(); - let mut wm_peer = install_client(&mut state, WM_ID); - let _saver_peer = install_client(&mut state, SAVER_ID); - let mut backend = RecordingBackend::new(); - - // Marco-like WM: SubstructureRedirect (0x0010_0000) on root. - state - .clients - .get_mut(&WM_ID) - .unwrap() - .event_masks - .insert(ROOT_WINDOW, 0x0010_0000); - - // mate-screensaver-like activation: client 2 calls - // `MapWindow(root)`. Per X11 spec this must be a silent - // no-op (root is always mapped). - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(SAVER_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window root"); - - wm_peer.set_nonblocking(true).unwrap(); - let mut tmp = [0u8; 1024]; - let mut wm_wire = Vec::new(); - loop { - match wm_peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wm_wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - let map_requests = wm_wire - .chunks_exact(32) - .filter(|chunk| chunk[0] & 0x7f == 20) - .count(); - assert_eq!( - map_requests, 0, - "MapWindow(root) must NOT generate a phantom MapRequest \ - event to the WM. Pre-fix yserver dispatched a bogus \ - MapRequest(parent=root, window=root) because root's parent \ - field points to itself; marco reacted by dropping its \ - SubstructureRedirect subscription, which broke compositing \ - of every subsequent top-level (mate-screensaver overlay \ - and dialogs went invisible while cursor still moved).", - ); - } - - /// Per X11 protocol: `cursor = None` (resource id 0) on - /// ChangeWindowAttributes(CWCursor) means "clear this window's - /// cursor so the effective cursor inherits from the parent - /// chain". Pre-fix the handler short-circuited because - /// `resources.cursor_host_xid(ResourceId(0))` returns `None` and - /// the `(Some, Some)` match below dropped the call — marco - /// resets its frame's cursor via `XDefineCursor(frame, None)` - /// when the pointer moves off the resize edge into the frame - /// interior, and that reset never propagated to the backend - /// (resize cursor sprite stayed visible until the pointer left - /// the top-level frame entirely). Matches Xorg - /// `dix/window.c:1487-1491`. - #[test] - fn cwa_cursor_none_propagates_define_cursor_zero_to_backend() { - use crate::backend::recording::RecordedCall; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0020; - const HOST_XID: u32 = 0x0040_0020; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - - // CWA body: window xid (4) + value_mask (4) + values. - // CWCursor is bit 14 (mask = 0x4000); value = 0 means - // X11 None. - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body.extend_from_slice(&0x4000u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - - handle_change_window_attributes( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_change_window_attributes"); - - let define_cursor_calls: Vec<_> = backend - .calls() - .into_iter() - .filter(|c| matches!(c, RecordedCall::DefineCursor { .. })) - .collect(); - assert_eq!( - define_cursor_calls, - vec![RecordedCall::DefineCursor { - host_window_xid: HOST_XID, - cursor_host_xid: 0, - }], - "CWA with CWCursor + value=0 must invoke \ - `backend.define_cursor(window, 0)` so the backend clears \ - its per-window cursor slot and refreshes the effective \ - cursor. Pre-fix this dropped silently, leaving stale \ - cursor state (marco's resize-frame XDefineCursor(frame, \ - None) reset on edge→interior transitions had no effect).", - ); - } - - /// A `ChangeWindowAttributes` that only changes the cursor (or any - /// other non-event-mask attribute) must NOT move the input focus. - /// In X11 focus changes only via `SetInputFocus` / grabs, never CWA. - /// - /// Regression (the evince / GTK4 titlebar-drag freeze): during a - /// `_NET_WM_MOVERESIZE` move, muffin sets the "fleur" move cursor on - /// its guard window via a cursor-only CWA. The handler promoted - /// keyboard focus to any "focus-wanting" (viewable + key-selecting) - /// window on *any* CWA, so focus was stolen to the guard window. The - /// app's next `SetInputFocus` to its own child was then computed from - /// that unrelated prev focus -> `FocusOut(detail=Nonlinear)` -> GTK4 - /// backdrop (greyed CSD buttons) and the drag collapsed. - #[test] - fn cursor_only_cwa_does_not_steal_keyboard_focus() { - const CLIENT_ID: u32 = 1; - const GUARD_XID: u32 = 0x0010_0011; // muffin's guard window - const FOCUSED_XID: u32 = 0x0010_0007; // the real focus window - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - for xid in [GUARD_XID, FOCUSED_XID] { - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(xid)); - } - // Guard window is viewable and selects key events, so - // `window_wants_keyboard_focus` would return true for it. - state - .clients - .get_mut(&CLIENT_ID) - .expect("client") - .event_masks - .insert(ResourceId(GUARD_XID), 0x1); // KeyPress - - // Establish the real focus on FOCUSED_XID before the CWA. - state.core_focus.raw = FOCUSED_XID; - for c in state.clients.values_mut() { - c.focused_window = ResourceId(FOCUSED_XID); - } - - // Cursor-only CWA on the guard window: CWCursor (bit 14 = - // 0x4000), value 0 = None. No event-mask change. - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&GUARD_XID.to_le_bytes()); - body.extend_from_slice(&0x4000u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - - handle_change_window_attributes( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_change_window_attributes"); - - assert_eq!( - state - .clients - .get(&CLIENT_ID) - .expect("client") - .focused_window, - ResourceId(FOCUSED_XID), - "a cursor-only ChangeWindowAttributes must not promote keyboard \ - focus to the target window; focus must stay where SetInputFocus \ - put it", - ); - } - - /// GTK4 (gnome-text-editor, modern GTK apps) sets per-widget - /// cursors through XInput2's `XIChangeCursor` (opcode 42), not - /// core X11's `XDefineCursor`. Pre-fix the handler was a logging - /// no-op, so the I-beam cursor over a text widget never reached - /// the backend and the area kept showing the default arrow. - /// Treat it as `XDefineCursor` (per-device cursors aren't routed - /// yet; a single effective cursor on the window matches what - /// `AllMasterDevices`-style calls produce in practice). - #[test] - fn xi_change_cursor_propagates_define_cursor_to_backend() { - use crate::backend::recording::RecordedCall; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0030; - const HOST_XID: u32 = 0x0040_0030; - const CURSOR_XID: u32 = 0x0090_0001; - const CURSOR_HOST_XID: u32 = 0x00a0_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - state - .resources - .create_cursor(ClientId(CLIENT_ID), ResourceId(CURSOR_XID)); - state.resources.set_cursor_host_xid( - ResourceId(CURSOR_XID), - crate::backend::CursorHandle::from_raw_panicking(CURSOR_HOST_XID), - ); - - // XIChangeCursor body: window(4), cursor(4), deviceid(2), pad(2). - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body.extend_from_slice(&CURSOR_XID.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, // doesn't matter — dispatcher is bypassed - data: 42, // XIChangeCursor minor - // XIChangeCursor is Fixed(4): 4 header + window(4) + cursor(4) - // + deviceid(2) + pad(2) = 16 bytes = 4 units. (Was 3 — pre- - // dated the length gate, now BadLengths before the handler.) - length_units: 4, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("handle_xi2_request"); - - let define_cursor_calls: Vec<_> = backend - .calls() - .into_iter() - .filter(|c| matches!(c, RecordedCall::DefineCursor { .. })) - .collect(); - assert_eq!( - define_cursor_calls, - vec![RecordedCall::DefineCursor { - host_window_xid: HOST_XID, - cursor_host_xid: CURSOR_HOST_XID, - }], - "XIChangeCursor must propagate to `backend.define_cursor` \ - so GTK4's per-widget cursor (I-beam on text areas, etc.) \ - becomes effective. Pre-fix the handler was a logging \ - no-op — gnome-text-editor and other GTK4 apps kept the \ - default arrow over text widgets.", - ); - - // cursor = None (xid 0) clears the per-window cursor. - let mut body_none = Vec::with_capacity(12); - body_none.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body_none.extend_from_slice(&0u32.to_le_bytes()); - body_none.extend_from_slice(&0u16.to_le_bytes()); - body_none.extend_from_slice(&[0u8; 2]); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(2), - header, - &body_none, - ) - .expect("handle_xi2_request none"); - - let define_cursor_calls: Vec<_> = backend - .calls() - .into_iter() - .filter(|c| matches!(c, RecordedCall::DefineCursor { .. })) - .collect(); - assert_eq!( - define_cursor_calls, - vec![ - RecordedCall::DefineCursor { - host_window_xid: HOST_XID, - cursor_host_xid: CURSOR_HOST_XID, - }, - RecordedCall::DefineCursor { - host_window_xid: HOST_XID, - cursor_host_xid: 0, - }, - ], - "XIChangeCursor with cursor=None (xid 0) must invoke \ - `backend.define_cursor(window, 0)` — same X11 None \ - semantics as the CWA cursor path.", - ); - } - - /// `XIGrabDevice` must wire into the existing core X11 grab - /// state (`state.active_pointer_grab` for - /// the master pointer, `state.active_keyboard_grab` for the - /// master keyboard) so the pointer/key fanout's - /// `active_grab_target` routing kicks in. Pre-fix the handler - /// was a no-op that just sent Success — GTK thought it owned - /// the device but events still went to whatever window the - /// pointer was over, so popups dismissed on the first stray - /// motion and `gtk_window_present` looped re-mapping at ~50 Hz. - #[test] - fn xi_grab_device_sets_active_grab_state() { - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0050; - const CURSOR_XID: u32 = 0x0090_0050; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - // Pointer grab (deviceid=2) — XIGrabDevice body: window(4) - // time(4) cursor(4) deviceid(2) mode(1) paired(1) - // owner_events(1) pad(1) mask_len(2) ... - let mut body = Vec::with_capacity(24); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); // window - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&CURSOR_XID.to_le_bytes()); // cursor - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid (pointer) - body.extend_from_slice(&[1, 1, 1, 0]); // mode async, paired async, owner_events=1, pad - body.extend_from_slice(&0u16.to_le_bytes()); // mask_len - body.extend_from_slice(&[0u8; 2]); // pad - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, // XIGrabDevice - length_units: 7, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("XIGrabDevice pointer"); - - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(CLIENT_ID), ResourceId(WINDOW_XID))), - "XIGrabDevice(pointer) must set active_pointer_grab so \ - pointer_fanout's active_grab_target redirect kicks in", - ); - assert!(state.active_pointer_grab.is_some_and(|grab| !grab.passive)); - let active = state.active_pointer_grab.expect("active_pointer_grab set"); - assert_eq!(active.owner, ClientId(CLIENT_ID)); - assert_eq!(active.grab_window, ResourceId(WINDOW_XID)); - assert_eq!(active.cursor, ResourceId(CURSOR_XID)); - - // Keyboard grab (deviceid=3) — same wire format. - let mut body_kbd = Vec::with_capacity(24); - body_kbd.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body_kbd.extend_from_slice(&0u32.to_le_bytes()); - body_kbd.extend_from_slice(&0u32.to_le_bytes()); - body_kbd.extend_from_slice(&3u16.to_le_bytes()); // keyboard - body_kbd.extend_from_slice(&[1, 1, 1, 0]); - body_kbd.extend_from_slice(&0u16.to_le_bytes()); - body_kbd.extend_from_slice(&[0u8; 2]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(2), - header, - &body_kbd, - ) - .expect("XIGrabDevice keyboard"); - let kgrab = state - .active_keyboard_grab - .expect("active_keyboard_grab set"); - assert_eq!(kgrab.owner, ClientId(CLIENT_ID)); - assert_eq!(kgrab.grab_window, ResourceId(WINDOW_XID)); - - // Ungrab both — XIUngrabDevice body: time(4) deviceid(2) pad(2). - let ungrab_header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 52, - // XIUngrabDevice is Fixed(3): 4 header + time(4) + deviceid(2) - // + pad(2) = 12 bytes = 3 units. (Was 2 — pre-dated the - // XTS-driven REQUEST_SIZE_MATCH length gate, so the malformed - // length slipped through; master now correctly BadLengths it.) - length_units: 3, - }; - let mut ungrab_p = Vec::with_capacity(8); - ungrab_p.extend_from_slice(&0u32.to_le_bytes()); // time - ungrab_p.extend_from_slice(&2u16.to_le_bytes()); // pointer - ungrab_p.extend_from_slice(&[0u8; 2]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(3), - ungrab_header, - &ungrab_p, - ) - .expect("XIUngrabDevice pointer"); - assert!(state.active_pointer_grab.is_none()); - - let mut ungrab_k = Vec::with_capacity(8); - ungrab_k.extend_from_slice(&0u32.to_le_bytes()); - ungrab_k.extend_from_slice(&3u16.to_le_bytes()); - ungrab_k.extend_from_slice(&[0u8; 2]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(4), - ungrab_header, - &ungrab_k, - ) - .expect("XIUngrabDevice keyboard"); - assert!( - state.active_keyboard_grab.is_none(), - "keyboard grab cleared" - ); - } - - /// On `XIGrabDevice` activation, Xorg synthesises an XI2 crossing - /// event (`XI_Enter`(7) for pointer / `XI_FocusIn`(9) for keyboard) - /// with `mode=NotifyGrab`(1) and `detail=NotifyNonlinear`(3) and - /// delivers it to the grab requester. Without these events, GTK3 - /// popup state machines never engage their hover/click tracking — - /// the menu is visible but items don't highlight or activate. - /// Captured in `mate-xorg.xtrace` (Xi/exevents.c::ActivatePointer - /// Grab / ActivateKeyboardGrab). On `XIUngrabDevice` the symmetric - /// `mode=NotifyUngrab`(2) crossings fire. - #[test] - fn xi_grab_device_emits_grab_activation_crossings() { - use std::io::Read; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0060; - const HOST_XID: u32 = 0x0040_0060; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 100, - y: 200, - width: 300, - height: 200, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - - // XIGrabDevice pointer. - let mut body = Vec::with_capacity(24); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.extend_from_slice(&[1, 1, 1, 0]); - body.extend_from_slice(&0u16.to_le_bytes()); // mask_len - body.extend_from_slice(&[0u8; 2]); - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 7, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("XIGrabDevice"); - - // Drain wire and look for the synthesised XI2 Enter event: - // byte 0: 35 (GenericEvent) - // byte 1: 137 (XInputExtension major) - // bytes 8-9: evtype = 7 (XI_Enter) - // byte 18: mode = 1 (NotifyGrab) - // byte 19: detail = 0 (NotifyAncestor — sprite is the ancestor) - peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 4096]; - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - // Wire contains both the 32-byte XIGrabDevice reply and the - // synthesised XI2 GenericEvent (76 bytes). Order may vary — - // scan for the GenericEvent signature: type=35, major=137, - // evtype=7 (XI_Enter). - let crossing_offset = (0..wire.len().saturating_sub(76)) - .find(|&i| { - wire[i] == 35 - && wire[i + 1] == 137 - && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 7 - }) - .unwrap_or_else(|| { - panic!( - "no XI_Enter GenericEvent found in {} wire bytes: {:?}", - wire.len(), - &wire[..wire.len().min(140)], - ) - }); - let crossing = &wire[crossing_offset..crossing_offset + 76]; - // Crossing event byte layout (from encode_xi2_crossing_event): - // 0:type=35, 1:major, 2..4:seq, 4..8:length, 8..10:evtype, - // 10..12:deviceid, 12..16:time, 16..18:sourceid, 18:mode, - // 19:detail, 20..24:root, 24..28:event, ... - assert_eq!(crossing[18], 1, "mode = NotifyGrab"); - // The sprite (pointer at (0,0)) is in root, an ancestor of the - // grab window — Xorg's `DeviceEnterLeaveEvents` IsParent(from,to) - // branch emits `XI_Enter(NotifyAncestor)` on the grab window - // (preceded by `XI_Leave(NotifyInferior)` on root). NotifyAncestor - // = 0. (Pre-fix this was a hardcoded NotifyNonlinear = 3.) - assert_eq!(crossing[19], 0, "detail = NotifyAncestor"); - let event_window = - u32::from_le_bytes([crossing[24], crossing[25], crossing[26], crossing[27]]); - assert_eq!(event_window, WINDOW_XID); - - // The activation chain also leaves the ancestor (root) the - // sprite was in: an `XI_Leave(NotifyInferior)` precedes the Enter. - let leave = (0..wire.len().saturating_sub(28)).find(|&i| { - wire[i] == 35 - && wire[i + 1] == 137 - && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 8 - }); - let leave = leave.expect("XI_Leave on the ancestor (root) must precede the Enter"); - let leave = &wire[leave..leave + 28]; - assert_eq!(leave[19], 2, "Leave detail = NotifyInferior"); - let leave_window = u32::from_le_bytes([leave[24], leave[25], leave[26], leave[27]]); - assert_eq!(leave_window, ROOT_WINDOW.0, "Leave is on the root ancestor"); - } - - /// XIGrabDevice whose `grab_window` is the very window the pointer - /// already sits in must emit NO pointer crossing — Xorg's - /// `DoEnterLeaveEvents` early-returns when `fromWin == toWin` - /// (dix/enterleave.c). mutter/muffin grabs its own full-screen - /// clutter stage on every button press; the pre-fix code emitted an - /// unconditional `XI_Enter(NotifyGrab)` on the grab window, which - /// desynced cinnamon's XEmbed-systray click-forward state machine — - /// pamac's tray icon became unclickable (HW trace 2026-06-22). The - /// sprite is resolved from the live pointer position, matching the - /// production handler. - #[test] - fn xi_grab_device_self_grab_emits_no_crossing() { - use std::io::Read; - - const CLIENT_ID: u32 = 1; - // Window covering the pointer position (RecordingBackend's - // query_pointer reports (0,0)), so it is the sprite window AND - // the grab window. - const STAGE_XID: u32 = 0x0010_0070; - const HOST_XID: u32 = 0x0040_0070; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(STAGE_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 2560, - height: 1440, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(STAGE_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - let _ = state.resources.map_window(ResourceId(STAGE_XID)); - // Precondition: the pointer (0,0) really does resolve to the - // grab window, otherwise the test would pass trivially. - assert_eq!( - state.root_pointer_target_at(0, 0).map(|h| h.0), - Some(ResourceId(STAGE_XID)), - "sprite must be the grab window for this fixture" - ); - - // XIGrabDevice pointer (device 2) on the stage window. - let mut body = Vec::with_capacity(24); - body.extend_from_slice(&STAGE_XID.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.extend_from_slice(&[1, 1, 1, 0]); // mode, paired, owner_events, pad - body.extend_from_slice(&0u16.to_le_bytes()); // mask_len - body.extend_from_slice(&[0u8; 2]); - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 7, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("XIGrabDevice"); - - peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 4096]; - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - // Scan for any XI2 GenericEvent that is an Enter (evtype 7) or - // Leave (evtype 8) from the XInput extension (major 137). There - // must be none — a self-grab is a no-op transition. - let crossing = (0..wire.len().saturating_sub(10)).find(|&i| { - wire[i] == 35 - && wire[i + 1] == 137 - && matches!(u16::from_le_bytes([wire[i + 8], wire[i + 9]]), 7 | 8) - }); - assert!( - crossing.is_none(), - "self-grab must emit no XI_Enter/XI_Leave crossing; got {} wire bytes: {:?}", - wire.len(), - &wire[..wire.len().min(140)], - ); - } - - /// A `SendEvent` with an empty `event_mask` is addressed to the - /// client that *created* the destination window (X11 SendEvent - /// semantics). That is the XEmbed input-forwarding contract: a - /// systray manager (cinnamon) forwards the synthetic core - /// ButtonPress of a user click on the tray icon to the embedded - /// client. The GDK3 NULL-device guard must NOT drop it even though - /// the owner has an overlapping XI2 selection on the destination — - /// the guard is only for mask-based (passive-selection) delivery - /// (mate-panel/wnck). Pre-fix this dropped every XEmbed-forwarded - /// button, so pamac's tray icon was unclickable (HW air 2026-06-22). - #[test] - fn send_event_empty_mask_delivers_synthetic_button_to_owner_despite_xi2_selection() { - use std::io::Read; - - const SENDER: u32 = 1; // cinnamon - const OWNER: u32 = 2; // pamac - const WIN: u32 = 0x0020_0001; // pamac's embedded icon window - - let mut state = ServerState::new(); - let _sender_peer = install_client(&mut state, SENDER); - let mut owner_peer = install_client(&mut state, OWNER); - - // Window created by (owned by) the pamac client. - state.resources.create_window( - yserver_protocol::x11::ClientId(OWNER), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 24, - height: 24, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - // pamac (GTK3) selects XI2 ButtonPress (bit 4) on its own window — - // exactly what makes the guard fire. - state - .clients - .get_mut(&OWNER) - .unwrap() - .xi2_masks - .insert((ResourceId(WIN), 1), 1 << 4); - - // SendEvent: destination=WIN, event_mask=0, template = core - // ButtonPress (type 4). - let mut body = Vec::with_capacity(40); - body.extend_from_slice(&WIN.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // empty event-mask - let mut tmpl = [0u8; 32]; - tmpl[0] = 4; // ButtonPress - body.extend_from_slice(&tmpl); - let header = yserver_protocol::x11::RequestHeader { - opcode: 25, - data: 0, // propagate = false - length_units: 11, - }; - handle_send_event( - &mut state, - ClientId(SENDER), - SequenceNumber(1), - header, - &body, - ) - .expect("SendEvent"); - - owner_peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 256]; - loop { - match owner_peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - // The owner must receive the synthetic ButtonPress (type 4 with - // the sent-event bit 0x80 set → 0x84). - assert!( - !wire.is_empty() && wire[0] == 0x84, - "owner must receive the XEmbed-forwarded ButtonPress; got {} bytes: {:?}", - wire.len(), - &wire[..wire.len().min(40)], - ); - } - - /// `XIPassiveGrabDevice` with grab_type=Button(0) installs entries - /// in `state.button_grabs`; grab_type=Keycode(1) installs entries - /// in `state.key_grabs`. One entry per modifier (or one entry with - /// modifiers=0 when num_modifiers=0). `XIPassiveUngrabDevice` - /// removes matching entries. - #[test] - fn xi_passive_grab_device_pushes_button_and_key_grabs() { - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0051; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - // Helper to build XIPassiveGrabDevice body per - // `xXIPassiveGrabDeviceReq` in X11/extensions/XI2proto.h: - // time, grab_window, cursor, detail, deviceid, num_modifiers, - // mask_len, grab_type, grab_mode, paired_device_mode, - // owner_events, pad1, mask, modifiers. - fn build_body(window: u32, detail: u32, grab_type: u8, modifiers: &[u32]) -> Vec { - #[allow(clippy::cast_possible_truncation)] - let num_modifiers = modifiers.len() as u16; - let mut b = Vec::with_capacity(28 + modifiers.len() * 4); - b.extend_from_slice(&0u32.to_le_bytes()); // time - b.extend_from_slice(&window.to_le_bytes()); - b.extend_from_slice(&0u32.to_le_bytes()); // cursor - b.extend_from_slice(&detail.to_le_bytes()); - b.extend_from_slice(&2u16.to_le_bytes()); // deviceid (pointer; harmless for keycode) - b.extend_from_slice(&num_modifiers.to_le_bytes()); - b.extend_from_slice(&0u16.to_le_bytes()); // mask_len - b.push(grab_type); - b.push(1); // grab_mode async - b.push(1); // paired async - b.push(0); // owner_events - b.extend_from_slice(&0u16.to_le_bytes()); // pad1 - for m in modifiers { - b.extend_from_slice(&m.to_le_bytes()); - } - b - } - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 54, - // XIPassiveGrabDevice is AtLeast(8) and has no exact-length - // gate (modifier count is read from the body's num_modifiers - // field, not derived from the request length). 8 is the spec - // minimum; was 6, which pre-dated the REQUEST_SIZE_MATCH gate - // and now BadLengths before the handler runs. - length_units: 8, - }; - - // Button grab on button 3 with modifiers [0, ControlMask(4)]. - let body = build_body(WINDOW_XID, 3, 0, &[0, 4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("button grab"); - assert_eq!(state.button_grabs.len(), 2, "one grab per modifier"); - assert!( - state - .button_grabs - .iter() - .any(|g| g.button == 3 && g.modifiers == 0) - ); - assert!( - state - .button_grabs - .iter() - .any(|g| g.button == 3 && g.modifiers == 4) - ); - - // Key grab on keycode 67 (F1) with no modifiers → single entry - // with modifier-mask 0. - let body = build_body(WINDOW_XID, 67, 1, &[]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(2), - header, - &body, - ) - .expect("key grab"); - assert_eq!(state.key_grabs.len(), 1); - assert_eq!(state.key_grabs[0].keycode, 67); - assert_eq!(state.key_grabs[0].modifiers, 0); - - // XI2 "Any" modifier (bit 31) → core X11 AnyModifier (0x8000). - let body = build_body(WINDOW_XID, 1, 0, &[0x8000_0000]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(3), - header, - &body, - ) - .expect("any-modifier grab"); - assert!( - state - .button_grabs - .iter() - .any(|g| g.button == 1 && g.modifiers == 0x8000), - "XI2 Any (bit 31) maps to core X11 AnyModifier 0x8000", - ); - - // XIPassiveUngrabDevice — body: window(4) detail(4) deviceid(2) - // num_modifiers(2) grab_type(1) pad(3) modifiers. - fn build_ungrab_body( - window: u32, - detail: u32, - grab_type: u8, - modifiers: &[u32], - ) -> Vec { - #[allow(clippy::cast_possible_truncation)] - let num_modifiers = modifiers.len() as u16; - let mut b = Vec::with_capacity(16 + modifiers.len() * 4); - b.extend_from_slice(&window.to_le_bytes()); - b.extend_from_slice(&detail.to_le_bytes()); - b.extend_from_slice(&2u16.to_le_bytes()); // deviceid - b.extend_from_slice(&num_modifiers.to_le_bytes()); - b.push(grab_type); - b.extend_from_slice(&[0u8; 3]); - for m in modifiers { - b.extend_from_slice(&m.to_le_bytes()); - } - b - } - let ungrab_header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 55, - // XIPassiveUngrabDevice is AtLeast(5), no exact gate. 5 is the - // spec minimum; was 4 (pre-gate placeholder → BadLength now). - length_units: 5, - }; - let body = build_ungrab_body(WINDOW_XID, 3, 0, &[0, 4]); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(4), - ungrab_header, - &body, - ) - .expect("button ungrab"); - assert!( - !state - .button_grabs - .iter() - .any(|g| g.button == 3 && (g.modifiers == 0 || g.modifiers == 4)), - "ungrab removes the matching button+modifier entries", - ); - // AnyModifier grab still present (we didn't ungrab it). - assert!( - state - .button_grabs - .iter() - .any(|g| g.button == 1 && g.modifiers == 0x8000) - ); - } - - /// Regression test for the XIPassiveGrabDevice field-offset bug. - /// `mask_len` and `grab_type` were swapped: a real client (muffin, - /// xfwm4) sending mask_len=2 + grab_type=Keycode(1) was mis-parsed - /// as grab_type=Enter(2), silently dropping every keyboard - /// accelerator. The body here matches `xXIPassiveGrabDeviceReq` - /// in `X11/extensions/XI2proto.h` byte-for-byte with mask_len=2, - /// which is what real WM clients send. - #[test] - fn xi_passive_grab_device_keycode_with_xi2_mask() { - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0051; - const KEYCODE: u32 = 116; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - // Spec-shaped body with mask_len=2 (two 4-byte mask words, - // matching what muffin emits for XI device-event masks). - let mut body = Vec::with_capacity(28 + 8 + 4); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); // grab_window - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&KEYCODE.to_le_bytes()); // detail - body.extend_from_slice(&3u16.to_le_bytes()); // deviceid (keyboard) - body.extend_from_slice(&1u16.to_le_bytes()); // num_modifiers - body.extend_from_slice(&2u16.to_le_bytes()); // mask_len = 2 - body.push(1); // grab_type = Keycode - body.push(1); // grab_mode async - body.push(1); // paired async - body.push(0); // owner_events - body.extend_from_slice(&0u16.to_le_bytes()); // pad1 - body.extend_from_slice(&[0u8; 8]); // mask (2 words) - body.extend_from_slice(&0u32.to_le_bytes()); // modifier 0 - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 54, - length_units: 10, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("keycode grab with mask"); - - assert_eq!( - state.key_grabs.len(), - 1, - "Keycode grab must be recorded — bug was misclassifying \ - as grab_type=Enter due to swapped mask_len/grab_type" - ); - #[allow(clippy::cast_possible_truncation)] - let expected_kc = KEYCODE as u8; - assert_eq!(state.key_grabs[0].keycode, expected_kc); - assert_eq!(state.key_grabs[0].modifiers, 0); - assert!(state.button_grabs.is_empty()); - } - - /// `XIAllowEvents` with `mode=AsyncDevice(0)` releases the - /// passive grab on the calling client's device, matching what - /// mutter/cinnamon shell call after their click-to-focus button - /// grab activates. Before this handler shipped, the call was a - /// debug-logged stub so `state.pointer_grab` stayed pinned until - /// the next ButtonRelease, leaking the grab across intermediate - /// motion events. - #[test] - fn xi_allow_events_async_device_releases_passive_pointer_grab() { - const CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x0010_0051; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - // Seed a SYNC passive grab that has activated: the grab is held, - // the device frozen, and the activating press stored — exactly the - // state the pointer-fanout Step-3 path leaves after a matched click. - set_test_pointer_grab(&mut state, CLIENT_ID, GRAB_WIN, true, false); - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - crate::server::Xi1Freeze { - state: crate::server::Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - - // Body per `xXIAllowEventsReq`: time(4) + deviceid(2) + - // mode(1) + pad(1). deviceid=2 (master pointer), mode=0 - // (AsyncDevice). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(0); // mode = AsyncDevice - body.push(0); // pad - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - // AsyncDevice thaws the frozen pointer so events flow again (Xorg - // AsyncPointer). Per Xorg the passive grab itself persists until the - // button is released — what matters is the device is no longer - // frozen (the freeze gate would otherwise queue every later event). - assert!( - !state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .is_some_and(crate::server::Xi1Freeze::frozen), - "AsyncDevice must thaw the frozen pointer device" - ); - } - - #[test] - fn xi_allow_events_replay_device_replays_frozen_button_press_to_target() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const TARGET_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0051; - const TARGET_WIN: u32 = 0x0020_0052; - const HOST_XID: u32 = 0xCAFE_0001; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer - .set_nonblocking(true) - .expect("grab peer nonblocking"); - target_peer - .set_nonblocking(true) - .expect("target peer nonblocking"); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(TARGET_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(TARGET_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - let _ = state.resources.map_window(ResourceId(TARGET_WIN)); - state - .clients - .get_mut(&TARGET_CLIENT_ID) - .expect("target client") - .event_masks - .insert(ResourceId(TARGET_WIN), 0x0000_0004); - - set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer( - HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - )); - } - Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) - .expect("register host xid"); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(2); // mode = ReplayDevice - body.push(0); // pad - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(TARGET_CLIENT_ID), ResourceId(TARGET_WIN))), - "the replayed press must install the implicit grab on the natural \ - recipient (#94 — Xorg ActivateImplicitGrab on the replayed delivery)" - ); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && !g.via_xi2), - "replayed core press installs a core-form implicit grab" - ); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_none() - ); - - let mut buf = [0u8; 32]; - let grab_read = grab_peer.read(&mut buf); - assert!( - matches!(grab_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), - "grab owner must not receive replayed ButtonPress; got {grab_read:?}", - ); - let target_read = target_peer.read(&mut buf); - assert!( - matches!(target_read, Ok(32)), - "target window subscriber should receive replayed ButtonPress; got {target_read:?}", - ); - assert_eq!(buf[0], 4, "event type should be ButtonPress"); - assert_eq!(&buf[12..16], &TARGET_WIN.to_le_bytes()); - } - - /// Regression for the MATE submenu-hover bug. mate-panel holds an - /// active XI2 grab on its main panel window with `owner_events=true`; - /// menu items it pops up are top-level override-redirect windows - /// OWNED BY mate-panel (siblings of the grab window, not - /// descendants). Pre-fix the active-grab-redirect check used pure - /// topology (`target == grab_window || is_descendant_of`), - /// which redirected motion on the menu items to the grab window - /// with grab-relative coords — GTK couldn't track which menu item - /// the cursor was over, hover-delay never fired the submenu. - /// The fix adds an ownership-aware path: window owned by the grab - /// client qualifies for natural delivery alongside descendants. - /// Note: this is a heuristic — the fully spec-correct rule is "the - /// event would normally be reported to the grab client" (a mask- - /// subscription check). Ownership is a close proxy: clients almost - /// always select events on windows they own. - #[test] - fn active_grab_owner_events_natural_delivery_to_sibling_window_owned_by_grab_client() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::ActivePointerGrab, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x0010_0070; - const SIBLING_WIN: u32 = 0x0010_0071; // top-level, owned by same client, not descendant of grab window - const HOST_GRAB_XID: u32 = 0xCAFE_0070; - const HOST_SIBLING_XID: u32 = 0xCAFE_0071; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut backend = RecordingBackend::new(); - peer.set_nonblocking(true).expect("nonblocking"); - - // Create two top-level windows under root, both owned by the - // grab client. They are siblings (both children of root), not - // in an ancestor relationship — the exact topology for - // mate-panel + popup-menu. - for (xid, host_xid) in [(GRAB_WIN, HOST_GRAB_XID), (SIBLING_WIN, HOST_SIBLING_XID)] { - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(xid)); - Backend::register_top_level(&mut backend, None, ResourceId(xid), host_xid) - .expect("register host xid"); - } - // XI2 mask selecting motion on the sibling window (the menu - // item the cursor will move over). XI_Motion evtype = 6 → - // mask bit 1<<6 = 0x40. - state - .clients - .get_mut(&GRAB_CLIENT_ID) - .expect("client") - .xi2_masks - .insert((ResourceId(SIBLING_WIN), 2), 0x40); - - // Install active grab on GRAB_WIN with owner_events=true. - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - event_mask: 0, - cursor: ResourceId(0), - time: 0, - owner_events: true, - via_xi2: true, - implicit: false, - passive: false, - xi2_mask: u64::MAX, - }); - // Sanity: sibling is NOT a descendant of grab window. - assert!( - !state - .resources - .is_descendant_of(ResourceId(SIBLING_WIN), ResourceId(GRAB_WIN)) - ); - // And IS owned by the grab client. - assert_eq!( - state.resources.window_owner(ResourceId(SIBLING_WIN)), - Some(ClientId(GRAB_CLIENT_ID)), - ); - - // Cursor at root_x=50, root_y=50 — landing on SIBLING_WIN. - // host_xid = SIBLING's host xid so the v2-style hit-test lands - // on the sibling window naturally. - let motion = HostPointerEvent { - kind: PointerEventKind::MotionNotify, - host_xid: HOST_SIBLING_XID, - detail: 0, - time: 0x1000, - root_x: 50, - root_y: 50, - event_x: 50, - event_y: 50, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); - - // Read whatever landed on the wire. With the ownership-aware - // natural-delivery check, the XI2 motion must report against - // the sibling window (event=SIBLING_WIN) with sensible coords - // (event_x ≈ 50), NOT redirected to the grab window with - // grab-relative coords. Pre-fix the event would be on - // GRAB_WIN with grab-clamped coords — for this layout - // (sibling at the same root origin) the difference might be - // subtle in coords but the `event` window XID is the - // smoking-gun: GRAB vs SIBLING. - let mut buf = [0u8; 256]; - let n = peer.read(&mut buf).expect("client got at least one event"); - assert!(n >= 32, "expected at least one event, got {n} bytes"); - // Scan for a Generic XI2 event (type=35, second byte=major opcode of XInputExtension). - // We just need to find the `event` window XID in the body. - let mut found_sibling = false; - let mut found_grab = false; - let mut i = 0; - while i + 32 <= n { - // Generic event byte 0 is type. XI2 Motion event window - // sits at a known offset; rather than parsing the full - // event structure, scan for either window XID in the - // first 64 bytes of the body. Cheap+robust. - let slice = &buf[i..(i + 64).min(n)]; - if slice.windows(4).any(|w| w == SIBLING_WIN.to_le_bytes()) { - found_sibling = true; - } - if slice.windows(4).any(|w| w == GRAB_WIN.to_le_bytes()) { - found_grab = true; - } - i += 32; - } - assert!( - found_sibling, - "XI2 motion must address the sibling window (owner=grab client) under owner_events=true; got buf bytes {:?}", - &buf[..n.min(64)], - ); - // The grab window XID may also appear (e.g., in root/sourceid - // fields by coincidence) so we don't assert !found_grab — the - // load-bearing assertion is that the natural target window - // shows up in the body. - let _ = found_grab; - } - - /// Regression for the MATE menu-click bug: when a release was - /// queued during a sync passive grab freeze (because the WM hadn't - /// yet called AllowEvents), the replay path MUST drain both the - /// frozen press AND the queued release to the natural target — in - /// that order. Pre-fix the release leaked through during freeze - /// and the press was never replayed (frozen state cleared by the - /// rogue release path), so the app saw release-then-nothing. - #[test] - fn xi_allow_events_replay_device_drains_queued_release_after_press() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const TARGET_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0061; - const TARGET_WIN: u32 = 0x0020_0062; - const HOST_XID: u32 = 0xCAFE_0010; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer - .set_nonblocking(true) - .expect("grab peer nonblocking"); - target_peer - .set_nonblocking(true) - .expect("target peer nonblocking"); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(TARGET_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(TARGET_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - let _ = state.resources.map_window(ResourceId(TARGET_WIN)); - // Target client selects ButtonPress | ButtonRelease. - state - .clients - .get_mut(&TARGET_CLIENT_ID) - .expect("target client") - .event_masks - .insert(ResourceId(TARGET_WIN), 0x0000_000c); - - set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x1c33, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); - } - // Queue a release that arrived while frozen. - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 0x1c89, - ..press - }; - state - .sync_pending - .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, - event: crate::server::QueuedInputEvent::HostPointer(release), - }); - Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) - .expect("register host xid"); - - // XIAllowEvents ReplayDevice on master pointer (deviceid=2). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); - body.push(2); // mode = ReplayDevice - body.push(0); // pad - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - // Both frozen slots cleared after drain. - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_none() - ); - assert!( - !state - .sync_pending - .iter() - .any(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER) - ); - assert!(state.active_pointer_grab.is_none()); - - // Grab owner must not receive the replayed events (they go to - // the natural target). - let mut buf = [0u8; 32]; - let grab_read = grab_peer.read(&mut buf); - assert!( - matches!(grab_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), - "grab owner must not receive replay; got {grab_read:?}", - ); - - // Target must receive BOTH events in order. Read a sequence of - // 32-byte core events, expecting Press(type=4) then - // Release(type=5). The XI2 fanout would also fire (each event - // shipping a GenericEvent), so we read until we've seen one - // press and one release. - let mut saw_press = false; - let mut saw_release = false; - let mut press_offset = usize::MAX; - let mut release_offset = usize::MAX; - let mut total_read = 0usize; - // Slurp whatever the wire has — bound the read loop to avoid - // hanging if something goes wrong. - for iter in 0..8 { - let mut chunk = [0u8; 256]; - match target_peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => { - // Scan 32-byte boundaries for core ButtonPress(4) - // / ButtonRelease(5). GenericEvents (XI2) are - // type=35 and longer; their first byte still - // shows up at a 32-byte offset. - let mut i = 0; - while i + 32 <= n { - let evt_type = chunk[i] & 0x7F; - if evt_type == 4 && !saw_press { - saw_press = true; - press_offset = total_read + i; - } else if evt_type == 5 && !saw_release { - saw_release = true; - release_offset = total_read + i; - } - // GenericEvent is variable-length; advance by 32 conservatively. - i += 32; - } - total_read += n; - if saw_press && saw_release { - break; - } - } - Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(e) => panic!("target read failed at iter {iter}: {e}"), - } - } - assert!(saw_press, "target must receive replayed ButtonPress"); - assert!(saw_release, "target must receive queued ButtonRelease"); - assert!( - press_offset < release_offset, - "Press must arrive BEFORE Release at the target (got press@{press_offset}, release@{release_offset})", - ); - } - - /// Regression: XI2 `XIAllowEvents(AsyncDevice)` must thaw the unified - /// per-device freeze AND replay the events withheld during the freeze. - /// muffin (Cinnamon) installs XI2 sync passive button grabs; activating - /// one engages `xi1_frozen[POINTER]` via `xi1_check_grab_for_syncs`, - /// after which the unified-freeze gate queues every core pointer event. - /// The XI2 AllowEvents handler historically never touched `xi1_frozen`, - /// so `AsyncDevice` left the pointer frozen forever and dropped the - /// withheld queue — the Cinnamon desktop never saw the drag's - /// ButtonRelease, leaving the selection rubber-band stuck. (Core grabs - /// — marco/xfwm4 — thaw via the core AllowEvents path, so MATE/XFCE - /// were unaffected.) - #[test] - fn xi_allow_events_async_device_thaws_freeze_and_replays_queue() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::{Xi1Freeze, Xi1SyncState}, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const TARGET_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0061; - const TARGET_WIN: u32 = 0x0020_0062; - const HOST_XID: u32 = 0xCAFE_0005; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer - .set_nonblocking(true) - .expect("grab peer nonblocking"); - target_peer - .set_nonblocking(true) - .expect("target peer nonblocking"); - - for (client, win) in [(GRAB_CLIENT_ID, GRAB_WIN), (TARGET_CLIENT_ID, TARGET_WIN)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - // Target selects ButtonPress | ButtonRelease. - state - .clients - .get_mut(&TARGET_CLIENT_ID) - .expect("target client") - .event_masks - .insert(ResourceId(TARGET_WIN), 0x0000_000c); - - // muffin's sync passive grab has activated: grab held, the - // activating press already delivered to the owner, the pointer - // device frozen, and a release queued during the freeze. - set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); - // The activated passive grab's defining record (present for any - // real activation) — its mask is what the drain-path redirect - // reports to the grab owner. - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - button: 1, - modifiers: 0x8000, - owner_events: false, - event_mask: 0x0000_000c, // press|release - pointer_mode: 0, // sync - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: false, - }); - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - Xi1Freeze { - state: Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x2a00, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); - } - state - .sync_pending - .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, - event: crate::server::QueuedInputEvent::HostPointer(HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 0x2a50, - ..press - }), - }); - Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) - .expect("register host xid"); - - // XIAllowEvents AsyncDevice on master pointer (deviceid=2). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(0); // mode = AsyncDevice - body.push(0); // pad - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - // The unified pointer freeze must be thawed — otherwise every - // later core pointer event is queued-then-dropped (dead pointer). - assert!( - !state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .is_some_and(crate::server::Xi1Freeze::frozen), - "AsyncDevice must thaw the unified per-device pointer freeze" - ); - assert!( - state.active_pointer_grab.is_none(), - "passive grab ended by the terminating (replayed) release, not by AsyncDevice" - ); - assert!( - !state - .sync_pending - .iter() - .any(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER), - "withheld queue must be replayed, not left pending" - ); - - // AsyncDevice thaws WITHOUT deactivating the grab (Xorg AllowSome - // THAWED, dix/events.c:1857 — DeactivateGrab is the NOT_GRABBED - // /Replay case only). So the withheld release replays THROUGH the - // grab (ComputeFreezes → PlayReleasedEvents → DeliverGrabbedEvent): - // it is reported to the GRAB OWNER on the grab window, then the - // terminating release ends the passive grab. It must NOT leak to - // the foreign natural target (pre-implicit-grab #94 bug). - assert!( - peer_saw_event(&mut grab_peer, 5, None), - "withheld ButtonRelease must replay THROUGH the grab to its owner \ - on AsyncDevice thaw" - ); - assert!( - !peer_saw_event(&mut target_peer, 5, None), - "the grab intercepts the release — it must not leak to the foreign \ - natural target (#94)" - ); - } - - /// Helper: drain a nonblocking peer and return true if any 32-byte core - /// event with `type & 0x7f == want_type` (and, if `want_detail` is Some, - /// matching `detail` byte) was delivered. - fn peer_saw_event(peer: &mut UnixStream, want_type: u8, want_detail: Option) -> bool { - for _ in 0..8 { - let mut chunk = [0u8; 512]; - match peer.read(&mut chunk) { - Ok(0) => return false, - Ok(n) => { - let mut i = 0; - while i + 32 <= n { - if chunk[i] & 0x7F == want_type - && want_detail.is_none_or(|d| chunk[i + 1] == d) - { - return true; - } - i += 32; - } - } - Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => return false, - Err(e) => panic!("peer read failed: {e}"), - } - } - false - } - - /// ISSUE 1 (known-issues.md 2026-07-15): `AllowEvents` admission keys ONLY - /// on the unified per-device sync state (Xorg `AllowSome`, - /// dix/events.c:1851). When the device is thawed in unified state, a - /// `ReplayDevice` from the grabbing client is a no-op — nothing is - /// replayed — regardless of any residual/legacy activating event. - #[test] - fn xi_allow_events_replay_no_op_when_unified_thawed() { - use crate::{ - resources::ROOT_VISUAL, - server::{Xi1Freeze, Xi1SyncState}, - }; - const GRAB_CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x0010_0101; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - grab_peer.set_nonblocking(true).expect("nonblocking"); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - state - .clients - .get_mut(&GRAB_CLIENT_ID) - .expect("grab client") - .event_masks - .insert(ResourceId(GRAB_WIN), 0x0000_000c); // ButtonPress|ButtonRelease - - set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); - // Unified state THAWED — the sole admission authority says "not frozen". - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - Xi1Freeze { - state: Xi1SyncState::Thawed, - ..Default::default() - }, - ); - - // XIAllowEvents XIReplayDevice (mode 2) on master pointer (deviceid=2). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(2); // XIReplayDevice - body.push(0); - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - assert!( - !peer_saw_event(&mut grab_peer, 4, None) && !peer_saw_event(&mut grab_peer, 5, None), - "ReplayDevice on a unified-thawed device must be a no-op (no stale replay)" - ); - } - - /// ISSUE 2 (known-issues.md 2026-07-15): a thaw via a path OTHER than - /// AllowEvents must still replay the withheld queue (Xorg ComputeFreezes -> - /// PlayReleasedEvents, dix/events.c:1368-1372), not drop it. Drives the - /// production representation (`sync_pending`) that the freeze gate fills. - #[test] - fn out_of_band_pointer_thaw_replays_withheld_release() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::{PendingSyncEvent, QueuedInputEvent, Xi1Freeze, Xi1SyncState}, - }; - const GRAB_CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x0010_0111; - const HOST_XID: u32 = 0xCAFE_0011; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - grab_peer.set_nonblocking(true).expect("nonblocking"); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - state - .clients - .get_mut(&GRAB_CLIENT_ID) - .expect("grab client") - .event_masks - .insert(ResourceId(GRAB_WIN), 0x0000_000c); - Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) - .expect("register host xid"); - - set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); - // A real activated passive grab always has its defining - // `button_grabs` record present; the drain-path redirect reads its - // `event_mask` to know what to report to the grab owner (Xorg - // DeliverGrabbedEvent consults the grab's own mask). Without it the - // grab captures the release but reports nothing. - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - button: 1, - modifiers: 0x8000, - owner_events: false, - event_mask: 0x0000_000c, // press|release - pointer_mode: 0, // sync - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: false, - }); - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - Xi1Freeze { - state: Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - // A release withheld during the freeze, in the global queue (what the - // production QUEUE-WHILE-FROZEN gate pushes). - state.sync_pending.push_back(PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, - event: QueuedInputEvent::HostPointer(HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - host_xid: HOST_XID, - detail: 1, - time: 0x2a50, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }), - }); - - // OUT-OF-BAND thaw (NOT AllowEvents). - let xid_map = backend.xid_map().clone(); - crate::core_loop::pointer_fanout::xi1_thaw_device( - &mut state, - &mut backend, - &xid_map, - crate::xinput::DEVICEID_SLAVE_POINTER, - ); - - assert!( - peer_saw_event(&mut grab_peer, 5, None), - "withheld ButtonRelease must be replayed on an out-of-band thaw, not dropped" - ); - assert!( - state.sync_pending.is_empty(), - "the global queue must be drained on thaw" - ); - } - - /// Global-queue replay preserves arrival order ACROSS devices (Xorg - /// PlayReleasedEvents over the single `syncEvents.pending`, - /// dix/events.c:1233-1291): a keyboard event queued before a pointer event - /// is replayed first when both thaw in a single `xi1_compute_freezes` pass. - #[test] - fn compute_freezes_replays_global_queue_in_arrival_order() { - use crate::{ - backend::Backend, - host_x11::{HostKeyEvent, HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::{CoreFocus, PendingSyncEvent, QueuedInputEvent, Xi1Freeze, Xi1SyncState}, - }; - const CLIENT_ID: u32 = 1; - const WIN: u32 = 0x0010_0121; - const HOST_XID: u32 = 0xCAFE_0021; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - peer.set_nonblocking(true).expect("nonblocking"); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WIN)); - Backend::register_top_level(&mut backend, None, ResourceId(WIN), HOST_XID) - .expect("register host xid"); - // KeyPress|KeyRelease|ButtonPress|ButtonRelease. - state - .clients - .get_mut(&CLIENT_ID) - .expect("client") - .event_masks - .insert(ResourceId(WIN), 0x0000_000f); - // Key delivery routes to the core focus window. - state.core_focus = CoreFocus { - raw: WIN, - revert_to: 0, - time: 0, - }; - - for dev in [ - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - crate::xinput::DEVICEID_SLAVE_POINTER, - ] { - state.xi1_frozen.insert( - dev, - Xi1Freeze { - state: Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - } - // Enqueue KEY (release) THEN POINTER (release), in that global order. - state.sync_pending.push_back(PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_KEYBOARD, - event: QueuedInputEvent::HostKey(HostKeyEvent { - pressed: false, - keycode: 38, - time: 0x1000, - root_x: 5, - root_y: 5, - event_x: 5, - event_y: 5, - state: 0, - }), - }); - state.sync_pending.push_back(PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, - event: QueuedInputEvent::HostPointer(HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - host_xid: HOST_XID, - detail: 1, - time: 0x2000, - root_x: 5, - root_y: 5, - event_x: 5, - event_y: 5, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }), - }); - - // Thaw BOTH, then ONE replay pass. - for dev in [ - crate::xinput::DEVICEID_SLAVE_KEYBOARD, - crate::xinput::DEVICEID_SLAVE_POINTER, - ] { - state.xi1_frozen.get_mut(&dev).unwrap().state = Xi1SyncState::Thawed; - } - let xid_map = backend.xid_map().clone(); - crate::core_loop::pointer_fanout::xi1_compute_freezes(&mut state, &mut backend, &xid_map); - - // Read the full wire once and compare offsets: KeyRelease (3) precedes - // ButtonRelease (5). - let mut buf = [0u8; 8192]; - let n = peer.read(&mut buf).expect("read wire"); - assert!( - n >= 64, - "expected both replayed events on the wire (got {n} bytes)" - ); - let mut key_pos = None; - let mut btn_pos = None; - let mut i = 0; - while i + 32 <= n { - let ty = buf[i] & 0x7F; - if ty == 3 && key_pos.is_none() { - key_pos = Some(i); - } - if ty == 5 && btn_pos.is_none() { - btn_pos = Some(i); - } - i += 32; - } - assert!( - key_pos.is_some() && btn_pos.is_some(), - "both the keyboard and pointer events must be delivered (key={key_pos:?} btn={btn_pos:?})" - ); - assert!( - key_pos < btn_pos, - "keyboard event (queued first) must replay before the pointer event" - ); - assert!(state.sync_pending.is_empty(), "queue fully drained"); - } - - /// Regression for the double-button-map hazard: the freeze gate stores the - /// PHYSICAL detail, and replay re-enters button mapping exactly once. With - /// a non-identity `pointer_mapping_override` (physical 1 -> logical 3), the - /// replayed release must carry logical button 3 (mapped once), not a - /// twice-mapped value. - #[test] - fn frozen_pointer_replay_maps_button_exactly_once() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::{Xi1Freeze, Xi1SyncState}, - }; - const CLIENT_ID: u32 = 1; - const WIN: u32 = 0x0010_0131; - const HOST_XID: u32 = 0xCAFE_0031; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - peer.set_nonblocking(true).expect("nonblocking"); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WIN)); - Backend::register_top_level(&mut backend, None, ResourceId(WIN), HOST_XID) - .expect("register host xid"); - state - .clients - .get_mut(&CLIENT_ID) - .expect("client") - .event_masks - .insert(ResourceId(WIN), 0x0000_000c); - - // Physical button 1 -> logical 3 (identity for 2/3). - state.pointer_mapping_override = Some(vec![3, 2, 1]); - // Pointer frozen so the release is withheld at the gate. - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - Xi1Freeze { - state: Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - - let xid_map = backend.xid_map().clone(); - // Drive a PHYSICAL button-1 release through the real fanout: the gate - // withholds it into sync_pending with the physical detail preserved. - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - host_xid: HOST_XID, - detail: 1, - time: 0x2a50, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let _ = crate::core_loop::pointer_fanout::pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - release, - true, - false, - ); - assert_eq!( - state.sync_pending.len(), - 1, - "release must be withheld while frozen" - ); - - // Thaw and replay. - crate::core_loop::pointer_fanout::xi1_thaw_device( - &mut state, - &mut backend, - &xid_map, - crate::xinput::DEVICEID_SLAVE_POINTER, - ); - - // The delivered ButtonRelease must carry LOGICAL button 3 (mapped once). - assert!( - peer_saw_event(&mut peer, 5, Some(3)), - "replayed release must map physical 1 -> logical 3 exactly once (not double-mapped)" - ); - } - - /// XI2 mode → core AllowSome mode mapping ([`xi2_allow_mode_to_core`]). - #[test] - fn xi2_allow_mode_to_core_maps_all_modes() { - // pointer (deviceid 2): Async/Sync/Replay → Pointer variants. - assert_eq!(xi2_allow_mode_to_core(0, 2), Some(0)); // AsyncDevice → AsyncPointer - assert_eq!(xi2_allow_mode_to_core(1, 2), Some(1)); // SyncDevice → SyncPointer - assert_eq!(xi2_allow_mode_to_core(2, 2), Some(2)); // ReplayDevice → ReplayPointer - // keyboard (deviceid 3): → Keyboard variants. - assert_eq!(xi2_allow_mode_to_core(0, 3), Some(3)); // → AsyncKeyboard - assert_eq!(xi2_allow_mode_to_core(1, 3), Some(4)); // → SyncKeyboard - assert_eq!(xi2_allow_mode_to_core(2, 3), Some(5)); // → ReplayKeyboard - // paired: AsyncPairedDevice acts on the OTHER device. - assert_eq!(xi2_allow_mode_to_core(3, 2), Some(3)); // ptr grab → async keyboard - assert_eq!(xi2_allow_mode_to_core(3, 3), Some(0)); // kbd grab → async pointer - assert_eq!(xi2_allow_mode_to_core(4, 2), Some(6)); // AsyncPair → AsyncBoth - assert_eq!(xi2_allow_mode_to_core(5, 2), Some(7)); // SyncPair → SyncBoth - // touch / unknown → unsupported. - assert_eq!(xi2_allow_mode_to_core(6, 2), None); // XIAcceptTouch - assert_eq!(xi2_allow_mode_to_core(7, 2), None); // XIRejectTouch - } - - /// Regression: XI2 `XIAllowEvents(XISyncDevice)` (mode 1) must thaw the - /// frozen device and replay the withheld queue. It used to be a no-op - /// ("we're always-async"), so muffin's click-to-focus SYNC path (mutter - /// `events.c` `maybe_unfreeze_pointer_events(EVENTS_UNFREEZE_SYNC)`) - /// could not clear the freeze → `QUEUE-WHILE-FROZEN` piled up → the - /// Cinnamon clicks-and-typing-dead freeze. Now routed through the shared - /// `apply_allow_events` (core SyncPointer). - #[test] - fn xi_allow_events_sync_device_thaws_and_drains_queue() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const GRAB_CLIENT_ID: u32 = 1; - const TARGET_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0071; - const TARGET_WIN: u32 = 0x0020_0072; - const HOST_XID: u32 = 0xCAFE_0007; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer.set_nonblocking(true).expect("nonblocking"); - target_peer.set_nonblocking(true).expect("nonblocking"); - - for (client, win) in [(GRAB_CLIENT_ID, GRAB_WIN), (TARGET_CLIENT_ID, TARGET_WIN)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - state - .clients - .get_mut(&TARGET_CLIENT_ID) - .expect("target") - .event_masks - .insert(ResourceId(TARGET_WIN), 0x0000_000c); - - // Activated SYNC passive grab: held, frozen, activating press stored, - // a release withheld during the freeze. - set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); - // The activated passive grab's defining record (its mask is what - // the drain-path redirect reports to the grab owner). - state.button_grabs.push(crate::server::PassiveButtonGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - button: 1, - modifiers: 0x8000, - owner_events: false, - event_mask: 0x0000_000c, // press|release - pointer_mode: 0, // sync - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: false, - }); - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - crate::server::Xi1Freeze { - state: crate::server::Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x10, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); - } - state - .sync_pending - .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, - event: crate::server::QueuedInputEvent::HostPointer(HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 0x20, - ..press - }), - }); - Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) - .expect("register host xid"); - - // XIAllowEvents XISyncDevice (mode 1) on master pointer (deviceid 2). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(1); // mode = XISyncDevice - body.push(0); // pad - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - assert!( - !state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .is_some_and(crate::server::Xi1Freeze::frozen), - "XISyncDevice must thaw the frozen pointer (was a no-op → Cinnamon freeze)" - ); - assert!( - !state - .sync_pending - .iter() - .any(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER), - "withheld queue must be drained on XISyncDevice" - ); - - // XISyncDevice (FREEZE_NEXT_EVENT) thaws WITHOUT deactivating the - // grab (Xorg AllowSome, dix/events.c:1864 — only NOT_GRABBED - // /Replay deactivates). The withheld release replays THROUGH the - // grab (DeliverGrabbedEvent) to the grab owner, then the - // terminating release ends the passive grab; it must NOT leak to - // the foreign natural target (#94). - assert!( - peer_saw_event(&mut grab_peer, 5, None), - "withheld ButtonRelease must replay THROUGH the grab to its owner \ - on XISyncDevice" - ); - assert!( - !peer_saw_event(&mut target_peer, 5, None), - "the grab intercepts the release — it must not leak to the foreign \ - natural target (#94)" - ); - } - - #[test] - fn xi_allow_events_replay_device_releases_active_pointer_grab() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::ActivePointerGrab, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const TARGET_WIN: u32 = 0x0020_0052; - const HOST_XID: u32 = 0xCAFE_0003; - - let mut state = ServerState::new(); - let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(TARGET_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(TARGET_WIN)); - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(TARGET_WIN), - event_mask: 0xFFFF, - cursor: ResourceId(0), - time: 0, - owner_events: false, - via_xi2: true, - implicit: false, - passive: false, - xi2_mask: u64::MAX, - }); - // ReplayDevice only acts on a FROZEN device with a stored event to - // replay (Xorg AllowSome) — engage the sync freeze + activating press. - state.xi1_frozen.insert( - crate::xinput::DEVICEID_SLAVE_POINTER, - crate::server::Xi1Freeze { - state: crate::server::Xi1SyncState::FrozenNoEvent, - ..Default::default() - }, - ); - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer( - HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }, - )); - } - Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) - .expect("register host xid"); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(2); // mode = ReplayDevice - body.push(0); // pad - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events replay pointer"); - - assert!(state.active_pointer_grab.is_none()); - } - - #[test] - fn xi_sync_passive_grab_replays_xi2_press_to_target_only_after_allow_events() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::PassiveButtonGrab, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const TARGET_CLIENT_ID: u32 = 2; - const TARGET_WIN: u32 = 0x0020_0052; - const HOST_XID: u32 = 0xCAFE_0002; - const XI2_BUTTON_PRESS_BIT: u32 = 1 << 4; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer - .set_nonblocking(true) - .expect("grab peer nonblocking"); - target_peer - .set_nonblocking(true) - .expect("target peer nonblocking"); - - state.resources.create_window( - ClientId(TARGET_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(TARGET_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(TARGET_WIN)); - state - .clients - .get_mut(&GRAB_CLIENT_ID) - .expect("grab client") - .xi2_masks - .insert((ResourceId(TARGET_WIN), 1), u64::from(XI2_BUTTON_PRESS_BIT)); - state - .clients - .get_mut(&TARGET_CLIENT_ID) - .expect("target client") - .xi2_masks - .insert((ResourceId(TARGET_WIN), 1), u64::from(XI2_BUTTON_PRESS_BIT)); - state.button_grabs.push(PassiveButtonGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(TARGET_WIN), - button: 1, - modifiers: 0, - owner_events: false, - event_mask: 0xFFFF_FFFF, - pointer_mode: 0, - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: true, - }); - Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) - .expect("register host xid"); - - let event = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x1234, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let _dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, event, true, false); - - assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_some() - ); - - let mut buf = [0u8; 128]; - let target_read = target_peer.read(&mut buf); - assert!( - matches!(target_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), - "sync passive XI2 grab must withhold the initial XI2 press from the target; got {target_read:?}", - ); - let grab_read = grab_peer.read(&mut buf); - assert!( - matches!(grab_read, Ok(n) if n > 0), - "grab owner should receive the grabbed press stream; got {grab_read:?}", - ); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0x1234u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid - body.push(2); // mode = ReplayDevice - body.push(0); // pad - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - let target_read = target_peer.read(&mut buf); - assert!( - matches!(target_read, Ok(n) if n >= 32 && buf[0] == 35), - "ReplayDevice must redeliver the XI2 press to the natural target; got {target_read:?}", - ); - } - - #[test] - fn xi_sync_passive_grab_release_during_freeze_queues_for_replay() { - // Regression: in a sync passive grab, a ButtonRelease arriving - // BEFORE the grab owner sends AllowEvents must NOT clear the - // grab nor leak to the natural target — it must queue alongside - // the activating press for replay. Pre-fix, the release cleared - // `frozen_pointer_event` + `pointer_grab_is_passive`, so when - // AllowEvents(ReplayPointer/ReplayDevice) finally arrived there - // was nothing to replay. Visible symptom on MATE: marco's slow - // ~10 round-trip grab handler vs a fast click → app never sees - // the press → menu/titlebar clicks dead. - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::PassiveButtonGrab, - }; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0020_0053; - const HOST_XID: u32 = 0xCAFE_0004; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - state.button_grabs.push(PassiveButtonGrab { - owner: ClientId(CLIENT_ID), - grab_window: ResourceId(WINDOW_XID), - button: 1, - modifiers: 0, - owner_events: true, - event_mask: 0xFFFF_FFFF, - pointer_mode: 0, // Synchronous → triggers freeze - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: true, - }); - Backend::register_top_level(&mut backend, None, ResourceId(WINDOW_XID), HOST_XID) - .expect("register host xid"); - - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x1234, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let _dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_some() - ); - // No ButtonRelease is withheld yet — it hasn't arrived. (The unified - // queue may already hold the activating press's XI1 form; that is - // expected — Xorg stores the activating event too. We assert on the - // RELEASE specifically, which is what this test is about.) - assert!( - !state - .sync_pending - .iter() - .any(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER - && matches!( - &p.event, - crate::server::QueuedInputEvent::HostPointer(e) - if e.kind == PointerEventKind::ButtonRelease - )), - "no ButtonRelease must be queued before the release arrives" - ); - - // Release arrives BEFORE AllowEvents (the load-bearing case). - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 0x1280, - ..press - }; - let xid_map = backend.xid_map().clone(); - let _dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - // Grab MUST still be active (waiting for AllowEvents). Press - // is still frozen. Release is in the queue. - assert!( - state.active_pointer_grab.is_some(), - "grab must remain active while frozen — release waits for AllowEvents", - ); - assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_some() - ); - // The withheld release must sit in the global replay queue as a core - // HostPointer event (Xorg syncEvents.pending), not be delivered to the - // natural target. - assert!( - state - .sync_pending - .iter() - .any(|p| p.device == crate::xinput::DEVICEID_SLAVE_POINTER - && matches!( - &p.event, - crate::server::QueuedInputEvent::HostPointer(e) - if e.kind == PointerEventKind::ButtonRelease - )), - "release must be queued for replay, not delivered to natural target", - ); - } - - /// Xorg semantics (`DeliverGrabbedEvent`, dix/events.c:4361): the - /// `owner_events=true` natural walk is filtered to the GRAB - /// CLIENT — `TryClientEvents` (dix/events.c:2069) returns -1 for - /// any other client ("not delivered due to grab"), aborting - /// propagation; the press then falls back to the grab window. - /// - /// This test previously pinned the OPPOSITE ("delivers descendant - /// window regardless of owner", from the 2b2680e cinnamon wip) — - /// that leak is what wedged wmaker on HW 2026-06-04: the sync - /// grab froze the queue while the press went to the app client, - /// so the WM never called AllowEvents and clicks died. - #[test] - fn xi_passive_grab_owner_events_redirects_foreign_descendant_press_to_grab_client() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::PassiveButtonGrab, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const CHILD_CLIENT_ID: u32 = 2; - const GRAB_WIN: u32 = 0x0020_0062; - const CHILD_WIN: u32 = 0x0020_0063; - const HOST_XID: u32 = 0xCAFE_0005; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut child_peer = install_client(&mut state, CHILD_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer - .set_nonblocking(true) - .expect("grab peer nonblocking"); - child_peer - .set_nonblocking(true) - .expect("child peer nonblocking"); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(CHILD_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_WIN), - parent: ResourceId(GRAB_WIN), - x: 10, - y: 10, - width: 40, - height: 40, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - let _ = state.resources.map_window(ResourceId(CHILD_WIN)); - state - .clients - .get_mut(&CHILD_CLIENT_ID) - .expect("child client") - .event_masks - .insert(ResourceId(CHILD_WIN), 0x0000_0004); - state.button_grabs.push(PassiveButtonGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - button: 1, - modifiers: 0, - owner_events: true, - event_mask: 0xFFFF_FFFF, - pointer_mode: 0, - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: true, - }); - Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) - .expect("register host xid"); - - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x1234, - root_x: 20, - root_y: 20, - event_x: 20, - event_y: 20, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let _dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - - let mut buf = [0u8; 128]; - let grab_read = grab_peer.read(&mut buf); - assert!( - matches!(grab_read, Ok(n) if n >= 32), - "press on a foreign-owned descendant must fall back to grab-window \ - delivery to the GRAB client (Xorg dix/events.c:2069 aborts the \ - natural walk on a foreign subscriber); got {grab_read:?}", - ); - assert_eq!(buf[0], 4, "core ButtonPress to the grab client"); - assert_eq!( - &buf[12..16], - &GRAB_WIN.to_le_bytes(), - "press reported on the grab window", - ); - let child_read = child_peer.read(&mut buf); - let child_got_core_press = - matches!(child_read, Ok(n) if buf[..n.min(128)].chunks(32).any(|c| c[0] == 4)); - assert!( - !child_got_core_press, - "the foreign descendant's owner must NOT see the core press while \ - the grab holds; got {child_read:?}", - ); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_POINTER) - .and_then(|f| f.stored.as_ref()) - .is_some(), - "GrabModeSync activation with a delivery must freeze the queue", - ); - } - - /// During a window move, muffin holds an *active* `XIGrabDevice` on - /// the master pointer. Every master-pointer XI2 event — including the - /// final `XI_ButtonRelease` — must be funnelled to the grab owner, - /// even after the drag has pulled the pointer over another client's - /// window. Regression: the XI2 fanout routed purely by window - /// mask-selection and ignored the active grab, so the release was - /// delivered to the window under the cursor (nemo-desktop) instead of - /// the grab owner (muffin) — leaving muffin stuck in its move loop - /// with the button apparently still held. - #[test] - fn xi_active_device_grab_funnels_button_release_to_grab_owner_not_window_under_cursor() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::ActivePointerGrab, - }; - - const GRAB_CLIENT_ID: u32 = 1; // muffin - const OTHER_CLIENT_ID: u32 = 2; // nemo-desktop - const GRAB_WIN: u32 = 0x0010_0011; // muffin's grab window - const OTHER_WIN: u32 = 0x0025_0003; // nemo-desktop fullscreen window - const OTHER_HOST_XID: u32 = 0xCAFE_0006; - const XI2_BUTTON_RELEASE_BIT: u32 = 1 << 5; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut other_peer = install_client(&mut state, OTHER_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer.set_nonblocking(true).unwrap(); - other_peer.set_nonblocking(true).unwrap(); - - // muffin's grab window — small, off in the corner. The drag pulls - // the pointer away from it onto the desktop. - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - // nemo-desktop's window — covers where the pointer ends up. - state.resources.create_window( - ClientId(OTHER_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(OTHER_WIN), - parent: ROOT_WINDOW, - x: 200, - y: 200, - width: 400, - height: 400, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - let _ = state.resources.map_window(ResourceId(OTHER_WIN)); - - // nemo selects XI2 ButtonRelease on its own window (XIAllDevices=1). - state - .clients - .get_mut(&OTHER_CLIENT_ID) - .expect("other client") - .xi2_masks - .insert( - (ResourceId(OTHER_WIN), 1), - u64::from(XI2_BUTTON_RELEASE_BIT), - ); - - // muffin holds an active master-pointer grab (XIGrabDevice). - // owner_events=false → every event funnels to the grab owner. - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - event_mask: 0xFFFF, - cursor: ResourceId(0), - time: 0, - owner_events: false, - via_xi2: true, - implicit: false, - passive: false, - xi2_mask: u64::MAX, - }); - - Backend::register_top_level(&mut backend, None, ResourceId(OTHER_WIN), OTHER_HOST_XID) - .expect("register host xid"); - - // Pointer has dragged onto nemo-desktop (200,200..600,600); button 1 - // still held. event_x/y are relative to OTHER_WIN's origin. - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - host_xid: OTHER_HOST_XID, - detail: 1, - time: 0x2000, - root_x: 300, - root_y: 300, - event_x: 100, - event_y: 100, - state: 0x100, // button 1 down - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let _dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let mut buf = [0u8; 256]; - - // The window under the cursor must NOT get the XI2 release — the - // active grab owns the device. - let other_read = other_peer.read(&mut buf); - assert!( - matches!(other_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), - "active device grab must withhold the XI2 ButtonRelease from the window under the cursor; got {other_read:?}", - ); - - // The grab owner must receive the XI2 ButtonRelease. The grab owner - // also gets the parallel core ButtonRelease (32 bytes) from the - // core redirect, so scan event boundaries for the XI2 GenericEvent. - let n = match grab_peer.read(&mut buf) { - Ok(n) => n, - Err(e) => panic!("grab owner must receive the grabbed XI2 release; got {e:?}"), - }; - let off = (0..n) - .step_by(32) - .find(|&off| off + 10 <= n && buf[off] == 35) - .expect("grab owner must receive an XI2 GenericEvent (got core-only stream)"); - assert_eq!( - u16::from_le_bytes([buf[off + 8], buf[off + 9]]), - 5, - "the grabbed XI2 event must be a ButtonRelease (evtype 5)", - ); - } - - /// A *core* `XGrabPointer` grab must NOT funnel XI2 XGE events to - /// the grab owner — the owner asked for core delivery only (Xorg's - /// `DeliverGrabbedEvent` consults the grab's own xi2mask, which is - /// empty for core grabs). Regression: the XI2 active-grab redirect - /// pushed the grab client unconditionally; a plain-Xlib client that - /// linked libXi without calling XIQueryVersion (every xts5 Xlib11 - /// TCM) NULL-derefs inside libXi's wire handler on the XGE event, - /// and TET's longjmp out of the SIGSEGV poisons the display mutex — - /// the rest of the test case hangs forever (Xlib11/ButtonPress - /// scenario 890-0 on eiger HW, 2026-06-04). - #[test] - fn core_pointer_grab_does_not_send_xi2_to_grab_owner() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - server::ActivePointerGrab, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x0010_0021; - const HOST_XID: u32 = 0xCAFE_0016; - - let mut state = ServerState::new(); - let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut backend = RecordingBackend::new(); - grab_peer.set_nonblocking(true).unwrap(); - - state.resources.create_window( - ClientId(GRAB_CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - // Select core ButtonPress on the grab window so the core - // redirect has a delivery target. - state - .clients - .get_mut(&GRAB_CLIENT_ID) - .expect("grab client") - .event_masks - .insert(ResourceId(GRAB_WIN), 0x0000_0004); - - // Core XGrabPointer, owner_events=false — the xts5 TP10 shape. - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - event_mask: 0xFFFF, - cursor: ResourceId(0), - time: 0, - owner_events: false, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }); - - Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) - .expect("register host xid"); - - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x3000, - root_x: 25, - root_y: 25, - event_x: 25, - event_y: 25, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let xid_map = backend.xid_map().clone(); - let _dropped = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - - // The grab owner gets the core ButtonPress (type 4) and nothing - // else — scan every 32-byte event for an XI2 GenericEvent (35). - let mut buf = [0u8; 512]; - let n = match grab_peer.read(&mut buf) { - Ok(n) => n, - Err(e) => panic!("grab owner must receive the core press; got {e:?}"), - }; - let mut saw_core_press = false; - for off in (0..n).step_by(32) { - assert_ne!( - buf[off], 35, - "core grab owner must not receive XI2 GenericEvents", - ); - if buf[off] == 4 { - saw_core_press = true; - } - } - assert!(saw_core_press, "core ButtonPress must reach the grab owner"); - } - - /// `XIQueryPointer` must report currently-held pointer buttons in - /// the XI2 `buttons` bitmask, not only in the legacy KeyButMask - /// `effective_mods`. A GTK4 CSD window move goes through - /// `_NET_WM_MOVERESIZE`: the app sends the request and muffin — which - /// never saw the ButtonPress — queries the pointer to learn whether - /// the initiating button is still held. With an empty `buttons` mask - /// muffin concluded the button was released and aborted the move - /// grab immediately (the window "didn't budge"). Button N maps to - /// bit N (button 1 -> bit 1). - #[test] - fn xi_query_pointer_reports_held_button_in_xi2_button_mask() { - use crate::{backend::Backend, resources::ROOT_VISUAL}; - use yserver_protocol::x11::ClientByteOrder; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0020_0070; - const HOST_XID: u32 = 0xCAFE_0007; - - // Run for both client byte orders. The XI2 button mask is a raw - // byte array indexed by `XIMaskIsSet` (X11/extensions/XI2.h), so it - // must NOT be byte-swapped per client order — a big-endian client - // must still read button 1 in mask byte 0. - for order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - peer.set_nonblocking(true).unwrap(); - state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = order; - let mut backend = RecordingBackend::new(); - // Model button 1 held (KeyButMask Button1Mask = 0x0100). - backend.query_pointer_mask = 0x0100; - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WINDOW_XID)); - Backend::register_top_level(&mut backend, None, ResourceId(WINDOW_XID), HOST_XID) - .expect("register host xid"); - - // XIQueryPointer body: window(4) + deviceid(2) + pad(2). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); // master pointer - body.extend_from_slice(&0u16.to_le_bytes()); // pad - - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 40, // XIQueryPointer - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("xi query pointer"); - - let mut buf = [0u8; 128]; - let n = peer.read(&mut buf).expect("reply"); - // Reply: 8-byte header + 24 coord bytes; same_screen@32, pad@33, - // buttons_len@34-35, mods@36-51, group@52-55, button mask@56+. - assert!( - n >= 60, - "{order:?}: XIQueryPointer reply must carry a 1-unit button bitmask (got {n})", - ); - let buttons_len = match order { - ClientByteOrder::LittleEndian => u16::from_le_bytes([buf[34], buf[35]]), - ClientByteOrder::BigEndian => u16::from_be_bytes([buf[34], buf[35]]), - }; - assert_eq!( - buttons_len, 1, - "{order:?}: buttons_len must be 1 so clients can read button state", - ); - // Byte-indexed exactly as `XIMaskIsSet(mask, 1) = mask[1>>3] & - // (1 << (1 & 7)) = mask[0] & 0x02` (the way muffin reads it), - // which is byte-order independent. - assert_ne!( - buf[56] & (1 << 1), - 0, - "{order:?}: button 1 must be held in XI2 button mask byte 0 \ - (raw byte array, not byte-swapped); muffin's \ - _NET_WM_MOVERESIZE move aborts on an empty mask", - ); - } - } - - /// Cinnamon alt-tab regression #2 (2026-06-10): `XIQueryPointer` - /// must report the keyboard modifier state in `ModifierInfo` — - /// Xorg `Xi/xiquerypointer.c:120,139` fills `rep.mods` from the - /// paired MASTER_KEYBOARD's XKB state. The backend mask is a core - /// KeyButMask (modifiers in the low byte, buttons at 0x100+); - /// `base_mods` must carry the modifier bits WITHOUT the button - /// bits. Pre-fix `base_mods` was hardcoded 0 — cinnamon's - /// `global.get_pointer()` (GDK → XIQueryPointer) saw "Alt not - /// held" mid-alt-tab and the switcher took the modifier-already- - /// released branch: `_activateSelected()` + destroy, so the popup - /// never appeared (trace: instant raise+SetInputFocus between the - /// modal grab and ungrab, same server timestamp). - #[test] - fn xi_query_pointer_reports_keyboard_mods_in_modifier_info() { - use yserver_protocol::x11::ClientByteOrder; - - const CLIENT_ID: u32 = 1; - for order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - peer.set_nonblocking(true).unwrap(); - state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = order; - let mut backend = RecordingBackend::new(); - // Alt (Mod1Mask = 0x8) held + button 1 held (Button1Mask = - // 0x100): the reply must separate them. - backend.query_pointer_mask = 0x0108; - - // XIQueryPointer body: window(4) + deviceid(2) + pad(2). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); // master pointer - body.extend_from_slice(&0u16.to_le_bytes()); // pad - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 40, // XIQueryPointer - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("xi query pointer"); - - let mut buf = [0u8; 128]; - let n = peer.read(&mut buf).expect("reply"); - assert!(n >= 56, "{order:?}: short XIQueryPointer reply ({n})"); - // ModifierInfo at bytes 36..52: base / latched / locked / - // effective (each CARD32, client byte order). - let read_u32 = |b: &[u8]| match order { - ClientByteOrder::LittleEndian => u32::from_le_bytes([b[0], b[1], b[2], b[3]]), - ClientByteOrder::BigEndian => u32::from_be_bytes([b[0], b[1], b[2], b[3]]), - }; - let base_mods = read_u32(&buf[36..40]); - let effective_mods = read_u32(&buf[48..52]); - assert_eq!( - base_mods, 0x8, - "{order:?}: base_mods must carry the held Mod1 (Alt) and \ - not the button bits (Xorg fills it from the paired \ - keyboard's XKB state)", - ); - assert_ne!( - effective_mods & 0x8, - 0, - "{order:?}: effective_mods must include the held Mod1 — \ - GDK reads the effective field for global.get_pointer()", - ); - } - } - - /// Cinnamon alt-tab regression #1 (2026-06-10): a SYNC passive key - /// grab (the muffin keybinding) activates on Alt+Tab and freezes - /// the keyboard; muffin then takes an ASYNC active `XIGrabDevice` - /// (pushModal) and later `XIUngrabDevice`s (popModal). Per Xorg the - /// async activation THAWS the frozen device — `ActivateKeyboardGrab` - /// → `CheckGrabForSyncs` (dix/events.c:1424: async → THAWED) — and - /// deactivation runs `ComputeFreezes` (`DeactivateKeyboardGrab`: - /// sync.state = NOT_GRABBED). The XIAllowEvents muffin sends after - /// the ungrab is then a no-op on an already-thawed device. Pre-fix - /// yserver's XI2 grab/ungrab never touched the sync state, so the - /// freeze outlived the whole modal cycle and EVERY later key event - /// was withheld — one alt-tab permanently killed keyboard input - /// (server log: "AllowEvents no-op ... state=FrozenNoEvent"; - /// trace: zero key events after the alt-tab cluster). - #[test] - fn async_xi2_grab_and_ungrab_thaw_sync_passive_key_freeze() { - use crate::{ - core_loop::key_fanout::key_event_fanout_to_state, host_x11::HostKeyEvent, - server::KeyGrab, xinput::DEVICEID_SLAVE_KEYBOARD, - }; - - const APP_WIN: u32 = 0x0030_0001; - const APP: u32 = 9; - const WM: u32 = 7; - let key_event = |pressed: bool, keycode: u8| HostKeyEvent { - pressed, - keycode, - time: 1, - root_x: 10, - root_y: 20, - event_x: 10, - event_y: 20, - state: 0, - }; - - let mut state = ServerState::new(); - let mut app = install_client(&mut state, APP); - app.set_nonblocking(true).unwrap(); - let _wm = install_client(&mut state, WM); - let mut backend = RecordingBackend::new(); - - // Focused app window with a core KeyPress selection. - state.resources.create_window( - yserver_protocol::x11::ClientId(APP), - CreateWindowRequest { - depth: 24, - window: ResourceId(APP_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(APP_WIN)); - state - .clients - .get_mut(&APP) - .unwrap() - .event_masks - .insert(ResourceId(APP_WIN), 0x1); // KeyPressMask - state.core_focus.raw = APP_WIN; - - // muffin keybinding: SYNC passive key grab on Tab (keycode 23). - state.key_grabs.push(KeyGrab { - owner: ClientId(WM), - grab_window: ROOT_WINDOW, - keycode: 23, - modifiers: 0, - owner_events: false, - pointer_mode: 1, - keyboard_mode: 0, // synchronous → freeze - via_xi2: true, - xi2_mask: 0, - }); - - // 1. Alt+Tab press: passive grab activates + keyboard freezes. - let _ = key_event_fanout_to_state(&mut state, &mut backend, key_event(true, 23)); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .and_then(|f| f.stored.as_ref()) - .is_some(), - "sync passive grab must freeze the activating press", - ); - - // 2. pushModal: ASYNC XIGrabDevice on the keyboard. Body per - // xXIGrabDeviceReq: window(4) time(4) cursor(4) deviceid(2) - // mode(1) paired(1) owner_events(1) pad(1) mask_len(2). - let mut grab_body = Vec::with_capacity(18); - grab_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - grab_body.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime - grab_body.extend_from_slice(&0u32.to_le_bytes()); // cursor = None - grab_body.extend_from_slice(&3u16.to_le_bytes()); // master keyboard - grab_body.push(1); // grab_mode = XIGrabModeAsync - grab_body.push(1); // paired_device_mode = Async - grab_body.push(0); // owner_events = false - grab_body.push(0); // pad - grab_body.extend_from_slice(&0u16.to_le_bytes()); // mask_len = 0 - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(WM), - SequenceNumber(2), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, // XIGrabDevice - length_units: 6, - }, - &grab_body, - ) - .expect("xi grab device"); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .and_then(|f| f.stored.as_ref()) - .is_none(), - "CheckGrabForSyncs: an ASYNC active grab must thaw the \ - sync-passive-grab freeze (Xorg dix/events.c:1431)", - ); - assert!( - !state - .xi1_frozen - .get(&DEVICEID_SLAVE_KEYBOARD) - .is_some_and(crate::server::Xi1Freeze::frozen), - "keyboard sync state must be THAWED after the async grab", - ); - - // 3. popModal: XIUngrabDevice. Body: time(4) deviceid(2) pad(2). - let mut ungrab_body = Vec::with_capacity(8); - ungrab_body.extend_from_slice(&0u32.to_le_bytes()); - ungrab_body.extend_from_slice(&3u16.to_le_bytes()); - ungrab_body.extend_from_slice(&0u16.to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(WM), - SequenceNumber(3), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 52, // XIUngrabDevice - length_units: 3, - }, - &ungrab_body, - ) - .expect("xi ungrab device"); - - // 4. The keyboard must still deliver: a fresh key press reaches - // the focused window's client. - let mut drain = [0u8; 512]; - while app.read(&mut drain).is_ok_and(|n| n > 0) {} - let _ = key_event_fanout_to_state(&mut state, &mut backend, key_event(true, 38)); - let mut buf = [0u8; 64]; - let n = app.read(&mut buf).unwrap_or(0); - assert!( - n >= 32, - "keyboard must keep delivering after the modal grab cycle \ - (got {n} bytes) — a leaked freeze kills all key input", - ); - assert_eq!(buf[0] & 0x7f, 2, "must be a core KeyPress"); - } - - /// `XIGetClientPointer` reply must place `deviceid` at bytes 10-11. - /// Per `xXIGetClientPointerReply` (X11/extensions/XI2proto.h): - /// `set` at byte 8, `pad0` at byte 9, `deviceid` (u16) at bytes - /// 10-11. Regression: the encoder wrote 3 pad bytes after `set`, - /// pushing deviceid to bytes 12-13, so clients read deviceid=0. - /// nemo's desktop rubber-band asks `XIGetClientPointer` for its - /// pointer device, got 0, and queried that for the band anchor — - /// anchoring it at (0,0). caja never calls it, so it was immune. - #[test] - fn xi_get_client_pointer_reply_deviceid_offset() { - const CLIENT_ID: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - // XIGetClientPointer body: window(4). - let body = 0u32.to_le_bytes().to_vec(); - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 45, // XIGetClientPointer - length_units: 2, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("xi get client pointer"); - - let mut buf = [0u8; 64]; - let n = peer.read(&mut buf).expect("reply"); - assert_eq!(n, 32, "reply must be 32 bytes"); - assert_eq!(buf[8], 1, "byte 8: set = True"); - assert_eq!( - u16::from_le_bytes([buf[10], buf[11]]), - 2, - "deviceid (bytes 10-11 per xXIGetClientPointerReply) must be the \ - master pointer (2); a wrong offset reads as 0 and breaks nemo's \ - pointer-device lookup for the rubber-band anchor", - ); - } - - /// XI2 `FocusIn`/`FocusOut` events share the `xXIEnterEvent` layout - /// and must carry the current pointer position (Xorg populates - /// root_x/root_y/event_x/event_y from it). yserver emits focus events - /// from request handlers that have no backend handle, so it reads the - /// cached `state.pointer_root`. Regression target: focus events - /// shipped at (0,0). - #[test] - fn xi_focus_in_carries_cached_pointer_position() { - use crate::resources::ROOT_VISUAL; - - const CLIENT_ID: u32 = 1; - const FOCUS_WIN: u32 = 0x0010_0007; - const PREV_WIN: u32 = 0x0010_0008; - const XI_FOCUS_IN: u16 = 9; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - peer.set_nonblocking(true).unwrap(); - - for xid in [FOCUS_WIN, PREV_WIN] { - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(xid)); - } - // Client selects XI_FocusIn on FOCUS_WIN (keyboard device 3). - state - .clients - .get_mut(&CLIENT_ID) - .unwrap() - .xi2_masks - .insert((ResourceId(FOCUS_WIN), 3), 1 << XI_FOCUS_IN); - - // Cache the pointer position; prior focus is on an unrelated window - // so a Focus crossing actually fires onto FOCUS_WIN. - state.pointer_root = (631, 641); - state.core_focus = crate::server::CoreFocus { - raw: PREV_WIN, - revert_to: 0, - time: 0, - }; - - emit_core_focus_transition(&mut state, PREV_WIN, FOCUS_WIN, 0); - state.core_focus.raw = FOCUS_WIN; - - let mut buf = [0u8; 128]; - let n = peer.read(&mut buf).expect("focus event"); - assert!(n >= 36, "expected an XI2 focus event (got {n} bytes)"); - assert_eq!(buf[0], 35, "must be an XI2 GenericEvent"); - assert_eq!( - u16::from_le_bytes([buf[8], buf[9]]), - XI_FOCUS_IN, - "evtype must be FocusIn", - ); - // root_x is FP1616 at bytes 32-35 (after the 32-byte boundary). - let root_x_fp = u32::from_le_bytes([buf[32], buf[33], buf[34], buf[35]]); - assert_eq!( - root_x_fp, - (631i32 << 16) as u32, - "FocusIn must carry the current pointer X (631), not 0; Xorg \ - populates focus-event coords from the pointer position", - ); - } - - /// Core `AllowEvents(ReplayKeyboard)` (mode 5 — what muffin/mutter - /// calls for a declined key) releases the passive keyboard grab and - /// replays the frozen key to the focused window. This is the - /// dead-`p`-in-wezterm fix end-to-end: a sync passive key grab held - /// `p`, the WM declined it, and ReplayKeyboard hands it to the - /// focused client. - #[test] - fn core_replay_keyboard_releases_grab_and_replays_to_focus() { - use crate::{ - host_x11::HostKeyEvent, - server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const FOCUS_CLIENT_ID: u32 = 2; - const FOCUS_WIN: u32 = 0x0020_0061; - const KEY_PRESS_MASK: u32 = 0x0000_0001; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut focus_peer = install_client(&mut state, FOCUS_CLIENT_ID); - focus_peer.set_nonblocking(true).unwrap(); - - // Focused client selects core KeyPress on its window. - { - let c = state.clients.get_mut(&FOCUS_CLIENT_ID).unwrap(); - c.focused_window = ResourceId(FOCUS_WIN); - c.event_masks.insert(ResourceId(FOCUS_WIN), KEY_PRESS_MASK); - } - state.core_focus.raw = FOCUS_WIN; - - // A sync passive key grab held by the WM is active, with a - // frozen press waiting. - state.active_keyboard_grab = Some(ActiveKeyboardGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ROOT_WINDOW, - owner_events: false, - source: ActiveKeyboardGrabSource::PassiveKey { keycode: 33 }, - via_xi2: true, - xi2_mask: 0, - }); - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostKey(HostKeyEvent { - pressed: true, - keycode: 33, - time: 0x1234, - root_x: 10, - root_y: 20, - event_x: 10, - event_y: 20, - state: 0, - })); - } - - let header = yserver_protocol::x11::RequestHeader { - opcode: 35, - data: 5, // ReplayKeyboard - length_units: 2, - }; - handle_allow_events( - &mut state, - &mut backend, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &[0u8; 4], - ) - .expect("allow events replay keyboard"); - - assert!( - state.active_keyboard_grab.is_none(), - "ReplayKeyboard must release the passive keyboard grab" - ); - assert!( - state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .and_then(|f| f.stored.as_ref()) - .is_none(), - "the frozen key must be consumed by the replay" - ); - let mut buf = [0u8; 64]; - let n = focus_peer.read(&mut buf).unwrap_or(0); - assert!( - n >= 32 && buf[0] == 2, - "replayed KeyPress (event type 2) must reach the focused client; got n={n} type={}", - buf[0] - ); - } - - /// GH #59 regression (bspwm/sxhkd dead keyboard). sxhkd holds a - /// SYNCHRONOUS core passive key grab; after the activating chord - /// press freezes the keyboard it issues exactly ONE - /// AllowEvents(SyncKeyboard) and waits. The terminating key release - /// must reach `key_route` (device still FreezeNextEvent, NOT - /// re-frozen), deactivate the passive grab, and thaw — so typing - /// reaches the focused window. Pre-fix the SyncKeyboard - /// `FreezeNextEvent` allowance was consumed by replaying the grab's - /// OWN already-delivered activating press (double-booked in the XI1 - /// queue), re-freezing to FrozenWithEvent; the release was then - /// withheld, the grab never deactivated, and the keyboard was dead. - /// Xorg's `ComputeFreezes` only replays the stored event for - /// `Replay*`, not `Sync*` (dix/events.c:1320-1370). - #[test] - fn sync_passive_kbd_grab_synckeyboard_release_thaws() { - use crate::{ - core_loop::key_fanout::key_event_fanout_to_state, - host_x11::HostKeyEvent, - server::{KeyGrab, Xi1SyncState}, - }; - - const GRAB_CLIENT_ID: u32 = 1; // sxhkd - const FOCUS_CLIENT_ID: u32 = 2; // kitty - const FOCUS_WIN: u32 = 0x0020_0091; - const KEY_PRESS_MASK: u32 = 0x0000_0001; - const RETURN_KC: u8 = 36; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - let mut focus_peer = install_client(&mut state, FOCUS_CLIENT_ID); - focus_peer.set_nonblocking(true).unwrap(); - { - let c = state.clients.get_mut(&FOCUS_CLIENT_ID).unwrap(); - c.focused_window = ResourceId(FOCUS_WIN); - c.event_masks.insert(ResourceId(FOCUS_WIN), KEY_PRESS_MASK); - } - state.core_focus.raw = FOCUS_WIN; - - // sxhkd's synchronous core passive grab on the chord key. - state.key_grabs.push(KeyGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ROOT_WINDOW, - keycode: RETURN_KC, - modifiers: 0, - owner_events: true, - pointer_mode: 1, - keyboard_mode: 0, // synchronous → freeze - via_xi2: false, - xi2_mask: 0, - }); - - let key = |pressed, keycode| HostKeyEvent { - pressed, - keycode, - time: 1, - root_x: 0, - root_y: 0, - event_x: 0, - event_y: 0, - state: 0, - }; - - // 1) chord press activates the grab and freezes the device. - let _ = key_event_fanout_to_state(&mut state, &mut backend, key(true, RETURN_KC)); - assert!( - state.active_keyboard_grab.is_some(), - "synchronous passive grab must activate on the chord press" - ); - - // 2) sxhkd issues a single AllowEvents(SyncKeyboard) (mode 4). - let header = yserver_protocol::x11::RequestHeader { - opcode: 35, - data: 4, // SyncKeyboard - length_units: 2, - }; - handle_allow_events( - &mut state, - &mut backend, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &[0u8; 4], - ) - .expect("allow events sync keyboard"); - - // 3) the terminating release must deactivate the grab and thaw. - let _ = key_event_fanout_to_state(&mut state, &mut backend, key(false, RETURN_KC)); - assert!( - state.active_keyboard_grab.is_none(), - "the matching key release must deactivate the passive grab" - ); - let frozen = state - .xi1_frozen - .get(&crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .map_or(Xi1SyncState::Thawed, |f| f.state); - assert_eq!( - frozen, - Xi1SyncState::Thawed, - "the terminating release must thaw the keyboard (not leave it FrozenWithEvent)" - ); - - // 4) typing (an ungrabbed key) must now reach the focused window. - let _ = key_event_fanout_to_state(&mut state, &mut backend, key(true, 38)); - let mut buf = [0u8; 64]; - let n = focus_peer.read(&mut buf).unwrap_or(0); - assert!( - n >= 32 && buf[0] == 2, - "after the grab releases, typing must reach the focused window; got n={n} type={}", - buf[0] - ); - } - - /// Regression (codex review): ReplayKeyboard must release an - /// EXPLICIT GrabKeyboard(GrabModeSync), not just a passive key - /// grab — Xorg NOT_GRABBED calls DeactivateGrab regardless of - /// grab kind (dix/events.c:1898). Pre-fix the grab stayed active - /// after the replay → stuck keyboard. - #[test] - fn core_replay_keyboard_releases_explicit_sync_grab() { - use crate::{ - host_x11::HostKeyEvent, - server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}, - }; - - const GRAB_CLIENT_ID: u32 = 1; - const FOCUS_WIN: u32 = 0x0020_0071; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); - state.core_focus.raw = FOCUS_WIN; - - // Explicit GrabKeyboard(GrabModeSync): active grab + the - // device frozen-no-event, with a key withheld in the freeze - // queue (the "with event" condition for replay). - state.active_keyboard_grab = Some(ActiveKeyboardGrab { - owner: ClientId(GRAB_CLIENT_ID), - grab_window: ROOT_WINDOW, - owner_events: false, - source: ActiveKeyboardGrabSource::Explicit, - via_xi2: false, - xi2_mask: 0, - }); - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_KEYBOARD) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenNoEvent; - state - .sync_pending - .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_KEYBOARD, - event: crate::server::QueuedInputEvent::HostKey(HostKeyEvent { - pressed: true, - keycode: 38, - time: 0x2222, - root_x: 1, - root_y: 2, - event_x: 1, - event_y: 2, - state: 0, - }), - }); - } - - let header = yserver_protocol::x11::RequestHeader { - opcode: 35, - data: 5, // ReplayKeyboard - length_units: 2, - }; - handle_allow_events( - &mut state, - &mut backend, - ClientId(GRAB_CLIENT_ID), - SequenceNumber(1), - header, - &[0u8; 4], - ) - .expect("allow events replay keyboard"); - - assert!( - state.active_keyboard_grab.is_none(), - "ReplayKeyboard must deactivate the explicit sync keyboard grab", - ); - } - - /// XFixes `SetCursorName(cursor, "name")` interns the name as an - /// atom and stores it on the cursor; the subsequent - /// `GetCursorName(cursor)` returns the same atom + name bytes. - /// A cursor that was never named reports atom=0 (None) + empty - /// name, matching Xorg `xfixes/cursor.c:ProcXFixesGetCursorName`'s - /// `pCursor->name == 0` branch. - #[test] - fn xfixes_cursor_name_round_trip() { - use std::io::Read; - - const CLIENT_ID: u32 = 1; - const CURSOR_XID: u32 = 0x0090_0042; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - state - .resources - .create_cursor(ClientId(CLIENT_ID), ResourceId(CURSOR_XID)); - - let name = b"xterm"; - // SetCursorName body: cursor(4) + nbytes(2) + pad(2) + name + pad. - let mut set_body = Vec::with_capacity(16); - set_body.extend_from_slice(&CURSOR_XID.to_le_bytes()); - #[allow(clippy::cast_possible_truncation)] - set_body.extend_from_slice(&(name.len() as u16).to_le_bytes()); - set_body.extend_from_slice(&[0u8; 2]); - set_body.extend_from_slice(name); - while !set_body.len().is_multiple_of(4) { - set_body.push(0); - } - - let header = yserver_protocol::x11::RequestHeader { - opcode: 140, // XFIXES major (dispatcher reads minor from header.data) - data: 23, // SET_CURSOR_NAME - length_units: 3, - }; - handle_xfixes_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &set_body, - ) - .expect("SetCursorName"); - - // The atom must be stored on the cursor and resolve back to - // the original name. - let stored = state - .resources - .cursor_name_atom(ResourceId(CURSOR_XID)) - .expect("name atom present after SetCursorName"); - assert!(stored.0 != 0, "non-None atom expected for non-empty name"); - assert_eq!( - state.atoms.name(stored).map(str::as_bytes), - Some(name.as_ref()), - "interned atom must reverse-resolve to the original name", - ); - - // GetCursorName body: cursor(4). - let get_body = CURSOR_XID.to_le_bytes().to_vec(); - let get_header = yserver_protocol::x11::RequestHeader { - opcode: 140, - data: 24, // GET_CURSOR_NAME - length_units: 2, - }; - handle_xfixes_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(2), - get_header, - &get_body, - ) - .expect("GetCursorName"); - - peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 1024]; - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - // Reply layout: type(1) + pad(1) + sequence(2) + length(4) + - // atom(4) + nbytes(2) + pad(18) + name(n) + pad-to-4. - assert_eq!(wire[0], 1, "X_Reply type byte"); - let reply_atom = u32::from_le_bytes(wire[8..12].try_into().unwrap()); - let reply_nbytes = u16::from_le_bytes(wire[12..14].try_into().unwrap()) as usize; - assert_eq!(reply_atom, stored.0, "reply atom matches stored atom"); - assert_eq!(reply_nbytes, name.len()); - assert_eq!( - &wire[32..32 + name.len()], - name, - "reply name bytes match the original", - ); - - // GetCursorName on an unnamed cursor → atom=0, nbytes=0. - const UNNAMED_XID: u32 = 0x0090_0099; - state - .resources - .create_cursor(ClientId(CLIENT_ID), ResourceId(UNNAMED_XID)); - let get_body = UNNAMED_XID.to_le_bytes().to_vec(); - handle_xfixes_request( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(3), - get_header, - &get_body, - ) - .expect("GetCursorName unnamed"); - let mut wire2 = Vec::new(); - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire2.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - let reply_atom = u32::from_le_bytes(wire2[8..12].try_into().unwrap()); - let reply_nbytes = u16::from_le_bytes(wire2[12..14].try_into().unwrap()) as usize; - assert_eq!(reply_atom, 0, "unnamed cursor reports atom=0 (None)"); - assert_eq!(reply_nbytes, 0, "unnamed cursor reports empty name"); - } - - /// One XFIXES request through the real dispatcher (version gate - /// included), little-endian body. - fn xfixes_req( - state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - minor: u8, - body: &[u8], - ) { - process_request( - state, - backend, - ClientId(client), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: minor, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - None, - ) - .expect("xfixes request"); - } - - fn xfixes_u32s(values: &[u32]) -> Vec { - values.iter().flat_map(|v| v.to_le_bytes()).collect() - } - - /// Split queued 32-byte packets (errors, events, fixed replies). - fn wire_packets(peer: &mut UnixStream) -> Vec<[u8; 32]> { - read_all_available(peer) - .chunks_exact(32) - .map(|c| <[u8; 32]>::try_from(c).unwrap()) - .collect() - } - - fn le_u32(p: &[u8], at: usize) -> u32 { - u32::from_le_bytes(p[at..at + 4].try_into().unwrap()) - } - - /// Error packet → (code, bad value, minor, major). - fn error_fields(p: &[u8; 32]) -> (u8, u32, u16, u8) { - assert_eq!(p[0], 0, "expected an error packet, got type {}", p[0]); - (p[1], le_u32(p, 4), u16::from_le_bytes([p[8], p[9]]), p[10]) - } - - /// QueryVersion follows Xorg's rule and gates requests on the - /// negotiated major. Ground truth: Xorg 21.1.24 Xvfb, raw xcb probe — - /// HideCursor before QueryVersion is BadRequest (major 138 there, - /// minor 29, value 0); 4.0 → 4.0; then 2.0 → 2.0 while HideCursor - /// still succeeds and DeletePointerBarrier (a 5.0 request) is - /// BadRequest; 7.0 is capped at the server version. - #[test] - fn xfixes_query_version_negotiates_and_gates_requests() { - use yserver_protocol::x11::xfixes as x11xfixes; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let root = ROOT_WINDOW.0; - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::HIDE_CURSOR, - &xfixes_u32s(&[root]), - ); - let packets = wire_packets(&mut peer); - assert_eq!(packets.len(), 1); - assert_eq!( - error_fields(&packets[0]), - (x11::error::BAD_REQUEST, 0, 29, XFIXES_MAJOR_OPCODE) - ); - assert!(state.xfixes_cursor_hide_counts.is_empty()); - - let query = |state: &mut ServerState, - backend: &mut RecordingBackend, - peer: &mut UnixStream, - major: u32, - minor: u32| { - xfixes_req( - state, - backend, - 1, - x11xfixes::QUERY_VERSION, - &xfixes_u32s(&[major, minor]), - ); - let packets = wire_packets(peer); - assert_eq!(packets.len(), 1); - assert_eq!(packets[0][0], 1, "reply"); - (le_u32(&packets[0], 8), le_u32(&packets[0], 12)) - }; - assert_eq!(query(&mut state, &mut backend, &mut peer, 4, 0), (4, 0)); - assert_eq!(query(&mut state, &mut backend, &mut peer, 2, 0), (2, 0)); - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::HIDE_CURSOR, - &xfixes_u32s(&[root]), - ); - assert!(wire_packets(&mut peer).is_empty(), "4.0 request set kept"); - assert_eq!(state.xfixes_cursor_hide_counts.get(&1), Some(&1)); - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::DELETE_POINTER_BARRIER, - &xfixes_u32s(&[0x1234]), - ); - let packets = wire_packets(&mut peer); - assert_eq!( - error_fields(&packets[0]), - (x11::error::BAD_REQUEST, 0, 32, XFIXES_MAJOR_OPCODE) - ); - - assert_eq!(query(&mut state, &mut backend, &mut peer, 7, 0), (5, 0)); - assert_eq!(query(&mut state, &mut backend, &mut peer, 3, 7), (3, 7)); - } - - /// Hide/Show counting, captured on Xvfb: bad window → BadWindow (value - /// = window) for both; ShowCursor without a hide → BadMatch (value = - /// window); two hides need two shows and a third show is BadMatch. - /// Across clients the sprite hides on the first hide anywhere and - /// comes back when the last hider shows or disconnects. - #[test] - fn xfixes_hide_show_cursor_counts_per_client() { - use yserver_protocol::x11::xfixes as x11xfixes; - let mut state = ServerState::new(); - let mut peer1 = install_client(&mut state, 1); - let _peer2 = install_client(&mut state, 2); - state.xfixes_client_major.insert(1, 5); - state.xfixes_client_major.insert(2, 5); - let mut backend = RecordingBackend::new(); - let root = ROOT_WINDOW.0; - let hidden_calls = |backend: &RecordingBackend| -> Vec { - backend - .calls - .lock() - .unwrap() - .iter() - .filter_map(|c| match c { - RecordedCall::SetCursorHidden(h) => Some(*h), - _ => None, - }) - .collect() - }; - - for minor in [x11xfixes::HIDE_CURSOR, x11xfixes::SHOW_CURSOR] { - xfixes_req( - &mut state, - &mut backend, - 1, - minor, - &xfixes_u32s(&[0x0bad_bad0]), - ); - let packets = wire_packets(&mut peer1); - assert_eq!( - error_fields(&packets[0]), - ( - x11::error::BAD_WINDOW, - 0x0bad_bad0, - u16::from(minor), - XFIXES_MAJOR_OPCODE - ) - ); - } - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SHOW_CURSOR, - &xfixes_u32s(&[root]), - ); - let packets = wire_packets(&mut peer1); - assert_eq!( - error_fields(&packets[0]), - (x11::error::BAD_MATCH, root, 30, XFIXES_MAJOR_OPCODE) - ); - assert!(hidden_calls(&backend).is_empty()); - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::HIDE_CURSOR, - &xfixes_u32s(&[root]), - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::HIDE_CURSOR, - &xfixes_u32s(&[root]), - ); - xfixes_req( - &mut state, - &mut backend, - 2, - x11xfixes::HIDE_CURSOR, - &xfixes_u32s(&[root]), - ); - assert_eq!( - hidden_calls(&backend), - vec![true], - "one edge for three hides" - ); - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SHOW_CURSOR, - &xfixes_u32s(&[root]), - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SHOW_CURSOR, - &xfixes_u32s(&[root]), - ); - assert!(wire_packets(&mut peer1).is_empty()); - assert_eq!(hidden_calls(&backend), vec![true], "client 2 still hides"); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SHOW_CURSOR, - &xfixes_u32s(&[root]), - ); - let packets = wire_packets(&mut peer1); - assert_eq!( - error_fields(&packets[0]), - (x11::error::BAD_MATCH, root, 30, XFIXES_MAJOR_OPCODE) - ); - - crate::core_loop::process_disconnect::process_disconnect( - &mut state, - &mut backend, - ClientId(2), - ); - assert_eq!( - hidden_calls(&backend), - vec![true, false], - "disconnect shows" - ); - assert!(state.xfixes_cursor_hide_counts.is_empty()); - assert!(!state.xfixes_client_major.contains_key(&2)); - } - - /// CursorNotify fan-out, per the Xvfb capture: one event per - /// (client, window) selection carrying that window, the cursor serial - /// and its name atom; a destroyed window's selection is gone; bad mask - /// → BadValue, bad window → BadWindow. - #[test] - fn xfixes_cursor_notify_goes_to_each_selection() { - use yserver_protocol::x11::xfixes as x11xfixes; - const CHILD: u32 = 0x0040_0001; - const CURSOR: u32 = 0x0040_0010; - const HOST: u32 = 0x0001_0077; - let mut state = ServerState::new(); - let mut peer1 = install_client(&mut state, 1); - let mut peer2 = install_client(&mut state, 2); - state.xfixes_client_major.insert(1, 5); - state.xfixes_client_major.insert(2, 5); - let mut backend = RecordingBackend::new(); - let root = ROOT_WINDOW.0; - create_present_test_window(&mut state, CHILD, 0, 0, 10, 10); - state - .resources - .create_cursor(ClientId(1), ResourceId(CURSOR)); - state.resources.set_cursor_host_xid( - ResourceId(CURSOR), - crate::backend::CursorHandle::from_raw(HOST).unwrap(), - ); - let name = state.atoms.intern("bname", false); - state - .resources - .set_cursor_name_atom(ResourceId(CURSOR), name); - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SELECT_CURSOR_INPUT, - &xfixes_u32s(&[root, 2]), - ); - assert_eq!( - error_fields(&wire_packets(&mut peer1)[0]), - (x11::error::BAD_VALUE, 2, 3, XFIXES_MAJOR_OPCODE) - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SELECT_CURSOR_INPUT, - &xfixes_u32s(&[0x0bad_bad0, 1]), - ); - assert_eq!( - error_fields(&wire_packets(&mut peer1)[0]), - (x11::error::BAD_WINDOW, 0x0bad_bad0, 3, XFIXES_MAJOR_OPCODE) - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SELECT_CURSOR_INPUT, - &xfixes_u32s(&[root, 1]), - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::SELECT_CURSOR_INPUT, - &xfixes_u32s(&[CHILD, 1]), - ); - assert!(wire_packets(&mut peer1).is_empty()); - - backend.displayed_cursor_change = Some(crate::backend::DisplayedCursor { - host_xid: HOST, - serial: 3, - }); - emit_xfixes_cursor_notify(&mut state, &mut backend); - let events = wire_packets(&mut peer1); - assert_eq!(events.len(), 2, "one per selection"); - let mut windows = Vec::new(); - for e in &events { - assert_eq!(e[0], crate::nested::XFIXES_FIRST_EVENT + 1); - assert_eq!(e[1], x11xfixes::DISPLAY_CURSOR_NOTIFY); - windows.push(le_u32(e, 4)); - assert_eq!(le_u32(e, 8), 3, "serial"); - assert_eq!(le_u32(e, 16), name.0, "name atom"); - } - windows.sort_unstable(); - assert_eq!(windows, vec![root, CHILD]); - assert!( - wire_packets(&mut peer2).is_empty(), - "client 2 never selected" - ); - emit_xfixes_cursor_notify(&mut state, &mut backend); - assert!( - wire_packets(&mut peer1).is_empty(), - "the report is consumed" - ); - - // Destroying the child drops its selection (Xorg CursorFreeWindow). - destroy_window_subtree(&mut state, &mut backend, None, ResourceId(CHILD)); - backend.displayed_cursor_change = Some(crate::backend::DisplayedCursor { - host_xid: 0x0001_0099, - serial: 1, - }); - emit_xfixes_cursor_notify(&mut state, &mut backend); - let events = wire_packets(&mut peer1); - assert_eq!(events.len(), 1); - assert_eq!(le_u32(&events[0], 4), root); - assert_eq!(le_u32(&events[0], 16), 0, "unnamed cursor"); - } - - /// ChangeCursor: every XID of the destination cursor now names the - /// source cursor, and the backend replaces its displayed uses. Xvfb: - /// bad source / bad destination → BadCursor naming it. - #[test] - fn xfixes_change_cursor_retargets_cursor_and_backend() { - use yserver_protocol::x11::xfixes as x11xfixes; - const A: u32 = 0x0040_0020; - const D: u32 = 0x0040_0021; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.xfixes_client_major.insert(1, 5); - let mut backend = RecordingBackend::new(); - for (xid, host) in [(A, 0x0001_0010), (D, 0x0001_0020)] { - state.resources.create_cursor(ClientId(1), ResourceId(xid)); - state.resources.set_cursor_host_xid( - ResourceId(xid), - crate::backend::CursorHandle::from_raw(host).unwrap(), - ); - } - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::CHANGE_CURSOR, - &xfixes_u32s(&[0x0bad_bad0, A]), - ); - assert_eq!( - error_fields(&wire_packets(&mut peer)[0]), - (x11::error::BAD_CURSOR, 0x0bad_bad0, 26, XFIXES_MAJOR_OPCODE) - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::CHANGE_CURSOR, - &xfixes_u32s(&[D, 0x0bad_bad0]), - ); - assert_eq!( - error_fields(&wire_packets(&mut peer)[0]), - (x11::error::BAD_CURSOR, 0x0bad_bad0, 26, XFIXES_MAJOR_OPCODE) - ); - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::CHANGE_CURSOR, - &xfixes_u32s(&[D, A]), - ); - assert!(wire_packets(&mut peer).is_empty()); - assert_eq!( - state.resources.cursor_host_xid(ResourceId(A)), - Some(0x0001_0020) - ); - let calls = backend.calls.lock().unwrap().clone(); - assert!(calls.contains(&RecordedCall::ReplaceCursor { - old_host_xid: 0x0001_0010, - new_host_xid: 0x0001_0020, - })); - // A and D now share one host cursor: freeing one XID must not free it. - assert_eq!(state.resources.free_cursor(ResourceId(A)), None); - assert_eq!( - state.resources.free_cursor(ResourceId(D)), - Some(0x0001_0020) - ); - } - - /// ChangeCursorByName matches the cursor object's name even after the - /// client freed its XID (the window still shows it); a name nobody - /// interned matches nothing and is not an error (Xvfb: OK). - #[test] - fn xfixes_change_cursor_by_name_replaces_named_cursors() { - use yserver_protocol::x11::xfixes as x11xfixes; - const A: u32 = 0x0040_0030; - const B: u32 = 0x0040_0031; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.xfixes_client_major.insert(1, 5); - let mut backend = RecordingBackend::new(); - for (xid, host) in [(A, 0x0001_0030), (B, 0x0001_0031)] { - state.resources.create_cursor(ClientId(1), ResourceId(xid)); - state.resources.set_cursor_host_xid( - ResourceId(xid), - crate::backend::CursorHandle::from_raw(host).unwrap(), - ); - } - let name = state.atoms.intern("bname", false); - state.resources.set_cursor_name_atom(ResourceId(B), name); - let _ = state.resources.free_cursor(ResourceId(B)); - - let by_name = |name: &[u8]| { - let mut body = Vec::new(); - body.extend_from_slice(&A.to_le_bytes()); - body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); - body.extend_from_slice(&[0, 0]); - body.extend_from_slice(name); - body.resize(body.len().div_ceil(4) * 4, 0); - body - }; - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::CHANGE_CURSOR_BY_NAME, - &by_name(b"zzznoname"), - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::CHANGE_CURSOR_BY_NAME, - &by_name(b"bname"), - ); - assert!(wire_packets(&mut peer).is_empty()); - let replaces: Vec = backend - .calls - .lock() - .unwrap() - .iter() - .filter(|c| matches!(c, RecordedCall::ReplaceCursor { .. })) - .cloned() - .collect(); - assert_eq!( - replaces, - vec![RecordedCall::ReplaceCursor { - old_host_xid: 0x0001_0031, - new_host_xid: 0x0001_0030, - }] - ); - assert_eq!(state.resources.cursor_name_for_host(0x0001_0031), None); - } - - /// ExpandRegion against Xvfb: {(10,10 5x5),(30,30 5x5)} expanded by - /// l1 r2 t3 b4 → {(9,7 8x12),(29,27 8x12)}; by l20 r20 → the - /// overlapping boxes are unioned into {(-10,10 45x5),(10,30 45x5)}; an - /// empty source leaves the destination as it was; bad source or - /// destination → XFixes BadRegion (error base + 0) naming it. - #[test] - fn xfixes_expand_region_matches_xvfb() { - use yserver_protocol::x11::xfixes::{self as x11xfixes, RegionRect}; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.xfixes_client_major.insert(1, 5); - let mut backend = RecordingBackend::new(); - let rect = |x, y, width, height| RegionRect { - x, - y, - width, - height, - }; - let region = |rects| crate::server::XFixesRegion { - owner: ClientId(1), - rects, - }; - state - .xfixes_regions - .insert(0x10, region(vec![rect(10, 10, 5, 5), rect(30, 30, 5, 5)])); - state - .xfixes_regions - .insert(0x11, region(vec![rect(100, 100, 7, 7)])); - state.xfixes_regions.insert(0x12, region(Vec::new())); - let expand = |src: u32, dst: u32, l: u16, r: u16, t: u16, b: u16| { - let mut body = xfixes_u32s(&[src, dst]); - for v in [l, r, t, b] { - body.extend_from_slice(&v.to_le_bytes()); - } - body - }; - - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::EXPAND_REGION, - &expand(0x10, 0x11, 1, 2, 3, 4), - ); - assert_eq!( - state.xfixes_regions[&0x11].rects, - vec![rect(9, 7, 8, 12), rect(29, 27, 8, 12)] - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::EXPAND_REGION, - &expand(0x10, 0x11, 20, 20, 0, 0), - ); - assert_eq!( - state.xfixes_regions[&0x11].rects, - vec![rect(-10, 10, 45, 5), rect(10, 30, 45, 5)] - ); - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::EXPAND_REGION, - &expand(0x12, 0x11, 1, 1, 1, 1), - ); - assert_eq!( - state.xfixes_regions[&0x11].rects, - vec![rect(-10, 10, 45, 5), rect(10, 30, 45, 5)] - ); - assert!(wire_packets(&mut peer).is_empty()); - - for (src, dst) in [(0x0bad_bad0, 0x11), (0x10, 0x0bad_bad0)] { - xfixes_req( - &mut state, - &mut backend, - 1, - x11xfixes::EXPAND_REGION, - &expand(src, dst, 1, 1, 1, 1), - ); - assert_eq!( - error_fields(&wire_packets(&mut peer)[0]), - ( - crate::nested::XFIXES_FIRST_ERROR, - 0x0bad_bad0, - 28, - XFIXES_MAJOR_OPCODE - ) - ); - } - } - - // ── SYNC Await / AwaitFence ───────────────────────────────────── - // Ground truth for every expectation below: Xorg 21.1.24 Xvfb driven - // by a two-connection xcb probe (client A changes counters and fences, - // client B awaits and then sends GetInputFocus; "suspended" means B's - // reply had not arrived after A's round trip). - - fn sync_req( - state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - minor: u8, - body: &[u8], - ) { - process_request( - state, - backend, - ClientId(client), - SequenceNumber(1), - RequestHeader { - opcode: 142, - data: minor, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - None, - ) - .expect("sync request"); - } - - fn sync_i64(v: i64) -> [u8; 8] { - let mut out = [0u8; 8]; - #[allow(clippy::cast_possible_truncation)] - out[..4].copy_from_slice(&((v >> 32) as i32).to_le_bytes()); - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - out[4..].copy_from_slice(&(v as u32).to_le_bytes()); - out - } - - fn sync_counter_body(counter: u32, value: i64) -> Vec { - let mut body = counter.to_le_bytes().to_vec(); - body.extend_from_slice(&sync_i64(value)); - body - } - - /// One `WAITCONDITION`: counter, value type, wait value, test type, - /// event threshold. - fn sync_wait( - counter: u32, - value_type: u32, - wait: i64, - test_type: u32, - threshold: i64, - ) -> Vec { - let mut body = counter.to_le_bytes().to_vec(); - body.extend_from_slice(&value_type.to_le_bytes()); - body.extend_from_slice(&sync_i64(wait)); - body.extend_from_slice(&test_type.to_le_bytes()); - body.extend_from_slice(&sync_i64(threshold)); - body - } - - /// CounterNotify → (counter, wait value, counter value, count, destroyed). - fn counter_notify_fields(p: &[u8; 32]) -> (u32, i64, i64, u16, bool) { - assert_eq!(p[0], crate::nested::SYNC_FIRST_EVENT, "CounterNotify type"); - assert_eq!(p[1], 0, "kind CounterNotify"); - let i64_at = |at: usize| { - #[allow(clippy::cast_possible_wrap)] - let hi = le_u32(p, at) as i32; - (i64::from(hi) << 32) | i64::from(le_u32(p, at + 4)) - }; - ( - le_u32(p, 4), - i64_at(8), - i64_at(16), - u16::from_le_bytes([p[28], p[29]]), - p[30] != 0, - ) - } - - struct SyncFixture { - state: ServerState, - backend: RecordingBackend, - _peer_a: UnixStream, - peer_b: UnixStream, - } - - const SYNC_A: u32 = 1; - const SYNC_B: u32 = 2; - const SYNC_C1: u32 = 0x0010_0001; - const SYNC_C2: u32 = 0x0010_0002; - - fn sync_fixture() -> SyncFixture { - let mut state = ServerState::new(); - let peer_a = install_client(&mut state, SYNC_A); - let peer_b = install_client(&mut state, SYNC_B); - SyncFixture { - state, - backend: RecordingBackend::new(), - _peer_a: peer_a, - peer_b, - } - } - - impl SyncFixture { - fn a(&mut self, minor: u8, body: &[u8]) { - sync_req(&mut self.state, &mut self.backend, SYNC_A, minor, body); - } - fn b(&mut self, minor: u8, body: &[u8]) { - sync_req(&mut self.state, &mut self.backend, SYNC_B, minor, body); - } - fn suspended(&self) -> bool { - crate::core_loop::sync_await::client_is_suspended(&self.state, ClientId(SYNC_B)) - } - fn b_packets(&mut self) -> Vec<[u8; 32]> { - wire_packets(&mut self.peer_b) - } - fn a_packets(&mut self) -> Vec<[u8; 32]> { - wire_packets(&mut self._peer_a) - } - } - - /// Xvfb: B awaits c1 >= 5 (PositiveComparison); A sets 3 → B stays - /// suspended; A sets 7 → B resumes with CounterNotify(c1, wait 5, - /// value 7, count 0, not destroyed). - #[test] - fn sync_await_suspends_until_the_counter_condition_holds() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 5, - s::TEST_POSITIVE_COMPARISON, - 0, - ), - ); - assert!(f.suspended()); - assert!(f.b_packets().is_empty()); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 3)); - assert!(f.suspended(), "3 < 5"); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 7)); - assert!(!f.suspended()); - let events = f.b_packets(); - assert_eq!(events.len(), 1); - assert_eq!(counter_notify_fields(&events[0]), (SYNC_C1, 5, 7, 0, false)); - - // Already satisfied at request time: no suspension, the event - // still goes out (Xvfb: reply arrives with CounterNotify wait 5 - // value 7). - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 5, - s::TEST_POSITIVE_COMPARISON, - 0, - ), - ); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (SYNC_C1, 5, 7, 0, false) - ); - } - - /// Transitions need a crossing and events respect the threshold, per - /// Xvfb: PositiveTransition 10 thr 2 from 7 → set 9 (no), set 12 → - /// event value 12; from 12, PositiveTransition 10 → set 1 does not - /// fire (no upward crossing); from 1, PositiveTransition 10 → 5 (no), - /// 11 → event; PositiveTransition 0 thr 5 from -5 → set 1 resumes the - /// client without an event (diff 1 < 5). - #[test] - fn sync_await_transitions_and_event_threshold() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 7)); - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 10, - s::TEST_POSITIVE_TRANSITION, - 2, - ), - ); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 9)); - assert!(f.suspended()); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 12)); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (SYNC_C1, 10, 12, 0, false) - ); - - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 10, - s::TEST_POSITIVE_TRANSITION, - 100, - ), - ); - assert!(f.suspended(), "12 >= 10 but no transition yet"); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 1)); - assert!(f.suspended()); - f.state.sync_awaits.remove(&SYNC_B); - - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 10, - s::TEST_POSITIVE_TRANSITION, - 0, - ), - ); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 5)); - assert!(f.suspended()); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 11)); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (SYNC_C1, 10, 11, 0, false) - ); - - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, -5)); - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 0, - s::TEST_POSITIVE_TRANSITION, - 5, - ), - ); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 1)); - assert!(!f.suspended()); - assert!(f.b_packets().is_empty(), "diff below threshold: no event"); - } - - /// Xvfb: c1=11, c2=100; B awaits [c1 >= 1000 thr -2000, c2 <= 45 thr - /// 0]; A sets c2 50 (suspended) then 40 → both conditions report, in - /// order, count 1 then 0. Relative waits add to the counter (c1=11, - /// +3 → wait 14); NegativeTransition -3 fires on the way down. - #[test] - fn sync_await_multi_condition_relative_and_negative() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 11)); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 100)); - let mut body = sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 1000, - s::TEST_POSITIVE_COMPARISON, - -2000, - ); - body.extend(sync_wait( - SYNC_C2, - s::VALUE_TYPE_ABSOLUTE, - 45, - s::TEST_NEGATIVE_COMPARISON, - 0, - )); - f.b(s::AWAIT, &body); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C2, 50)); - assert!(f.suspended()); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C2, 40)); - assert!(!f.suspended()); - let events = f.b_packets(); - assert_eq!(events.len(), 2); - assert_eq!( - counter_notify_fields(&events[0]), - (SYNC_C1, 1000, 11, 1, false) - ); - assert_eq!( - counter_notify_fields(&events[1]), - (SYNC_C2, 45, 40, 0, false) - ); - - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_RELATIVE, - 3, - s::TEST_POSITIVE_COMPARISON, - 0, - ), - ); - f.a(s::CHANGE_COUNTER, &sync_counter_body(SYNC_C1, 2)); - assert!(f.suspended()); - f.a(s::CHANGE_COUNTER, &sync_counter_body(SYNC_C1, 1)); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (SYNC_C1, 14, 14, 0, false) - ); - - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - -3, - s::TEST_NEGATIVE_TRANSITION, - 0, - ), - ); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, -5)); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (SYNC_C1, -3, -5, 0, false) - ); - } - - /// Xvfb: destroying an awaited counter resumes the client with a - /// destroyed event carrying its last value, plus threshold events for - /// the other conditions; an alarm on it goes Inactive with an - /// AlarmNotify. A counter owner disconnecting does the same (value 0). - #[test] - fn sync_await_fires_destroyed_when_the_counter_goes_away() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, -5)); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 40)); - let mut body = sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 1000, - s::TEST_POSITIVE_COMPARISON, - 0, - ); - body.extend(sync_wait( - SYNC_C2, - s::VALUE_TYPE_ABSOLUTE, - 1000, - s::TEST_POSITIVE_COMPARISON, - -2000, - )); - f.b(s::AWAIT, &body); - f.state.sync_alarms.insert( - 0x0020_0009, - crate::server::SyncAlarm { - owner: ClientId(SYNC_B), - counter: SYNC_C1, - wait_value: 1000, - delta: 1, - test_type: s::TEST_POSITIVE_COMPARISON, - events: true, - state: s::ALARM_STATE_ACTIVE, - event_clients: Vec::new(), - value_type: 0, - raw_wait: 1000, - check_type: s::TEST_POSITIVE_COMPARISON, - }, - ); - f.a(s::DESTROY_COUNTER, &SYNC_C1.to_le_bytes()); - assert!(!f.suspended()); - let packets = f.b_packets(); - let notifies: Vec<_> = packets - .iter() - .filter(|p| p[0] == crate::nested::SYNC_FIRST_EVENT) - .map(counter_notify_fields) - .collect(); - assert_eq!( - notifies, - vec![(SYNC_C1, 1000, -5, 1, true), (SYNC_C2, 1000, 40, 0, false)] - ); - let alarm = packets - .iter() - .find(|p| p[0] == crate::nested::SYNC_FIRST_EVENT + 1) - .expect("AlarmNotify for the alarm on the destroyed counter"); - assert_eq!(alarm[28], s::ALARM_STATE_INACTIVE); - assert_eq!( - f.state.sync_alarms[&0x0020_0009].state, - s::ALARM_STATE_INACTIVE - ); - assert_eq!(f.state.sync_alarms[&0x0020_0009].counter, 0); - - // Owner disconnect: Xvfb sends destroyed, wait 10, value 0. - const C3: u32 = 0x0030_0001; - let _peer_c = install_client(&mut f.state, 3); - sync_req( - &mut f.state, - &mut f.backend, - 3, - s::CREATE_COUNTER, - &sync_counter_body(C3, 0), - ); - f.b( - s::AWAIT, - &sync_wait( - C3, - s::VALUE_TYPE_ABSOLUTE, - 10, - s::TEST_POSITIVE_COMPARISON, - 0, - ), - ); - assert!(f.suspended()); - crate::core_loop::process_disconnect::process_disconnect( - &mut f.state, - &mut f.backend, - ClientId(3), - ); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (C3, 10, 0, 0, true) - ); - } - - /// Xvfb: Initialize with client 3.1 / 3.0 / 2.0 / 4.0 always replies 3.1. - #[test] - fn sync_initialize_always_answers_the_server_version() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - for (major, minor) in [(3u8, 1u8), (3, 0), (2, 0), (4, 0)] { - f.b(s::INITIALIZE, &[major, minor, 0, 0]); - let reply = f.b_packets(); - assert_eq!(reply[0][0], 1); - assert_eq!((reply[0][8], reply[0][9]), (3, 1), "client {major}.{minor}"); - } - } - - /// Xvfb error table for Await and the counter requests. - #[test] - fn sync_await_and_counter_errors_match_xvfb() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - let bad_counter = crate::nested::SYNC_FIRST_ERROR + s::BAD_COUNTER; - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 100)); - let cases: [(Vec, u8, u32); 6] = [ - (Vec::new(), x11::error::BAD_VALUE, 0), - (sync_wait(0, 0, 1, 2, 0), bad_counter, 0), - (sync_wait(0x0bad_bad0, 0, 1, 2, 0), bad_counter, 0x0bad_bad0), - (sync_wait(SYNC_C2, 7, 1, 2, 0), x11::error::BAD_VALUE, 7), - (sync_wait(SYNC_C2, 0, 1, 9, 0), x11::error::BAD_VALUE, 9), - ( - sync_wait(SYNC_C2, 1, i64::MAX, 2, 0), - x11::error::BAD_VALUE, - 0x7fff_ffff, - ), - ]; - for (body, code, value) in cases { - f.b(s::AWAIT, &body); - assert!(!f.suspended(), "an erroring Await never suspends"); - assert_eq!( - error_fields(&f.b_packets()[0]), - (code, value, u16::from(s::AWAIT), 142) - ); - } - let mut peer_a = std::mem::replace(&mut f._peer_a, UnixStream::pair().unwrap().0); - let st = s::SERVERTIME_COUNTER; - let a_cases: [(u8, Vec, u8, u32); 5] = [ - ( - s::SET_COUNTER, - sync_counter_body(st, 1), - x11::error::BAD_ACCESS, - st, - ), - ( - s::SET_COUNTER, - sync_counter_body(0x0bad_bad0, 1), - bad_counter, - 0x0bad_bad0, - ), - ( - s::CHANGE_COUNTER, - sync_counter_body(SYNC_C2, i64::MAX), - x11::error::BAD_VALUE, - 0x7fff_ffff, - ), - ( - s::DESTROY_COUNTER, - st.to_le_bytes().to_vec(), - x11::error::BAD_ACCESS, - st, - ), - ( - s::DESTROY_COUNTER, - 0x0bad_bad0u32.to_le_bytes().to_vec(), - bad_counter, - 0x0bad_bad0, - ), - ]; - for (minor, body, code, value) in a_cases { - f.a(minor, &body); - assert_eq!( - error_fields(&wire_packets(&mut peer_a)[0]), - (code, value, u16::from(minor), 142) - ); - } - assert_eq!( - f.state.sync_counters[&SYNC_C2].value, 100, - "overflow left it alone" - ); - } - - /// Xvfb: AwaitFence on an untriggered fence suspends until TriggerFence - /// (no events); on a triggered fence it returns at once; destroying the - /// fence resumes with CounterNotify(counter = fence, 0, 0, destroyed). - /// Errors: empty → BadValue, None / unknown → BadFence; ResetFence of an - /// untriggered fence → BadMatch naming it. - #[test] - fn sync_await_fence_suspends_until_triggered() { - use yserver_protocol::x11::sync as s; - const F1: u32 = 0x0010_0010; - const F2: u32 = 0x0010_0011; - let mut f = sync_fixture(); - let fence_body = |fence: u32, triggered: bool| { - let mut body = ROOT_WINDOW.0.to_le_bytes().to_vec(); - body.extend_from_slice(&fence.to_le_bytes()); - body.extend_from_slice(&[u8::from(triggered), 0, 0, 0]); - body - }; - f.a(s::CREATE_FENCE, &fence_body(F1, false)); - f.a(s::CREATE_FENCE, &fence_body(F2, true)); - - f.b(s::AWAIT_FENCE, &F1.to_le_bytes()); - assert!(f.suspended()); - f.a(s::TRIGGER_FENCE, &F1.to_le_bytes()); - assert!(!f.suspended()); - assert!( - f.b_packets().is_empty(), - "fences send no events when triggered" - ); - - f.b(s::AWAIT_FENCE, &F2.to_le_bytes()); - assert!(!f.suspended(), "already triggered"); - - f.a(s::RESET_FENCE, &F1.to_le_bytes()); - f.b(s::AWAIT_FENCE, &F1.to_le_bytes()); - assert!(f.suspended()); - f.a(s::DESTROY_FENCE, &F1.to_le_bytes()); - assert!(!f.suspended()); - assert_eq!( - counter_notify_fields(&f.b_packets()[0]), - (F1, 0, 0, 0, true) - ); - - let bad_fence = crate::nested::SYNC_FIRST_ERROR + s::BAD_FENCE; - for (body, code, value) in [ - (Vec::new(), x11::error::BAD_VALUE, 0), - (0u32.to_le_bytes().to_vec(), bad_fence, 0), - ( - 0x0bad_bad0u32.to_le_bytes().to_vec(), - bad_fence, - 0x0bad_bad0, - ), - ] { - f.b(s::AWAIT_FENCE, &body); - assert!(!f.suspended()); - assert_eq!( - error_fields(&f.b_packets()[0]), - (code, value, u16::from(s::AWAIT_FENCE), 142) - ); - } - f.b(s::RESET_FENCE, &F2.to_le_bytes()); - f.b(s::RESET_FENCE, &F2.to_le_bytes()); - assert_eq!( - error_fields(&f.b_packets()[0]), - (x11::error::BAD_MATCH, F2, u16::from(s::RESET_FENCE), 142) - ); - } - - /// A Present idle fence triggered by the server wakes an AwaitFence on - /// it. A deliberate difference from Xorg: `present_fence_set_triggered` - /// only calls the fence's `SetTriggered`, not `miSyncTriggerFence`, so - /// on Xorg such an await is only re-checked by a TriggerFence request - /// or the fence's destruction and would otherwise stay suspended. - #[test] - fn sync_await_fence_wakes_on_server_side_trigger() { - use yserver_protocol::x11::sync as s; - const F1: u32 = 0x0010_0020; - let mut f = sync_fixture(); - f.state.sync_fences.insert( - F1, - crate::server::SyncFence { - owner: ClientId(SYNC_A), - triggered: false, - }, - ); - f.b(s::AWAIT_FENCE, &F1.to_le_bytes()); - assert!(f.suspended()); - crate::core_loop::sync_await::fence_triggered(&mut f.state, F1); - assert!(!f.suspended()); - assert!(f.state.sync_fences[&F1].triggered); - } - - /// A ChangeAlarm body: alarm, value mask, value list. - fn sync_alarm_body(alarm: u32, mask: u32, values: &[u32]) -> Vec { - let mut body = alarm.to_le_bytes().to_vec(); - body.extend_from_slice(&mask.to_le_bytes()); - for v in values { - body.extend_from_slice(&v.to_le_bytes()); - } - body - } - - /// Xvfb: ChangeAlarm / QueryAlarm / DestroyAlarm on an alarm that - /// does not exist (unknown, None, or destroyed) answer BadAlarm (SYNC - /// error base + 1) naming it. Xorg's order: QueryAlarm and DestroyAlarm - /// check the exact request size first (BadLength), ChangeAlarm checks - /// the minimum size, then looks the alarm up, and only then matches the - /// value list against the mask (BadLength naming the alarm). - #[test] - fn sync_alarm_requests_on_a_missing_alarm_answer_bad_alarm() { - use yserver_protocol::x11::sync as s; - const ALARM: u32 = 0x0010_0030; - const GONE: u32 = 0x0010_0031; - const UNKNOWN: u32 = 0x0bad_bad0; - let bad_alarm = crate::nested::SYNC_FIRST_ERROR + s::BAD_ALARM; - let bad_length = x11::error::BAD_LENGTH; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); - f.a( - s::CREATE_ALARM, - &sync_alarm_body(ALARM, s::CA_COUNTER, &[SYNC_C1]), - ); - f.a( - s::CREATE_ALARM, - &sync_alarm_body(GONE, s::CA_COUNTER, &[SYNC_C1]), - ); - f.a(s::DESTROY_ALARM, &GONE.to_le_bytes()); - let _ = f.b_packets(); - let long = sync_alarm_body(UNKNOWN, s::CA_EVENTS, &[]); - let cases: Vec<(u8, Vec, u8, u32)> = vec![ - ( - s::QUERY_ALARM, - UNKNOWN.to_le_bytes().to_vec(), - bad_alarm, - UNKNOWN, - ), - (s::QUERY_ALARM, 0u32.to_le_bytes().to_vec(), bad_alarm, 0), - (s::QUERY_ALARM, GONE.to_le_bytes().to_vec(), bad_alarm, GONE), - ( - s::CHANGE_ALARM, - sync_alarm_body(UNKNOWN, 0, &[]), - bad_alarm, - UNKNOWN, - ), - ( - s::CHANGE_ALARM, - sync_alarm_body(GONE, 0, &[]), - bad_alarm, - GONE, - ), - (s::CHANGE_ALARM, long.clone(), bad_alarm, UNKNOWN), - ( - s::DESTROY_ALARM, - UNKNOWN.to_le_bytes().to_vec(), - bad_alarm, - UNKNOWN, - ), - ( - s::DESTROY_ALARM, - GONE.to_le_bytes().to_vec(), - bad_alarm, - GONE, - ), - (s::QUERY_ALARM, long.clone(), bad_length, 0), - (s::DESTROY_ALARM, long, bad_length, 0), - ( - s::CHANGE_ALARM, - UNKNOWN.to_le_bytes().to_vec(), - bad_length, - 0, - ), - ( - s::CHANGE_ALARM, - sync_alarm_body(ALARM, s::CA_EVENTS, &[]), - bad_length, - ALARM, - ), - ( - s::CHANGE_ALARM, - sync_alarm_body(ALARM, s::CA_VALUE, &[0]), - bad_length, - ALARM, - ), - ]; - for (minor, body, code, value) in cases { - f.b(minor, &body); - let packets = f.b_packets(); - assert!( - !packets.is_empty(), - "minor {minor} body {body:x?}: no error" - ); - assert_eq!( - error_fields(&packets[0]), - (code, value, u16::from(minor), 142), - "minor {minor} body {body:x?}" - ); - } - assert!(f.state.sync_alarms.contains_key(&ALARM)); - } - - /// QueryAlarm → (counter, value type, wait value, test type, delta, - /// events, state), per `xSyncQueryAlarmReply`. - fn query_alarm_fields(f: &mut SyncFixture, alarm: u32) -> (u32, u32, i64, u32, i64, u8, u8) { - use yserver_protocol::x11::sync as s; - f.b(s::QUERY_ALARM, &alarm.to_le_bytes()); - let r = read_all_available(&mut f.peer_b); - assert_eq!((r.len(), r[0]), (40, 1), "QueryAlarm reply"); - let i64_at = |at: usize| { - #[allow(clippy::cast_possible_wrap)] - let hi = le_u32(&r, at) as i32; - (i64::from(hi) << 32) | i64::from(le_u32(&r, at + 4)) - }; - ( - le_u32(&r, 8), - le_u32(&r, 12), - i64_at(16), - le_u32(&r, 24), - i64_at(28), - r[36], - r[37], - ) - } - - /// Xvfb: QueryAlarm reports the alarm's test type (a fresh alarm's - /// default is PositiveComparison, 2) and, as Xorg's - /// `ProcSyncQueryAlarm`, always value type Absolute with the resolved - /// wait value. - #[test] - fn sync_query_alarm_reports_the_test_type() { - use yserver_protocol::x11::sync as s; - const AL: u32 = 0x0010_0080; - const AN: u32 = 0x0010_0081; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); - f.a( - s::CREATE_ALARM, - &sync_alarm_body(AL, s::CA_COUNTER | s::CA_VALUE, &[SYNC_C1, 0, 10]), - ); - assert_eq!( - query_alarm_fields(&mut f, AL), - ( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 10, - s::TEST_POSITIVE_COMPARISON, - 1, - 1, - s::ALARM_STATE_ACTIVE - ) - ); - f.a(s::CREATE_ALARM, &sync_alarm_body(AN, s::CA_VALUE, &[0, 5])); - assert_eq!( - query_alarm_fields(&mut f, AN), - ( - 0, - s::VALUE_TYPE_ABSOLUTE, - 5, - s::TEST_POSITIVE_COMPARISON, - 1, - 1, - s::ALARM_STATE_INACTIVE - ) - ); - } - - /// Xvfb ("CreateAlarm attribute errors"): Xorg's checks, in its order — - /// the value list in mask-bit order (`events` not True/False, unknown - /// bits naming the bits above), the delta sign against the test type - /// (the default delta 1 counts), then the trigger: unknown counter, - /// value type, Relative without a counter, INT64 overflow (naming the - /// value's high word), test type. BadMatch names the alarm. A failing - /// CreateAlarm creates nothing. - #[test] - fn sync_create_alarm_attribute_errors_match_xvfb() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 14)); - let bad_counter = crate::nested::SYNC_FIRST_ERROR + s::BAD_COUNTER; - let (value, matchh) = (x11::error::BAD_VALUE, x11::error::BAD_MATCH); - let c = SYNC_C1; - let unknown = 0x0bad_bad0; - // (mask, values, expected error (code, value; None = the alarm id)). - type Case = (u32, Vec, Option<(u8, Option)>); - let cases: Vec = vec![ - ( - s::CA_COUNTER | s::CA_TEST_TYPE, - vec![c, 9], - Some((value, Some(9))), - ), - ( - s::CA_COUNTER | s::CA_VALUE_TYPE, - vec![c, 7], - Some((value, Some(7))), - ), - ( - s::CA_COUNTER | s::CA_EVENTS, - vec![c, 2], - Some((value, Some(2))), - ), - ( - s::CA_COUNTER, - vec![unknown], - Some((bad_counter, Some(unknown))), - ), - ( - s::CA_VALUE_TYPE, - vec![s::VALUE_TYPE_RELATIVE], - Some((matchh, None)), - ), - ( - s::CA_COUNTER | s::CA_TEST_TYPE | s::CA_DELTA, - vec![c, s::TEST_POSITIVE_COMPARISON, u32::MAX, u32::MAX], - Some((matchh, None)), - ), - ( - s::CA_COUNTER | s::CA_TEST_TYPE, - vec![c, s::TEST_NEGATIVE_COMPARISON], - Some((matchh, None)), - ), - ( - s::CA_COUNTER | s::CA_TEST_TYPE | s::CA_DELTA, - vec![c, s::TEST_NEGATIVE_COMPARISON, 0, 0], - None, - ), - ( - s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE, - vec![c, s::VALUE_TYPE_RELATIVE, 0x7fff_ffff, u32::MAX], - Some((value, Some(0x7fff_ffff))), - ), - ( - s::CA_COUNTER | s::CA_TEST_TYPE, - vec![unknown, 9], - Some((bad_counter, Some(unknown))), - ), - ( - s::CA_VALUE_TYPE | s::CA_TEST_TYPE, - vec![7, 9], - Some((value, Some(7))), - ), - (1 << 6, vec![0], Some((value, Some(0)))), - (s::CA_EVENTS | 1 << 6, vec![2, 0], Some((value, Some(2)))), - ]; - for (index, (mask, values, expect)) in cases.into_iter().enumerate() { - let alarm = 0x0020_0100 + u32::try_from(index).unwrap(); - f.b(s::CREATE_ALARM, &sync_alarm_body(alarm, mask, &values)); - let packets = f.b_packets(); - match expect { - Some((code, bad)) => { - assert_eq!( - error_fields(&packets[0]), - (code, bad.unwrap_or(alarm), u16::from(s::CREATE_ALARM), 142), - "case {index}" - ); - assert!(!f.state.sync_alarms.contains_key(&alarm), "case {index}"); - } - None => { - assert!(packets.is_empty(), "case {index}"); - assert!(f.state.sync_alarms.contains_key(&alarm), "case {index}"); - } - } - } - } - - /// Xvfb ("ChangeAlarm attribute errors: what sticks"): a failing - /// ChangeAlarm keeps what Xorg's `SyncChangeAlarmAttributes` stored - /// before `SyncInitTrigger` failed — delta, value type, value and the - /// test type — while the counter, the resolved wait value (except an - /// overflowing Relative sum, which is stored wrapped), the test the - /// trigger runs and the state stay. A stored bad value type makes a - /// later value-only change Relative; a stored bad test type is what - /// QueryAlarm reports, passes the delta-sign check, and the alarm keeps - /// firing on its old PositiveComparison. - #[test] - fn sync_change_alarm_failures_keep_what_xorg_keeps() { - use yserver_protocol::x11::sync as s; - const X: u32 = 0x0010_0090; - let mut f = sync_fixture(); - let bad_counter = crate::nested::SYNC_FIRST_ERROR + s::BAD_COUNTER; - let (value, matchh) = (x11::error::BAD_VALUE, x11::error::BAD_MATCH); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 20)); - f.a( - s::CREATE_ALARM, - &sync_alarm_body( - X, - s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE | s::CA_TEST_TYPE | s::CA_DELTA, - &[SYNC_C1, 0, 0, 30, s::TEST_POSITIVE_COMPARISON, 0, 1], - ), - ); - let q = |f: &mut SyncFixture| query_alarm_fields(f, X); - let pc = s::TEST_POSITIVE_COMPARISON; - assert_eq!(q(&mut f), (SYNC_C1, 0, 30, pc, 1, 1, 0)); - let change = |f: &mut SyncFixture, mask: u32, values: &[u32]| { - f.a(s::CHANGE_ALARM, &sync_alarm_body(X, mask, values)); - f.a_packets() - .first() - .map(error_fields) - .map(|(code, bad, minor, _)| { - assert_eq!(minor, u16::from(s::CHANGE_ALARM)); - (code, bad) - }) - }; - let m = u32::MAX; - assert_eq!( - change(&mut f, s::CA_VALUE_TYPE | s::CA_VALUE, &[7, 0, 50]), - Some((value, 7)) - ); - assert_eq!(q(&mut f), (SYNC_C1, 0, 30, pc, 1, 1, 0)); - assert_eq!(change(&mut f, s::CA_VALUE, &[0, 5]), None); - assert_eq!( - q(&mut f), - (SYNC_C1, 0, 25, pc, 1, 1, 0), - "stored type 7 acts Relative" - ); - assert_eq!( - change( - &mut f, - s::CA_COUNTER | s::CA_VALUE | s::CA_DELTA, - &[0x0bad_bad0, 0, 70, 0, 3] - ), - Some((bad_counter, 0x0bad_bad0)) - ); - assert_eq!(q(&mut f), (SYNC_C1, 0, 25, pc, 3, 1, 0), "delta sticks"); - assert_eq!(change(&mut f, s::CA_DELTA, &[m, m]), Some((matchh, X))); - assert_eq!( - change( - &mut f, - s::CA_VALUE_TYPE | s::CA_VALUE | s::CA_TEST_TYPE, - &[0, 0, 100, s::TEST_NEGATIVE_TRANSITION] - ), - Some((matchh, X)) - ); - assert_eq!(q(&mut f), (SYNC_C1, 0, 25, pc, 3, 1, 0)); - assert_eq!(change(&mut f, s::CA_TEST_TYPE, &[9]), Some((value, 9))); - assert_eq!(q(&mut f), (SYNC_C1, 0, 25, 9, 3, 1, 0)); - assert_eq!( - change(&mut f, s::CA_DELTA, &[m, m]), - None, - "no sign for test type 9" - ); - assert_eq!(q(&mut f), (SYNC_C1, 0, 25, 9, -1, 1, 0)); - assert_eq!(change(&mut f, s::CA_DELTA, &[0, 1]), None); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 25)); - assert_eq!( - alarm_notifies(&f.a_packets()), - vec![(X, 25, 25, s::ALARM_STATE_ACTIVE)] - ); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 21)); - assert!(f.a_packets().is_empty()); - assert_eq!(q(&mut f), (SYNC_C1, 0, 26, 9, 1, 1, 0)); - f.a(s::CHANGE_ALARM, &sync_alarm_body(X, s::CA_COUNTER, &[0])); - assert_eq!( - alarm_notifies(&f.a_packets()), - vec![(X, 0, 26, s::ALARM_STATE_INACTIVE)] - ); - assert_eq!( - change(&mut f, s::CA_VALUE_TYPE, &[s::VALUE_TYPE_RELATIVE]), - Some((matchh, X)) - ); - assert_eq!(q(&mut f), (0, 0, 26, 9, 1, 1, s::ALARM_STATE_INACTIVE)); - assert_eq!( - change( - &mut f, - s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE, - &[SYNC_C1, s::VALUE_TYPE_RELATIVE, 0x7fff_ffff, m] - ), - Some((value, 0x7fff_ffff)) - ); - let wrapped = 21i64.wrapping_add(i64::MAX); - assert_eq!(q(&mut f), (0, 0, wrapped, 9, 1, 1, s::ALARM_STATE_INACTIVE)); - assert_eq!(change(&mut f, 1 << 6, &[0]), Some((value, 0))); - f.a(s::DESTROY_ALARM, &X.to_le_bytes()); - assert_eq!( - alarm_notifies(&f.a_packets()), - vec![(X, 0, wrapped, s::ALARM_STATE_DESTROYED)] - ); - } - - /// Xvfb (the "bad test type" line of "AlarmNotify selection"): B's - /// ChangeAlarm {test type 9, events True} on A's alarm is BadValue(9), - /// yet B is selected (the selection precedes the check) and the alarm, - /// still running PositiveComparison, notifies B when the counter - /// reaches it; QueryAlarm reports test type 9. - #[test] - fn sync_alarm_bad_test_type_still_selects_and_fires() { - use yserver_protocol::x11::sync as s; - const AL: u32 = 0x0010_00a0; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 13)); - f.a( - s::CREATE_ALARM, - &sync_alarm_body( - AL, - s::CA_COUNTER | s::CA_VALUE | s::CA_EVENTS, - &[SYNC_C1, 0, 14, 0], - ), - ); - f.b( - s::CHANGE_ALARM, - &sync_alarm_body(AL, s::CA_TEST_TYPE | s::CA_EVENTS, &[9, 1]), - ); - assert_eq!( - error_fields(&f.b_packets()[0]), - (x11::error::BAD_VALUE, 9, u16::from(s::CHANGE_ALARM), 142) - ); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 14)); - assert_eq!( - alarm_notifies(&f.b_packets()), - vec![(AL, 14, 14, s::ALARM_STATE_ACTIVE)] - ); - assert!(f.a_packets().is_empty()); - assert_eq!(query_alarm_fields(&mut f, AL), (SYNC_C1, 0, 15, 9, 1, 0, 0)); - } - - /// Every AlarmNotify in `packets` → (alarm, counter value, alarm - /// value, state). - fn alarm_notifies(packets: &[[u8; 32]]) -> Vec<(u32, i64, i64, u8)> { - let i64_at = |p: &[u8; 32], at: usize| { - #[allow(clippy::cast_possible_wrap)] - let hi = le_u32(p, at) as i32; - (i64::from(hi) << 32) | i64::from(le_u32(p, at + 4)) - }; - packets - .iter() - .filter(|p| p[0] == crate::nested::SYNC_FIRST_EVENT + 1) - .map(|p| { - assert_eq!(p[1], 1, "kind AlarmNotify"); - (le_u32(p, 4), i64_at(p, 8), i64_at(p, 16), p[28]) - }) - .collect() - } - - fn sync_events_body(alarm: u32, on: u32) -> Vec { - use yserver_protocol::x11::sync as s; - sync_alarm_body(alarm, s::CA_EVENTS, &[on]) - } - - /// Xvfb (tools/sync-await-probe.c, "AlarmNotify selection"): an alarm - /// owned by A (c >= 10, delta 1, events). B and D select AlarmNotify - /// with ChangeAlarm(events=True) — any client may — and every firing - /// reaches the owner (while its own flag is set) and each selecting - /// client once. events=False by B removes B; by A clears only the - /// owner's flag (what QueryAlarm reports). A selecting client that - /// disconnects drops off the list. A non-owner may change other - /// attributes too. DestroyAlarm sends a Destroyed notify to the - /// selecting clients. An `events` value other than True/False is - /// BadValue naming it and selects nothing. - #[test] - fn sync_alarm_notify_reaches_every_client_that_selected_it() { - use yserver_protocol::x11::sync as s; - const AL: u32 = 0x0010_0040; - const D: u32 = 3; - let mut f = sync_fixture(); - let mut peer_d = install_client(&mut f.state, D); - let d_req = |f: &mut SyncFixture, minor: u8, body: &[u8]| { - sync_req(&mut f.state, &mut f.backend, D, minor, body); - }; - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); - let mut create = AL.to_le_bytes().to_vec(); - create.extend_from_slice( - &(s::CA_COUNTER - | s::CA_VALUE_TYPE - | s::CA_VALUE - | s::CA_TEST_TYPE - | s::CA_DELTA - | s::CA_EVENTS) - .to_le_bytes(), - ); - for v in [ - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 0, - 10, - s::TEST_POSITIVE_COMPARISON, - 0, - 1, - 1, - ] { - create.extend_from_slice(&v.to_le_bytes()); - } - f.a(s::CREATE_ALARM, &create); - f.b(s::CHANGE_ALARM, &sync_events_body(AL, 1)); - d_req(&mut f, s::CHANGE_ALARM, &sync_events_body(AL, 1)); - f.b(s::CHANGE_ALARM, &sync_events_body(AL, 1)); - assert!(f.b_packets().is_empty(), "selecting sends nothing"); - assert!(f.state.sync_alarms[&AL].events, "owner flag untouched"); - assert!(f.a_packets().is_empty()); - - let set = |f: &mut SyncFixture, v: i64| f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, v)); - set(&mut f, 10); - let fired = |v: i64| vec![(AL, v, v, s::ALARM_STATE_ACTIVE)]; - assert_eq!(alarm_notifies(&f.a_packets()), fired(10)); - assert_eq!(alarm_notifies(&f.b_packets()), fired(10), "B once"); - assert_eq!(alarm_notifies(&wire_packets(&mut peer_d)), fired(10)); - - f.b(s::CHANGE_ALARM, &sync_events_body(AL, 0)); - set(&mut f, 11); - assert_eq!(alarm_notifies(&f.a_packets()), fired(11)); - assert!(f.b_packets().is_empty(), "B deselected"); - assert_eq!(alarm_notifies(&wire_packets(&mut peer_d)), fired(11)); - - f.a(s::CHANGE_ALARM, &sync_events_body(AL, 0)); - set(&mut f, 12); - assert!(f.a_packets().is_empty(), "owner flag off"); - assert!(!f.state.sync_alarms[&AL].events); - assert_eq!(alarm_notifies(&wire_packets(&mut peer_d)), fired(12)); - - crate::core_loop::process_disconnect::process_disconnect( - &mut f.state, - &mut f.backend, - ClientId(D), - ); - assert!(f.state.sync_alarms[&AL].event_clients.is_empty()); - set(&mut f, 13); - assert!(f.a_packets().is_empty() && f.b_packets().is_empty()); - - f.b(s::CHANGE_ALARM, &sync_events_body(AL, 9)); - assert_eq!( - error_fields(&f.b_packets()[0]), - (x11::error::BAD_VALUE, 9, u16::from(s::CHANGE_ALARM), 142) - ); - assert!(f.state.sync_alarms[&AL].event_clients.is_empty()); - - f.b(s::CHANGE_ALARM, &sync_events_body(AL, 1)); - set(&mut f, 14); - assert_eq!(alarm_notifies(&f.b_packets()), fired(14)); - f.b( - s::CHANGE_ALARM, - &sync_alarm_body(AL, s::CA_VALUE, &[0, 100]), - ); - assert!(f.b_packets().is_empty(), "a non-owner may change the value"); - assert_eq!(f.state.sync_alarms[&AL].wait_value, 100); - - f.a(s::DESTROY_ALARM, &AL.to_le_bytes()); - assert!(f.a_packets().is_empty()); - assert_eq!( - alarm_notifies(&f.b_packets()), - vec![(AL, 14, 100, s::ALARM_STATE_DESTROYED)] - ); - } - - /// Xvfb: a non-owner may DestroyAlarm (owner and selecting clients get - /// the Destroyed notify); the owner's disconnect destroys its alarms, - /// and the clients that selected them get the Destroyed notify with - /// the counter's value. A destroyed counter deactivates the alarm with - /// an Inactive notify to them as well. - #[test] - fn sync_alarm_destruction_notifies_every_selecting_client() { - use yserver_protocol::x11::sync as s; - const E: u32 = 3; - const CE: u32 = 0x0030_0001; - const AE1: u32 = 0x0030_0002; - const AE2: u32 = 0x0030_0003; - const A2: u32 = 0x0010_0050; - let mut f = sync_fixture(); - let mut peer_e = install_client(&mut f.state, E); - let e_req = |f: &mut SyncFixture, minor: u8, body: &[u8]| { - sync_req(&mut f.state, &mut f.backend, E, minor, body); - }; - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 14)); - e_req(&mut f, s::CREATE_COUNTER, &sync_counter_body(CE, 0)); - e_req( - &mut f, - s::CREATE_ALARM, - &sync_alarm_body(AE1, s::CA_COUNTER | s::CA_VALUE, &[CE, 0, 50]), - ); - e_req( - &mut f, - s::CREATE_ALARM, - &sync_alarm_body(AE2, s::CA_COUNTER | s::CA_VALUE, &[SYNC_C1, 0, 50]), - ); - f.b(s::CHANGE_ALARM, &sync_events_body(AE1, 1)); - f.b(s::CHANGE_ALARM, &sync_events_body(AE2, 1)); - f.b(s::DESTROY_ALARM, &AE1.to_le_bytes()); - let destroyed = vec![(AE1, 0, 50, s::ALARM_STATE_DESTROYED)]; - assert_eq!(alarm_notifies(&wire_packets(&mut peer_e)), destroyed); - assert_eq!(alarm_notifies(&f.b_packets()), destroyed); - assert!(!f.state.sync_alarms.contains_key(&AE1)); - - crate::core_loop::process_disconnect::process_disconnect( - &mut f.state, - &mut f.backend, - ClientId(E), - ); - assert_eq!( - alarm_notifies(&f.b_packets()), - vec![(AE2, 14, 50, s::ALARM_STATE_DESTROYED)] - ); - assert!(!f.state.sync_alarms.contains_key(&AE2)); - - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 3)); - f.a( - s::CREATE_ALARM, - &sync_alarm_body(A2, s::CA_COUNTER | s::CA_VALUE, &[SYNC_C2, 0, 50]), - ); - f.b(s::CHANGE_ALARM, &sync_events_body(A2, 1)); - f.a(s::DESTROY_COUNTER, &SYNC_C2.to_le_bytes()); - let inactive = vec![(A2, 3, 50, s::ALARM_STATE_INACTIVE)]; - assert_eq!(alarm_notifies(&f.a_packets()), inactive); - assert_eq!(alarm_notifies(&f.b_packets()), inactive); - f.a(s::DESTROY_ALARM, &A2.to_le_bytes()); - let destroyed = vec![(A2, 0, 50, s::ALARM_STATE_DESTROYED)]; - assert_eq!(alarm_notifies(&f.a_packets()), destroyed); - assert_eq!(alarm_notifies(&f.b_packets()), destroyed); - } - - /// Xvfb: CreateAlarm defaults are Xorg's (PositiveComparison, value 0, - /// delta 1, events): on a counter at 0 it fires at once and re-arms to - /// a wait value of 1. Without a counter the alarm starts Inactive and - /// silent; a ChangeAlarm on it then fires Inactive with counter value - /// 0 ("NULL counter WILL trigger in ChangeAlarm"). - #[test] - fn sync_alarm_defaults_and_counterless_alarms_match_xvfb() { - use yserver_protocol::x11::sync as s; - const GONE: u32 = 0x0010_0060; - const AN: u32 = 0x0020_0060; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); - f.a( - s::CREATE_ALARM, - &sync_alarm_body(GONE, s::CA_COUNTER, &[SYNC_C1]), - ); - assert_eq!( - alarm_notifies(&f.a_packets()), - vec![(GONE, 0, 0, s::ALARM_STATE_ACTIVE)] - ); - f.a(s::DESTROY_ALARM, &GONE.to_le_bytes()); - assert_eq!( - alarm_notifies(&f.a_packets()), - vec![(GONE, 0, 1, s::ALARM_STATE_DESTROYED)] - ); - - f.b(s::CREATE_ALARM, &sync_alarm_body(AN, s::CA_VALUE, &[0, 5])); - assert!(f.b_packets().is_empty()); - assert_eq!(f.state.sync_alarms[&AN].state, s::ALARM_STATE_INACTIVE); - f.b(s::CHANGE_ALARM, &sync_events_body(AN, 1)); - assert_eq!( - alarm_notifies(&f.b_packets()), - vec![(AN, 0, 5, s::ALARM_STATE_INACTIVE)] - ); - f.b(s::DESTROY_ALARM, &AN.to_le_bytes()); - assert_eq!( - alarm_notifies(&f.b_packets()), - vec![(AN, 0, 5, s::ALARM_STATE_DESTROYED)] - ); - } - - /// A DRI3 FenceFromFD xshmfence keeps its state in memory the client - /// can trigger and reset itself (`xshmfence_trigger` / - /// `xshmfence_reset`). Xorg's shm fence (`misyncshm.c`) answers every - /// `CheckTriggered` from that memory — QueryFence, the AwaitFence - /// epilogue, ResetFence's BadMatch test, and `miSyncTriggerFence`'s - /// re-check — and never from the server's own bit; ResetFence resets - /// the memory and DestroyFence triggers it before unmapping. Nothing in - /// Xorg watches the memory, so an AwaitFence already suspended stays - /// suspended when the client triggers it in memory, until a - /// TriggerFence request or the fence's destruction. Xvfb has no DRI3, - /// so this follows the source (`miSyncShmFenceCheckTriggered`, - /// `miSyncShmFenceReset`, `miSyncShmScreenDestroyFence`, - /// `SyncAwaitEpilogue`, `miSyncTriggerFence`). - #[test] - fn sync_shm_fence_state_is_read_from_shared_memory() { - use yserver_protocol::x11::sync as s; - const F: u32 = 0x0010_0070; - const G: u32 = 0x0010_0071; - let mut f = sync_fixture(); - for fence in [F, G] { - f.state.sync_fences.insert( - fence, - crate::server::SyncFence { - owner: ClientId(SYNC_A), - triggered: false, - }, - ); - f.backend.shm_fences.insert(fence, false); - } - let query = |f: &mut SyncFixture| { - f.b(s::QUERY_FENCE, &F.to_le_bytes()); - let reply = f.b_packets(); - assert_eq!(reply[0][0], 1, "QueryFence reply"); - reply[0][8] != 0 - }; - - // The client triggers it in memory: QueryFence sees it and an - // AwaitFence returns at once. - f.backend.shm_fences.insert(F, true); - assert!(query(&mut f)); - f.b(s::AWAIT_FENCE, &F.to_le_bytes()); - assert!(!f.suspended()); - - // The client resets it in memory after the server triggered it: - // the memory wins over the server's bit. - f.a(s::TRIGGER_FENCE, &F.to_le_bytes()); - assert!(f.state.sync_fences[&F].triggered); - f.backend.shm_fences.insert(F, false); - assert!(!query(&mut f)); - f.b(s::RESET_FENCE, &F.to_le_bytes()); - assert_eq!( - error_fields(&f.b_packets()[0]), - (x11::error::BAD_MATCH, F, u16::from(s::RESET_FENCE), 142), - "untriggered in memory" - ); - f.b(s::AWAIT_FENCE, &F.to_le_bytes()); - assert!(f.suspended(), "untriggered in memory"); - - // A trigger in memory alone wakes nothing (Xorg never looks); - // a TriggerFence request does. - f.backend.shm_fences.insert(F, true); - assert!(f.suspended()); - f.a(s::TRIGGER_FENCE, &F.to_le_bytes()); - assert!(!f.suspended()); - - // ResetFence of a fence triggered in memory resets the memory. - f.b(s::RESET_FENCE, &F.to_le_bytes()); - assert!(f.b_packets().is_empty()); - assert_eq!(f.backend.shm_fences.get(&F), Some(&false)); - assert!(!query(&mut f)); - - // DestroyFence triggers the memory (releasing client waiters) and - // unmaps it; so does the owner's disconnect. - f.a(s::DESTROY_FENCE, &F.to_le_bytes()); - assert_eq!(f.backend.destroyed_shm_fences, vec![(F, true)]); - assert!(!f.backend.shm_fences.contains_key(&F)); - crate::core_loop::process_disconnect::process_disconnect( - &mut f.state, - &mut f.backend, - ClientId(SYNC_A), - ); - assert_eq!(f.backend.destroyed_shm_fences, vec![(F, true), (G, true)]); - assert!(f.backend.shm_fences.is_empty()); - } - - /// SERVERTIME awaits wake when the clock reaches the value (Xvfb: an - /// absolute now+300 PositiveComparison blocked ~300 ms and reported - /// wait == value), and the loop gets a deadline for it. - #[test] - fn sync_await_on_servertime_fires_when_the_clock_gets_there() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - let now = i64::from(f.state.timestamp_now()); - f.b( - s::AWAIT, - &sync_wait( - s::SERVERTIME_COUNTER, - s::VALUE_TYPE_ABSOLUTE, - now + 300, - s::TEST_POSITIVE_COMPARISON, - 0, - ), - ); - assert!(f.suspended()); - let deadline = crate::core_loop::sync_await::system_counter_deadline(&f.state) - .expect("a SERVERTIME deadline"); - let wait = deadline.saturating_duration_since(std::time::Instant::now()); - assert!( - wait > std::time::Duration::from_millis(200) - && wait <= std::time::Duration::from_millis(300), - "deadline ~300 ms out, got {wait:?}" - ); - crate::core_loop::sync_await::evaluate_servertime(&mut f.state); - assert!(f.suspended(), "not there yet"); - // Let 400 ms of server time pass. Until the loop evaluates it, the - // passed value must read as due now — never as "no deadline", or - // an idle loop would block past it. - f.state.start_instant -= std::time::Duration::from_millis(400); - let due = crate::core_loop::sync_await::system_counter_deadline(&f.state) - .expect("still pending until evaluated"); - assert!(due <= std::time::Instant::now()); - crate::core_loop::sync_await::evaluate_servertime(&mut f.state); - assert!(!f.suspended()); - let (counter, wait_value, value, count, destroyed) = - counter_notify_fields(&f.b_packets()[0]); - assert_eq!( - (counter, wait_value, count, destroyed), - (s::SERVERTIME_COUNTER, now + 300, 0, false) - ); - assert!(value >= now + 300); - assert!(crate::core_loop::sync_await::system_counter_deadline(&f.state).is_none()); - } - - /// SERVERTIME alarms fire too (Xvfb: an absolute now+200 - /// PositiveComparison alarm with delta 0 sent AlarmNotify after ~200 ms - /// with state Inactive and counter >= alarm value). - #[test] - fn sync_alarm_on_servertime_fires_when_the_clock_gets_there() { - use yserver_protocol::x11::sync as s; - const ALARM: u32 = 0x0010_0030; - let mut f = sync_fixture(); - let now = i64::from(f.state.timestamp_now()); - let mut body = ALARM.to_le_bytes().to_vec(); - let mask = s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE | s::CA_TEST_TYPE | s::CA_DELTA; - body.extend_from_slice(&mask.to_le_bytes()); - body.extend_from_slice(&s::SERVERTIME_COUNTER.to_le_bytes()); - body.extend_from_slice(&s::VALUE_TYPE_ABSOLUTE.to_le_bytes()); - body.extend_from_slice(&sync_i64(now + 200)); - body.extend_from_slice(&s::TEST_POSITIVE_COMPARISON.to_le_bytes()); - body.extend_from_slice(&sync_i64(0)); - f.b(s::CREATE_ALARM, &body); - assert!(f.b_packets().is_empty(), "not due yet"); - assert!(crate::core_loop::sync_await::system_counter_deadline(&f.state).is_some()); - f.state.start_instant -= std::time::Duration::from_millis(300); - crate::core_loop::sync_await::evaluate_servertime(&mut f.state); - let packets = f.b_packets(); - assert_eq!(packets.len(), 1); - assert_eq!( - packets[0][0], - crate::nested::SYNC_FIRST_EVENT + 1, - "AlarmNotify" - ); - assert_eq!(packets[0][28], s::ALARM_STATE_INACTIVE); - assert_eq!(f.state.sync_alarms[&ALARM].state, s::ALARM_STATE_INACTIVE); - } - - /// IDLETIME awaits: a positive test wakes when idle time reaches it; a - /// negative transition wakes on input (idle drops to 0). - #[test] - fn sync_await_on_idletime_fires_on_idle_and_on_input() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.state.dpms.last_activity = std::time::Instant::now(); - f.b( - s::AWAIT, - &sync_wait( - s::IDLETIME_COUNTER, - s::VALUE_TYPE_ABSOLUTE, - 5_000, - s::TEST_POSITIVE_TRANSITION, - 0, - ), - ); - assert!(f.suspended()); - assert!(crate::core_loop::sync_await::system_counter_deadline(&f.state).is_some()); - f.state.dpms.last_activity -= std::time::Duration::from_secs(6); - crate::core_loop::run::evaluate_idletime_alarms_post_poll(&mut f.state, &mut f.backend); - assert!(!f.suspended()); - let (counter, wait_value, _, _, _) = counter_notify_fields(&f.b_packets()[0]); - assert_eq!((counter, wait_value), (s::IDLETIME_COUNTER, 5_000)); - - f.b( - s::AWAIT, - &sync_wait( - s::IDLETIME_COUNTER, - s::VALUE_TYPE_ABSOLUTE, - 1_000, - s::TEST_NEGATIVE_TRANSITION, - 0, - ), - ); - assert!(f.suspended(), "idle is ~6 s, no downward crossing yet"); - evaluate_idletime_negative_alarms_on_input_wake(&mut f.state, 2, 6_000, 6_000); - assert!(!f.suspended()); - } - - /// The awaiting client's own disconnect drops its await. - #[test] - fn sync_await_dies_with_its_client() { - use yserver_protocol::x11::sync as s; - let mut f = sync_fixture(); - f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); - f.b( - s::AWAIT, - &sync_wait( - SYNC_C1, - s::VALUE_TYPE_ABSOLUTE, - 5, - s::TEST_POSITIVE_COMPARISON, - 0, - ), - ); - assert!(f.suspended()); - crate::core_loop::process_disconnect::process_disconnect( - &mut f.state, - &mut f.backend, - ClientId(SYNC_B), - ); - assert!(f.state.sync_awaits.is_empty()); - f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 9)); - assert!(f.state.sync_counters.contains_key(&SYNC_C1)); - } - - fn xfixes_create_barrier( - state: &mut ServerState, - client: ClientId, - barrier: u32, - window: u32, - x1: i16, - y1: i16, - x2: i16, - y2: i16, - directions: u32, - devices: &[u16], - ) -> io::Result { - use yserver_protocol::x11::xfixes as x11xfixes; - - let mut body = Vec::new(); - body.extend_from_slice(&barrier.to_le_bytes()); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&x1.to_le_bytes()); - body.extend_from_slice(&y1.to_le_bytes()); - body.extend_from_slice(&x2.to_le_bytes()); - body.extend_from_slice(&y2.to_le_bytes()); - body.extend_from_slice(&directions.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&(devices.len() as u16).to_le_bytes()); - for &device in devices { - body.extend_from_slice(&device.to_le_bytes()); - } - - let header = RequestHeader { - opcode: 140, - data: x11xfixes::CREATE_POINTER_BARRIER, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }; - handle_xfixes_request( - state, - &mut RecordingBackend::new(), - None, - client, - SequenceNumber(1), - header, - &body, - ) - } - - fn xfixes_delete_barrier( - state: &mut ServerState, - client: ClientId, - barrier: u32, - ) -> io::Result { - use yserver_protocol::x11::xfixes as x11xfixes; - let body = barrier.to_le_bytes(); - let header = RequestHeader { - opcode: 140, - data: x11xfixes::DELETE_POINTER_BARRIER, - length_units: 2, - }; - handle_xfixes_request( - state, - &mut RecordingBackend::new(), - None, - client, - SequenceNumber(1), - header, - &body, - ) - } - - fn xi2_barrier_release( - state: &mut ServerState, - client: ClientId, - entries: &[(u16, u32, u32)], - ) -> io::Result { - let mut body = Vec::new(); - body.extend_from_slice(&(entries.len() as u32).to_le_bytes()); - for &(deviceid, barrier, eventid) in entries { - body.extend_from_slice(&deviceid.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.extend_from_slice(&barrier.to_le_bytes()); - body.extend_from_slice(&eventid.to_le_bytes()); - } - handle_xi2_request( - state, - &mut RecordingBackend::new(), - None, - client, - SequenceNumber(1), - xi2_header_for_body(61, &body), - &body, - ) - } - - #[test] - fn create_pointer_barrier_stores_resource() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let bid = 0x0040_0001u32; - - xfixes_create_barrier( - &mut state, - ClientId(1), - bid, - ROOT_WINDOW.0, - 100, - 0, - 100, - 200, - 0, - &[], - ) - .expect("create barrier"); - - let b = state.pointer_barriers.get(&bid).expect("stored"); - assert_eq!((b.x1, b.y1, b.x2, b.y2), (100, 0, 100, 200)); - assert_eq!(b.event_id, 1); - assert_eq!(b.release_event_id, 0); - assert!(read_all_available(&mut peer).is_empty()); - } - - #[test] - fn create_pointer_barrier_diagonal_is_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let bid = 0x0040_0001u32; - - xfixes_create_barrier( - &mut state, - ClientId(1), - bid, - ROOT_WINDOW.0, - 0, - 0, - 50, - 80, - 0, - &[], - ) - .expect("request handled"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert!(!state.pointer_barriers.contains_key(&bid)); - } - - #[test] - fn create_pointer_barrier_bad_window() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - xfixes_create_barrier( - &mut state, - ClientId(1), - 0x0040_0001, - 0x9999, - 100, - 0, - 100, - 200, - 0, - &[], - ) - .expect("request handled"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_WINDOW); - } - - #[test] - fn create_pointer_barrier_negative_on_fixed_axis_is_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - xfixes_create_barrier( - &mut state, - ClientId(1), - 0x0040_0001, - ROOT_WINDOW.0, - -1, - 0, - -1, - 200, - 0, - &[], - ) - .expect("request handled"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - } - - #[test] - fn create_pointer_barrier_bad_device() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - - xfixes_create_barrier( - &mut state, - ClientId(1), - 0x0040_0001, - ROOT_WINDOW.0, - 100, - 0, - 100, - 200, - 0, - &[3], - ) - .expect("request handled"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], XI2_FIRST_ERROR); - } - - #[test] - fn delete_pointer_barrier_frees_and_owner_checks() { - let mut state = ServerState::new(); - let mut peer1 = install_client(&mut state, 1); - let mut peer2 = install_client(&mut state, 2); - let bid = 0x0040_0001u32; - - xfixes_create_barrier( - &mut state, - ClientId(1), - bid, - ROOT_WINDOW.0, - 100, - 0, - 100, - 200, - 0, - &[], - ) - .expect("create barrier"); - assert!(read_all_available(&mut peer1).is_empty()); - - xfixes_delete_barrier(&mut state, ClientId(2), bid).expect("wrong-client delete handled"); - let bytes = read_all_available(&mut peer2); - assert_eq!(bytes[1], x11::error::BAD_ACCESS); - assert!(state.pointer_barriers.contains_key(&bid)); - - xfixes_delete_barrier(&mut state, ClientId(1), bid).expect("owner delete handled"); - assert!(!state.pointer_barriers.contains_key(&bid)); - } - - #[test] - fn xi2_barrier_release_arms_matching_barrier() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let bid = 0x0040_0002u32; - - xfixes_create_barrier( - &mut state, - ClientId(1), - bid, - ROOT_WINDOW.0, - 100, - 0, - 100, - 200, - 0, - &[], - ) - .expect("create barrier"); - - xi2_barrier_release(&mut state, ClientId(1), &[(2, bid, 1)]).expect("release handled"); - - let barrier = state.pointer_barriers.get(&bid).expect("barrier"); - assert_eq!(barrier.release_event_id, 1); - } - - #[test] - fn delete_while_hit_emits_released_leave() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - if let Some(client) = state.clients.get_mut(&1) { - client.xi2_masks.insert((ROOT_WINDOW, 2), 1 << 26); - } - let bid = 0x0040_0003u32; - - xfixes_create_barrier( - &mut state, - ClientId(1), - bid, - ROOT_WINDOW.0, - 100, - 0, - 100, - 200, - 0, - &[], - ) - .expect("create barrier"); - { - let barrier = state.pointer_barriers.get_mut(&bid).expect("barrier"); - barrier.hit = true; - barrier.event_id = 1; - barrier.last_timestamp = 10; - } - // Sprite resting on the barrier. The released leave must carry the - // CURRENT position (not 0,0 — the pre-fix bug). - state.pointer_root = (100, 50); - - xfixes_delete_barrier(&mut state, ClientId(1), bid).expect("owner delete handled"); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 68); - assert_eq!(bytes[0], 35, "GenericEvent"); - assert_eq!(bytes[1], XI2_MAJOR_OPCODE, "XI2 major opcode"); - assert_eq!(&bytes[8..10], &26u16.to_le_bytes(), "BarrierLeave"); - assert_eq!( - &bytes[36..40], - &1u32.to_le_bytes(), - "XIBarrierPointerReleased" - ); - assert_eq!(&bytes[40..42], &0u16.to_le_bytes(), "sourceid = 0"); - // root_x/root_y carry the current sprite position as FP1616 (v<<16), - // not the pre-fix 0,0. - assert_eq!( - &bytes[44..48], - &(100i32 << 16).to_le_bytes(), - "root_x = 100" - ); - assert_eq!(&bytes[48..52], &(50i32 << 16).to_le_bytes(), "root_y = 50"); - assert!(!state.pointer_barriers.contains_key(&bid)); - } - - #[test] - fn shape_input_change_emits_shape_notify_to_selectors() { - // A client that ShapeSelectInput'd a window must receive a - // ShapeNotify when that window's input region changes. Regression - // for the cinnamon "nemo rises" bug: nautilus grows its input shape - // from a tiny startup rect to full size; without ShapeNotify the - // compositing WM keeps the stale tiny region, treats the window as - // click-through over most of its area, and focuses/raises the - // window below on a click. - use yserver_protocol::x11::{shape as x11shape, xfixes::RegionRect}; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x1b00004); - seed_window(&mut state, win, ROOT_WINDOW, 800, 600); - - // WM selected ShapeNotify on the window. - state.shape_select_masks.insert((1, win), true); - - // Window sets its (grown) input shape, then we notify. - crate::nested::set_shape_rects( - &mut state, - win, - x11shape::KIND_INPUT, - vec![RegionRect { - x: 13, - y: 13, - width: 1482, - height: 1024, - }], - ); - emit_shape_notify(&mut state, win, x11shape::KIND_INPUT); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "one 32-byte ShapeNotify"); - assert_eq!( - bytes[0], - crate::nested::SHAPE_FIRST_EVENT, - "ShapeNotify type" - ); - assert_eq!(bytes[1], x11shape::KIND_INPUT, "kind = Input"); - assert_eq!(&bytes[4..8], &win.0.to_le_bytes(), "affected window"); - assert_eq!(bytes[20], 1, "shaped = true"); - - // A client that did NOT select gets nothing. - let mut peer2 = install_client(&mut state, 2); - emit_shape_notify(&mut state, win, x11shape::KIND_INPUT); - assert!( - read_all_available(&mut peer2).is_empty(), - "non-selecting client must not receive ShapeNotify" - ); - } - - /// A `ShapeMask(kind=Input, src=None)` that clears an already-unset - /// input shape is a no-op and must NOT generate a ShapeNotify — - /// matching Xorg. xfwm4 re-asserts exactly this on its panel frames - /// repeatedly; a spurious notify each time made it re-derive the - /// frame's input shape from a stale geometry-default rect, so XFCE - /// bottom-panel buttons fell through to xfdesktop (HW xfce - /// 2026-06-22). Drives the real `handle_shape_request` MASK path. - #[test] - fn shape_mask_none_clearing_unset_input_emits_no_shape_notify() { - use yserver_protocol::x11::shape as x11shape; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let win = ResourceId(0x1b00004); - seed_window(&mut state, win, ROOT_WINDOW, 25, 49); - // WM (xfwm4-like) selected ShapeNotify on the window. - state.shape_select_masks.insert((1, win), true); - - // MASK body: op(1) dest_kind(1) pad(2) dest(4) x_off(2) y_off(2) src(4). - let mut body = vec![0u8; 16]; - body[0] = x11shape::OP_SET; - body[1] = x11shape::KIND_INPUT; - body[4..8].copy_from_slice(&win.0.to_le_bytes()); - // src stays 0 == None → clear the (already-unset) input shape. - let header = yserver_protocol::x11::RequestHeader { - opcode: 129, // SHAPE major (unused by handle_shape_request) - data: 2, // SHAPE minor: Mask - length_units: 5, - }; - handle_shape_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - header, - &body, - ) - .expect("ShapeMask"); - - assert!( - read_all_available(&mut peer).is_empty(), - "no-op input clear must emit no ShapeNotify", - ); - } - - /// `RRSetCrtcConfig` real handler — validates mode/output/rotation and - /// calls `apply_crtc_config`. Replaces the old no-op-accept test. - /// - /// Cases: - /// The fixture has two outputs with the same connector name. Requests - /// target the second by `(crtc=5, output=4)` so routing cannot fall back - /// to a globally-ambiguous name. - /// - /// 1. valid enable (mode=3, crtc=5, outputs=[4], rotation=RR_Rotate_0) - /// → reply status=0 (Success). - /// 2. disable (mode=0, crtc=2, no outputs) - /// → reply status=0. - /// 3. bad mode (555 not in output's mode_ids) - /// → X11 error BadMatch (type byte = 0). - /// 4. bad rotation (rotation=2, i.e. RR_Rotate_90 which we don't support) - /// → X11 error BadMatch (type byte = 0; rotation valid but not identity). - #[test] - fn randr_set_crtc_config_validates_mode_id() { - use crate::randr::{RandrMode, RandrOutput, RandrState}; - - const CLIENT_ID: u32 = 1; - let mode_table = vec![RandrMode { - mode_id: 3, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - }]; - let outputs = vec![ - RandrOutput { - name: "test-0".to_string(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }, - // Equal connector names are legal across different DRM devices. - // Address this second row by CRTC/XID to prove the core never - // re-resolves the request through the ambiguous display name. - RandrOutput { - name: "test-0".to_string(), - output_id: 4, - crtc_id: 5, - mode_id: 3, - connected: true, - x: 1920, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }, - ]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs_with_modes(1, outputs, mode_table); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - - // Body layout: crtc(4) ts(4) cts(4) x(2) y(2) mode(4) rotation(2) - // pad(2) outputs(4*N). - fn build_body(mode: u32, rotation: u16, output_ids: &[u32]) -> Vec { - let mut b = Vec::with_capacity(24 + output_ids.len() * 4); - b.extend_from_slice(&5u32.to_le_bytes()); // target the second same-name CRTC - b.extend_from_slice(&0u32.to_le_bytes()); // timestamp - b.extend_from_slice(&0u32.to_le_bytes()); // config_timestamp - b.extend_from_slice(&0i16.to_le_bytes()); // x - b.extend_from_slice(&0i16.to_le_bytes()); // y - b.extend_from_slice(&mode.to_le_bytes()); // mode - b.extend_from_slice(&rotation.to_le_bytes()); // rotation - b.extend_from_slice(&[0u8; 2]); // pad - for &oid in output_ids { - b.extend_from_slice(&oid.to_le_bytes()); - } - b - } - let header = yserver_protocol::x11::RequestHeader { - opcode: 140, - data: 21, // RR_SET_CRTC_CONFIG - length_units: 7, - }; - - // (1) Valid enable: mode=3, rotation=RR_Rotate_0(1), outputs=[4] → Success reply. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &build_body(3, 1, &[4]), - ) - .expect("valid enable"); - - // (2) Disable: mode=0, no outputs → Success reply. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(2), - header, - &build_body(0, 1, &[]), - ) - .expect("disable"); - - // (3) Bad mode: mode=555 not in output's mode_ids → BadMatch error. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(3), - header, - &build_body(555, 1, &[4]), - ) - .expect("bad mode → error"); - - // (4) Bad rotation (valid code but not RR_Rotate_0): - // rotation=2 (RR_Rotate_90) is valid but our CRTC is identity-only. - // validate_set_crtc_config succeeds (mode 3 known), then rotation check - // fires BadMatch. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(4), - header, - &build_body(3, 2, &[4]), - ) - .expect("bad rotation → error"); - - use std::io::Read; - peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 1024]; - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - // All 4 responses are 32 bytes. type byte at offset 0: - // 1 = reply, 0 = error. - assert_eq!(wire.len(), 128, "4 × 32-byte packets"); - let type_bytes: Vec = wire.chunks_exact(32).map(|c| c[0]).collect(); - assert_eq!(type_bytes[0], 1, "valid enable → reply"); - let status_enable = wire[1]; // data byte of first reply - assert_eq!(status_enable, 0, "valid enable → status=0 (Success)"); - assert_eq!(type_bytes[1], 1, "disable → reply"); - let status_disable = wire[32 + 1]; - assert_eq!(status_disable, 0, "disable → status=0"); - assert_eq!(type_bytes[2], 0, "bad mode → X11 error (type=0)"); - assert_eq!(type_bytes[3], 0, "bad rotation → X11 error (type=0)"); - - let crtc_calls: Vec<_> = backend - .calls() - .into_iter() - .filter(|call| matches!(call, RecordedCall::ApplyCrtcConfig { .. })) - .collect(); - assert_eq!( - crtc_calls, - vec![ - RecordedCall::ApplyCrtcConfig { - output_id: 4, - connector: "test-0".to_string(), - mode: Some(ModeSpec { - width: 1920, - height: 1080, - vrefresh: 60, - }), - x: 0, - y: 0, - }, - RecordedCall::ApplyCrtcConfig { - output_id: 4, - connector: "test-0".to_string(), - mode: None, - x: 0, - y: 0, - }, - ], - "the second same-name output XID must be carried into backend routing", - ); - - // An asynchronous backend returns a continuation token without - // sending a premature reply. The core loop owns parking and later - // invokes `complete_crtc_config` with the finished result. - let token = CrtcConfigToken(0x1234); - backend.pending_crtc_config = Some(token); - let outcome = handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(5), - header, - &build_body(3, 1, &[4]), - ) - .expect("asynchronous enable begins"); - let RequestOutcome::PendingCrtcConfig(pending) = outcome else { - panic!("asynchronous backend must return a pending continuation"); - }; - assert_eq!(pending.token, token); - assert_eq!(pending.completion.output_id, 4); - assert!( - read_all_available(&mut peer).is_empty(), - "pending request must not receive a reply before completion" - ); - } - - #[test] - fn randr_get_crtc_gamma_size_uses_backend_and_invalid_crtc_is_bad_crtc() { - use crate::randr::{RandrOutput, RandrState}; - use yserver_protocol::x11::randr as x11randr; - - const CLIENT_ID: u32 = 1; - let outputs = vec![RandrOutput { - name: "DP-1".to_string(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs(1, outputs); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - - let header = RequestHeader { - opcode: 128, - data: x11randr::RR_GET_CRTC_GAMMA_SIZE, - length_units: 2, - }; - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &2u32.to_le_bytes(), - ) - .expect("valid get gamma size"); - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(2), - header, - &999u32.to_le_bytes(), - ) - .expect("invalid get gamma size"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 64, "reply + error"); - assert_eq!(bytes[0], 1, "valid query replies"); - assert_eq!(&bytes[8..10], &256u16.to_le_bytes(), "gamma size"); - assert_eq!(bytes[32], 0, "invalid crtc emits error packet"); - assert_eq!(bytes[33], RANDR_BAD_CRTC); - } - - #[test] - fn randr_get_crtc_gamma_reports_seeded_identity_ramp() { - use crate::randr::{RandrOutput, RandrState}; - use yserver_protocol::x11::randr as x11randr; - - const CLIENT_ID: u32 = 1; - let outputs = vec![RandrOutput { - name: "DP-1".to_string(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs(1, outputs); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: x11randr::RR_GET_CRTC_GAMMA, - length_units: 2, - }, - &2u32.to_le_bytes(), - ) - .expect("get gamma"); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32 + 256 * 3 * 2); - assert_eq!(bytes[0], 1); - assert_eq!(&bytes[8..10], &256u16.to_le_bytes()); - assert_eq!(&bytes[32..34], &0u16.to_le_bytes(), "red[0]"); - assert_eq!( - &bytes[32 + 510..32 + 512], - &65535u16.to_le_bytes(), - "red[last]" - ); - assert_eq!(&bytes[32 + 512..32 + 514], &0u16.to_le_bytes(), "green[0]"); - assert_eq!( - &bytes[32 + 1022..32 + 1024], - &65535u16.to_le_bytes(), - "green[last]" - ); - assert_eq!(&bytes[32 + 1024..32 + 1026], &0u16.to_le_bytes(), "blue[0]"); - assert_eq!( - &bytes[32 + 1534..32 + 1536], - &65535u16.to_le_bytes(), - "blue[last]" - ); - } - - #[test] - fn randr_set_crtc_gamma_validates_and_roundtrips() { - use crate::randr::{RandrOutput, RandrState}; - use yserver_protocol::x11::randr as x11randr; - - fn set_gamma_body(crtc: u32, red: &[u16], green: &[u16], blue: &[u16]) -> Vec { - let size = u16::try_from(red.len()).unwrap(); - let mut body = Vec::with_capacity(8 + red.len() * 6); - body.extend_from_slice(&crtc.to_le_bytes()); - body.extend_from_slice(&size.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - for channel in [red, green, blue] { - for &entry in channel { - body.extend_from_slice(&entry.to_le_bytes()); - } - } - body - } - - const CLIENT_ID: u32 = 1; - let outputs = vec![RandrOutput { - name: "DP-1".to_string(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs(1, outputs); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - - let red = vec![1u16; 256]; - let green = vec![2u16; 256]; - let blue = vec![3u16; 256]; - let body = set_gamma_body(2, &red, &green, &blue); - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_CRTC_GAMMA, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - &body, - ) - .expect("set gamma"); - assert_eq!(backend.get_crtc_gamma(2), (red, green, blue)); - - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(2), - RequestHeader { - opcode: 128, - data: x11randr::RR_GET_CRTC_GAMMA, - length_units: 2, - }, - &2u32.to_le_bytes(), - ) - .expect("get gamma"); - - let short_body = { - let mut b = Vec::new(); - b.extend_from_slice(&2u32.to_le_bytes()); - b.extend_from_slice(&256u16.to_le_bytes()); - b.extend_from_slice(&[0u8; 2]); - b - }; - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(3), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_CRTC_GAMMA, - length_units: 3, - }, - &short_body, - ) - .expect("short set gamma"); - - let red_small = vec![9u16; 128]; - let green_small = vec![8u16; 128]; - let blue_small = vec![7u16; 128]; - let mismatch_body = set_gamma_body(2, &red_small, &green_small, &blue_small); - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(4), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_CRTC_GAMMA, - length_units: u32::try_from(1 + mismatch_body.len().div_ceil(4)).unwrap(), - }, - &mismatch_body, - ) - .expect("size mismatch set gamma"); - - let invalid_body = set_gamma_body(999, &[0u16; 256], &[0u16; 256], &[0u16; 256]); - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(5), - RequestHeader { - opcode: 128, - data: x11randr::RR_SET_CRTC_GAMMA, - length_units: u32::try_from(1 + invalid_body.len().div_ceil(4)).unwrap(), - }, - &invalid_body, - ) - .expect("invalid crtc set gamma"); - - let bytes = read_all_available(&mut peer); - assert_eq!( - bytes.len(), - (32 + 256 * 3 * 2) + (32 * 3), - "one gamma reply + three errors" - ); - let gamma_reply_len = 32 + 256 * 3 * 2; - assert_eq!(bytes[0], 1, "get reply"); - assert_eq!(bytes[gamma_reply_len], 0, "short body => error"); - assert_eq!(bytes[gamma_reply_len + 1], x11::error::BAD_LENGTH); - assert_eq!(bytes[gamma_reply_len + 32], 0, "size mismatch => error"); - assert_eq!(bytes[gamma_reply_len + 33], x11::error::BAD_MATCH); - assert_eq!(bytes[gamma_reply_len + 64], 0, "invalid crtc => error"); - assert_eq!(bytes[gamma_reply_len + 65], RANDR_BAD_CRTC); - } - - #[test] - fn map_window_seeds_damage_for_newly_viewable_descendant() { - use crate::server::DamageObject; - - const CLIENT_ID: u32 = 1; - const PARENT_XID: u32 = 0x0010_0012; - const PARENT_HOST_XID: u32 = 0x0040_0012; - const CHILD_XID: u32 = 0x0010_0013; - const CHILD_HOST_XID: u32 = 0x0040_0013; - const CHILD_DAMAGE_ID: u32 = 0x0080_0013; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(PARENT_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 400, - height: 300, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_XID), - parent: ResourceId(PARENT_XID), - x: 20, - y: 30, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let parent = state - .resources - .window_mut(ResourceId(PARENT_XID)) - .expect("parent installed"); - parent.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - PARENT_HOST_XID, - )); - parent.map_state = crate::resources::MapState::Unmapped; - } - { - let child = state - .resources - .window_mut(ResourceId(CHILD_XID)) - .expect("child installed"); - child.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - CHILD_HOST_XID, - )); - child.map_state = crate::resources::MapState::Unviewable; - } - - state.damage_objects.insert( - CHILD_DAMAGE_ID, - DamageObject { - owner: ClientId(CLIENT_ID), - drawable: ResourceId(CHILD_XID), - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&PARENT_XID.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window"); - - let child_damage = state - .damage_objects - .get(&CHILD_DAMAGE_ID) - .expect("child damage object survives"); - assert!( - !child_damage.rects.is_empty(), - "mapping a parent must seed damage for descendants promoted from \ - Unviewable to Viewable; otherwise compositors miss the child's \ - first visible frame" - ); - } - - #[test] - fn map_window_rereports_nonempty_damage_for_newly_viewable_descendant() { - use crate::{nested::DAMAGE_FIRST_EVENT, server::DamageObject}; - use std::io::Read; - use yserver_protocol::x11::{damage as x11damage, xfixes::RegionRect}; - - const CLIENT_ID: u32 = 1; - const PARENT_XID: u32 = 0x0010_0022; - const PARENT_HOST_XID: u32 = 0x0040_0022; - const CHILD_XID: u32 = 0x0010_0023; - const CHILD_HOST_XID: u32 = 0x0040_0023; - const CHILD_DAMAGE_ID: u32 = 0x0080_0023; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(PARENT_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 400, - height: 300, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_XID), - parent: ResourceId(PARENT_XID), - x: 20, - y: 30, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let parent = state - .resources - .window_mut(ResourceId(PARENT_XID)) - .expect("parent installed"); - parent.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - PARENT_HOST_XID, - )); - parent.map_state = crate::resources::MapState::Unmapped; - } - { - let child = state - .resources - .window_mut(ResourceId(CHILD_XID)) - .expect("child installed"); - child.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - CHILD_HOST_XID, - )); - child.map_state = crate::resources::MapState::Unviewable; - } - - state.damage_objects.insert( - CHILD_DAMAGE_ID, - DamageObject { - owner: ClientId(CLIENT_ID), - drawable: ResourceId(CHILD_XID), - level: x11damage::report_level::NON_EMPTY, - rects: vec![RegionRect { - x: 0, - y: 0, - width: 200, - height: 80, - }], - pending_notify_fired: true, - last_reported_geometry: Some(x11damage::Rectangle { - x: 20, - y: 30, - width: 200, - height: 80, - }), - }, - ); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&PARENT_XID.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window"); - - peer.set_nonblocking(true).expect("set nonblocking"); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - - assert!( - all.chunks_exact(32).any(|evt| evt[0] == DAMAGE_FIRST_EVENT), - "mapping a parent must re-report NON_EMPTY damage for descendants promoted \ - from Unviewable to Viewable even when they already fired before becoming viewable" - ); - } - - /// F{ A{ A1 }, B{ B1 }, C }: F viewable, A and B unmapped with their - /// child mapped (Unviewable), C mapped. - fn subwindows_delta_fixture(state: &mut ServerState) -> [ResourceId; 6] { - let [f, a, a1, b, b1, c] = [ - 0x0010_0200, - 0x0010_0201, - 0x0010_0202, - 0x0010_0203, - 0x0010_0204, - 0x0010_0205, - ] - .map(ResourceId); - for (id, parent) in [(f, ROOT_WINDOW), (a, f), (a1, a), (b, f), (b1, b), (c, f)] { - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: id, - parent, - x: 0, - y: 0, - width: 40, - height: 40, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - for w in [a1, b1, f, c] { - let _ = state.resources.map_window(w); - } - [f, a, a1, b, b1, c] - } - - /// Window storage follows the delta: realize parent first, release child first, never the COW. - #[test] - fn window_storage_follows_viewability_delta_in_order() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let [f, a, a1, b, b1, c] = subwindows_delta_fixture(&mut state); - for w in [f, a, a1, b, b1, c] { - state.resources.window_mut(w).expect("window").host_xid = - Some(crate::backend::WindowHandle::from_raw_for_test(w.0)); - } - let _ = state.resources.map_window(a); - let _ = state.resources.map_window(b); - let storage_calls = |backend: &RecordingBackend, from: usize| -> Vec { - backend - .calls() - .into_iter() - .skip(from) - .filter(|c| { - matches!( - c, - RecordedCall::RealizeWindowStorage(_) - | RecordedCall::ReleaseWindowStorage(_) - ) - }) - .collect() - }; - let unmap = |state: &mut ServerState, backend: &mut RecordingBackend, w: ResourceId| { - handle_unmap_window( - state, - backend, - None, - ClientId(1), - SequenceNumber(1), - &w.0.to_le_bytes(), - ) - .expect("UnmapWindow"); - }; - let map = |state: &mut ServerState, backend: &mut RecordingBackend, w: ResourceId| { - handle_map_window( - state, - backend, - None, - ClientId(1), - SequenceNumber(2), - &w.0.to_le_bytes(), - ) - .expect("MapWindow"); - }; - - unmap(&mut state, &mut backend, f); - assert_eq!( - storage_calls(&backend, 0), - [a1, a, b1, b, c, f].map(|w| RecordedCall::ReleaseWindowStorage(w.0)), - "the whole subtree releases, child first", - ); - let from = backend.calls().len(); - map(&mut state, &mut backend, f); - assert_eq!( - storage_calls(&backend, from), - [f, a, a1, b, b1, c].map(|w| RecordedCall::RealizeWindowStorage(w.0)), - "the whole subtree realizes, parent first", - ); - let realize_at = backend - .calls() - .iter() - .skip(from) - .position(|c| matches!(c, RecordedCall::RealizeWindowStorage(_))) - .expect("realize recorded"); - let map_at = backend - .calls() - .iter() - .skip(from) - .position(|c| matches!(c, RecordedCall::MapSubwindow(_))) - .expect("map recorded"); - assert!( - map_at < realize_at, - "map_subwindow flips `mapped` before realize reads it" - ); - - // A mapped window under an unmapped parent gets nothing; the root and the COW never do. - unmap(&mut state, &mut backend, a); - let _ = state.resources.unmap_window(a1); - let from = backend.calls().len(); - map(&mut state, &mut backend, a1); - assert!( - storage_calls(&backend, from).is_empty(), - "Unmapped -> Unviewable is no transition" - ); - state - .resources - .materialize_cow_resource(crate::backend::WindowHandle::from_raw_for_test( - COMPOSITE_OVERLAY_WINDOW.0, - )); - let from = backend.calls().len(); - unmap(&mut state, &mut backend, COMPOSITE_OVERLAY_WINDOW); - map(&mut state, &mut backend, COMPOSITE_OVERLAY_WINDOW); - assert!( - storage_calls(&backend, from).is_empty(), - "the COW is outside the lifecycle" - ); - assert_eq!(storage_lifecycle_host_xid(&state, ROOT_WINDOW), None); - assert_eq!( - storage_lifecycle_host_xid(&state, COMPOSITE_OVERLAY_WINDOW), - None - ); - } - - #[test] - fn map_subwindows_delta_includes_promoted_grandchildren() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let [f, a, a1, b, b1, _c] = subwindows_delta_fixture(&mut state); - - let (_, delta) = map_subwindows_with_delta( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &f.0.to_le_bytes(), - ) - .expect("MapSubwindows"); - // C was already viewable; A and B each bring their grandchild. - assert_eq!(delta.became_viewable, vec![a, a1, b, b1]); - assert!(delta.became_unviewable.is_empty()); - } - - #[test] - fn unmap_subwindows_delta_is_union_in_post_order() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let [f, a, a1, b, b1, c] = subwindows_delta_fixture(&mut state); - let _ = state.resources.map_window(a); - let _ = state.resources.map_window(b); - - let (_, delta) = unmap_subwindows_with_delta( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &f.0.to_le_bytes(), - ) - .expect("UnmapSubwindows"); - assert!(delta.became_viewable.is_empty()); - assert_eq!(delta.became_unviewable, vec![a1, a, b1, b, c]); - } - - #[test] - fn map_and_unmap_under_unmapped_parent_still_send_notify() { - const STRUCTURE_NOTIFY: u32 = 0x0002_0000; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let [_f, _a, a1, ..] = subwindows_delta_fixture(&mut state); - let _ = state.resources.unmap_window(a1); - state - .clients - .get_mut(&1) - .expect("client") - .event_masks - .insert(a1, STRUCTURE_NOTIFY); - let notified = |bytes: &[u8], code: u8| { - bytes.chunks_exact(32).any(|evt| { - evt[0] == code && u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]) == a1.0 - }) - }; - - // A1 under unmapped A: Unmapped -> Unviewable, still MapNotify. - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - &a1.0.to_le_bytes(), - ) - .expect("MapWindow"); - assert_eq!( - state.resources.window(a1).map(|w| w.map_state), - Some(MapState::Unviewable) - ); - assert!(notified(&read_all_available(&mut peer), 19), "MapNotify"); - - // Unviewable -> Unmapped, still UnmapNotify. - handle_unmap_window( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - &a1.0.to_le_bytes(), - ) - .expect("UnmapWindow"); - assert_eq!( - state.resources.window(a1).map(|w| w.map_state), - Some(MapState::Unmapped) - ); - assert!(notified(&read_all_available(&mut peer), 18), "UnmapNotify"); - } - - #[test] - fn map_subwindows_exposes_grandchild_promoted_by_viewability_cascade() { - // MapSubwindows(parent) maps parent's direct children. When a - // child transitions Unmapped -> Viewable, the viewability cascade - // (map_window) also promotes any of the - // child's descendants that were sitting Unviewable (mapped while - // their ancestor was unmapped) to Viewable. Xorg fires Expose on - // every newly-viewable window, not just the directly-mapped child. - // handle_map_subwindows previously emitted Expose only for the - // direct children, so a promoted grandchild never got its Expose - // and never painted its first frame (docs/known-issues.md). - const CLIENT_ID: u32 = 1; - const PARENT_XID: u32 = 0x0010_0032; - const CHILD_XID: u32 = 0x0010_0033; - const CHILD_HOST_XID: u32 = 0x0040_0033; - const GRANDCHILD_XID: u32 = 0x0010_0034; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(PARENT_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 400, - height: 300, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_XID), - parent: ResourceId(PARENT_XID), - x: 20, - y: 30, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRANDCHILD_XID), - parent: ResourceId(CHILD_XID), - x: 5, - y: 5, - width: 100, - height: 40, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - // Parent already viewable; child unmapped so MapSubwindows maps it; - // grandchild mapped-but-Unviewable so the cascade promotes it. - state - .resources - .window_mut(ResourceId(PARENT_XID)) - .expect("parent installed") - .map_state = crate::resources::MapState::Viewable; - { - let child = state - .resources - .window_mut(ResourceId(CHILD_XID)) - .expect("child installed"); - child.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - CHILD_HOST_XID, - )); - child.map_state = crate::resources::MapState::Unmapped; - } - state - .resources - .window_mut(ResourceId(GRANDCHILD_XID)) - .expect("grandchild installed") - .map_state = crate::resources::MapState::Unviewable; - - // Client selects ExposureMask (0x8000) on both child and grandchild. - let client = state.clients.get_mut(&CLIENT_ID).expect("client"); - client - .event_masks - .insert(ResourceId(CHILD_XID), 0x0000_8000); - client - .event_masks - .insert(ResourceId(GRANDCHILD_XID), 0x0000_8000); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&PARENT_XID.to_le_bytes()); - handle_map_subwindows( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_subwindows"); - - // Grandchild is now Viewable (cascade worked)... - assert_eq!( - state - .resources - .window(ResourceId(GRANDCHILD_XID)) - .map(|w| w.map_state), - Some(crate::resources::MapState::Viewable), - "the viewability cascade must promote the grandchild" - ); - - let bytes = read_all_available(&mut peer); - let exposed = |xid: u32| { - bytes.chunks_exact(32).any(|evt| { - evt[0] == 12 && u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]) == xid - }) - }; - assert!( - exposed(CHILD_XID), - "the directly-mapped child must receive Expose (harness sanity)" - ); - assert!( - exposed(GRANDCHILD_XID), - "a grandchild promoted Unviewable->Viewable by MapSubwindows must \ - also receive Expose, else it never paints its first frame" - ); - } - - #[test] - fn damage_create_on_viewable_window_seeds_full_damage() { - use yserver_protocol::x11::{RequestHeader, damage as x11damage}; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0100; - const HOST_XID: u32 = 0x0040_0100; - const DAMAGE_ID: u32 = 0x0080_0100; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - - state.resources.create_window( - ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 11, - y: 22, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - w.map_state = crate::resources::MapState::Viewable; - } - let mut body = Vec::new(); - body.extend_from_slice(&DAMAGE_ID.to_le_bytes()); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - body.push(x11damage::report_level::NON_EMPTY); - body.extend_from_slice(&[0, 0, 0]); - - let header = RequestHeader { - opcode: 0, - data: x11damage::CREATE, - length_units: 0, - }; - handle_damage_request( - &mut state, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("damage create handled"); - - let damage = state - .damage_objects - .get(&DAMAGE_ID) - .expect("damage object created"); - assert!( - !damage.rects.is_empty(), - "creating DAMAGE on an already-viewable window must seed initial \ - damage so the subscriber does not miss the current visible frame" - ); - } - - // X11 wire-event ordering on map. Verified divergence vs Xorg: - // - // - **Xorg** (mate-xorg.xtrace lines 5164→5173 around mate-panel-top - // map): MapNotify(event=root) first, then DAMAGE-Notify. - // - **yserver pre-fix** (mate.xtrace lines 4938→4940): DAMAGE-Notify - // first, then MapNotify(event=root). - // - // Marco's compositor relies on MapNotify(SubstructureNotify on root) - // to register a window in its compositor tree, and on the *next* - // DAMAGE-Notify on that window to trigger NameWindowPixmap. When - // damage arrives first, marco's tree doesn't know about the window - // yet and the damage is silently discarded. Marco then never sees - // the audit-#11 initial-paint damage and never Names the window; - // the panel renders blank until a *later* damage event arrives - // (typically the post-resize damage), by which point the icon-paint - // CopyAreas have already missed their compositor pickup window. - // - // The audit-#11 fix (`accumulate_damage_full_to_state` inside - // `handle_map_window`) is structurally correct but was placed - // before the MapNotify emissions — inverting the spec-correct - // order. This test pins MapNotify-before-DAMAGE on the wire. - #[test] - fn map_window_emits_map_notify_before_damage_notify() { - use crate::server::DamageObject; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0011; - const HOST_XID: u32 = 0x0040_0011; - const DAMAGE_ID: u32 = 0x0080_0011; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - } - - // Compositor-like subscription: SubstructureNotify on root - // (0x0008_0000) — gets MapNotify(event=root) when a child of - // root maps. Plus an `XDamageCreate(window)` subscription — - // gets DAMAGE-Notify on the new window. - state - .clients - .get_mut(&CLIENT_ID) - .unwrap() - .event_masks - .insert(ROOT_WINDOW, 0x0008_0000); - state.damage_objects.insert( - DAMAGE_ID, - DamageObject { - owner: ClientId(CLIENT_ID), - drawable: ResourceId(WINDOW_XID), - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window"); - - // Drain everything emitted to the client. Each X11 event is - // 32 bytes — read until WouldBlock and walk event-by-event. - peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 1024]; - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - - // First occurrence of MapNotify(opcode 19, event=ROOT) and - // DAMAGE-Notify(opcode 91) by 32-byte event index. MapNotify's - // `event` field is at offset 4..8 (after response_type, pad, - // sequence_number_lo, sequence_number_hi). - let mut map_root_idx: Option = None; - let mut damage_idx: Option = None; - for (i, chunk) in wire.chunks_exact(32).enumerate() { - let opcode = chunk[0] & 0x7f; // top bit is SendEvent flag - if opcode == 19 && map_root_idx.is_none() { - let event_xid = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); - if event_xid == ROOT_WINDOW.0 { - map_root_idx = Some(i); - } - } else if opcode == 91 && damage_idx.is_none() { - damage_idx = Some(i); - } - } - - let m = map_root_idx.expect( - "MapNotify(event=root) must be emitted to a SubstructureNotify-on-root listener", - ); - let d = damage_idx.expect("DAMAGE-Notify must be emitted to a subscribed damage object"); - assert!( - m < d, - "MapNotify(event=root, idx={m}) must precede DAMAGE-Notify(idx={d}) on the \ - wire — pre-fix the audit-#11 damage emission inside `handle_map_window` ran \ - before the MapNotify emissions, so marco's compositor saw the damage on a \ - window that hadn't yet entered its compositor tree, silently discarded it, \ - and never NameWindowPixmap'd the freshly-mapped window. \ - See mate.xtrace lines 4938→4940 vs mate-xorg.xtrace lines 5164→5173.", - ); - } - - /// Mapping a viewable window emits `VisibilityNotify(Unobscured)` - /// (event type 15, state 0) to clients selecting - /// `VisibilityChangeMask` (0x10000). Without it, GTK3 suppresses - /// all frame-clock paints after the first expose-driven frame — - /// the cinnamon-settings "title updates but content never - /// repaints" freeze, confirmed by diffing the Xorg vs yserver - /// wire traces (Xorg sends Unobscured; yserver previously sent - /// nothing). - #[test] - fn map_window_emits_visibility_notify_unobscured() { - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0021; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - // Client selects VisibilityChangeMask on its own window. - state - .clients - .get_mut(&CLIENT_ID) - .unwrap() - .event_masks - .insert(ResourceId(WINDOW_XID), 0x0001_0000); - - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&WINDOW_XID.to_le_bytes()); - handle_map_window( - &mut state, - &mut backend, - None, - ClientId(CLIENT_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_map_window"); - - peer.set_nonblocking(true).unwrap(); - let mut wire = Vec::new(); - let mut tmp = [0u8; 1024]; - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - - let vis = wire.chunks_exact(32).find(|chunk| chunk[0] & 0x7f == 15); - let vis = vis.expect("VisibilityNotify (type 15) must be emitted on map"); - let window = u32::from_le_bytes([vis[4], vis[5], vis[6], vis[7]]); - assert_eq!(window, WINDOW_XID, "VisibilityNotify targets the window"); - assert_eq!(vis[8], 0, "state must be Unobscured (0)"); - } - - /// Resize rotates the redirected backing by releasing the old - /// backing and allocating a new one. The fresh allocation must - /// preserve the effective redirect mode's scene-participation - /// flags; otherwise a Manual-redirected frame can become visible - /// through normal scene traversal after a ConfigureWindow resize. - #[test] - fn rotate_redirected_backing_preserves_manual_scene_participation() { - use crate::backend::recording::RecordedCall; - - const CLIENT_ID: u32 = 1; - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - const OLD_BACKING: u32 = 0x0050_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 32, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), - width: 100, - height: 50, - depth: 32, - }); - } - state.composite_redirects.insert( - (ResourceId(WINDOW_XID), false), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: yserver_protocol::x11::ClientId(CLIENT_ID), - }, - ); - - rotate_redirected_backing_on_resize( - &mut state, - &mut backend, - None, - ResourceId(WINDOW_XID), - 100, - 75, - false, - 0, - ); - - let calls = backend.calls(); - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::SetWindowSceneParticipation { - host_window: HOST_XID, - participating: false, - } - )), - "rotate must reapply Manual W scene_participating=false; got {calls:?}", - ); - // The fresh backing must be scene-participating so the - // scene's `redirected_target` damage-peek sees paints into - // it post-resize — same invariant as - // `manual_redirect_marks_backing_scene_participating_so_paints_emit_damage`. - assert!( - calls.iter().any(|c| matches!( - c, - RecordedCall::SetBackingSceneParticipation { - participating: true, - .. - } - )), - "rotate must mark the fresh Manual backing scene-participating; got {calls:?}", - ); - } - - /// XFIXES SUBTRACT_REGION partial-overlap: subtracting a - /// region that overlaps part of `a` must return the bands of - /// `a` *not* covered by `b`. The pre-fix dispatcher collapsed - /// any overlap to an empty result; compositors that build - /// "screen MINUS windows" wallpaper clips this way would end - /// up with no clip at all. - #[test] - fn xfixes_subtract_region_partial_overlap_returns_remaining_bands() { - use crate::server::XFixesRegion; - use yserver_protocol::x11::xfixes::RegionRect; - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - // Region A: a 100x100 square at the origin. - state.xfixes_regions.insert( - 0x10, - XFixesRegion { - owner: ClientId(1), - rects: vec![RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }], - }, - ); - // Region B: a 50x100 strip overlapping the right half of A. - state.xfixes_regions.insert( - 0x11, - XFixesRegion { - owner: ClientId(1), - rects: vec![RegionRect { - x: 50, - y: 0, - width: 50, - height: 100, - }], - }, - ); - // SUBTRACT_REGION body: source1(4) + source2(4) + dest(4). - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&0x10u32.to_le_bytes()); - body.extend_from_slice(&0x11u32.to_le_bytes()); - body.extend_from_slice(&0x12u32.to_le_bytes()); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(1, 5); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 140, // XFIXES major - data: yserver_protocol::x11::xfixes::SUBTRACT_REGION, - length_units: 4, - }, - &body, - None, - ) - .unwrap(); - - let result = state - .xfixes_regions - .get(&0x12) - .expect("dest region recorded"); - assert!( - !result.rects.is_empty(), - "partial-overlap subtraction must NOT collapse to empty — \ - pre-fix this returns Vec::new() and breaks compositor \ - wallpaper-clip computation", - ); - // Geometrically: A (0,0 100x100) minus B (50,0 50x100) - // leaves the left band (0,0 50x100). Allow any equivalent - // rect decomposition that covers exactly that area. - let total_area: u64 = result - .rects - .iter() - .map(|r| u64::from(r.width) * u64::from(r.height)) - .sum(); - assert_eq!( - total_area, - 50 * 100, - "result area must be 5000 (the left half of A); got rects {:?}", - result.rects, - ); - // No result rect may extend into B's x-range [50, 100). - for r in &result.rects { - assert!( - r.x + i16::try_from(r.width).unwrap_or(i16::MAX) <= 50, - "result rect {r:?} extends into the subtracted region", - ); - } - } - - fn dispatch_damage_subtract( - state: &mut ServerState, - backend: &mut RecordingBackend, - damage_id: u32, - repair: u32, - parts: u32, - ) { - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&damage_id.to_le_bytes()); - body.extend_from_slice(&repair.to_le_bytes()); - body.extend_from_slice(&parts.to_le_bytes()); - process_request( - state, - backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 143, // DAMAGE major - data: yserver_protocol::x11::damage::SUBTRACT, - length_units: 4, - }, - &body, - None, - ) - .unwrap(); - } - - #[test] - fn damage_subtract_with_no_repair_returns_old_damage_in_parts_and_clears() { - use crate::server::{DamageObject, XFixesRegion}; - use yserver_protocol::x11::xfixes::RegionRect; - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let damaged_rect = RegionRect { - x: 10, - y: 20, - width: 30, - height: 40, - }; - state.damage_objects.insert( - 0x20, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(0x100), - level: 0, - rects: vec![damaged_rect], - pending_notify_fired: true, - last_reported_geometry: None, - }, - ); - // Pre-create the parts region so the handler writes into it. - state.xfixes_regions.insert( - 0x21, - XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - - dispatch_damage_subtract(&mut state, &mut backend, 0x20, 0, 0x21); - - // Per X11 DAMAGE spec: repair==None → parts gets old damage, - // damage is cleared. - let parts = state - .xfixes_regions - .get(&0x21) - .expect("parts region must exist"); - assert_eq!( - parts.rects, - vec![damaged_rect], - "with repair=None, parts must receive the entire old damage region; \ - pre-fix this returns Vec::new() and starves compositors of a real clip" - ); - let damage = state.damage_objects.get(&0x20).unwrap(); - assert!( - damage.rects.is_empty(), - "with repair=None, damage must be fully cleared" - ); - assert!( - !damage.pending_notify_fired, - "Subtract is the cycle boundary — pending_notify_fired must reset" - ); - } - - #[test] - fn damage_subtract_with_no_repair_canonicalizes_parts_region() { - use crate::server::{DamageObject, XFixesRegion}; - use yserver_protocol::x11::xfixes::RegionRect; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - state.damage_objects.insert( - 0x40, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(0x100), - level: 0, - rects: vec![ - RegionRect { - x: 0, - y: 0, - width: 10, - height: 10, - }, - RegionRect { - x: 10, - y: 0, - width: 10, - height: 10, - }, - RegionRect { - x: 0, - y: 0, - width: 20, - height: 10, - }, - ], - pending_notify_fired: true, - last_reported_geometry: None, - }, - ); - state.xfixes_regions.insert( - 0x41, - XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - - dispatch_damage_subtract(&mut state, &mut backend, 0x40, 0, 0x41); - - let parts = state - .xfixes_regions - .get(&0x41) - .expect("parts region must exist"); - assert_eq!( - parts.rects, - vec![RegionRect { - x: 0, - y: 0, - width: 20, - height: 10, - }], - "with repair=None, parts must be canonicalized before they are handed to the client" - ); - } - - #[test] - fn damage_subtract_with_repair_returns_intersection_and_subtracts_from_damage() { - use crate::server::{DamageObject, XFixesRegion}; - use yserver_protocol::x11::xfixes::RegionRect; - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - // Damage: 100x100 at origin. - state.damage_objects.insert( - 0x30, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(0x100), - level: 0, - rects: vec![RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }], - pending_notify_fired: true, - last_reported_geometry: None, - }, - ); - // Repair: right-half strip 50x100 at (50, 0). MUST remain - // unchanged by Subtract — it's an input filter, not an output. - let repair_rect = RegionRect { - x: 50, - y: 0, - width: 50, - height: 100, - }; - state.xfixes_regions.insert( - 0x31, - XFixesRegion { - owner: ClientId(1), - rects: vec![repair_rect], - }, - ); - state.xfixes_regions.insert( - 0x32, - XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - - dispatch_damage_subtract(&mut state, &mut backend, 0x30, 0x31, 0x32); - - // parts = damage ∩ repair → right half 50x100 at (50, 0). - let parts = &state.xfixes_regions.get(&0x32).unwrap().rects; - let parts_area: u64 = parts - .iter() - .map(|r| u64::from(r.width) * u64::from(r.height)) - .sum(); - assert_eq!( - parts_area, - 50 * 100, - "parts must cover the intersection (5000 px²); got {parts:?}" - ); - for r in parts { - assert!( - r.x >= 50, - "parts rect {r:?} extends outside the repair filter" - ); - } - - // damage = damage − repair → left half 50x100 at (0, 0). - let damage = &state.damage_objects.get(&0x30).unwrap().rects; - let damage_area: u64 = damage - .iter() - .map(|r| u64::from(r.width) * u64::from(r.height)) - .sum(); - assert_eq!( - damage_area, - 50 * 100, - "damage must retain the un-repaired left half (5000 px²); got {damage:?}" - ); - for r in damage { - assert!( - r.x + i16::try_from(r.width).unwrap_or(i16::MAX) <= 50, - "damage rect {r:?} extends into the repaired region" - ); - } - - // repair region MUST NOT have been overwritten — pre-fix this - // stomped repair with `damage.rects.clone()`. - let repair_now = &state.xfixes_regions.get(&0x31).unwrap().rects; - assert_eq!( - repair_now, - &vec![repair_rect], - "Subtract must treat the repair region as read-only input; \ - pre-fix this overwrote it with the damage rects" - ); - } - - #[test] - fn damage_subtract_with_remaining_nonempty_damage_rereports_immediately() { - use crate::server::{DamageObject, XFixesRegion}; - use yserver_protocol::x11::{CreateWindowRequest, damage as x11damage, xfixes::RegionRect}; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let _peer = install_client(&mut state, 1); - - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(0x100), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(0x100)); - - state.damage_objects.insert( - 0x40, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(0x100), - level: x11damage::report_level::NON_EMPTY, - rects: vec![RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }], - pending_notify_fired: true, - last_reported_geometry: None, - }, - ); - state.xfixes_regions.insert( - 0x41, - XFixesRegion { - owner: ClientId(1), - rects: vec![RegionRect { - x: 50, - y: 0, - width: 50, - height: 100, - }], - }, - ); - state.xfixes_regions.insert( - 0x42, - XFixesRegion { - owner: ClientId(1), - rects: Vec::new(), - }, - ); - - dispatch_damage_subtract(&mut state, &mut backend, 0x40, 0x41, 0x42); - - let damage = state.damage_objects.get(&0x40).expect("damage object"); - assert!( - !damage.rects.is_empty(), - "repair only covered part of the damage; some damage must remain" - ); - assert!( - damage.pending_notify_fired, - "Xorg immediately re-reports remaining non-empty damage after Subtract; \ - pre-fix yserver left fired=false and waited for unrelated future drawing" - ); - } - - /// X11 Composite + DAMAGE interaction: a configure that changes a - /// redirected window's screen-space presentation must emit a - /// `DamageNotify` to the compositor's damage subscription on that - /// window. Xorg behaviour (compositor.c) — without this event, - /// marco/picom/etc. never mark the moved window dirty and their - /// SetPictureClipRectangles excludes the window's region, so - /// composites against the redirected backing no-op or partially - /// blend, producing the "CC disappears on drag / muddy bands on - /// caja-redraw" symptom we measured against a Xephyr (Xorg-family) - /// reference run: yserver emitted 0 DamageNotify events to marco; - /// Xephyr emitted 776. - /// - /// Reproduce minimally: install marco client, create a top-level - /// window with a damage object owned by marco, set the window - /// `redirected_backing` (Manual-redirect activated state), then - /// send a move-only ConfigureWindow. Read marco's socket and - /// look for the DamageNotify event (event opcode 94 = DAMAGE - /// first_event + 0). - #[test] - fn configure_window_on_redirected_window_emits_damage_to_subscriber() { - use crate::{ - resources::{ROOT_WINDOW, RedirectedBacking}, - server::{CompositeRedirectMode, DamageObject, RedirectRecord}, - }; - use std::io::Read; - use yserver_protocol::x11::CreateWindowRequest; - const MARCO: u32 = 14; - const FRAME_XID: u32 = 0x0010_0001; - const DAMAGE_XID: u32 = 0x0010_0002; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, MARCO); - - // Frame W under root. - state.resources.create_window( - ClientId(MARCO), - CreateWindowRequest { - depth: 24, - window: ResourceId(FRAME_XID), - parent: ROOT_WINDOW, - x: 100, - y: 100, - width: 997, - height: 652, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(FRAME_XID)); - state.composite_redirects.insert( - (ResourceId(FRAME_XID), false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(MARCO), - }, - ); - // Mark the frame as redirected (Manual-redirect activated - // state). `host_pixmap` value is opaque to the damage path. - if let Some(w) = state.resources.window_mut(ResourceId(FRAME_XID)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0xDEAD_BEEF); - w.redirected_backing = Some(RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw(0xC0DE).unwrap(), - width: 997, - height: 652, - depth: 24, - }); - } - // Damage subscription on the frame, owned by marco, NonEmpty - // level (0x03) so any change fires. - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(MARCO), - drawable: ResourceId(FRAME_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - // ConfigureWindow body: window(4) + value_mask(2) + pad(2) + - // x(4 as i16) + y(4 as i16). value_mask = 0x03 = CWX | CWY. - // Move from (100, 100) to (250, 300). - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&FRAME_XID.to_le_bytes()); - body.extend_from_slice(&0x0003u16.to_le_bytes()); // value_mask - body.extend_from_slice(&[0u8; 2]); // pad - body.extend_from_slice(&250i32.to_le_bytes()); // x - body.extend_from_slice(&300i32.to_le_bytes()); // y - process_request( - &mut state, - &mut backend, - ClientId(MARCO), - SequenceNumber(1), - RequestHeader { - opcode: 12, // ConfigureWindow - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - // Drain marco's socket. Look for a DamageNotify event: - // event_code = DAMAGE_FIRST_EVENT + 0. - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let damage_evt: [u8; 32] = all - .chunks_exact(32) - .find(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT) - .map(|s| { - let mut a = [0u8; 32]; - a.copy_from_slice(s); - a - }) - .unwrap_or_else(|| { - panic!( - "ConfigureWindow on a redirected window must emit DamageNotify \ - (event code 94) to the compositor's damage subscriber. \ - Pre-fix yserver emits 0 DamageNotify events vs Xephyr's 776, \ - which leaves marco's compositor unable to mark the moved \ - window dirty. Got {} bytes; first 32: {:02x?}", - all.len(), - all.get(..32.min(all.len())).unwrap_or(&[]), - ) - }); - // Per X11 DAMAGE proto: DamageNotify.geometry encodes the - // damaged drawable's CURRENT root-relative position + extent - // (Xorg damageext.c fills from pDrawable->{x,y,width,height}; - // for windows, x/y are root-relative). marco/picom etc. use - // this to map the damage region into screen space. yserver's - // encoder historically hardcoded {x: 0, y: 0, w, h}, leaving - // marco mapping the damage to the wrong screen rect after - // every move — visible as "top-left bits stay rendered" - // after dragging (marco recomposites at the OLD position - // because the geometry origin points back to (0,0)). - // - // Wire layout: offsets 24..32 hold geometry as - // (x i16, y i16, w u16, h u16) little-endian. The window - // was configured to (250, 300) above. - let geom_x = i16::from_le_bytes([damage_evt[24], damage_evt[25]]); - let geom_y = i16::from_le_bytes([damage_evt[26], damage_evt[27]]); - let geom_w = u16::from_le_bytes([damage_evt[28], damage_evt[29]]); - let geom_h = u16::from_le_bytes([damage_evt[30], damage_evt[31]]); - assert_eq!( - (geom_x, geom_y, geom_w, geom_h), - (250, 300, 997, 652), - "DamageNotify.geometry must encode the window's CURRENT \ - root-relative position + extent; pre-fix this hardcodes \ - (0, 0, w, h) and breaks marco's screen-rect mapping", - ); - } - - /// Effective redirect state includes inherited `RedirectSubwindows` - /// mode, not just a directly populated `window.redirected_backing`. - /// A move-only ConfigureWindow under an inherited redirect still - /// needs to wake the compositor with DamageNotify. - #[test] - fn configure_window_on_inherited_redirect_emits_damage_to_subscriber() { - use crate::{ - resources::ROOT_WINDOW, - server::{CompositeRedirectMode, DamageObject, RedirectRecord}, - }; - use std::io::Read; - use yserver_protocol::x11::CreateWindowRequest; - - const MARCO: u32 = 14; - const CHILD_XID: u32 = 0x0010_0101; - const DAMAGE_XID: u32 = 0x0010_0102; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, MARCO); - - state.composite_redirects.insert( - (ROOT_WINDOW, true), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(MARCO), - }, - ); - - state.resources.create_window( - ClientId(MARCO), - CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_XID), - parent: ROOT_WINDOW, - x: 100, - y: 100, - width: 545, - height: 204, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(CHILD_XID)); - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(MARCO), - drawable: ResourceId(CHILD_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&CHILD_XID.to_le_bytes()); - body.extend_from_slice(&0x0003u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&250i32.to_le_bytes()); - body.extend_from_slice(&300i32.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(MARCO), - SequenceNumber(1), - RequestHeader { - opcode: 12, - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - - assert!( - all.chunks_exact(32) - .any(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT), - "move-only ConfigureWindow under inherited RedirectSubwindows \ - must emit DamageNotify even when redirected_backing is not \ - directly populated on the child window", - ); - } - - #[test] - fn configure_window_move_on_unmapped_redirected_window_emits_no_damage() { - // i3 floating-drag smear repro: i3 creates a "floatingcon" - // frame as a root child, sizes/moves it during the drag, but - // NEVER maps it. Root is composite-redirected (fastcompmgr), - // so the child inherits the redirect. A move/resize - // ConfigureWindow on this UNMAPPED window must NOT emit - // DamageNotify — Xorg damages only realized/viewable windows on - // configure. Without the map-state gate, fastcompmgr receives - // damage for the unmapped floatingcon, NameWindowPixmaps it, and - // composites its stale backing at the drag position → the trail. - use crate::{ - resources::ROOT_WINDOW, - server::{CompositeRedirectMode, DamageObject, RedirectRecord}, - }; - use std::io::Read; - use yserver_protocol::x11::CreateWindowRequest; - - const FASTCOMPMGR: u32 = 14; - const FLOATINGCON_XID: u32 = 0x0010_0101; - const DAMAGE_XID: u32 = 0x0010_0102; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, FASTCOMPMGR); - - state.composite_redirects.insert( - (ROOT_WINDOW, true), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(FASTCOMPMGR), - }, - ); - - state.resources.create_window( - ClientId(FASTCOMPMGR), - CreateWindowRequest { - depth: 24, - window: ResourceId(FLOATINGCON_XID), - parent: ROOT_WINDOW, - x: 100, - y: 100, - width: 545, - height: 204, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - // NOTE: deliberately NOT calling map_window — the floatingcon - // stays Unmapped for its whole life. - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(FASTCOMPMGR), - drawable: ResourceId(FLOATINGCON_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - // ConfigureWindow move: value-mask x|y (0x0003), new (250, 300). - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&FLOATINGCON_XID.to_le_bytes()); - body.extend_from_slice(&0x0003u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&250i32.to_le_bytes()); - body.extend_from_slice(&300i32.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(FASTCOMPMGR), - SequenceNumber(1), - RequestHeader { - opcode: 12, - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - - assert!( - !all.chunks_exact(32) - .any(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT), - "move ConfigureWindow on an UNMAPPED redirected window must \ - NOT emit DamageNotify (i3 floatingcon smear); Xorg damages \ - only realized windows on configure", - ); - } - - #[test] - fn configure_window_stack_only_on_redirected_window_does_not_emit_damage() { - use crate::{ - resources::{ROOT_WINDOW, RedirectedBacking}, - server::{CompositeRedirectMode, DamageObject, RedirectRecord}, - }; - use std::io::Read; - use yserver_protocol::x11::CreateWindowRequest; - - const MARCO: u32 = 14; - const FRAME_XID: u32 = 0x0010_0201; - const SIBLING_XID: u32 = 0x0010_0202; - const DAMAGE_XID: u32 = 0x0010_0203; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, MARCO); - - for xid in [FRAME_XID, SIBLING_XID] { - state.resources.create_window( - ClientId(MARCO), - CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 5120, - height: 1440, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(xid)); - state.composite_redirects.insert( - (ResourceId(xid), false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(MARCO), - }, - ); - if let Some(w) = state.resources.window_mut(ResourceId(xid)) { - w.host_xid = crate::backend::WindowHandle::from_raw(0xD000_0000 | xid); - w.redirected_backing = Some(RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw(0xC000_0000 | xid).unwrap(), - width: 5120, - height: 1440, - depth: 24, - }); - } - } - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(MARCO), - drawable: ResourceId(FRAME_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - // value_mask = 0x60 = CWSibling | CWStackMode, no geometry bits. - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&FRAME_XID.to_le_bytes()); - body.extend_from_slice(&0x0060u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&SIBLING_XID.to_le_bytes()); - body.push(1); // Below - body.extend_from_slice(&[0u8; 3]); - process_request( - &mut state, - &mut backend, - ClientId(MARCO), - SequenceNumber(1), - RequestHeader { - opcode: 12, - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - - assert!( - !all.chunks_exact(32) - .any(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT), - "stack-only ConfigureWindow on a redirected window must not emit synthetic \ - DamageNotify; that turns restacks into bogus full-window damage", - ); - } - - /// Audit #9 (`docs/protocol-audit-2026-05-19.md`): when a client - /// takes ownership of a selection via core `SetSelectionOwner`, the - /// server must fire `XFixesSelectionNotify(SetSelectionOwner)` to - /// every client that has subscribed via `SelectSelectionInput` with - /// the matching mask bit. Without this, every clipboard manager - /// (klipper, copyq, gpaste, gnome-shell clipboard indicator) wedges - /// waiting for the event that says "the clipboard contents - /// changed". Xorg's `xfixes/select.c:158-210` `XFixesSelectionCallback` - /// is the reference. - #[test] - fn set_selection_owner_emits_xfixes_set_owner_notify_to_subscribers() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - - const CLIPBOARD_MGR: u32 = 7; - const APP: u32 = 9; - const SUBSCRIBER_WIN: u32 = 0x0070_0001; - const OWNER_WIN: u32 = 0x0090_0001; - const PRIMARY: u32 = 1; // X11 atom PRIMARY - - let mut state = ServerState::new(); - // Clipboard manager: subscribes; we'll inspect its peer socket. - let mut peer = install_client(&mut state, CLIPBOARD_MGR); - // App: issues SetSelectionOwner (no peer needed). - let _app_peer = install_client(&mut state, APP); - - // OWNER_WIN must exist for the SetSelectionOwner window - // validation gate (`dix/selection.c:169-173`). - state.resources.create_window( - ClientId(APP), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(OWNER_WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - // Subscribe clipboard mgr to PRIMARY's set-owner events on - // SUBSCRIBER_WIN. This is what `SelectSelectionInput` writes. - state.xfixes_selection_masks.insert( - (CLIPBOARD_MGR, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_SET_OWNER, - ); - - // SetSelectionOwner(window=OWNER_WIN, selection=PRIMARY, time=0). - // time=0 is X11's `CurrentTime` which Xorg's - // `ClientTimeToServerTime` resolves to the server's - // currentTime — guaranteed to clear both the future-shift - // (`time > currentTime`) and stale (`time < lastTimeChanged`) - // checks at `dix/selection.c:166,192`. - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&OWNER_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - handle_set_selection_owner(&mut state, ClientId(APP), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - // Drain clipboard mgr's socket and locate the XFixesSelectionNotify. - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let evt: [u8; 32] = all - .chunks_exact(32) - .find(|evt| evt[0] == crate::nested::XFIXES_FIRST_EVENT) - .map(|s| { - let mut a = [0u8; 32]; - a.copy_from_slice(s); - a - }) - .unwrap_or_else(|| { - panic!( - "expected XFixesSelectionNotify (type={}) in clipboard manager's stream; \ - got {} bytes: {:02x?}", - crate::nested::XFIXES_FIRST_EVENT, - all.len(), - all, - ) - }); - assert_eq!( - evt[1], - x11xfixes::SELECTION_NOTIFY_SET_OWNER, - "subtype must be SetSelectionOwnerNotify (0)", - ); - // Skip the 2-byte sequence and verify the payload (windows / - // selection / timestamps). - assert_eq!( - u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]), - SUBSCRIBER_WIN, - "window field must be the subscriber's window", - ); - assert_eq!( - u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]), - OWNER_WIN, - "owner field must be the new selection-owner window", - ); - assert_eq!( - u32::from_le_bytes([evt[12], evt[13], evt[14], evt[15]]), - PRIMARY, - "selection field must be the selection atom", - ); - // `timestamp` is Xorg's `currentTime.milliseconds` - // (`xfixes/select.c:88`) — NOT the request's `time` arg as - // the pre-fix code assumed. `selection_timestamp` is the - // freshly-updated `lastTimeChanged`. With request `time=0` - // resolving to `currentTime`, both should reflect server - // uptime at the moment of the call. The window/owner/selection - // fields above are the load-bearing identity assertions; the - // timestamp wire encoding is covered by the destroy/close - // tests where the prior `lastTimeChanged` is seeded directly. - } - - fn assert_window_removal_releases_pointer_grab(opcode: u8) { - use crate::server::ActivePointerGrab; - - const OWNER: u32 = 1; - let grab_window = ResourceId(0x0010_0001); - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let _peer = install_client(&mut state, OWNER); - - state.resources.create_window( - ClientId(OWNER), - CreateWindowRequest { - depth: 24, - window: grab_window, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(grab_window); - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(OWNER), - grab_window, - event_mask: 0xFFFF, - cursor: ResourceId(0), - time: 0, - owner_events: true, - via_xi2: true, - implicit: false, - passive: false, - xi2_mask: u64::MAX, - }); - - process_request( - &mut state, - &mut backend, - ClientId(OWNER), - SequenceNumber(1), - RequestHeader { - opcode, - data: 0, - length_units: 2, - }, - &grab_window.0.to_le_bytes(), - None, - ) - .expect("window removal request"); - - assert!( - state.active_pointer_grab.is_none(), - "opcode {opcode} must deactivate a grab held on the removed window", - ); - } - - /// Destroying a grab window deactivates the grab, matching Xorg's - /// DeleteWindowFromAnyEvents teardown. - #[test] - fn destroying_a_grab_window_releases_the_pointer_grab() { - assert_window_removal_releases_pointer_grab(4); - } - - /// An unmapped grab window is no longer viewable and cannot retain an - /// active grab. - #[test] - fn unmapping_a_grab_window_releases_the_pointer_grab() { - assert_window_removal_releases_pointer_grab(10); - } - - /// Audit #9: when the window currently owning a selection is - /// destroyed, the server must fire - /// `XFixesSelectionNotify(SelectionWindowDestroy)` to every - /// subscribing client whose mask includes the WindowDestroy bit, - /// and clear the selection ownership in `state.selections`. - /// Reference: Xorg `xfixes/select.c:158-210` + the - /// `SelectionCallback`'s `SelectionWindowDestroy` branch. - #[test] - fn destroy_window_owning_selection_fires_window_destroy_notify_and_clears_ownership() { - use std::io::Read; - use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; - const SUBSCRIBER_ID: u32 = 8; - const OWNER_ID: u32 = 10; - const SUBSCRIBER_WIN: u32 = 0x0080_0001; - const OWNER_WIN: u32 = 0x00a0_0001; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER_ID); - let _ = install_client(&mut state, OWNER_ID); - - // Create the owner window so DestroyWindow can find it. - state.resources.create_window( - ClientId(OWNER_ID), - CreateWindowRequest { - depth: 24, - window: ResourceId(OWNER_WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - // PRIMARY currently owned by OWNER_WIN. - state - .selections - .insert(AtomId(PRIMARY), (ResourceId(OWNER_WIN), 0)); - - // Subscriber registered with WindowDestroy bit. - state.xfixes_selection_masks.insert( - (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_WINDOW_DESTROY, - ); - - // Destroy OWNER_WIN — should fire WindowDestroy notify + clear. - let mut body = Vec::with_capacity(4); - body.extend_from_slice(&OWNER_WIN.to_le_bytes()); - let mut backend = RecordingBackend::new(); - handle_destroy_window( - &mut state, - &mut backend, - None, - ClientId(OWNER_ID), - SequenceNumber(1), - &body, - ) - .expect("handle_destroy_window"); - - // Verify selection ownership cleared. - assert!( - !state.selections.contains_key(&AtomId(PRIMARY)), - "destroying the owning window must clear state.selections[PRIMARY]; \ - got {:?}", - state.selections.get(&AtomId(PRIMARY)), - ); - - // Verify subscriber received the event. - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let evt: [u8; 32] = all - .chunks_exact(32) - .find(|evt| { - evt[0] == crate::nested::XFIXES_FIRST_EVENT - && evt[1] == x11xfixes::SELECTION_NOTIFY_WINDOW_DESTROY - }) - .map(|s| { - let mut a = [0u8; 32]; - a.copy_from_slice(s); - a - }) - .unwrap_or_else(|| { - panic!( - "expected XFixesSelectionNotify(WindowDestroy) on subscriber; \ - got {} bytes: {:02x?}", - all.len(), - all, - ) - }); - assert_eq!( - u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]), - SUBSCRIBER_WIN, - "window field must be the subscriber's window", - ); - assert_eq!( - u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]), - 0, - "owner field must be None (0) after window-destroy", - ); - assert_eq!( - u32::from_le_bytes([evt[12], evt[13], evt[14], evt[15]]), - PRIMARY, - "selection field must be the cleared selection atom", - ); - } - - /// Audit #9: when a client disconnects while owning a selection, - /// the server must fire - /// `XFixesSelectionNotify(SelectionClientClose)` to every subscriber - /// whose mask includes the ClientClose bit, and drop the selection - /// ownership entry. Reference: Xorg - /// `xfixes/select.c:158-210`'s `SelectionClientClose` branch. - #[test] - fn client_disconnect_owning_selection_fires_client_close_notify_and_clears_ownership() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - const SUBSCRIBER_ID: u32 = 11; - const OWNER_ID: u32 = 12; - const SUBSCRIBER_WIN: u32 = 0x00b0_0001; - const OWNER_WIN: u32 = 0x00c0_0001; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER_ID); - let _ = install_client(&mut state, OWNER_ID); - - // OWNER_WIN belongs to OWNER_ID via window_owner mapping — - // `selection_owner_target_id` walks that mapping. - state.resources.create_window( - ClientId(OWNER_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(OWNER_WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .selections - .insert(AtomId(PRIMARY), (ResourceId(OWNER_WIN), 0)); - state.xfixes_selection_masks.insert( - (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_CLIENT_CLOSE, - ); - - // Simulate client disconnect cleanup for OWNER_ID's selections. - fanout_xfixes_selection_client_close_for_client(&mut state, ClientId(OWNER_ID)); - - assert!( - !state.selections.contains_key(&AtomId(PRIMARY)), - "client disconnect must clear selections it owns", - ); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let evt: [u8; 32] = all - .chunks_exact(32) - .find(|evt| { - evt[0] == crate::nested::XFIXES_FIRST_EVENT - && evt[1] == x11xfixes::SELECTION_NOTIFY_CLIENT_CLOSE - }) - .map(|s| { - let mut a = [0u8; 32]; - a.copy_from_slice(s); - a - }) - .unwrap_or_else(|| { - panic!( - "expected XFixesSelectionNotify(ClientClose); \ - got {} bytes: {:02x?}", - all.len(), - all, - ) - }); - assert_eq!( - u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]), - SUBSCRIBER_WIN, - "window field = subscriber", - ); - assert_eq!( - u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]), - 0, - "owner field = None on client-close", - ); - assert_eq!( - u32::from_le_bytes([evt[12], evt[13], evt[14], evt[15]]), - PRIMARY, - "selection field", - ); - } - - /// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` - /// (`dix/selection.c:194`) gates SelectionClear on the previous - /// OWNER's client identity, not on the window identity: - /// `if (pSel->client && (!pWin || (pSel->client != client)))` - /// A single client moving its own selection between two of its - /// own windows must NOT receive a spurious SelectionClear. Pre-fix - /// yserver gated on `old_window != new_window`, which over-fires. - #[test] - fn set_selection_owner_no_clear_when_same_client_moves_between_own_windows() { - use std::io::Read; - use yserver_protocol::x11::CreateWindowRequest; - const APP: u32 = 50; - const WIN_A: u32 = 0x0050_0001; - const WIN_B: u32 = 0x0050_0002; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - // Both windows owned by the same client. - for win in [WIN_A, WIN_B] { - state.resources.create_window( - ClientId(APP), - CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - // Seed prior ownership directly so we isolate the second-call - // path. Owner = WIN_A (belongs to APP). - state - .selections - .insert(AtomId(PRIMARY), (ResourceId(WIN_A), 0)); - - // Same client takes ownership at WIN_B. - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&WIN_B.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time=CurrentTime - handle_set_selection_owner(&mut state, ClientId(APP), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - // SelectionClear has event type 29 (X11 core). - assert!( - !all.chunks_exact(32).any(|e| e[0] == 29), - "no SelectionClear must be sent when the same client \ - moves selection between its own windows; got {} bytes: \ - {:02x?}", - all.len(), - all, - ); - } - - /// Audit #9 (code-review follow-up): Xorg encodes the resolved - /// server time (post-`ClientTimeToServerTime`, so CurrentTime/0 - /// becomes the actual `currentTime`) into the SelectionClear - /// event's time field at `dix/selection.c:196`. Pre-fix yserver - /// encoded the raw `time_val`, so a client sending `time=0` made - /// the SelectionClear carry `time=0` (the CurrentTime sentinel). - #[test] - fn set_selection_owner_clear_event_uses_resolved_time_when_client_sends_zero() { - use std::{io::Read, thread, time::Duration}; - use yserver_protocol::x11::CreateWindowRequest; - const PRIOR_OWNER: u32 = 51; - const NEW_OWNER: u32 = 52; - const PRIOR_WIN: u32 = 0x0051_0001; - const NEW_WIN: u32 = 0x0052_0001; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, PRIOR_OWNER); - let _ = install_client(&mut state, NEW_OWNER); - for (owner, win) in &[(PRIOR_OWNER, PRIOR_WIN), (NEW_OWNER, NEW_WIN)] { - state.resources.create_window( - ClientId(*owner), - CreateWindowRequest { - depth: 24, - window: ResourceId(*win), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - // Seed prior ownership with lastTimeChanged=0 so the stale - // check at the new call never trips. - state - .selections - .insert(AtomId(PRIMARY), (ResourceId(PRIOR_WIN), 0)); - - // Sleep so `state.timestamp_now()` is non-zero when the new - // request runs — pre-fix the SelectionClear's `time` field - // carries the raw `time_val=0` (CurrentTime sentinel), so - // pinning `>= ts_before` after a sleep distinguishes the - // resolved-time encoding from the raw-passthrough encoding. - thread::sleep(Duration::from_millis(2)); - let ts_before = state.timestamp_now(); - assert!(ts_before > 0, "sanity: sleep advanced server time"); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&NEW_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time=CurrentTime - handle_set_selection_owner(&mut state, ClientId(NEW_OWNER), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let clear: [u8; 32] = all - .chunks_exact(32) - .find(|e| e[0] == 29) - .map(|s| { - let mut a = [0u8; 32]; - a.copy_from_slice(s); - a - }) - .unwrap_or_else(|| { - panic!( - "expected SelectionClear (event type 29) on prior \ - owner's stream; got {} bytes: {:02x?}", - all.len(), - all, - ); - }); - let clear_time = u32::from_le_bytes([clear[4], clear[5], clear[6], clear[7]]); - assert!( - clear_time >= ts_before, - "SelectionClear.time must be the resolved server time \ - (>= ts_before={ts_before}), not the raw time_val=0 the \ - client sent; got {clear_time}", - ); - } - - /// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` - /// (`dix/selection.c:169-173`) returns BadWindow when `window` is - /// non-`None` and `dixLookupWindow` fails. Pre-fix yserver - /// silently stored an unknown window xid as the new owner and - /// fired XFixesSelectionNotify as if it were valid. - #[test] - fn set_selection_owner_with_unknown_window_returns_bad_window() { - use std::io::Read; - const APP: u32 = 40; - const UNKNOWN_WIN: u32 = 0x0040_dead; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&UNKNOWN_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: 22, // core SetSelectionOwner - data: 0, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!(buf[0], 0, "first byte = error class"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_WINDOW, - "expected BadWindow (3) for unknown window xid; got {}", - buf[1], - ); - // SetSelectionOwner is core opcode 22; the error reply's - // major_opcode field (byte 10) MUST reflect that, or - // clients that key on major_opcode see a malformed error. - assert_eq!( - buf[10], 22, - "BadWindow reply must carry SetSelectionOwner's major opcode (22); got {}", - buf[10], - ); - assert!( - !state.selections.contains_key(&AtomId(PRIMARY)), - "no ownership must be recorded on BadWindow; got {:?}", - state.selections.get(&AtomId(PRIMARY)), - ); - } - - /// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` - /// (`dix/selection.c:175-178`) returns BadAtom for an unknown - /// selection atom. window=None bypasses the BadWindow gate so the - /// BadAtom path is isolated. - #[test] - fn set_selection_owner_with_invalid_atom_returns_bad_atom() { - use std::io::Read; - const APP: u32 = 41; - const BOGUS_ATOM: u32 = 0xdead_beef; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&0u32.to_le_bytes()); // window=None - body.extend_from_slice(&BOGUS_ATOM.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time=CurrentTime - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: 22, // core SetSelectionOwner - data: 0, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!(buf[0], 0, "first byte = error class"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_ATOM, - "expected BadAtom (5) for an unknown selection atom; got {}", - buf[1], - ); - assert_eq!( - buf[10], 22, - "BadAtom reply must carry SetSelectionOwner's major opcode (22); got {}", - buf[10], - ); - assert!( - !state.selections.contains_key(&AtomId(BOGUS_ATOM)), - "no ownership must be recorded on BadAtom", - ); - } - - /// Audit #9 (code-review follow-up): Xorg's - /// `dixSetSelectionOwner` (`dix/selection.c:164-167`) silently - /// ignores a request whose timestamp is in the future relative - /// to the server's currentTime, returning Success without - /// changing ownership and without firing any callbacks. Pre-fix - /// yserver accepted any timestamp, which lets a misbehaving - /// client jump the ownership queue past a well-behaved one. - #[test] - fn set_selection_owner_with_future_time_is_silently_ignored() { - use std::io::Read; - use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; - const SUBSCRIBER_ID: u32 = 30; - const OWNER_ID: u32 = 31; - const SUBSCRIBER_WIN: u32 = 0x0030_0001; - const OWNER_WIN: u32 = 0x0031_0001; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER_ID); - let _ = install_client(&mut state, OWNER_ID); - state.resources.create_window( - ClientId(OWNER_ID), - CreateWindowRequest { - depth: 24, - window: ResourceId(OWNER_WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.xfixes_selection_masks.insert( - (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_SET_OWNER, - ); - - // u32::MAX is guaranteed > state.timestamp_now() during the - // test (≈49 days post-start would be needed to reach it). - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&OWNER_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&u32::MAX.to_le_bytes()); - handle_set_selection_owner(&mut state, ClientId(OWNER_ID), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - assert!( - !state.selections.contains_key(&AtomId(PRIMARY)), - "future-timestamp request must not update ownership; \ - got {:?}", - state.selections.get(&AtomId(PRIMARY)), - ); - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - assert!( - !all.chunks_exact(32) - .any(|e| e[0] == crate::nested::XFIXES_FIRST_EVENT), - "no XFixesSelectionNotify must fire on silent-ignore; \ - got {} bytes: {:02x?}", - all.len(), - all, - ); - } - - /// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` - /// (`dix/selection.c:188-193`) silently ignores a request whose - /// timestamp predates the selection's current `lastTimeChanged`, - /// preserving the existing ownership. Pre-fix yserver accepted - /// the stale request and overwrote the newer ownership. - #[test] - fn set_selection_owner_with_stale_time_is_silently_ignored() { - use std::io::Read; - use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; - const SUBSCRIBER_ID: u32 = 32; - const PRIOR_OWNER_ID: u32 = 33; - const NEW_OWNER_ID: u32 = 34; - const SUBSCRIBER_WIN: u32 = 0x0032_0001; - const PRIOR_OWNER_WIN: u32 = 0x0033_0001; - const NEW_OWNER_WIN: u32 = 0x0034_0001; - const PRIMARY: u32 = 1; - const PRIOR_LAST_TIME: u32 = 1000; - const STALE_TIME: u32 = 500; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER_ID); - let _ = install_client(&mut state, PRIOR_OWNER_ID); - let _ = install_client(&mut state, NEW_OWNER_ID); - for (owner, win) in &[ - (PRIOR_OWNER_ID, PRIOR_OWNER_WIN), - (NEW_OWNER_ID, NEW_OWNER_WIN), - ] { - state.resources.create_window( - ClientId(*owner), - CreateWindowRequest { - depth: 24, - window: ResourceId(*win), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - // Seed prior ownership with lastTimeChanged = 1000. - state.selections.insert( - AtomId(PRIMARY), - (ResourceId(PRIOR_OWNER_WIN), PRIOR_LAST_TIME), - ); - state.xfixes_selection_masks.insert( - (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_SET_OWNER, - ); - - // Attempt to take ownership at time=500 (before - // prior_last_time=1000). - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&NEW_OWNER_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&STALE_TIME.to_le_bytes()); - handle_set_selection_owner(&mut state, ClientId(NEW_OWNER_ID), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - let preserved = state.selections.get(&AtomId(PRIMARY)).copied(); - assert_eq!( - preserved, - Some((ResourceId(PRIOR_OWNER_WIN), PRIOR_LAST_TIME)), - "stale-timestamp request must NOT overwrite a newer \ - ownership; got {preserved:?}", - ); - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - assert!( - !all.chunks_exact(32) - .any(|e| e[0] == crate::nested::XFIXES_FIRST_EVENT), - "no XFixesSelectionNotify must fire on stale-ignore; \ - got {} bytes: {:02x?}", - all.len(), - all, - ); - } - - /// Audit #7 (code-review follow-up): Xorg's - /// `ProcXFixesCreateRegionFromPicture` (`xfixes/region.c:257-258`) - /// returns `RenderErrBase + BadPicture` when the picture has no - /// underlying drawable. yserver models this case as - /// `PictureKind::Sourceless` (SolidFill / gradient pictures). - /// Pre-fix the handler fell through to `picture_client_clip_rects` - /// and surfaced BadMatch — wrong error class for a sourceless - /// picture. - #[test] - fn create_region_from_picture_with_sourceless_picture_returns_bad_picture() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - const APP: u32 = 84; - const PICTURE_XID: u32 = 0x0084_0001; - const REGION_XID: u32 = 0x0084_0002; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - state.resources.create_picture( - ResourceId(PICTURE_XID), - crate::resources::PictureState { - client: ClientId(APP), - host_picture_xid: Some(crate::backend::PictureHandle::from_raw_for_test(0x42)), - host_owned_pixmap: None, - kind: crate::resources::PictureKind::Sourceless, - drawable: None, - window: None, - }, - ); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(®ION_XID.to_le_bytes()); - body.extend_from_slice(&PICTURE_XID.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION_FROM_PICTURE, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!( - buf[1], - crate::nested::RENDER_FIRST_ERROR + 1, - "expected BadPicture (Render first_error + 1 = 153) for \ - sourceless picture; got {}", - buf[1], - ); - assert!( - !state.xfixes_regions.contains_key(®ION_XID), - "no region must be inserted on BadPicture", - ); - } - - /// Audit #7 (code-review follow-up): Xorg's - /// `ProcXFixesCreateRegionFromPicture` uses `VERIFY_PICTURE` - /// (`xfixes/region.c:255`) which returns - /// `RenderErrBase + BadPicture` for an unknown picture xid, - /// not BadDrawable. yserver was emitting BadDrawable. - #[test] - fn create_region_from_picture_with_unknown_picture_returns_bad_picture() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - const APP: u32 = 85; - const UNKNOWN_PIC: u32 = 0x0085_dead; - const REGION_XID: u32 = 0x0085_0001; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(®ION_XID.to_le_bytes()); - body.extend_from_slice(&UNKNOWN_PIC.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION_FROM_PICTURE, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!( - buf[1], - crate::nested::RENDER_FIRST_ERROR + 1, - "expected BadPicture for unknown picture xid (Xorg VERIFY_PICTURE \ - returns RenderErrBase+BadPicture, NOT BadDrawable); got {}", - buf[1], - ); - } - - /// Audit #7 (code-review follow-up): Xorg's - /// `ProcXFixesCreateRegionFromWindow` (`xfixes/region.c:158-163`) - /// returns BadWindow when `dixLookupResourceByType` on the - /// window xid fails, with `client->error_value = stuff->window`. - /// Pre-fix yserver passed any xid (including 0) through to - /// `shape_rects_for` and silently inserted a default/empty - /// region. - #[test] - fn create_region_from_window_with_unknown_window_returns_bad_window() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - const APP: u32 = 82; - const REGION_XID: u32 = 0x0082_0001; - const UNKNOWN_WIN: u32 = 0x0082_ffff; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - // body: region(4) + window(4) + kind(1) + pad(3) - let mut body = Vec::with_capacity(12); - body.extend_from_slice(®ION_XID.to_le_bytes()); - body.extend_from_slice(&UNKNOWN_WIN.to_le_bytes()); - body.push(0); // kind = Bounding (valid) - body.extend_from_slice(&[0u8; 3]); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION_FROM_WINDOW, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_WINDOW, - "expected BadWindow (3) for unknown window xid; got {}", - buf[1], - ); - assert_eq!( - u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]), - UNKNOWN_WIN, - "error.bad_value must carry the offending window xid", - ); - assert!( - !state.xfixes_regions.contains_key(®ION_XID), - "no region must be inserted on BadWindow", - ); - } - - /// Audit #7 (code-review follow-up): Xorg's - /// `ProcXFixesCreateRegionFromWindow` (`xfixes/region.c:164-181`) - /// accepts only `WindowRegionBounding` (0) and `WindowRegionClip` - /// (1); any other `kind` returns BadValue with - /// `client->error_value = stuff->kind`. The SHAPE-shaped value 2 - /// (Input) is rejected per X11 XFIXES spec. - #[test] - fn create_region_from_window_with_invalid_kind_returns_bad_value() { - use std::io::Read; - use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; - const APP: u32 = 83; - const REGION_XID: u32 = 0x0083_0001; - const WIN_XID: u32 = 0x0083_0002; - const INVALID_KIND: u8 = 2; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - // Window must exist so the BadWindow gate doesn't fire - // first — we want to isolate the BadValue(kind) path. - state.resources.create_window( - ClientId(APP), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(®ION_XID.to_le_bytes()); - body.extend_from_slice(&WIN_XID.to_le_bytes()); - body.push(INVALID_KIND); - body.extend_from_slice(&[0u8; 3]); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION_FROM_WINDOW, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_VALUE, - "expected BadValue (2) for kind={INVALID_KIND}; got {}", - buf[1], - ); - assert_eq!( - u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]), - u32::from(INVALID_KIND), - "error.bad_value must carry the offending kind", - ); - assert!( - !state.xfixes_regions.contains_key(®ION_XID), - "no region must be inserted on BadValue", - ); - } - - /// Audit #7 (code-review follow-up): every XFIXES - /// `CreateRegion*` opcode begins with - /// `LEGAL_NEW_RESOURCE(stuff->region, client)` in Xorg - /// (`xfixes/region.c:78,114,157,213,…`). Reusing an existing - /// region XID must surface BadIDChoice. Pre-fix yserver silently - /// overwrote `state.xfixes_regions[region]` via `.insert(…)`, - /// matching the colormap/window/etc. bug class that the - /// codebase already gates elsewhere. - #[test] - fn create_region_with_in_use_xid_returns_bad_id_choice() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - const APP: u32 = 80; - const REGION_XID: u32 = 0x0080_0001; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - // Pre-populate the region xid so the new request is a - // duplicate. - state.xfixes_regions.insert( - REGION_XID, - crate::server::XFixesRegion { - owner: ClientId(APP), - rects: Vec::new(), - }, - ); - - // CreateRegion body: region(4) + N×8 (rects). Zero rects = - // empty region; the duplicate-xid check must fire BEFORE - // any rect parsing. - let mut body = Vec::with_capacity(4); - body.extend_from_slice(®ION_XID.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!(buf[0], 0, "first byte = error class"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_ID_CHOICE, - "expected BadIDChoice (14) when reusing an existing region xid; got {}", - buf[1], - ); - // The duplicate must not be overwritten — the pre-existing - // entry's marker (empty rects placeholder) survives intact. - let r = state - .xfixes_regions - .get(®ION_XID) - .expect("pre-existing region must remain"); - assert!( - r.rects.is_empty(), - "pre-existing region must not be overwritten on BadIDChoice; \ - got rects={:?}", - r.rects, - ); - } - - /// Audit #7 (code-review follow-up): the duplicate-xid gate - /// also applies to `CREATE_REGION_FROM_GC` (and all other - /// CreateRegion variants). The GC path is the audit-#7 patch - /// site — confirm the new gate is wired in front of the raw - /// clip-copy too. - #[test] - fn create_region_from_gc_with_in_use_xid_returns_bad_id_choice() { - use std::io::Read; - use yserver_protocol::x11::{ - ClipRectangles, CreateGcRequest, CreateWindowRequest, SetClipRectanglesRequest, - xfixes as x11xfixes, - }; - const APP: u32 = 81; - const WIN_XID: u32 = 0x0081_0001; - const GC_XID: u32 = 0x0081_0002; - const REGION_XID: u32 = 0x0081_0003; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - state.resources.create_window( - ClientId(APP), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_gc( - ClientId(APP), - CreateGcRequest { - gc: ResourceId(GC_XID), - drawable: ResourceId(WIN_XID), - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - // Single-rect clip so the GC's `clientClip` exists. - let mut rect_bytes = Vec::with_capacity(8); - rect_bytes.extend_from_slice(&0i16.to_le_bytes()); - rect_bytes.extend_from_slice(&0i16.to_le_bytes()); - rect_bytes.extend_from_slice(&5u16.to_le_bytes()); - rect_bytes.extend_from_slice(&5u16.to_le_bytes()); - state.resources.set_clip_rectangles( - yserver_protocol::x11::ClientId(1), - SetClipRectanglesRequest { - gc: ResourceId(GC_XID), - clip: ClipRectangles { - ordering: 0, - x_origin: 0, - y_origin: 0, - rectangles: rect_bytes, - }, - }, - ); - - // Pre-occupy REGION_XID. - state.xfixes_regions.insert( - REGION_XID, - crate::server::XFixesRegion { - owner: ClientId(APP), - rects: Vec::new(), - }, - ); - - let mut body = Vec::with_capacity(8); - body.extend_from_slice(®ION_XID.to_le_bytes()); - body.extend_from_slice(&GC_XID.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION_FROM_GC, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_ID_CHOICE, - "CreateRegionFromGC must gate on LEGAL_NEW_RESOURCE before \ - copying the GC's clip; got error code {}", - buf[1], - ); - } - - /// Audit #7 (`docs/protocol-audit-2026-05-19.md`): - /// `CreateRegionFromGC` must return the GC's clip rectangles in - /// their RAW clip-coordinate space — Xorg's - /// `ProcXFixesCreateRegionFromGC` (`xfixes/region.c:219-226`) - /// just `XFixesRegionCopy(pGC->clientClip)` with NO origin - /// translation applied. yserver was offsetting by - /// `(clip.x_origin, clip.y_origin)` at insert time. When a WM - /// later re-installs the resulting region as a GC's clip via - /// `SetGcClipRegion(gc, region, x_origin, y_origin)`, the - /// GC-side origin is applied a SECOND time → double-translation - /// → wrong area shadowed/repainted. - #[test] - fn create_region_from_gc_copies_clip_rects_without_origin_translation() { - use yserver_protocol::x11::{ - ClipRectangles, CreateGcRequest, CreateWindowRequest, SetClipRectanglesRequest, - xfixes as x11xfixes, - }; - const APP: u32 = 70; - const WIN_XID: u32 = 0x0070_0001; - const GC_XID: u32 = 0x0070_0002; - const REGION_XID: u32 = 0x0070_0003; - const X_ORIGIN: i16 = 100; - const Y_ORIGIN: i16 = 200; - const RECT_X: i16 = 10; - const RECT_Y: i16 = 20; - const RECT_W: u16 = 5; - const RECT_H: u16 = 5; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - // Drawable to attach the GC to. - state.resources.create_window( - ClientId(APP), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_gc( - ClientId(APP), - CreateGcRequest { - gc: ResourceId(GC_XID), - drawable: ResourceId(WIN_XID), - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - // Set the GC's clip: single rect at (10, 20, 5×5) in - // clip-coordinate space, with origin (100, 200). The wire - // format is (x i16, y i16, w u16, h u16) per rect. - let mut rect_bytes = Vec::with_capacity(8); - rect_bytes.extend_from_slice(&RECT_X.to_le_bytes()); - rect_bytes.extend_from_slice(&RECT_Y.to_le_bytes()); - rect_bytes.extend_from_slice(&RECT_W.to_le_bytes()); - rect_bytes.extend_from_slice(&RECT_H.to_le_bytes()); - state.resources.set_clip_rectangles( - yserver_protocol::x11::ClientId(1), - SetClipRectanglesRequest { - gc: ResourceId(GC_XID), - clip: ClipRectangles { - ordering: 0, - x_origin: X_ORIGIN, - y_origin: Y_ORIGIN, - rectangles: rect_bytes, - }, - }, - ); - - // CREATE_REGION_FROM_GC body: region(4) + gc(4). - let mut body = Vec::with_capacity(8); - body.extend_from_slice(®ION_XID.to_le_bytes()); - body.extend_from_slice(&GC_XID.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(APP, 5); - process_request( - &mut state, - &mut backend, - ClientId(APP), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::CREATE_REGION_FROM_GC, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - let region = state - .xfixes_regions - .get(®ION_XID) - .expect("CreateRegionFromGC inserted region"); - assert_eq!( - region.rects.len(), - 1, - "expected exactly one rect from the GC's single-rect clip; got {:?}", - region.rects, - ); - let r = ®ion.rects[0]; - assert_eq!( - (r.x, r.y, r.width, r.height), - (RECT_X, RECT_Y, RECT_W, RECT_H), - "rect must be in raw clip-coord space (NOT translated by \ - clip_origin=({X_ORIGIN},{Y_ORIGIN})); the symptom of \ - over-translation is x={}, y={} (= raw + clip_origin).", - r.x, - r.y, - ); - } - - /// Audit #9 (code-review follow-up): Xorg's - /// `ProcXFixesSelectSelectionInput` (`xfixes/select.c:189-192`) - /// runs `dixLookupWindow` first and propagates its return code - /// (`BadWindow` for an unknown xid). Before the fix yserver - /// silently stored the subscription, accepting illegal records. - #[test] - fn select_selection_input_with_invalid_window_returns_bad_window() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - - const CLIENT: u32 = 21; - const UNKNOWN_WIN: u32 = 0x00ff_eeee; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&UNKNOWN_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&x11xfixes::SELECTION_MASK_SET_OWNER.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(CLIENT, 5); - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::SELECT_SELECTION_INPUT, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!(buf[0], 0, "first byte = error class"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_WINDOW, - "expected BadWindow (3) for unknown window xid; got {}", - buf[1], - ); - assert!( - state.xfixes_selection_masks.is_empty(), - "the subscription must NOT be recorded on BadWindow; got {:?}", - state.xfixes_selection_masks, - ); - } - - /// Audit #9 (code-review follow-up): Xorg's - /// `ProcXFixesSelectSelectionInput` (`xfixes/select.c:193-196`) - /// returns BadValue when `eventMask & ~SelectionAllEvents` is - /// non-zero. Before the fix yserver stored arbitrary mask bits. - #[test] - fn select_selection_input_with_mask_outside_known_bits_returns_bad_value() { - use std::io::Read; - use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; - - const CLIENT: u32 = 22; - const WIN: u32 = 0x0150_0001; - const PRIMARY: u32 = 1; - const ILLEGAL_MASK: u32 = 1 << 8; // outside SelectionAllEvents - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT); - let mut backend = RecordingBackend::new(); - // Window must exist for the window-validation step to pass, - // so we cleanly isolate the mask-validation path. - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&ILLEGAL_MASK.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - // The client negotiated XFIXES (Xorg gates requests on QueryVersion). - state.xfixes_client_major.insert(CLIENT, 5); - process_request( - &mut state, - &mut backend, - ClientId(CLIENT), - SequenceNumber(1), - RequestHeader { - opcode: XFIXES_MAJOR_OPCODE, - data: x11xfixes::SELECT_SELECTION_INPUT, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).expect("error reply delivered"); - assert_eq!(buf[0], 0, "first byte = error class"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_VALUE, - "expected BadValue (2) for mask with bits outside \ - SelectionAllEvents (0b111); got {}", - buf[1], - ); - assert!( - state.xfixes_selection_masks.is_empty(), - "the subscription must NOT be recorded on BadValue; got {:?}", - state.xfixes_selection_masks, - ); - } - - /// Audit #9 (code-review follow-up): the destroy/close path - /// must emit the notify BEFORE clearing the selection (matching - /// Xorg's `DeleteWindowFromAnySelections` order at - /// `dix/selection.c:131-138`) so the wire payload carries the - /// stored `selection_timestamp` — `selection->lastTimeChanged` - /// in Xorg's `xfixes/select.c:89`. yserver tracks - /// `lastTimeChanged` as the second element of the - /// `state.selections` tuple, stamped by SetSelectionOwner with - /// the request's `time` arg. - #[test] - fn destroy_window_owning_selection_carries_prior_last_time_changed_in_selection_timestamp() { - use std::io::Read; - use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; - const SUBSCRIBER_ID: u32 = 15; - const OWNER_ID: u32 = 16; - const SUBSCRIBER_WIN: u32 = 0x00f0_0001; - const OWNER_WIN: u32 = 0x0100_0001; - const PRIMARY: u32 = 1; - const SET_OWNER_TIME: u32 = 0x0a0b_0c0d; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER_ID); - let _ = install_client(&mut state, OWNER_ID); - - state.resources.create_window( - ClientId(OWNER_ID), - CreateWindowRequest { - depth: 24, - window: ResourceId(OWNER_WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.xfixes_selection_masks.insert( - (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_WINDOW_DESTROY, - ); - - // Seed ownership directly with a known `lastTimeChanged`. - // This decouples the destroy-path assertion from - // `handle_set_selection_owner`'s time-resolution logic - // (future/stale checks, ClientTime → ServerTime conversion); - // we only care here that whatever value is in the second - // tuple slot flows through to the notify wire payload. - state - .selections - .insert(AtomId(PRIMARY), (ResourceId(OWNER_WIN), SET_OWNER_TIME)); - - let mut destroy_body = Vec::with_capacity(4); - destroy_body.extend_from_slice(&OWNER_WIN.to_le_bytes()); - let mut backend = RecordingBackend::new(); - handle_destroy_window( - &mut state, - &mut backend, - None, - ClientId(OWNER_ID), - SequenceNumber(2), - &destroy_body, - ) - .expect("handle_destroy_window"); - peer.set_nonblocking(true).unwrap(); - - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let evt: [u8; 32] = all - .chunks_exact(32) - .find(|e| { - e[0] == crate::nested::XFIXES_FIRST_EVENT - && e[1] == x11xfixes::SELECTION_NOTIFY_WINDOW_DESTROY - }) - .map(|s| { - let mut a = [0u8; 32]; - a.copy_from_slice(s); - a - }) - .expect("WindowDestroy notify in stream"); - - assert_eq!( - u32::from_le_bytes([evt[20], evt[21], evt[22], evt[23]]), - SET_OWNER_TIME, - "selection_timestamp must carry the prior SetSelectionOwner \ - time arg (Xorg `selection->lastTimeChanged`); pre-fix the \ - payload was zeroed", - ); - // The `timestamp` field is `state.timestamp_now()` (Xorg's - // `currentTime.milliseconds` equivalent); not asserted here - // because in a sub-millisecond test it's legitimately 0 — which - // matches Xorg behavior (`UpdateCurrentTimeIf` snapshots - // `GetTimeInMillis()` with no floor). The - // `selection_timestamp` assertion above is the load-bearing - // spec-compliance check. - } - - /// Audit #9 (code-review follow-up): Xorg's - /// `XFixesSelectionCallback` (`xfixes/select.c:79-91`) walks - /// every matching subscription record and emits one event per - /// `(client, window, selection)` tuple. A single client that - /// has two windows subscribed to the same selection must - /// receive TWO events whose `window` fields are the two - /// distinct subscriber windows — not one collapsed event nor - /// two events with the same window field. - /// - /// `fanout_event_to_clients` deduplicates by ClientId *within - /// one call* via a freshly-allocated `seen` set, so calling it - /// once per subscription with a single-element slice is the - /// correct shape; the closure captures the per-iteration - /// subscriber window. This test pins that invariant against - /// future refactors. - #[test] - fn set_selection_owner_emits_one_event_per_subscription_when_client_has_two_windows() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - const SUBSCRIBER: u32 = 13; - const APP: u32 = 14; - const WIN_A: u32 = 0x00d0_0001; - const WIN_B: u32 = 0x00d0_0002; - const OWNER_WIN: u32 = 0x00e0_0001; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER); - let _ = install_client(&mut state, APP); - - // OWNER_WIN must exist for SetSelectionOwner's window - // validation gate. - state.resources.create_window( - ClientId(APP), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(OWNER_WIN), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - // Same client, two subscription records on the same selection. - state.xfixes_selection_masks.insert( - (SUBSCRIBER, ResourceId(WIN_A), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_SET_OWNER, - ); - state.xfixes_selection_masks.insert( - (SUBSCRIBER, ResourceId(WIN_B), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_SET_OWNER, - ); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&OWNER_WIN.to_le_bytes()); - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - handle_set_selection_owner(&mut state, ClientId(APP), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - let mut subscriber_windows: Vec = all - .chunks_exact(32) - .filter(|e| { - e[0] == crate::nested::XFIXES_FIRST_EVENT - && e[1] == x11xfixes::SELECTION_NOTIFY_SET_OWNER - }) - .map(|e| u32::from_le_bytes([e[4], e[5], e[6], e[7]])) - .collect(); - subscriber_windows.sort_unstable(); - assert_eq!( - subscriber_windows, - vec![WIN_A, WIN_B], - "must get one event per (client, window, selection) subscription \ - record with distinct `window` fields; got {} bytes total: {:02x?}", - all.len(), - all, - ); - } - - /// Audit #9: subscribing with mask=0 then re-subscribing with the - /// set-owner bit, the FIRST owner-change must still emit (verifies - /// the mask-bit gate, not the presence of the subscription key). - #[test] - fn set_selection_owner_skips_subscribers_whose_mask_excludes_set_owner() { - use std::io::Read; - use yserver_protocol::x11::xfixes as x11xfixes; - - const SUBSCRIBER: u32 = 5; - const APP: u32 = 6; - const SUBSCRIBER_WIN: u32 = 0x0050_0001; - const PRIMARY: u32 = 1; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, SUBSCRIBER); - let _ = install_client(&mut state, APP); - - // Subscribe with a mask that does NOT include SET_OWNER — - // only WINDOW_DESTROY. SetSelectionOwner must NOT fire for - // this subscription. - state.xfixes_selection_masks.insert( - (SUBSCRIBER, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), - x11xfixes::SELECTION_MASK_WINDOW_DESTROY, - ); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&0x0090_0001u32.to_le_bytes()); // owner window - body.extend_from_slice(&PRIMARY.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time - handle_set_selection_owner(&mut state, ClientId(APP), SequenceNumber(1), &body) - .expect("handle_set_selection_owner"); - - peer.set_nonblocking(true).unwrap(); - let mut all = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - match peer.read(&mut chunk) { - Ok(0) => break, - Ok(n) => all.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - } - assert!( - !all.chunks_exact(32) - .any(|evt| evt[0] == crate::nested::XFIXES_FIRST_EVENT), - "no XFixesSelectionNotify expected when subscriber's mask excludes \ - SET_OWNER; got {} bytes: {:02x?}", - all.len(), - all, - ); - } - - /// X11 §CopyArea source-availability split: requested source - /// rect vs source drawable bounds → (clamped copy, missing - /// dst-coord rects for GraphicsExpose). - #[test] - fn copy_area_source_split_right_half_missing() { - let mut state = ServerState::new(); - // 100×100 pixmap as the source. - state.resources.create_pixmap( - ClientId(1), - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(0x700), - drawable: crate::resources::ROOT_WINDOW, - width: 100, - height: 100, - }, - ); - // Copy 100 wide from x=50 → right 50 missing. - let (avail, missing) = - copy_area_source_split(&state, ResourceId(0x700), 50, 0, 0, 0, 100, 100); - assert_eq!(avail, Some((50, 0, 0, 0, 50, 100)), "clamped copy"); - assert_eq!( - missing, - vec![(50, 0, 50, 100)], - "missing right half in DST coords (xts XCopyArea-4 expects x=50 w=50)" - ); - // Fully in-bounds → NoExposure (empty missing list). - let (avail, missing) = - copy_area_source_split(&state, ResourceId(0x700), 0, 0, 10, 10, 80, 80); - assert_eq!(avail, Some((0, 0, 10, 10, 80, 80))); - assert!(missing.is_empty(), "fully available → NoExposure"); - // Fully out of bounds → no copy, whole rect exposed. - let (avail, missing) = - copy_area_source_split(&state, ResourceId(0x700), 200, 0, 5, 5, 30, 30); - assert!(avail.is_none()); - assert_eq!(missing, vec![(5, 5, 30, 30)]); - } - - /// Stage 4d follow-up (codex review 2026-05-18): when ClipByChildren - /// (or any other clipping) fully covers the destination so no pixels - /// are actually copied, the X11 spec still requires the server to - /// emit a GraphicsExpose / NoExposure event for clients with - /// `graphics-exposures=True`. Pre-fix the early-return-on-empty - /// path silently swallowed this event; clients waiting on it - /// (xterm, gtk2 backing-store users) would hang. - #[test] - fn copy_area_fully_clipped_still_emits_graphics_expose_event() { - use std::io::Read; - use yserver_protocol::x11::{CreateGcRequest, CreateWindowRequest}; - - const FRAME_XID: u32 = 0x0010_0001; - const FRAME_HOST: u32 = 0x0040_0001; - const FRAME_BACKING_HOST: u32 = 0x0050_0001; - const CHILD_XID: u32 = 0x0010_0002; - const CHILD_HOST: u32 = 0x0040_0002; - const SRC_PIXMAP_XID: u32 = 0x0010_0010; - const SRC_PIXMAP_HOST: u32 = 0x0040_0010; - const GC_XID: u32 = 0x0010_0020; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // Make the peer-read non-blocking so an absent event doesn't - // hang the test. - peer.set_nonblocking(true).expect("nonblocking"); - let mut backend = RecordingBackend::new(); - - // Frame 100×100 entirely covered by child window 100×100 at - // (0, 0). Any CopyArea(dst=frame, 0,0 100x100) gets fully - // clipped by the child. - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(FRAME_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(FRAME_XID)) - .expect("frame"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(FRAME_HOST)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(FRAME_BACKING_HOST), - width: 100, - height: 100, - depth: 24, - }); - w.map_state = crate::resources::MapState::Viewable; - } - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_XID), - parent: ResourceId(FRAME_XID), - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(CHILD_XID)) - .expect("child"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(CHILD_HOST)); - w.map_state = crate::resources::MapState::Viewable; - } - state.resources.create_pixmap( - ClientId(1), - yserver_protocol::x11::CreatePixmapRequest { - pixmap: ResourceId(SRC_PIXMAP_XID), - drawable: ROOT_WINDOW, - width: 100, - height: 100, - depth: 24, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(SRC_PIXMAP_XID), - crate::backend::PixmapHandle::from_raw_for_test(SRC_PIXMAP_HOST), - ); - // GC with graphics_exposures = True (the spec default; without - // explicit override the GC inherits that default). - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(GC_XID), - drawable: ResourceId(FRAME_XID), - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: Some(true), - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - let mut body = Vec::with_capacity(24); - body.extend_from_slice(&SRC_PIXMAP_XID.to_le_bytes()); - body.extend_from_slice(&FRAME_XID.to_le_bytes()); - body.extend_from_slice(&GC_XID.to_le_bytes()); - body.extend_from_slice(&0_i16.to_le_bytes()); - body.extend_from_slice(&0_i16.to_le_bytes()); - body.extend_from_slice(&0_i16.to_le_bytes()); - body.extend_from_slice(&0_i16.to_le_bytes()); - body.extend_from_slice(&100_u16.to_le_bytes()); - body.extend_from_slice(&100_u16.to_le_bytes()); - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 62, - data: 0, - length_units: 7, - }, - &body, - None, - ) - .expect("dispatch CopyArea"); - - // No backend.copy_area should have fired (fully clipped). - let copy_calls = backend - .calls() - .into_iter() - .filter(|c| matches!(c, crate::backend::recording::RecordedCall::CopyArea { .. })) - .count(); - assert_eq!( - copy_calls, 0, - "fully-clipped CopyArea must NOT call backend.copy_area", - ); - - // The graphics-exposures contract still fires for a fully - // dst-clipped copy — but as NoExposure: the SOURCE was fully - // available (GraphicsExpose only describes missing source - // regions; dst-side child clipping doesn't expose anything). - let mut buf = [0u8; 64]; - let n = peer.read(&mut buf).unwrap_or(0); - assert!( - n >= 32, - "expected a 32-byte NoExposure event even for a \ - fully-clipped CopyArea (codex review 2026-05-18); got \ - {n} bytes", - ); - assert_eq!( - buf[0], 14, - "first byte must be NoExposure (event type 14) — source \ - fully available", - ); - } - - // ---- Unviewable CopyArea/CopyPlane sources (Xorg micopy.c / miexpose.c) ---- - - const UV_FRAME: u32 = 0x0010_0101; - const UV_CHILD: u32 = 0x0010_0102; - const UV_LONE: u32 = 0x0010_0103; - const UV_SHOWN: u32 = 0x0010_0104; - const UV_PIXMAP: u32 = 0x0010_0110; - const UV_DST_PIXMAP: u32 = 0x0010_0111; - const UV_GC: u32 = 0x0010_0120; - const UV_GC_NOEXP: u32 = 0x0010_0121; - - fn uv_gc_request(gc: u32, graphics_exposures: bool) -> yserver_protocol::x11::CreateGcRequest { - yserver_protocol::x11::CreateGcRequest { - gc: ResourceId(gc), - drawable: ROOT_WINDOW, - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: Some(graphics_exposures), - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - } - } - - fn uv_window( - state: &mut ServerState, - xid: u32, - parent: ResourceId, - map_state: crate::resources::MapState, - ) { - state.resources.create_window( - ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let w = state.resources.window_mut(ResourceId(xid)).expect("window"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( - xid | 0x0040_0000, - )); - w.map_state = map_state; - } - - fn uv_pixmap(state: &mut ServerState, xid: u32) { - state.resources.create_pixmap( - ClientId(1), - yserver_protocol::x11::CreatePixmapRequest { - pixmap: ResourceId(xid), - drawable: ROOT_WINDOW, - width: 100, - height: 100, - depth: 24, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(xid), - crate::backend::PixmapHandle::from_raw_for_test(xid | 0x0040_0000), - ); - } - - /// Unmapped frame with a mapped (so Unviewable) child, a lone unmapped - /// window, a viewable window, two pixmaps and GCs with exposures on/off. - fn uv_fixture() -> (ServerState, UnixStream) { - use crate::resources::MapState; - let mut state = ServerState::new(); - let peer = install_client(&mut state, 1); - uv_window(&mut state, UV_FRAME, ROOT_WINDOW, MapState::Unmapped); - uv_window( - &mut state, - UV_CHILD, - ResourceId(UV_FRAME), - MapState::Unviewable, - ); - uv_window(&mut state, UV_LONE, ROOT_WINDOW, MapState::Unmapped); - uv_window(&mut state, UV_SHOWN, ROOT_WINDOW, MapState::Viewable); - uv_pixmap(&mut state, UV_PIXMAP); - uv_pixmap(&mut state, UV_DST_PIXMAP); - state - .resources - .create_gc(ClientId(1), uv_gc_request(UV_GC, true)); - state - .resources - .create_gc(ClientId(1), uv_gc_request(UV_GC_NOEXP, false)); - (state, peer) - } - - #[allow(clippy::too_many_arguments)] - fn uv_copy( - state: &mut ServerState, - backend: &mut RecordingBackend, - opcode: u8, - src: u32, - dst: u32, - gc: u32, - src_xy: (i16, i16), - dst_xy: (i16, i16), - size: (u16, u16), - ) { - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&src.to_le_bytes()); - body.extend_from_slice(&dst.to_le_bytes()); - body.extend_from_slice(&gc.to_le_bytes()); - body.extend_from_slice(&src_xy.0.to_le_bytes()); - body.extend_from_slice(&src_xy.1.to_le_bytes()); - body.extend_from_slice(&dst_xy.0.to_le_bytes()); - body.extend_from_slice(&dst_xy.1.to_le_bytes()); - body.extend_from_slice(&size.0.to_le_bytes()); - body.extend_from_slice(&size.1.to_le_bytes()); - if opcode == 63 { - body.extend_from_slice(&1u32.to_le_bytes()); - } - process_request( - state, - backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode, - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .expect("dispatch copy"); - } - - fn uv_copy_calls(backend: &RecordingBackend) -> usize { - use crate::backend::recording::RecordedCall; - backend - .calls() - .into_iter() - .filter(|c| { - matches!( - c, - RecordedCall::CopyArea { .. } | RecordedCall::CopyPlane { .. } - ) - }) - .count() - } - - /// Decoded (type, drawable, x, y, w, h, count, major) per 32-byte event. - type UvEvent = (u8, u32, u16, u16, u16, u16, u16, u8); - - fn uv_events(bytes: &[u8]) -> Vec { - bytes - .chunks_exact(32) - .map(|e| { - let u16_at = |i: usize| u16::from_le_bytes([e[i], e[i + 1]]); - let drawable = u32::from_le_bytes([e[4], e[5], e[6], e[7]]); - if e[0] == 13 { - ( - 13, - drawable, - u16_at(8), - u16_at(10), - u16_at(12), - u16_at(14), - u16_at(18), - e[20], - ) - } else { - (e[0], drawable, 0, 0, 0, 0, 0, e[10]) - } - }) - .collect() - } - - /// Xorg: an unrealized source window has an empty clipList - /// (mivaltree.c:691-696, miwindow.c:741-744, window.c:892), so miDoCopy - /// copies nothing and miHandleExposures exposes the whole rect. - #[test] - fn copy_area_from_unviewable_window_exposes_whole_dest_rect() { - for (opcode, src) in [ - (62u8, UV_LONE), - (62, UV_CHILD), - (63, UV_LONE), - (63, UV_CHILD), - ] { - let (mut state, mut peer) = uv_fixture(); - let mut backend = RecordingBackend::new(); - uv_copy( - &mut state, - &mut backend, - opcode, - src, - UV_DST_PIXMAP, - UV_GC, - (10, 20), - (5, 7), - (30, 40), - ); - assert_eq!( - uv_copy_calls(&backend), - 0, - "op {opcode} src 0x{src:x}: nothing copied" - ); - assert_eq!( - uv_events(&read_all_available(&mut peer)), - vec![(13, UV_DST_PIXMAP, 5, 7, 30, 40, 0, opcode)], - "op {opcode} src 0x{src:x}: one GraphicsExpose for the dest rect, no NoExpose", - ); - } - } - - #[test] - fn copy_area_from_unviewable_window_without_exposures_sends_nothing() { - for opcode in [62u8, 63] { - let (mut state, mut peer) = uv_fixture(); - let mut backend = RecordingBackend::new(); - uv_copy( - &mut state, - &mut backend, - opcode, - UV_CHILD, - UV_DST_PIXMAP, - UV_GC_NOEXP, - (0, 0), - (0, 0), - (30, 40), - ); - assert_eq!(uv_copy_calls(&backend), 0); - assert!( - read_all_available(&mut peer).is_empty(), - "op {opcode}: no events" - ); - } - } - - /// A pixmap or viewable window source is unchanged: copied, NoExpose. - #[test] - fn copy_area_from_pixmap_or_viewable_window_still_copies_with_no_expose() { - for opcode in [62u8, 63] { - for src in [UV_PIXMAP, UV_SHOWN] { - let (mut state, mut peer) = uv_fixture(); - let mut backend = RecordingBackend::new(); - uv_copy( - &mut state, - &mut backend, - opcode, - src, - UV_DST_PIXMAP, - UV_GC, - (10, 20), - (5, 7), - (30, 40), - ); - assert_eq!(uv_copy_calls(&backend), 1, "op {opcode} src 0x{src:x}"); - assert_eq!( - uv_events(&read_all_available(&mut peer)), - vec![(14, UV_DST_PIXMAP, 0, 0, 0, 0, 0, opcode)], - "op {opcode} src 0x{src:x}: NoExpose", - ); - } - } - } - - /// Xorg miDoCopy returns NULL for an unrealized destination before any - /// copy or exposure (micopy.c:157-160), so the requestor gets NoExpose - /// even when the source is unavailable. - #[test] - fn copy_area_to_unviewable_window_copies_nothing_and_sends_no_expose() { - for opcode in [62u8, 63] { - for (src, src_xy) in [(UV_PIXMAP, (0, 0)), (UV_PIXMAP, (90, 0)), (UV_LONE, (0, 0))] { - let (mut state, mut peer) = uv_fixture(); - let mut backend = RecordingBackend::new(); - uv_copy( - &mut state, - &mut backend, - opcode, - src, - UV_CHILD, - UV_GC, - src_xy, - (0, 0), - (30, 40), - ); - assert_eq!(uv_copy_calls(&backend), 0, "op {opcode} src 0x{src:x}"); - assert!( - !backend.calls().iter().any(|c| matches!( - c, - crate::backend::recording::RecordedCall::PaintWindowBackgroundRect { .. } - )), - "op {opcode} src 0x{src:x}: no background paint", - ); - assert_eq!( - uv_events(&read_all_available(&mut peer)), - vec![(14, UV_CHILD, 0, 0, 0, 0, 0, opcode)], - "op {opcode} src 0x{src:x} at {src_xy:?}: NoExpose", - ); - } - } - } - - /// Drawing to an unmapped window records no damage (Xorg damage.c:197). - #[test] - fn poly_fill_on_unmapped_window_records_no_damage() { - use crate::server::DamageObject; - const DAMAGE_XID: u32 = 0x0010_0130; - for (window, expect_damage) in [(UV_LONE, false), (UV_CHILD, false), (UV_SHOWN, true)] { - let (mut state, _peer) = uv_fixture(); - let mut backend = RecordingBackend::new(); - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: ResourceId(window), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - let body = poly_fill_rectangle_body(window, UV_GC); - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 70, - data: 0, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .expect("PolyFillRectangle"); - let dmg = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object"); - assert_eq!( - !dmg.rects.is_empty() || dmg.pending_notify_fired, - expect_damage, - "window 0x{window:x}: rects={:?} fired={}", - dmg.rects, - dmg.pending_notify_fired, - ); - } - } - - /// Stage 4d Manual-redirect CopyArea ClipByChildren fix. - /// - /// Scenario (matches marco's failing #6886 / #7450 CopyArea on - /// the MATE Control Center frame): - /// - Frame window 997×652 at root, mapped, with a redirected - /// backing pixmap allocated. - /// - CC client window 975×600 reparented under the frame at - /// (11, 41), mapped. - /// - X11 CopyArea(src=decoration_pixmap, dst=frame_window, - /// gc=default) 997×652. - /// - /// Pre-fix: dispatch resolves `dst` to the backing pixmap and - /// hands the backend a single full-extent copy, which clobbers - /// the area where CC's content lives in the backing. - /// - /// Spec-correct (Xorg `mi/midispcur.c` + the X11 GC - /// `subwindow-mode` default): under `ClipByChildren`, subtract - /// every mapped child's geometry before copying. Result is the - /// four border strips (top/bottom/left/right of CC). - #[test] - fn copy_area_into_window_with_mapped_child_excludes_child_area() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::{CreateGcRequest, CreateWindowRequest}; - - const FRAME_XID: u32 = 0x0010_0001; - const FRAME_HOST: u32 = 0x0040_0001; - const FRAME_BACKING_HOST: u32 = 0x0050_0001; - const CHILD_XID: u32 = 0x0010_0002; - const CHILD_HOST: u32 = 0x0040_0002; - const SRC_PIXMAP_XID: u32 = 0x0010_0010; - const SRC_PIXMAP_HOST: u32 = 0x0040_0010; - const GC_XID: u32 = 0x0010_0020; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Frame: top-level under root, viewable, redirected (backing - // present). Mirrors the post-Reparent + post-Map + post- - // activate_redirect_backing state. - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(FRAME_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 997, - height: 652, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(FRAME_XID)) - .expect("frame"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(FRAME_HOST)); - w.redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(FRAME_BACKING_HOST), - width: 997, - height: 652, - depth: 24, - }); - w.map_state = crate::resources::MapState::Viewable; - } - // CC: child of frame, viewable, at (11, 41) sized 975×600. - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD_XID), - parent: ResourceId(FRAME_XID), - x: 11, - y: 41, - width: 975, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let w = state - .resources - .window_mut(ResourceId(CHILD_XID)) - .expect("child"); - w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(CHILD_HOST)); - w.map_state = crate::resources::MapState::Viewable; - } - // Source pixmap (depth-24, same depth as frame). - state.resources.create_pixmap( - ClientId(1), - yserver_protocol::x11::CreatePixmapRequest { - pixmap: ResourceId(SRC_PIXMAP_XID), - drawable: ROOT_WINDOW, - width: 997, - height: 652, - depth: 24, - }, - ); - let _ = state.resources.set_pixmap_host_xid( - ResourceId(SRC_PIXMAP_XID), - crate::backend::PixmapHandle::from_raw_for_test(SRC_PIXMAP_HOST), - ); - // GC for client 1. Every value-mask field is None → defaults - // apply, including subwindow-mode = ClipByChildren. - state.resources.create_gc( - ClientId(1), - CreateGcRequest { - gc: ResourceId(GC_XID), - drawable: ResourceId(FRAME_XID), - function: None, - plane_mask: None, - foreground: None, - background: None, - line_width: None, - line_style: None, - cap_style: None, - join_style: None, - fill_style: None, - fill_rule: None, - tile: None, - stipple: None, - tile_x_origin: None, - tile_y_origin: None, - font: None, - subwindow_mode: None, - graphics_exposures: None, - clip_x_origin: None, - clip_y_origin: None, - clip_mask: None, - dash_offset: None, - dashes: None, - arc_mode: None, - }, - ); - - // Build CopyArea body: src(4) dst(4) gc(4) src_x(2) src_y(2) - // dst_x(2) dst_y(2) width(2) height(2). - let mut body = Vec::with_capacity(24); - body.extend_from_slice(&SRC_PIXMAP_XID.to_le_bytes()); - body.extend_from_slice(&FRAME_XID.to_le_bytes()); - body.extend_from_slice(&GC_XID.to_le_bytes()); - body.extend_from_slice(&0_i16.to_le_bytes()); // src_x - body.extend_from_slice(&0_i16.to_le_bytes()); // src_y - body.extend_from_slice(&0_i16.to_le_bytes()); // dst_x - body.extend_from_slice(&0_i16.to_le_bytes()); // dst_y - body.extend_from_slice(&997_u16.to_le_bytes()); // width - body.extend_from_slice(&652_u16.to_le_bytes()); // height - - process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 62, // CopyArea major opcode - data: 0, - length_units: 7, // 1 header + 6 body words = 7 (4-byte units) - }, - &body, - None, - ) - .expect("dispatch CopyArea"); - - let copy_calls: Vec<_> = backend - .calls() - .into_iter() - .filter_map(|c| match c { - RecordedCall::CopyArea { - src_host_xid, - dst_host_xid, - src_x, - src_y, - dst_x, - dst_y, - width, - height, - } => Some(( - src_host_xid, - dst_host_xid, - src_x, - src_y, - dst_x, - dst_y, - width, - height, - )), - _ => None, - }) - .collect(); - - // Pre-fix: a single 997×652 CopyArea covering CC's area. - // Post-fix: four border strips that miss the (11, 41, 975, 600) - // child rect entirely. - assert_eq!( - copy_calls.len(), - 4, - "expected 4 border strips for ClipByChildren around the \ - mapped child; pre-fix this is 1 (the full-extent copy \ - that clobbers CC's area in the backing); got {copy_calls:?}", - ); - - // No copy may overlap the child rect (11, 41, 975, 600). - let child = (11_i32, 41_i32, 11_i32 + 975, 41_i32 + 600); - for (_, dst_host, _, _, dx, dy, w, h) in ©_calls { - let r = ( - i32::from(*dx), - i32::from(*dy), - i32::from(*dx) + i32::from(*w), - i32::from(*dy) + i32::from(*h), - ); - let overlaps = r.0 < child.2 && r.2 > child.0 && r.1 < child.3 && r.3 > child.1; - assert!( - !overlaps, - "copy strip ({dx},{dy} {w}x{h}) overlaps the child rect (11,41 975x600); \ - ClipByChildren must exclude mapped children", - ); - // Preserve window identity for backend border translation. - assert_eq!( - *dst_host, FRAME_HOST, - "ClipByChildren strips stay in window-local coordinates", - ); - } - } - - /// InputOnly children do not contribute visible pixels and must - /// not be subtracted by ClipByChildren. - #[test] - fn copy_area_clip_by_children_ignores_input_only_child() { - use crate::resources::{MapState, WindowClass}; - use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; - - let mut state = ServerState::new(); - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(0x0020_0001), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - CreateWindowRequest { - depth: 0, - window: ResourceId(0x0020_0002), - parent: ResourceId(0x0020_0001), - x: 10, - y: 10, - width: 20, - height: 20, - border_width: 0, - class: 2, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let child = state - .resources - .window_mut(ResourceId(0x0020_0002)) - .expect("child"); - child.map_state = MapState::Viewable; - assert_eq!(child.class, WindowClass::InputOnly); - } - - let rect = yserver_protocol::x11::CopyAreaRequest { - src: ResourceId(0x1), - dst: ResourceId(0x0020_0001), - gc: ResourceId(0x1), - src_x: 0, - src_y: 0, - dst_x: 0, - dst_y: 0, - width: 100, - height: 80, - }; - let draw_state = crate::backend::DrawState { - subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, - ..Default::default() - }; - - let got = - copy_area_effective_dst_rects(&state, ResourceId(0x0020_0001), &draw_state, &rect); - assert_eq!(got.len(), 1); - assert_eq!(got[0].x, 0); - assert_eq!(got[0].y, 0); - assert_eq!(got[0].width, 100); - assert_eq!(got[0].height, 80); - } - - /// MANUALLY-redirected children must not be subtracted by - /// ClipByChildren. They don't claim the parent's pixmap real - /// estate — the redirecting compositor (which may be the - /// parent's own client) puts the children's pixels there - /// itself via subsequent ops. Subtracting them strips the - /// compositor's own composite-target rect to empty. - /// - /// Live trigger: mate-panel notification-area-applet, which - /// calls `RedirectWindow(socket, Manual)` on each tray slot and - /// then `CopyArea` from each embedded applet's redirected - /// pixmap into its own visible top-level. Pre-fix every such - /// CopyArea is "fully clipped, no backend call" because the - /// manually-redirected socket children fully overlap the - /// destination — so the tray icons never make it into the - /// notification-area-applet's own backing, and mate-compositor - /// (which reads that backing via NameWindowPixmap) shows the - /// panel without icons. - #[test] - fn copy_area_clip_by_children_ignores_manually_redirected_child() { - use crate::{ - resources::{MapState, WindowClass}, - server::{CompositeRedirectMode, RedirectRecord}, - }; - use yserver_protocol::x11::{ClientId, CreateWindowRequest, ResourceId}; - - let mut state = ServerState::new(); - let parent_xid = ResourceId(0x0021_0003); - let child_xid = ResourceId(0x0021_0013); - - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: parent_xid, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: child_xid, - parent: parent_xid, - x: 0, - y: 0, - width: 100, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let child = state.resources.window_mut(child_xid).expect("child"); - child.map_state = MapState::Viewable; - assert_eq!(child.class, WindowClass::InputOutput); - } - // RedirectWindow(child, Manual). Key shape is - // `(window, subwindows=false)` for per-window - // RedirectWindow (vs `(parent, true)` for the inherited - // RedirectSubwindows form). - state.composite_redirects.insert( - (child_xid, false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); - - let rect = yserver_protocol::x11::CopyAreaRequest { - src: ResourceId(0x1), - dst: parent_xid, - gc: ResourceId(0x1), - src_x: 0, - src_y: 0, - dst_x: 0, - dst_y: 0, - width: 100, - height: 80, - }; - let draw_state = crate::backend::DrawState { - subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, - ..Default::default() - }; - - let got = copy_area_effective_dst_rects(&state, parent_xid, &draw_state, &rect); - assert_eq!( - got.len(), - 1, - "manual-redirected child must not be subtracted; got {got:?}" - ); - assert_eq!(got[0].x, 0); - assert_eq!(got[0].y, 0); - assert_eq!(got[0].width, 100); - assert_eq!(got[0].height, 80); - } - - /// Regression guard: an AUTOMATIC-redirected child *must* - /// still be subtracted by ClipByChildren. With Automatic - /// redirect the X server auto-composites the child's backing - /// into the parent's pixmap; the parent's own paint then - /// clipping out the child's area is the correct shape (the - /// child's pixels arrive via the auto-composite, not via the - /// parent's paint). The manual-only exception above must not - /// loosen this case. - #[test] - fn copy_area_clip_by_children_still_subtracts_automatic_redirected_child() { - use crate::{ - resources::{MapState, WindowClass}, - server::{CompositeRedirectMode, RedirectRecord}, - }; - use yserver_protocol::x11::{ClientId, CreateWindowRequest, ResourceId}; - - let mut state = ServerState::new(); - let parent_xid = ResourceId(0x0022_0001); - let child_xid = ResourceId(0x0022_0002); - - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: parent_xid, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 80, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: child_xid, - parent: parent_xid, - x: 10, - y: 10, - width: 50, - height: 50, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let child = state.resources.window_mut(child_xid).expect("child"); - child.map_state = MapState::Viewable; - assert_eq!(child.class, WindowClass::InputOutput); - } - state.composite_redirects.insert( - (child_xid, false), - RedirectRecord { - mode: CompositeRedirectMode::Automatic, - owner: ClientId(1), - }, - ); - - let rect = yserver_protocol::x11::CopyAreaRequest { - src: ResourceId(0x1), - dst: parent_xid, - gc: ResourceId(0x1), - src_x: 0, - src_y: 0, - dst_x: 0, - dst_y: 0, - width: 100, - height: 80, - }; - let draw_state = crate::backend::DrawState { - subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, - ..Default::default() - }; - - let got = copy_area_effective_dst_rects(&state, parent_xid, &draw_state, &rect); - // Automatic-redirected child is still subtracted, so we - // expect the original 100×80 rect to be split into four - // border strips around the (10,10 50x50) child rect. - assert!( - got.len() >= 2, - "automatic-redirected child must still be subtracted; expected > 1 \ - strip, got {got:?}" - ); - let child = (10_i32, 10_i32, 60_i32, 60_i32); - for r in &got { - let rr = ( - i32::from(r.x), - i32::from(r.y), - i32::from(r.x) + i32::from(r.width), - i32::from(r.y) + i32::from(r.height), - ); - let overlaps = rr.0 < child.2 && rr.2 > child.0 && rr.1 < child.3 && rr.3 > child.1; - assert!( - !overlaps, - "strip ({},{} {}x{}) overlaps automatic-redirected child (10,10 50x50)", - r.x, r.y, r.width, r.height, - ); - } - } - - fn render_damage_fixture( - render_return_region: Vec, - ) -> (ServerState, RecordingBackend) { - use crate::{ - backend::PictureHandle, - resources::{PictureKind, PictureState}, - server::DamageObject, - }; - use yserver_protocol::x11::CreateWindowRequest; - - const COMPOSITOR: u32 = 7; - const WIN_XID: u32 = 0x0020_0001; - const SRC_PIC_XID: u32 = 0x0020_0010; - const DST_PIC_XID: u32 = 0x0020_0011; - const DAMAGE_XID: u32 = 0x0020_0020; - const HOST_SRC: u32 = 0xAA01; - const HOST_DST: u32 = 0xAA02; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - backend.render_return_region = render_return_region; - let _peer = install_client(&mut state, COMPOSITOR); - - state.resources.create_window( - ClientId(COMPOSITOR), - CreateWindowRequest { - depth: 24, - window: ResourceId(WIN_XID), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - state.resources.create_picture( - ResourceId(SRC_PIC_XID), - PictureState { - client: ClientId(COMPOSITOR), - host_picture_xid: Some(PictureHandle::from_raw_for_test(HOST_SRC)), - host_owned_pixmap: None, - kind: PictureKind::Drawable, - drawable: Some(ResourceId(WIN_XID)), - window: None, - }, - ); - state.resources.create_picture( - ResourceId(DST_PIC_XID), - PictureState { - client: ClientId(COMPOSITOR), - host_picture_xid: Some(PictureHandle::from_raw_for_test(HOST_DST)), - host_owned_pixmap: None, - kind: PictureKind::Drawable, - drawable: Some(ResourceId(WIN_XID)), - window: None, - }, - ); - // The dst window must be MAPPED for these tests to describe a real - // situation. Damage is gated on viewability (issue #97): Xorg's - // `checkPictureDamage` requires `RegionNotEmpty(pCompositeClip)` - // (miext/damage/damage.c:474) and an unmapped window's clip is empty, - // so a RENDER op into it damages nothing there either. Leaving the - // window unmapped made these tests assert damage that Xorg would not - // produce; mapping it keeps each test's real subject — "the render op - // damages exactly the backend-returned region" — intact. - let _ = state.resources.map_window(ResourceId(WIN_XID)); - - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(COMPOSITOR), - drawable: ResourceId(WIN_XID), - level: 3, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - (state, backend) - } - - fn assert_damage_rects_exact( - state: &ServerState, - expected: &[(i16, i16, u16, u16)], - message: &str, - ) { - const DAMAGE_XID: u32 = 0x0020_0020; - let damage = state.damage_objects.get(&DAMAGE_XID).unwrap(); - let got: Vec<(i16, i16, u16, u16)> = damage - .rects - .iter() - .map(|r| (r.x, r.y, r.width, r.height)) - .collect(); - assert_eq!(got, expected, "{message}"); - } - - /// RENDER Composite must damage exactly the backend-returned region on - /// the dst picture's underlying drawable. - #[test] - fn render_composite_emits_damage_on_dst_drawable() { - const COMPOSITOR: u32 = 7; - const SRC_PIC_XID: u32 = 0x0020_0010; - const DST_PIC_XID: u32 = 0x0020_0011; - let (mut state, mut backend) = - render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 80, - }]); - - // RENDER Composite body (minor=8, total 32 bytes): - // op(1) + pad(3) + src(4) + mask(4) + dst(4) + src_xy(4) + - // mask_xy(4) + dst_xy(4) + size(4) - let mut body = vec![0u8; 32]; - body[0] = 3; // PictOpOver - body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); - body[8..12].copy_from_slice(&0u32.to_le_bytes()); // no mask - body[12..16].copy_from_slice(&DST_PIC_XID.to_le_bytes()); - body[28..30].copy_from_slice(&100u16.to_le_bytes()); // width - body[30..32].copy_from_slice(&80u16.to_le_bytes()); // height - - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, // RENDER major opcode - data: 8, // minor: Composite - length_units: u32::try_from(1 + 32 / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - - assert_damage_rects_exact( - &state, - &[(0, 0, 100, 80)], - "render_composite must damage exactly the backend-returned region", - ); - } - - #[test] - fn render_trapezoids_damages_returned_region() { - const COMPOSITOR: u32 = 7; - const DST_PIC_XID: u32 = 0x0020_0011; - const SRC_PIC_XID: u32 = 0x0020_0010; - let (mut state, mut backend) = - render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { - x: 3, - y: 4, - width: 20, - height: 30, - }]); - - let mut body = vec![0u8; 60]; - body[0] = 3; - body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); - body[8..12].copy_from_slice(&DST_PIC_XID.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, - data: 10, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - assert_damage_rects_exact( - &state, - &[(3, 4, 20, 30)], - "render_trapezoids must damage exactly the backend-returned region", - ); - - let (mut state, mut backend) = render_damage_fixture(Vec::new()); - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, - data: 10, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - assert_damage_rects_exact(&state, &[], "empty trapezoid region must not damage"); - } - - #[test] - fn render_triangles_damages_returned_region() { - const COMPOSITOR: u32 = 7; - const DST_PIC_XID: u32 = 0x0020_0011; - const SRC_PIC_XID: u32 = 0x0020_0010; - let (mut state, mut backend) = - render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { - x: 7, - y: 8, - width: 11, - height: 12, - }]); - - let mut body = vec![0u8; 44]; - body[0] = 3; - body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); - body[8..12].copy_from_slice(&DST_PIC_XID.to_le_bytes()); - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, - data: 11, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - assert_damage_rects_exact( - &state, - &[(7, 8, 11, 12)], - "render_triangles must damage exactly the backend-returned region", - ); - - let (mut state, mut backend) = render_damage_fixture(Vec::new()); - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, - data: 11, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - assert_damage_rects_exact(&state, &[], "empty triangle region must not damage"); - } - - #[test] - fn render_composite_glyphs_damages_returned_region() { - const COMPOSITOR: u32 = 7; - const DST_PIC_XID: u32 = 0x0020_0011; - const SRC_PIC_XID: u32 = 0x0020_0010; - const GLYPHSET_XID: u32 = 0x0020_0030; - const HOST_GS: u32 = 0xAA03; - let (mut state, mut backend) = - render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { - x: 9, - y: 10, - width: 13, - height: 14, - }]); - state.resources.create_glyphset( - ResourceId(GLYPHSET_XID), - crate::resources::GlyphSetState { - client: ClientId(COMPOSITOR), - host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_GS), - }, - ); - - let mut body = vec![0u8; 28]; - body[0] = 3; - body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); - body[8..12].copy_from_slice(&DST_PIC_XID.to_le_bytes()); - body[16..20].copy_from_slice(&GLYPHSET_XID.to_le_bytes()); - body[20..28].copy_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0]); - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, - data: 23, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - assert_damage_rects_exact( - &state, - &[(9, 10, 13, 14)], - "render_composite_glyphs must damage exactly the backend-returned region", - ); - - let (mut state, mut backend) = render_damage_fixture(Vec::new()); - state.resources.create_glyphset( - ResourceId(GLYPHSET_XID), - crate::resources::GlyphSetState { - client: ClientId(COMPOSITOR), - host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_GS), - }, - ); - process_request( - &mut state, - &mut backend, - ClientId(COMPOSITOR), - SequenceNumber(1), - RequestHeader { - opcode: 133, - data: 23, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - &body, - None, - ) - .unwrap(); - assert_damage_rects_exact(&state, &[], "empty glyph region must not damage"); - } - - #[test] - fn render_picture_damage_drawable_prefers_named_window_pixmap_owner() { - use crate::{backend::PixmapHandle, resources::NamedCompositePixmap}; - use yserver_protocol::x11::CreateWindowRequest; - - const CLIENT: u32 = 7; - const WINDOW_XID: u32 = 0x0030_0001; - const ALIAS_PIXMAP_XID: u32 = 0x0030_0002; - const ALIAS_PIXMAP_HOST: u32 = 0x0050_0102; - const ORDINARY_PIXMAP_XID: u32 = 0x0030_0003; - - let mut state = ServerState::new(); - state.resources.create_window( - ClientId(CLIENT), - CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: ROOT_WINDOW, - x: 100, - y: 200, - width: 800, - height: 600, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - { - let window = state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window"); - window.composite_named_pixmaps.push(NamedCompositePixmap { - client_pixmap: ResourceId(ALIAS_PIXMAP_XID), - host_pixmap: PixmapHandle::from_raw_for_test(ALIAS_PIXMAP_HOST), - width: 800, - height: 600, - }); - } - assert!( - render_picture_damage_drawable(&state, ResourceId(ALIAS_PIXMAP_XID)) - == ResourceId(WINDOW_XID), - "RENDER pictures created on a NameWindowPixmap alias must route later damage to the \ - owning window XID so XDamageCreate(window) subscriptions wake", - ); - assert!( - render_picture_damage_drawable(&state, ResourceId(ORDINARY_PIXMAP_XID)) - == ResourceId(ORDINARY_PIXMAP_XID), - "ordinary pixmaps must keep their own drawable identity; only Composite aliases \ - remap to the owner window", - ); - } - - // ──────────────────────────────────────────────────────────── - // Phase 2 reparent-redirect-reconciliation pins (Task 7). - // - // Mirrors Xorg's `compReparentWindow` (xserver/composite/ - // compwindow.c:453-454) — which dispatches to - // `compUnredirectOneSubwindow` (revoke inherited redirect), - // `compRedirectOneSubwindow` (grant inherited redirect), and - // `flip_redirect_target_mode` (mode flip across redirected - // parents). Direct RedirectWindow(W) is per-window so the - // backing is not touched by reparent. - // - // The fifth, user-visible pin lives in - // `crates/yserver/src/kms/render/backend.rs` — it drives the v2 - // `resolve_paint_target` ancestor walk through the full - // `process_request` dispatcher. - // ──────────────────────────────────────────────────────────── - - fn make_test_state() -> ServerState { - ServerState::new() - } - - /// Seed a `Window` resource under `parent` with the given size - /// and a deterministic `host_xid` derived from the nested xid. - /// Mirrors what the production `CreateWindow` path leaves in - /// `state.resources` once the host create has roundtripped. - fn seed_window( - state: &mut ServerState, - xid: ResourceId, - parent: ResourceId, - width: u16, - height: u16, - ) { - use yserver_protocol::x11::CreateWindowRequest; - state.resources.create_window( - ClientId(14), - CreateWindowRequest { - depth: 24, - window: xid, - parent, - x: 0, - y: 0, - width, - height, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - if let Some(w) = state.resources.window_mut(xid) { - // Synthesise a host_xid from the nested xid (high bit - // set so it can't collide with a low-numbered nested - // xid in a different role). Production assigns these - // out of the backend; tests just need stable values. - w.host_xid = crate::backend::WindowHandle::from_raw(0x8000_0000 | xid.0); - } - } - - /// Attach a `RedirectedBacking` to an already-seeded window. - /// The `backend` argument keeps the helper's signature - /// symmetrical with the (eventual) production path which - /// allocates a real backing through the backend; the recording - /// backend doesn't need to be consulted for the test - /// pre-condition, so we just synthesise a PixmapHandle. - fn seed_redirected_window( - state: &mut ServerState, - _backend: &mut crate::backend::recording::RecordingBackend, - xid: ResourceId, - ) { - use crate::resources::RedirectedBacking; - if let Some(w) = state.resources.window_mut(xid) { - w.redirected_backing = Some(RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw(0x9000_0000 | xid.0) - .expect("non-zero PixmapHandle"), - width: w.width, - height: w.height, - depth: w.depth, - }); - } - } - - /// Drive a ReparentWindow through `handle_reparent_window` (the - /// module-private dispatch path) via `process_request`'s public - /// entry. ReparentWindow body = window(4 LE) + parent(4 LE) + - /// x(2 LE i16) + y(2 LE i16) = 12 bytes; length_units = 4 - /// (header + body = 16 bytes / 4). - fn dispatch_reparent_window( - state: &mut ServerState, - backend: &mut crate::backend::recording::RecordingBackend, - window: ResourceId, - parent: ResourceId, - x: i16, - y: i16, - ) { - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&window.0.to_le_bytes()); - body.extend_from_slice(&parent.0.to_le_bytes()); - body.extend_from_slice(&x.to_le_bytes()); - body.extend_from_slice(&y.to_le_bytes()); - process_request( - state, - backend, - ClientId(14), - SequenceNumber(1), - RequestHeader { - opcode: 7, // ReparentWindow - data: 0, - length_units: 4, - }, - &body, - None, - ) - .expect("process_request(ReparentWindow) must succeed"); - } - - #[test] - fn reparent_out_of_redirected_subtree_revokes_inherited_redirect() { - // Phase 2: mirrors compUnredirectOneSubwindow in - // /home/jos/Projects/xserver/composite/compwindow.c:453. - // A window that inherited redirect from its parent's - // RedirectSubwindows must lose its backing when reparented - // to a parent without RedirectSubwindows. - // - // The actual regression: nm-applet (created as a direct - // child of root with RedirectSubwindows(root, Manual) - // active, then reparented into mate-panel's notification - // socket) keeps a stale backing. Paints land there instead - // of in mate-panel's pixmap; the compositor reads mate- - // panel's pixmap and sees an empty tray area. - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - - let root_xid = crate::resources::ROOT_WINDOW; - let mate_panel_xid = ResourceId(0x110_0003); - let socket_xid = ResourceId(0x210_0013); - let nm_applet_xid = ResourceId(0x180_000b); - - // root has RedirectSubwindows(Manual); socket does not. - state.composite_redirects.insert( - (root_xid, true), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: ClientId(14), - }, - ); - - seed_window(&mut state, mate_panel_xid, root_xid, 2560, 28); - seed_redirected_window(&mut state, &mut backend, mate_panel_xid); - seed_window(&mut state, socket_xid, mate_panel_xid, 26, 27); - seed_window(&mut state, nm_applet_xid, root_xid, 26, 27); - seed_redirected_window(&mut state, &mut backend, nm_applet_xid); - - assert!( - state - .resources - .window(nm_applet_xid) - .unwrap() - .redirected_backing - .is_some(), - "pre-condition: nm-applet has an inherited-redirect backing" - ); - - dispatch_reparent_window(&mut state, &mut backend, nm_applet_xid, socket_xid, 0, 0); - - assert_eq!( - state.resources.window(nm_applet_xid).unwrap().parent, - socket_xid, - ); - assert!( - state - .resources - .window(nm_applet_xid) - .unwrap() - .redirected_backing - .is_none(), - "post-condition: nm-applet's inherited-redirect backing is freed after \ - reparenting out of the redirected subtree" - ); - } - - #[test] - fn muffin_manual_probe_cannot_pin_redirect_across_reparent() { - // Live Warframe transition: while temporarily a root child, W - // inherits RedirectSubwindows(root, Manual). Muffin then probes - // RedirectWindow(W, Manual), which Xorg rejects with BadAccess. - // If accepted, that direct record makes the subsequent reparent - // into Muffin's frame skip inherited-redirect teardown and W keeps - // painting a stale inner backing that Muffin never samples. - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - let root = crate::resources::ROOT_WINDOW; - let frame = ResourceId(0x510_0040); - let window = ResourceId(0x530_0003); - - state.composite_redirects.insert( - (root, true), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: ClientId(14), - }, - ); - seed_window(&mut state, frame, root, 1024, 768); - seed_window(&mut state, window, root, 1024, 768); - seed_redirected_window(&mut state, &mut backend, window); - - dispatch_composite_redirect(&mut state, &mut backend, ClientId(14), window.0, 1); - assert!( - !state.composite_redirects.contains_key(&(window, false)), - "BadAccess probe must not create a direct redirect", - ); - - dispatch_reparent_window(&mut state, &mut backend, window, frame, 0, 0); - assert!( - state - .resources - .window(window) - .unwrap() - .redirected_backing - .is_none(), - "reparent into Muffin frame must revoke W's inherited Manual backing", - ); - } - - #[test] - fn reparent_into_redirected_subtree_grants_inherited_redirect() { - // Phase 2: mirrors compRedirectOneSubwindow at - // /home/jos/Projects/xserver/composite/compwindow.c:454. A - // window with no own redirect, no parent RedirectSubwindows, - // gains a backing when reparented under a parent with active - // RedirectSubwindows. - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - - let root_xid = crate::resources::ROOT_WINDOW; - let mate_panel_xid = ResourceId(0x110_0003); - let unredirected_parent_xid = ResourceId(0x300_0001); - let target_xid = ResourceId(0x300_0010); - - state.composite_redirects.insert( - (mate_panel_xid, true), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Automatic, - owner: ClientId(14), - }, - ); - - seed_window(&mut state, mate_panel_xid, root_xid, 2560, 28); - seed_window(&mut state, unredirected_parent_xid, root_xid, 100, 100); - seed_window(&mut state, target_xid, unredirected_parent_xid, 50, 50); - // Viewable throughout: an unviewable window gets its backing at realize instead. - for w in [mate_panel_xid, unredirected_parent_xid, target_xid] { - let _ = state.resources.map_window(w); - } - - assert!( - state - .resources - .window(target_xid) - .unwrap() - .redirected_backing - .is_none(), - "pre-condition: target has no backing" - ); - - dispatch_reparent_window(&mut state, &mut backend, target_xid, mate_panel_xid, 0, 0); - - assert_eq!( - state.resources.window(target_xid).unwrap().parent, - mate_panel_xid, - ); - assert!( - state - .resources - .window(target_xid) - .unwrap() - .redirected_backing - .is_some(), - "post-condition: target gained an inherited-redirect backing" - ); - } - - #[test] - fn reparent_with_direct_redirect_keeps_backing() { - // Phase 2 invariant: RedirectWindow(W) is a per-window - // redirect independent of W's parent. Reparenting W must - // NOT touch its backing. - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - - let root_xid = crate::resources::ROOT_WINDOW; - let mate_panel_xid = ResourceId(0x110_0003); - let socket_xid = ResourceId(0x210_0013); - let directly_redirected_xid = ResourceId(0x400_0001); - - state.composite_redirects.insert( - (directly_redirected_xid, false), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: ClientId(14), - }, - ); - - seed_window(&mut state, mate_panel_xid, root_xid, 2560, 28); - seed_window(&mut state, socket_xid, mate_panel_xid, 26, 27); - seed_window(&mut state, directly_redirected_xid, root_xid, 50, 50); - seed_redirected_window(&mut state, &mut backend, directly_redirected_xid); - - let backing_before = state - .resources - .window(directly_redirected_xid) - .unwrap() - .redirected_backing - .as_ref() - .map(|b| b.host_pixmap); - assert!(backing_before.is_some()); - - dispatch_reparent_window( - &mut state, - &mut backend, - directly_redirected_xid, - socket_xid, - 0, - 0, - ); - - let backing_after = state - .resources - .window(directly_redirected_xid) - .unwrap() - .redirected_backing - .as_ref() - .map(|b| b.host_pixmap); - assert_eq!( - backing_before, backing_after, - "RedirectWindow(W) survives reparent" - ); - } - - // Window-storage step 4: a redirect backing follows viewability (Xorg - // compRealizeWindow / compUnrealizeWindow → compCheckRedirect); the - // redirect itself survives until Unredirect or destruction. - - fn storage_req( - state: &mut ServerState, - backend: &mut crate::backend::recording::RecordingBackend, - opcode: u8, - data: u8, - body: &[u8], - ) { - process_request( - state, - backend, - ClientId(14), - SequenceNumber(1), - RequestHeader { - opcode, - data, - length_units: u32::try_from(1 + body.len() / 4).unwrap(), - }, - body, - None, - ) - .expect("process_request must succeed"); - } - - fn storage_redirect( - state: &mut ServerState, - backend: &mut crate::backend::recording::RecordingBackend, - minor: u8, - window: ResourceId, - ) { - let mut body = window.0.to_le_bytes().to_vec(); - body.extend_from_slice(&[1, 0, 0, 0]); // Manual - storage_req(state, backend, 144, minor, &body); - } - - fn storage_window_req( - state: &mut ServerState, - backend: &mut crate::backend::recording::RecordingBackend, - opcode: u8, - window: ResourceId, - ) { - storage_req(state, backend, opcode, 0, &window.0.to_le_bytes()); - } - - fn drain_calls( - backend: &crate::backend::recording::RecordingBackend, - ) -> Vec { - std::mem::take(&mut *backend.calls.lock().unwrap()) - } - - const MAP_WINDOW: u8 = 8; - const MAP_SUBWINDOWS: u8 = 9; - const UNMAP_WINDOW: u8 = 10; - const UNMAP_SUBWINDOWS: u8 = 11; - - fn backing_of(state: &ServerState, window: ResourceId) -> Option { - state - .resources - .window(window) - .and_then(|w| w.redirected_backing.as_ref()) - .map(|b| b.host_pixmap.as_raw()) - } - - fn storage_host(window: ResourceId) -> u32 { - 0x8000_0000 | window.0 - } - - fn released(calls: &[crate::backend::recording::RecordedCall], backing: u32) -> bool { - calls.iter().any(|c| { - matches!(c, crate::backend::recording::RecordedCall::ReleaseRedirectedBacking(b) if *b == backing) - }) - } - - fn allocations_for( - calls: &[crate::backend::recording::RecordedCall], - window: ResourceId, - ) -> usize { - calls - .iter() - .filter(|c| { - matches!(c, crate::backend::recording::RecordedCall::AllocateRedirectedBacking { host_window, .. } if *host_window == storage_host(window)) - }) - .count() - } - - fn participation_restored( - calls: &[crate::backend::recording::RecordedCall], - window: ResourceId, - ) -> bool { - calls.iter().any(|c| { - matches!(c, crate::backend::recording::RecordedCall::SetWindowSceneParticipation { host_window, participating: true } if *host_window == storage_host(window)) - }) - } - - fn last_participation( - calls: &[crate::backend::recording::RecordedCall], - window: ResourceId, - ) -> Option { - calls.iter().rev().find_map(|c| match c { - crate::backend::recording::RecordedCall::SetWindowSceneParticipation { - host_window, - participating, - } if *host_window == storage_host(window) => Some(*participating), - _ => None, - }) - } - - /// A mapped top-level `W`, Manual-redirected through the dispatcher. - fn storage_redirected_top_level() -> ( - ServerState, - crate::backend::recording::RecordingBackend, - ResourceId, - u32, - ) { - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - let window = ResourceId(0x0600_0001); - seed_window(&mut state, window, crate::resources::ROOT_WINDOW, 64, 48); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); - storage_redirect(&mut state, &mut backend, 1, window); - let backing = backing_of(&state, window).expect("viewable redirected window has a backing"); - (state, backend, window, backing) - } - - #[test] - fn unmap_of_redirected_window_frees_backing_keeps_redirect_and_exclusion() { - let (mut state, mut backend, window, backing) = storage_redirected_top_level(); - drain_calls(&backend); - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); - let calls = drain_calls(&backend); - assert!( - released(&calls, backing), - "unmap releases the backing; calls={calls:#?}" - ); - assert_eq!(backing_of(&state, window), None); - assert!( - state.composite_redirects.contains_key(&(window, false)), - "redirect record kept" - ); - assert!( - !participation_restored(&calls, window), - "window stays out of the scene" - ); - } - - #[test] - fn remap_of_redirected_window_allocates_a_fresh_backing() { - let (mut state, mut backend, window, backing) = storage_redirected_top_level(); - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); - drain_calls(&backend); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); - let calls = drain_calls(&backend); - assert_eq!(allocations_for(&calls, window), 1); - let fresh = backing_of(&state, window).expect("remap re-creates the backing"); - assert_ne!(fresh, backing); - assert_eq!( - last_participation(&calls, window), - Some(false), - "Manual stays excluded" - ); - } - - #[test] - fn redirect_of_unviewable_window_allocates_at_map() { - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - let window = ResourceId(0x0600_0001); - seed_window(&mut state, window, crate::resources::ROOT_WINDOW, 64, 48); - storage_redirect(&mut state, &mut backend, 1, window); - assert_eq!( - allocations_for(&drain_calls(&backend), window), - 0, - "Xorg: not realized, no pixmap" - ); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); - assert_eq!(allocations_for(&drain_calls(&backend), window), 1); - assert!(backing_of(&state, window).is_some()); - } - - #[test] - fn ancestor_unmap_frees_redirected_descendant_backing_and_remap_restores_it() { - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - let frame = ResourceId(0x0600_0010); - let window = ResourceId(0x0600_0011); - seed_window(&mut state, frame, crate::resources::ROOT_WINDOW, 64, 48); - seed_window(&mut state, window, frame, 32, 24); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); - storage_redirect(&mut state, &mut backend, 1, window); - let backing = backing_of(&state, window).expect("backing"); - drain_calls(&backend); - - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, frame); - let calls = drain_calls(&backend); - assert!(released(&calls, backing)); - assert_eq!(backing_of(&state, window), None); - assert!(state.composite_redirects.contains_key(&(window, false))); - assert!(!participation_restored(&calls, window)); - - storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); - let calls = drain_calls(&backend); - assert_eq!( - allocations_for(&calls, window), - 1, - "descendant realized with its ancestor" - ); - assert_ne!(backing_of(&state, window), Some(backing)); - assert!(backing_of(&state, window).is_some()); - assert_eq!(last_participation(&calls, window), Some(false)); - } - - #[test] - fn redirect_subwindows_children_follow_viewability() { - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - let parent = ResourceId(0x0600_0020); - let shown = ResourceId(0x0600_0021); - let hidden = ResourceId(0x0600_0022); - seed_window(&mut state, parent, crate::resources::ROOT_WINDOW, 64, 48); - seed_window(&mut state, shown, parent, 16, 16); - seed_window(&mut state, hidden, parent, 16, 16); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, parent); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, shown); - storage_redirect(&mut state, &mut backend, 2, parent); // RedirectSubwindows - let shown_backing = backing_of(&state, shown).expect("viewable child redirected"); - assert_eq!( - backing_of(&state, hidden), - None, - "unmapped child has no backing" - ); - assert_eq!( - backing_of(&state, parent), - None, - "the parent itself is not redirected" - ); - - storage_window_req(&mut state, &mut backend, UNMAP_SUBWINDOWS, parent); - let calls = drain_calls(&backend); - assert!(released(&calls, shown_backing)); - assert_eq!(backing_of(&state, shown), None); - assert!(state.composite_redirects.contains_key(&(parent, true))); - assert!(!participation_restored(&calls, shown)); - - storage_window_req(&mut state, &mut backend, MAP_SUBWINDOWS, parent); - let calls = drain_calls(&backend); - assert_eq!(allocations_for(&calls, shown), 1); - assert_eq!(allocations_for(&calls, hidden), 1); - assert_eq!(last_participation(&calls, shown), Some(false)); - assert_eq!(last_participation(&calls, hidden), Some(false)); - - let (a, b) = ( - backing_of(&state, shown).unwrap(), - backing_of(&state, hidden).unwrap(), - ); - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, parent); - let calls = drain_calls(&backend); - assert!( - released(&calls, a) && released(&calls, b), - "ancestor unmap frees every child" - ); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, parent); - let calls = drain_calls(&backend); - assert_eq!(allocations_for(&calls, shown), 1); - assert_eq!(allocations_for(&calls, hidden), 1); - } - - #[test] - fn unredirect_window_still_tears_down_and_restores_participation() { - let (mut state, mut backend, window, backing) = storage_redirected_top_level(); - drain_calls(&backend); - storage_redirect(&mut state, &mut backend, 3, window); // UnredirectWindow - let calls = drain_calls(&backend); - assert!(released(&calls, backing)); - assert_eq!(backing_of(&state, window), None); - assert!(!state.composite_redirects.contains_key(&(window, false))); - assert_eq!(last_participation(&calls, window), Some(true)); - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); - assert_eq!( - allocations_for(&drain_calls(&backend), window), - 0, - "no redirect, no backing" - ); - } - - #[test] - fn unredirect_of_hidden_mapped_window_restores_participation_without_backing() { - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - let frame = ResourceId(0x0600_0030); - let window = ResourceId(0x0600_0031); - seed_window(&mut state, frame, crate::resources::ROOT_WINDOW, 64, 48); - seed_window(&mut state, window, frame, 32, 24); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); - storage_redirect(&mut state, &mut backend, 1, window); - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, frame); - drain_calls(&backend); - storage_redirect(&mut state, &mut backend, 3, window); - let calls = drain_calls(&backend); - assert_eq!( - last_participation(&calls, window), - Some(true), - "mapped window rejoins the scene" - ); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); - assert_eq!(allocations_for(&drain_calls(&backend), window), 0); - } - - #[test] - fn destroy_of_redirected_window_still_releases_backing_and_record() { - let (mut state, mut backend, window, backing) = storage_redirected_top_level(); - drain_calls(&backend); - storage_window_req(&mut state, &mut backend, 4, window); // DestroyWindow - let calls = drain_calls(&backend); - assert!(released(&calls, backing)); - assert!(!state.composite_redirects.contains_key(&(window, false))); - } - - #[test] - fn destroy_of_unmapped_redirected_window_drops_the_record() { - let (mut state, mut backend, window, _backing) = storage_redirected_top_level(); - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); - storage_window_req(&mut state, &mut backend, 4, window); - assert!(!state.composite_redirects.contains_key(&(window, false))); - } - - #[test] - fn reparent_under_unmapped_parent_frees_backing_keeps_redirect() { - let (mut state, mut backend, window, backing) = storage_redirected_top_level(); - let hidden_parent = ResourceId(0x0600_0040); - seed_window( - &mut state, - hidden_parent, - crate::resources::ROOT_WINDOW, - 64, - 48, - ); - drain_calls(&backend); - dispatch_reparent_window(&mut state, &mut backend, window, hidden_parent, 0, 0); - assert!(released(&drain_calls(&backend), backing)); - assert_eq!(backing_of(&state, window), None); - assert!(state.composite_redirects.contains_key(&(window, false))); - storage_window_req(&mut state, &mut backend, MAP_WINDOW, hidden_parent); - assert_eq!(allocations_for(&drain_calls(&backend), window), 1); - } - - #[test] - fn unmap_severs_named_pixmaps_from_the_window() { - let (mut state, mut backend, window, backing) = storage_redirected_top_level(); - let named = ResourceId(0x0600_0050); - if let Some(w) = state.resources.window_mut(window) { - w.composite_named_pixmaps - .push(crate::resources::NamedCompositePixmap { - client_pixmap: named, - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(backing), - width: 64, - height: 48, - }); - } - storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); - assert!( - state - .resources - .window(window) - .unwrap() - .composite_named_pixmaps - .is_empty() - ); - assert_eq!( - render_picture_damage_drawable(&state, named), - named, - "no longer the window's" - ); - } - - #[test] - fn reparent_between_redirected_parents_with_different_modes_flips_mode() { - // Phase 2: when both old_parent and new_parent have - // RedirectSubwindows but with different modes (Manual ↔ - // Automatic), the production reconciliation calls - // flip_redirect_target_mode. That helper preserves the - // backing handle (X Composite spec: old named pixmaps remain - // allocated until FreePixmap; only redirectDraw flips) and - // updates the window's own scene_participating flag per the - // new mode (Manual ⇒ false, Automatic ⇒ true). - let mut state = make_test_state(); - let mut backend = - crate::backend::recording::RecordingBackend::new().with_redirect_activation(); - - let root_xid = crate::resources::ROOT_WINDOW; - let parent_manual_xid = ResourceId(0x500_0001); - let parent_automatic_xid = ResourceId(0x500_0002); - let target_xid = ResourceId(0x500_0010); - - state.composite_redirects.insert( - (parent_manual_xid, true), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Manual, - owner: ClientId(14), - }, - ); - state.composite_redirects.insert( - (parent_automatic_xid, true), - crate::server::RedirectRecord { - mode: crate::server::CompositeRedirectMode::Automatic, - owner: ClientId(14), - }, - ); - - seed_window(&mut state, parent_manual_xid, root_xid, 100, 100); - seed_window(&mut state, parent_automatic_xid, root_xid, 100, 100); - // target is initially a child of parent_manual_xid → inherits - // Manual redirect → has a backing allocated, and its own - // scene_participating is false (Manual semantics). - seed_window(&mut state, target_xid, parent_manual_xid, 50, 50); - seed_redirected_window(&mut state, &mut backend, target_xid); - - let backing_before = state - .resources - .window(target_xid) - .unwrap() - .redirected_backing - .as_ref() - .map(|b| b.host_pixmap); - assert!( - backing_before.is_some(), - "pre: target has Manual-inherited backing" - ); - - // Reparent to the Automatic parent. - dispatch_reparent_window( - &mut state, - &mut backend, - target_xid, - parent_automatic_xid, - 0, - 0, - ); - - let backing_after = state - .resources - .window(target_xid) - .unwrap() - .redirected_backing - .as_ref() - .map(|b| b.host_pixmap); - assert_eq!( - backing_before, backing_after, - "mode-flip across redirected parents preserves the backing handle (X Composite spec)" - ); - - // Mode flip side effect: scene_participating flag on the - // window itself follows the new parent's mode. The flip is - // visible in the RecordingBackend's call log — look for a - // SetWindowSceneParticipation(_, true) for target's host xid - // (Automatic ⇒ participating=true; pre-reparent it was - // false under Manual). - let calls = backend.calls.lock().expect("calls poisoned"); - let saw_participation_true = calls.iter().any(|c| { - matches!( - c, - crate::backend::recording::RecordedCall::SetWindowSceneParticipation { - participating: true, - .. - } - ) - }); - assert!( - saw_participation_true, - "expected SetWindowSceneParticipation(_, true) after Manual → Automatic flip; \ - got {:?}", - *calls, - ); - } - - #[test] - fn dpms_force_level_rejects_when_disabled() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = false; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 134, - data: 6, - length_units: 2, - }; - let body = [3u8, 0, 0, 0]; // level=Off - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - let calls = backend.calls(); - assert!( - !calls - .iter() - .any(|c| matches!(c, RecordedCall::SetDpmsPower(_))), - "ForceLevel must not call backend when !enabled" - ); - assert_eq!(state.dpms.power_level, 0, "state unchanged on BadMatch"); - // Error reply: byte 0 == 0 (Error), byte 1 == x11::error::BAD_MATCH. - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0, "reply is an X11 error"); - assert_eq!(bytes[1], x11::error::BAD_MATCH); - } - - #[test] - fn dpms_force_level_changes_state_and_notifies() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.selected_by.insert(ClientId(1)); - let header = RequestHeader { - opcode: 134, - data: 6, - length_units: 2, - }; - let body = [3u8, 0, 0, 0]; // level=Off - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - assert_eq!(state.dpms.power_level, 3); - assert!( - backend - .calls() - .iter() - .any(|c| matches!(c, RecordedCall::SetDpmsPower(3))) - ); - // GenericEvent tag = 35 should appear exactly once in this client's stream. - let bytes = read_all_available(&mut peer); - let notifies = bytes.iter().filter(|&&b| b == 35).count(); - assert_eq!(notifies, 1, "ForceLevel(Off) from On: exactly one notify"); - } - - #[test] - fn dpms_disable_from_off_emits_two_notifies() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - state.dpms.power_level = 3; // Off - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.selected_by.insert(ClientId(1)); - let header = RequestHeader { - opcode: 134, - data: 5, - length_units: 1, - }; // Disable - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[], - ); - // First notify: Off→On (level change). Second: enabled true→false. - let bytes = read_all_available(&mut peer); - let notifies = bytes.iter().filter(|&&b| b == 35).count(); - assert_eq!(notifies, 2, "Disable from Off must emit two XGE notifies"); - assert!(!state.dpms.enabled); - assert_eq!(state.dpms.power_level, 0); - // Verify ordering: byte 18 of each event is the `state` - // (enabled) field. The first event fires from - // apply_dpms_transition before `enabled` is cleared, so it - // should show enabled=1; the second event fires after the - // enable flip, so it should show enabled=0. - assert_eq!( - bytes[18], 1, - "first notify is the level-change notify; enabled still true" - ); - assert_eq!( - bytes[32 + 18], - 0, - "second notify is the enable-change notify; enabled now false" - ); - } - - #[test] - fn dpms_disable_from_on_emits_one_notify() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.selected_by.insert(ClientId(1)); - let header = RequestHeader { - opcode: 134, - data: 5, - length_units: 1, - }; - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[], - ); - let bytes = read_all_available(&mut peer); - let notifies = bytes.iter().filter(|&&b| b == 35).count(); - assert_eq!( - notifies, 1, - "Disable from On: only the enable-change notify fires" - ); - assert!(!state.dpms.enabled); - } - - #[test] - fn dpms_enable_when_already_enabled_emits_no_notify() { - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.selected_by.insert(ClientId(1)); - let header = RequestHeader { - opcode: 134, - data: 4, - length_units: 1, - }; // Enable - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[], - ); - let bytes = read_all_available(&mut peer); - assert!(!bytes.contains(&35), "no notify when state didn't change"); - } - - #[test] - fn dpms_set_timeouts_rejects_inverted_ordering() { - // off=10 but suspend=20 violates the non-zero - // off >= suspend ordering — must produce BadValue. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 134, - data: 3, - length_units: 2, - }; // SetTimeouts - // Body: standby=30, suspend=20, off=10, pad=0 — clearly out of order. - let body = [30u8, 0, 20, 0, 10, 0, 0, 0]; - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0, "reply is an X11 error"); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - // Timeouts must NOT have been stored. - assert_eq!(state.dpms.standby_ms, 600_000); - assert_eq!(state.dpms.suspend_ms, 600_000); - assert_eq!(state.dpms.off_ms, 600_000); - } - - #[test] - fn dpms_select_input_zero_removes_subscriber() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Pre-seed: client is already subscribed. - state.dpms.selected_by.insert(ClientId(1)); - assert!(state.dpms.selected_by.contains(&ClientId(1))); - - let header = RequestHeader { - opcode: 134, - data: 8, - length_units: 2, - }; // SelectInput - let body = [0u8, 0, 0, 0]; // mask = 0 → unsubscribe - let _ = handle_dpms_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - assert!( - !state.dpms.selected_by.contains(&ClientId(1)), - "mask=0 must remove the client from selected_by" - ); - } - - #[test] - fn dpms_off_drives_screensaver_on_with_forced_true() { - // Xorg dpms.c:269-279 — DPMS Non-On + SS Off → - // dixSaveScreens(SCREEN_SAVER_FORCER, ScreenSaverActive) - // → SendScreenSaverNotify(... forced=true). - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - let mut peer = install_client(&mut state, 1); - state - .screensaver - .selected_by - .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); - let mut backend = RecordingBackend::new(); - - apply_dpms_transition(&mut state, &mut backend, 3); // Off - - assert_eq!(state.screensaver.active, ScreenSaverActive::On); - assert!(state.screensaver.forced); - - let bytes = read_all_available(&mut peer); - // Sequential event tag is first_event + 0 = 92. - let idx = bytes - .iter() - .position(|&b| b == 92) - .expect("ScreenSaverNotify must be present"); - assert_eq!(bytes[idx + 1], x11screensaver::SCREEN_SAVER_ON, "state=On"); - assert_eq!(bytes[idx + 17], 1, "forced byte = 1"); - } - - #[test] - fn dpms_on_drives_screensaver_off_with_forced_false_and_no_activity_reset() { - // Xorg dpms.c:275-278 + window.c:3187-3193 — DPMS On + SS On - // takes the SCREEN_SAVER_OFF (not FORCER) path, so forced=0. - // NoticeTime only fires on the FORCER+Reset combination, so - // last_activity must NOT be touched by the coupling itself. - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - state.dpms.power_level = 3; - state.screensaver.active = ScreenSaverActive::On; - let prior = state.dpms.last_activity; - - let mut peer = install_client(&mut state, 1); - state - .screensaver - .selected_by - .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); - let mut backend = RecordingBackend::new(); - - apply_dpms_transition(&mut state, &mut backend, 0); - - assert_eq!(state.screensaver.active, ScreenSaverActive::Off); - assert!( - !state.screensaver.forced, - "DPMS-On→SS-Off is non-FORCER path" - ); - assert_eq!(state.dpms.last_activity, prior, "coupling must NOT reset"); - - let bytes = read_all_available(&mut peer); - let idx = bytes.iter().position(|&b| b == 92).unwrap(); - assert_eq!(bytes[idx + 1], x11screensaver::SCREEN_SAVER_OFF); - assert_eq!(bytes[idx + 17], 0, "forced byte = 0"); - } - - #[test] - fn dpms_coupling_emits_screensaver_notify_before_dpms_notify() { - // SS notify (sequential event tag 92) must appear at a lower - // wire offset than the DPMS XGE notify (GenericEvent tag 35) - // — matches Xorg ordering in DPMSSet (dpms.c:262-293). - let mut state = ServerState::new(); - state.dpms.kms_capable = true; - state.dpms.enabled = true; - let mut peer = install_client(&mut state, 1); - state.dpms.selected_by.insert(ClientId(1)); - state - .screensaver - .selected_by - .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); - let mut backend = RecordingBackend::new(); - - apply_dpms_transition(&mut state, &mut backend, 3); - - let bytes = read_all_available(&mut peer); - let ss_pos = bytes.iter().position(|&b| b == 92).unwrap(); - let dpms_pos = bytes.iter().position(|&b| b == 35).unwrap(); - assert!( - ss_pos < dpms_pos, - "SS notify (offset {ss_pos}) must precede DPMS notify (offset {dpms_pos})" - ); - } - - #[test] - fn force_screen_saver_activate_emits_notify_with_forced_true() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state - .screensaver - .selected_by - .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); - let mut backend = RecordingBackend::new(); - - apply_screen_saver_transition( - &mut state, - &mut backend, - ScreenSaverActive::On, - /*forced=*/ true, - ); - - let bytes = read_all_available(&mut peer); - let idx = bytes.iter().position(|&b| b == 92).unwrap(); - assert_eq!(bytes[idx + 1], x11screensaver::SCREEN_SAVER_ON); - assert_eq!(bytes[idx + 17], 1, "forced=1"); - } - - #[test] - fn apply_screen_saver_transition_does_not_touch_last_activity() { - // last_activity update is the *handler's* responsibility - // (FORCER+Reset path runs Xorg's NoticeTime, window.c:3187-3193). - // The pure helper must NOT touch last_activity — otherwise the - // input-fanout SS-only sibling check (Task 3 step 5) would - // double-bump it, and the DPMS coupling would too. - let mut state = ServerState::new(); - state.screensaver.active = ScreenSaverActive::On; - let prior = state.dpms.last_activity; - let mut backend = RecordingBackend::new(); - - apply_screen_saver_transition( - &mut state, - &mut backend, - ScreenSaverActive::Off, - /*forced=*/ true, - ); - - assert_eq!(state.screensaver.active, ScreenSaverActive::Off); - assert_eq!( - state.dpms.last_activity, prior, - "helper alone must not touch last_activity" - ); - } - - #[test] - fn force_screen_saver_invalid_mode_returns_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 115, - data: 2, // mode=2 — only 0 (Reset) and 1 (Activate) are valid - length_units: 1, - }; - let _ = handle_force_screen_saver( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0, "error reply tag"); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - // bad_value at offset 4 = 2 - assert_eq!( - u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), - 2 - ); - } - - #[test] - fn force_screen_saver_activate_via_handler_transitions_to_on() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 115, - data: 1, - length_units: 1, - }; // mode=1 (Activate) - - let _ = handle_force_screen_saver( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - ); - - assert_eq!(state.screensaver.active, ScreenSaverActive::On); - assert!( - state.screensaver.forced, - "Activate is the FORCER path → forced=true" - ); - } - - #[test] - fn force_screen_saver_reset_via_handler_advances_last_activity() { - // Reset is the FORCER+Reset path Xorg runs NoticeTime on - // (window.c:3187-3193) — the handler must bump last_activity. - use std::time::Duration; - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - state.screensaver.active = ScreenSaverActive::On; - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); - let stale = state.dpms.last_activity; - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 115, - data: 0, - length_units: 1, - }; // mode=0 (Reset) - - let _ = handle_force_screen_saver( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - ); - - assert_eq!(state.screensaver.active, ScreenSaverActive::Off); - assert!( - state.dpms.last_activity > stale, - "handler must bump last_activity on Reset" - ); - } - - #[test] - fn set_screen_saver_stores_fields() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let header = RequestHeader { - opcode: 107, - data: 0, - length_units: 3, - }; - // timeout=300, interval=900, prefer_blanking=0 (no), - // allow_exposures=1 (yes), pad:u16 - let body = [ - 44, 1, // 300 (LE) - 132, 3, // 900 (LE) - 0, // prefer_blanking - 1, // allow_exposures - 0, 0, // pad - ]; - let _ = handle_set_screen_saver(&mut state, ClientId(1), SequenceNumber(1), header, &body); - assert_eq!(state.screensaver.timeout_ms, 300_000); - assert_eq!(state.screensaver.interval_ms, 900_000); - assert!(!state.screensaver.prefer_blanking); - assert!(state.screensaver.allow_exposures); - } - - #[test] - fn set_screen_saver_minus_one_restores_default() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - state.screensaver.timeout_ms = 12_345; - state.screensaver.interval_ms = 67_890; - let header = RequestHeader { - opcode: 107, - data: 0, - length_units: 3, - }; - // -1 (0xffff), -1, default(2), default(2), pad - let body = [0xff, 0xff, 0xff, 0xff, 2, 2, 0, 0]; - let _ = handle_set_screen_saver(&mut state, ClientId(1), SequenceNumber(1), header, &body); - // defaults: timeout=600s, interval=600s, prefer=true, allow=true - assert_eq!(state.screensaver.timeout_ms, 600_000); - assert_eq!(state.screensaver.interval_ms, 600_000); - assert!(state.screensaver.prefer_blanking); - assert!(state.screensaver.allow_exposures); - } - - #[test] - fn set_screen_saver_invalid_prefer_blanking_returns_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let header = RequestHeader { - opcode: 107, - data: 0, - length_units: 3, - }; - // prefer_blanking=3 is invalid (only 0/1/2 valid). - let body = [60, 0, 60, 0, 3, 1, 0, 0]; - let _ = handle_set_screen_saver(&mut state, ClientId(1), SequenceNumber(1), header, &body); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert_eq!( - u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), - 3 - ); - } - - /// Build a ChangeKeyboardControl body: mask + one u32 per set bit. - fn kbctrl_body(mask: u32, values: &[u32]) -> Vec { - let mut body = mask.to_le_bytes().to_vec(); - for v in values { - body.extend_from_slice(&v.to_le_bytes()); - } - body - } - - fn kbctrl_header() -> RequestHeader { - RequestHeader { - opcode: 102, - data: 0, - length_units: 2, - } - } - - #[test] - fn change_keyboard_control_stores_bell_fields() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - // key-click(0x01)=30, bell-percent(0x02)=80, bell-pitch(0x04)=528, - // bell-duration(0x08)=200 - let body = kbctrl_body(0x0f, &[30, 80, 528, 200]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - assert_eq!(state.keyboard_control.key_click_percent, 30); - assert_eq!(state.keyboard_control.bell_percent, 80); - assert_eq!(state.keyboard_control.bell_pitch, 528); - assert_eq!(state.keyboard_control.bell_duration, 200); - } - - #[test] - fn change_keyboard_control_minus_one_restores_defaults() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - state.keyboard_control.bell_percent = 7; - state.keyboard_control.bell_pitch = 7; - let neg1 = 0xffff_ffffu32; - let body = kbctrl_body(0x0f, &[neg1, neg1, neg1, neg1]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - assert_eq!(state.keyboard_control.key_click_percent, 0); - assert_eq!(state.keyboard_control.bell_percent, 50); - assert_eq!(state.keyboard_control.bell_pitch, 400); - assert_eq!(state.keyboard_control.bell_duration, 100); - } - - #[test] - fn change_keyboard_control_led_without_mode_is_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // led(0x10)=3 without led-mode(0x20) → BadMatch (Xorg - // dix/devices.c:2121). - let body = kbctrl_body(0x10, &[3]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_MATCH); - } - - #[test] - fn change_keyboard_control_key_without_repeat_mode_is_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // key(0x40)=64 without auto-repeat-mode(0x80) → BadMatch - // (Xorg dix/devices.c:2158). - let body = kbctrl_body(0x40, &[64]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_MATCH); - } - - #[test] - fn change_keyboard_control_led_mask_bits() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - // led-mode On for leds 1, 20, 32 → bits 0, 19, 31. - for led in [1u32, 20, 32] { - let body = kbctrl_body(0x30, &[led, 1]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - } - assert_eq!(state.keyboard_control.led_mask, 0x8008_0001); - // led-mode Off with no led → all off. - let body = kbctrl_body(0x20, &[0]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - assert_eq!(state.keyboard_control.led_mask, 0); - } - - #[test] - fn change_keyboard_control_per_key_and_global_auto_repeat() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - // key=64 auto-repeat-mode=Off → clear bit (64>>3=8, bit 0). - let body = kbctrl_body(0xc0, &[64, 0]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - assert_eq!(state.keyboard_control.auto_repeats[8] & 0x01, 0); - // global auto-repeat Off (no key). - let body = kbctrl_body(0x80, &[0]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - assert!(!state.keyboard_control.global_auto_repeat); - } - - /// Xorg `DoChangeKeyboardControl` calls `XkbDisableComputedAutoRepeats` - /// for a per-key auto-repeat change: the key gets - /// `XkbExplicitAutoRepeatMask`, so a later mapping change leaves its bit - /// alone (`XkbUpdateDescActions`), while other keys' bits follow the - /// keymap and a change reports `XkbControlsNotify(PerKeyRepeat)`. - #[test] - fn per_key_auto_repeat_set_by_a_client_survives_a_mapping_change() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - crate::core_loop::xkb_select::xkb_select_events(&mut state, 1, 0x0100, 0x0008); - // key=64 auto-repeat-mode=On (already on by default). - let body = kbctrl_body(0xc0, &[64, 1]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - assert_eq!(state.keyboard_control.auto_repeats_explicit[8], 0x01); - let change = crate::backend::KeyboardMappingChange { - map_notify: x11::XkbMapNotify::default(), - num_groups: 1, - enabled_controls: 1, - repeats: vec![(64, false), (65, false)], - indicator_map_changed: 0, - indicator_state: 0, - compat_changed_groups: 0, - compat_total_si: 0, - }; - crate::core_loop::xkb_layout::apply_keyboard_mapping_repeats( - &mut state, - 85, - &change, - (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), - ); - assert_eq!( - state.keyboard_control.auto_repeats[8] & 0x03, - 0x01, - "64 keeps the client's bit, 65 follows the keymap" - ); - let ev = read_all_available(&mut peer); - assert_eq!(ev.len(), 32, "one ControlsNotify"); - assert_eq!((ev[0], ev[1]), (85, 3)); - assert_eq!(&ev[12..16], &0x4000_0000u32.to_le_bytes()); - - // Nothing changes: no event. - crate::core_loop::xkb_layout::apply_keyboard_mapping_repeats( - &mut state, - 85, - &change, - (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), - ); - assert!(read_all_available(&mut peer).is_empty()); - } - - /// SetModifierMapping through the dispatcher on a backend without an XKB - /// keymap (the fallback store); returns everything the client received. - fn set_modifier_mapping( - state: &mut ServerState, - peer: &mut UnixStream, - kpm: u8, - keys: &[u8], - ) -> Vec { - let mut backend = RecordingBackend::new(); - process_request( - state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 118, - data: kpm, - length_units: u32::try_from(1 + keys.len() / 4).unwrap(), - }, - keys, - None, - ) - .expect("SetModifierMapping dispatch"); - read_all_or_buffered(state, 1, peer) - } - - /// Xorg `build_modmap_from_modkeymap`: a keycode listed twice is - /// BadValue with value 0 (golden `duplicate-keycode`), before the range - /// check; `check_modmap_change`: a keycode below 8 is BadValue with that - /// keycode, the lowest one (golden `keycode-out-of-range`). Nothing is - /// stored or notified. - #[test] - fn set_modifier_mapping_refusals_as_xorg() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let r = set_modifier_mapping(&mut state, &mut peer, 1, &[50, 0, 37, 0, 0, 0, 0, 50]); - assert_eq!(r.len(), 32); - assert_eq!((r[0], r[1]), (0, x11::error::BAD_VALUE), "{r:02x?}"); - assert_eq!(&r[4..8], &0u32.to_le_bytes(), "duplicate: value 0"); - - let r = set_modifier_mapping(&mut state, &mut peer, 1, &[50, 5, 37, 3, 0, 0, 0, 0]); - assert_eq!(r.len(), 32); - assert_eq!((r[0], r[1]), (0, x11::error::BAD_VALUE)); - assert_eq!(&r[4..8], &3u32.to_le_bytes(), "the lowest keycode below 8"); - assert_eq!(state.modifier_mapping_override, None); - } - - /// Xorg `check_modmap_change`: MappingBusy (reply status 1, nothing - /// applied, no MappingNotify) when a key of the new map is down or a key - /// of the old one is — golden `busy-held-key-changes`, - /// `busy-held-modifier-unchanged`, `busy-held-key-becomes-modifier`; a - /// held key that is in neither doesn't block (`held-nonmodifier- - /// unaffected`). Xorg's loop over the old modifiers stops before the - /// last keycode, so a held keycode 255 in the old map doesn't block. - #[test] - fn set_modifier_mapping_busy_as_xorg() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let old = [50u8, 0, 66, 0, 37, 0, 0, 255]; - let r = set_modifier_mapping(&mut state, &mut peer, 1, &old); - assert_eq!(r.len(), 64, "MappingNotify then the reply: {r:02x?}"); - assert_eq!(r[0] & 0x7f, 34); - assert_eq!((r[32], r[33]), (1, 0), "Success"); - - let press = |state: &mut ServerState, kc: u8, down: bool| { - if down { - state.keys_down[usize::from(kc >> 3)] |= 1 << (kc & 7); - } else { - state.keys_down[usize::from(kc >> 3)] &= !(1 << (kc & 7)); - } - }; - let new = [62u8, 0, 66, 0, 37, 0, 0, 0]; - // 50 held: an old modifier, not in the new map. - press(&mut state, 50, true); - let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); - assert_eq!(r.len(), 32, "only the reply: {r:02x?}"); - assert_eq!((r[0], r[1]), (1, 1), "MappingBusy"); - press(&mut state, 50, false); - // 62 held: a new modifier. - press(&mut state, 62, true); - let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); - assert_eq!((r.len(), r[1]), (32, 1), "MappingBusy"); - press(&mut state, 62, false); - assert_eq!(state.modifier_mapping_override, Some((1, old.to_vec()))); - // 38 held: neither. - press(&mut state, 38, true); - let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); - assert_eq!((r.len(), r[33]), (64, 0), "applied"); - press(&mut state, 38, false); - - // 255 held and in the old map only: not checked by Xorg. - let with_255 = [62u8, 0, 66, 0, 37, 0, 0, 255]; - let _ = set_modifier_mapping(&mut state, &mut peer, 1, &with_255); - press(&mut state, 255, true); - let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); - assert_eq!((r.len(), r[33]), (64, 0), "held 255 doesn't block"); - assert_eq!(state.modifier_mapping_override, Some((1, new.to_vec()))); - } - - #[test] - fn change_keyboard_control_bad_value_does_not_commit() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // valid bell-percent(0x02)=80 staged, then key-click... order is - // mask-bit order: key-click(0x01)=101 (out of range) errors and - // nothing commits. - let body = kbctrl_body(0x03, &[101, 80]); - let _ = handle_change_keyboard_control( - &mut state, - ClientId(1), - SequenceNumber(1), - kbctrl_header(), - &body, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert_eq!( - u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), - 101 - ); - assert_eq!(state.keyboard_control.bell_percent, 50, "no partial commit"); - } - - #[test] - fn get_keyboard_control_reflects_state() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.keyboard_control.key_click_percent = 21; - state.keyboard_control.bell_percent = 12; - state.keyboard_control.bell_pitch = 402; - state.keyboard_control.bell_duration = 222; - state.keyboard_control.global_auto_repeat = false; - state.keyboard_control.led_mask = 0x8008_000f; - let _ = handle_get_keyboard_control(&mut state, ClientId(1), SequenceNumber(1)); - let bytes = read_all_available(&mut peer); - // reply(0) global_auto_repeat(1) seq(2-3) len(4-7) led_mask(8-11) - // key_click(12) bell_pct(13) bell_pitch(14-15) bell_duration(16-17) - assert_eq!(bytes[0], 1); - assert_eq!(bytes[1], 0, "global_auto_repeat off"); - assert_eq!( - u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]), - 0x8008_000f - ); - assert_eq!(bytes[12], 21); - assert_eq!(bytes[13], 12); - assert_eq!(u16::from_le_bytes([bytes[14], bytes[15]]), 402); - assert_eq!(u16::from_le_bytes([bytes[16], bytes[17]]), 222); - assert_eq!(&bytes[20..52], &crate::server::DEFAULT_AUTO_REPEATS); - } - - #[test] - fn bell_out_of_range_percent_is_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let header = RequestHeader { - opcode: 104, - data: 101u8, // percent=101 (and -101 = 155u8 also invalid) - length_units: 1, - }; - let _ = handle_bell(&mut state, ClientId(1), SequenceNumber(1), header); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - } - - #[test] - fn change_pointer_control_stores_and_restores() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let header = RequestHeader { - opcode: 105, - data: 0, - length_units: 3, - }; - // accel 12/11, threshold 43, do_accel=1 do_thresh=1 - let body = [12, 0, 11, 0, 43, 0, 1, 1]; - let _ = handle_change_pointer_control( - &mut state, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - assert_eq!(state.pointer_control.accel_numerator, 12); - assert_eq!(state.pointer_control.accel_denominator, 11); - assert_eq!(state.pointer_control.threshold, 43); - // -1 everywhere restores defaults 2/1, threshold 4. - let body = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, 1]; - let _ = handle_change_pointer_control( - &mut state, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - assert_eq!(state.pointer_control.accel_numerator, 2); - assert_eq!(state.pointer_control.accel_denominator, 1); - assert_eq!(state.pointer_control.threshold, 4); - } - - #[test] - fn change_pointer_control_zero_denominator_is_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let header = RequestHeader { - opcode: 105, - data: 0, - length_units: 3, - }; - // denominator 0 → BadValue (Xorg dix/devices.c:2362 `<= 0`). - let body = [2, 0, 0, 0, 4, 0, 1, 0]; - let _ = handle_change_pointer_control( - &mut state, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert_eq!( - state.pointer_control.accel_numerator, 2, - "no partial commit" - ); - } - - #[test] - fn get_pointer_control_reflects_state() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.pointer_control.accel_numerator = 34; - state.pointer_control.accel_denominator = 35; - state.pointer_control.threshold = 36; - let _ = handle_get_pointer_control(&mut state, ClientId(1), SequenceNumber(1)); - let bytes = read_all_available(&mut peer); - // reply(0) pad(1) seq(2-3) len(4-7) accel_num(8-9) accel_den(10-11) - // threshold(12-13) - assert_eq!(u16::from_le_bytes([bytes[8], bytes[9]]), 34); - assert_eq!(u16::from_le_bytes([bytes[10], bytes[11]]), 35); - assert_eq!(u16::from_le_bytes([bytes[12], bytes[13]]), 36); - } - - #[test] - fn get_screen_saver_reflects_current_state() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.screensaver.timeout_ms = 120_000; - state.screensaver.interval_ms = 240_000; - state.screensaver.prefer_blanking = false; - state.screensaver.allow_exposures = true; - let _ = handle_get_screen_saver(&mut state, ClientId(1), SequenceNumber(1)); - let bytes = read_all_available(&mut peer); - // Reply layout: tag(0) data(1) seq(2-3) length(4-7) timeout(8-9) - // interval(10-11) prefer(12) allow(13) pad to 32. - assert_eq!(bytes[0], 1, "reply tag"); - assert_eq!( - u16::from_le_bytes([bytes[8], bytes[9]]), - 120, - "timeout in s" - ); - assert_eq!( - u16::from_le_bytes([bytes[10], bytes[11]]), - 240, - "interval in s" - ); - assert_eq!(bytes[12], 0, "prefer_blanking = false"); - assert_eq!(bytes[13], 1, "allow_exposures = true"); - } - - #[test] - fn suspend_per_client_refcount_stacks() { - // Two Suspend(true) from the same client stacks the refcount. - // It takes two Suspend(false) calls to drain. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let true_body = [1u8, 0, 0, 0]; - let false_body = [0u8, 0, 0, 0]; - let header = RequestHeader { - opcode: 150, - data: x11screensaver::SUSPEND, - length_units: 2, - }; - - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &true_body, - ); - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(2), - header, - &true_body, - ); - assert!(state.screensaver_idle_deadline().is_none(), "suspended"); - assert_eq!( - state.screensaver.suspend_counts.get(&ClientId(1)).copied(), - Some(2) - ); - - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(3), - header, - &false_body, - ); - assert!( - state.screensaver_idle_deadline().is_none(), - "still suspended" - ); - - state.screensaver.timeout_ms = 60_000; // arm the timer - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(4), - header, - &false_body, - ); - assert!(state.screensaver_idle_deadline().is_some(), "drained"); - assert!(!state.screensaver.suspend_counts.contains_key(&ClientId(1))); - } - - #[test] - fn suspend_release_last_resets_last_activity_when_screensaver_off_and_dpms_on() { - use std::time::Duration; - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - state.screensaver.timeout_ms = 60_000; - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); - let stale = state.dpms.last_activity; - state.screensaver.suspend_counts.insert(ClientId(1), 1); - let mut backend = RecordingBackend::new(); - - let header = RequestHeader { - opcode: 150, - data: x11screensaver::SUSPEND, - length_units: 2, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[0u8, 0, 0, 0], - ); - - assert!( - state.dpms.last_activity > stale, - "last_activity must advance" - ); - } - - #[test] - fn force_screen_saver_activate_still_works_while_suspended() { - // Xorg saver.c: "suspending it (by design) doesn't prevent it - // from being forcibly activated". - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - state.screensaver.suspend_counts.insert(ClientId(2), 1); - let mut backend = RecordingBackend::new(); - - let header = RequestHeader { - opcode: 115, - data: 1, - length_units: 1, - }; // Activate - let _ = handle_force_screen_saver( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - ); - - assert_eq!(state.screensaver.active, ScreenSaverActive::On); - } - - #[test] - fn screen_saver_query_version_returns_one_one() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::QUERY_VERSION, - length_units: 2, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[1, 1, 0, 0], - ); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 1, "reply tag"); - assert_eq!( - u16::from_le_bytes([bytes[8], bytes[9]]), - x11screensaver::SERVER_MAJOR_VERSION - ); - assert_eq!( - u16::from_le_bytes([bytes[10], bytes[11]]), - x11screensaver::SERVER_MINOR_VERSION - ); - } - - #[test] - fn screen_saver_query_info_returns_disabled_when_timeout_zero() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.screensaver.timeout_ms = 0; - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::QUERY_INFO, - length_units: 2, - }; - let drawable = ROOT_WINDOW.0.to_le_bytes(); - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &drawable, - ); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11screensaver::SCREEN_SAVER_DISABLED); - assert_eq!( - u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]), - 0, - "window field is always 0 (no SetAttributes path)" - ); - assert_eq!( - u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]), - 0, - "til_or_since = 0 in Disabled" - ); - assert_eq!( - bytes[24], - x11screensaver::SCREEN_SAVER_BLANKED, - "kind = Blanked (prefer_blanking default true)" - ); - } - - #[test] - fn screen_saver_query_info_off_carries_til_remaining_and_caller_mask() { - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let _ = install_client(&mut state, 2); // other subscriber; must not influence reply - state.screensaver.timeout_ms = 60_000; - state.dpms.last_activity = std::time::Instant::now() - Duration::from_millis(20_000); - state - .screensaver - .selected_by - .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); - state - .screensaver - .selected_by - .insert(ClientId(2), x11screensaver::SCREEN_SAVER_CYCLE_MASK); - let mut backend = RecordingBackend::new(); - - let header = RequestHeader { - opcode: 150, - data: x11screensaver::QUERY_INFO, - length_units: 2, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &ROOT_WINDOW.0.to_le_bytes(), - ); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11screensaver::SCREEN_SAVER_OFF, "state Off"); - let til = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); - assert!( - til > 30_000 && til <= 40_000, - "til_remaining ≈ 60_000 - idle(~20_000); got {til}" - ); - let idle = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]); - assert!( - (19_000..=30_000).contains(&idle), - "idle≈20_000ms (slack for test scheduling); got {idle}" - ); - let mask = u32::from_le_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]); - assert_eq!( - mask, - x11screensaver::SCREEN_SAVER_NOTIFY_MASK, - "event_mask is caller's only, not union with client 2" - ); - } - - #[test] - fn screen_saver_query_info_on_state_uses_til_since_underflow_when_idle_lt_timeout() { - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.screensaver.active = ScreenSaverActive::On; - state.screensaver.timeout_ms = 60_000; - state.dpms.last_activity = std::time::Instant::now() - Duration::from_millis(5_000); - let mut backend = RecordingBackend::new(); - - let header = RequestHeader { - opcode: 150, - data: x11screensaver::QUERY_INFO, - length_units: 2, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &ROOT_WINDOW.0.to_le_bytes(), - ); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11screensaver::SCREEN_SAVER_ON); - let til = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); - assert!( - til > 0xff00_0000, - "underflow wrap expected when idle < timeout; got 0x{til:08x}" - ); - } - - #[test] - fn screen_saver_query_info_kind_reflects_prefer_blanking() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.screensaver.prefer_blanking = false; - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::QUERY_INFO, - length_units: 2, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &ROOT_WINDOW.0.to_le_bytes(), - ); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[24], x11screensaver::SCREEN_SAVER_INTERNAL); - } - - #[test] - fn screen_saver_select_input_accepts_unknown_mask_bits() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::SELECT_INPUT, - length_units: 3, - }; - let mut body = Vec::new(); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&0x0000_0004u32.to_le_bytes()); - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let bytes = read_all_available(&mut peer); - assert!(bytes.is_empty(), "SelectInput has no reply on success"); - assert_eq!( - state.screensaver.selected_by.get(&ClientId(1)).copied(), - Some(0x04) - ); - - apply_screen_saver_transition( - &mut state, - &mut backend, - ScreenSaverActive::On, - /*forced=*/ false, - ); - let bytes2 = read_all_available(&mut peer); - assert!( - !bytes2.contains(&92), - "client without NOTIFY_MASK bit must not receive notify" - ); - } - - #[test] - fn screen_saver_set_attributes_returns_bad_access() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::SET_ATTRIBUTES, - length_units: 4, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[0u8; 12], - ); - - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[0], 0, "error reply"); - assert_eq!(bytes[1], x11::error::BAD_ACCESS); - } - - #[test] - fn screen_saver_unset_attributes_returns_success_noop() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::UNSET_ATTRIBUTES, - length_units: 2, - }; - let drawable = ROOT_WINDOW.0.to_le_bytes(); - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &drawable, - ); - - let bytes = read_all_available(&mut peer); - assert!(bytes.is_empty(), "UnsetAttributes must be a silent no-op"); - } - - #[test] - fn cycle_event_delivered_only_to_cycle_mask_subscribers() { - // Two clients: A subscribed with NOTIFY_MASK, B with CYCLE_MASK. - // After SS goes Active and we fire a Cycle event, only B sees it. - let mut state = ServerState::new(); - let mut peer_a = install_client(&mut state, 1); - let mut peer_b = install_client(&mut state, 2); - state - .screensaver - .selected_by - .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); - state - .screensaver - .selected_by - .insert(ClientId(2), x11screensaver::SCREEN_SAVER_CYCLE_MASK); - let mut backend = RecordingBackend::new(); - - apply_screen_saver_transition( - &mut state, - &mut backend, - ScreenSaverActive::On, - /*forced=*/ false, - ); - // A received the activation Notify; drain so the next read is clean. - let _ = read_all_available(&mut peer_a); - // B was NOT a NOTIFY subscriber; it should have received nothing yet. - assert!(read_all_available(&mut peer_b).is_empty()); - - emit_screen_saver_notify(&mut state, ScreenSaverActive::Cycle, /*forced=*/ false); - assert!( - read_all_available(&mut peer_a).is_empty(), - "Cycle must NOT deliver to NOTIFY_MASK subscriber" - ); - let b = read_all_available(&mut peer_b); - let idx = b.iter().position(|&x| x == 92).expect("B receives Cycle"); - assert_eq!(b[idx + 1], x11screensaver::SCREEN_SAVER_CYCLE); - } - - /// Read the XSync i64 counter value from a QueryCounter reply. - /// Protocol encoding: hi(INT32 LE at bytes[8..12]) || lo(CARD32 LE at - /// bytes[12..16]) — NOT a raw 8-byte little-endian integer. - fn read_query_counter_reply_value(bytes: &[u8]) -> i64 { - let hi = i32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]); - let lo = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); - (i64::from(hi) << 32) | i64::from(lo) - } - - #[test] - fn query_counter_idletime_returns_elapsed_since_last_activity_not_uptime() { - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(30); - - let header = RequestHeader { - opcode: 142, - data: x11sync::QUERY_COUNTER, - length_units: 2, - }; - let body = x11sync::IDLETIME_COUNTER.to_le_bytes(); - let _ = handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let bytes = read_all_available(&mut peer); - // QueryCounter reply: tag(1) data(1) seq(2) length(4) value:i64(8) pad(16) - assert_eq!(bytes[0], 1, "reply tag"); - let value = read_query_counter_reply_value(&bytes); - assert!( - (29_000..=35_000).contains(&value), - "IDLETIME ≈ 30_000ms ± scheduling slack; got {value}" - ); - } - - #[test] - fn query_counter_idletime_device_vcp_uses_per_device_baseline() { - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Global was idle 60s ago, but the pointer device is fresh. - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(60); - state.per_device_last_activity.insert( - 2, /* VCP */ - std::time::Instant::now() - Duration::from_millis(500), - ); - - let header = RequestHeader { - opcode: 142, - data: x11sync::QUERY_COUNTER, - length_units: 2, - }; - let body = x11sync::IDLETIME_DEVICE_VCP.to_le_bytes(); - let _ = handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let bytes = read_all_available(&mut peer); - let value = read_query_counter_reply_value(&bytes); - assert!( - (400..=5_000).contains(&value), - "VCP IDLETIME ≈ 500ms; got {value}" - ); - } - - #[test] - fn query_counter_idletime_device_vck_uses_per_device_baseline() { - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(60); - state.per_device_last_activity.insert( - 3, /* VCK */ - std::time::Instant::now() - Duration::from_millis(200), - ); - - let header = RequestHeader { - opcode: 142, - data: x11sync::QUERY_COUNTER, - length_units: 2, - }; - let body = x11sync::IDLETIME_DEVICE_VCK.to_le_bytes(); - let _ = handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let bytes = read_all_available(&mut peer); - let value = read_query_counter_reply_value(&bytes); - assert!( - (100..=3_000).contains(&value), - "VCK IDLETIME ≈ 200ms; got {value}" - ); - } - - #[test] - fn evaluate_alarms_positive_transition_with_delta_zero_stays_active() { - // Regression: Xorg sync.c:548-555 — only delta=0 + Comparison - // goes Inactive. Transitions with delta=0 must stay Active so - // the next crossing re-fires. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let counter = 0x1000; - state.sync_counters.insert( - counter, - crate::server::SyncCounter { - owner: ClientId(1), - value: 0, - }, - ); - let alarm_id = 0x2000; - state.sync_alarms.insert( - alarm_id, - crate::server::SyncAlarm { - owner: ClientId(1), - counter, - wait_value: 100, - delta: 0, - test_type: x11sync::TEST_POSITIVE_TRANSITION, - events: true, - state: x11sync::ALARM_STATE_ACTIVE, - event_clients: Vec::new(), - value_type: 0, - raw_wait: 100, - check_type: x11sync::TEST_POSITIVE_TRANSITION, - }, - ); - - // Counter transition from 50 → 150 crosses the trigger. - evaluate_alarms_for_counter(&mut state, counter, 50, 150); - - let after = &state.sync_alarms[&alarm_id]; - assert_eq!( - after.state, - x11sync::ALARM_STATE_ACTIVE, - "PositiveTransition + delta=0 must stay Active (Xorg sync.c:548-555)" - ); - assert_eq!( - after.wait_value, 100, - "wait_value unchanged for delta=0 Transition" - ); - } - - #[test] - fn evaluate_alarms_positive_comparison_with_delta_zero_goes_inactive() { - // Companion test: PositiveComparison + delta=0 SHOULD go Inactive. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let counter = 0x1000; - state.sync_counters.insert( - counter, - crate::server::SyncCounter { - owner: ClientId(1), - value: 0, - }, - ); - let alarm_id = 0x2000; - state.sync_alarms.insert( - alarm_id, - crate::server::SyncAlarm { - owner: ClientId(1), - counter, - wait_value: 100, - delta: 0, - test_type: x11sync::TEST_POSITIVE_COMPARISON, - events: true, - state: x11sync::ALARM_STATE_ACTIVE, - event_clients: Vec::new(), - value_type: 0, - raw_wait: 100, - check_type: x11sync::TEST_POSITIVE_COMPARISON, - }, - ); - - evaluate_alarms_for_counter(&mut state, counter, 50, 150); - - let after = &state.sync_alarms[&alarm_id]; - assert_eq!(after.state, x11sync::ALARM_STATE_INACTIVE); - } - - #[test] - fn evaluate_alarms_re_arm_overflow_transitions_alarm_to_inactive() { - // Xorg sync.c:589-597 — re-arm overflow on i64::checked_add - // must transition the alarm to Inactive and leave wait_value - // unchanged. - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let counter = 0x1000; - state.sync_counters.insert( - counter, - crate::server::SyncCounter { - owner: ClientId(1), - value: 0, - }, - ); - let alarm_id = 0x2000; - // Start near i64::MAX so adding delta overflows on the very - // first re-arm step. Use PositiveTransition so the trigger fires - // when new >= wait_value. - let near_max = i64::MAX - 10; - state.sync_alarms.insert( - alarm_id, - crate::server::SyncAlarm { - owner: ClientId(1), - counter, - wait_value: near_max, - delta: 100, // would overflow on first add - test_type: x11sync::TEST_POSITIVE_TRANSITION, - events: true, - state: x11sync::ALARM_STATE_ACTIVE, - event_clients: Vec::new(), - value_type: 0, - raw_wait: near_max, - check_type: x11sync::TEST_POSITIVE_TRANSITION, - }, - ); - - // Crossing: old < wait_value, new >= wait_value → trigger fires. - evaluate_alarms_for_counter(&mut state, counter, near_max - 1, near_max + 5); - - let after = &state.sync_alarms[&alarm_id]; - assert_eq!( - after.state, - x11sync::ALARM_STATE_INACTIVE, - "overflow on re-arm → Inactive" - ); - assert_eq!( - after.wait_value, near_max, - "wait_value unchanged on overflow (Xorg sync.c:589-597)" - ); - } - - /// Encode an INT64 value in XSync wire format: hi(INT32 LE) || lo(CARD32 LE). - /// This is NOT the same as `i64::to_le_bytes()` (which is lo-first). - fn xsync_i64(v: i64) -> [u8; 8] { - #[allow(clippy::cast_possible_truncation)] - let hi = (v >> 32) as i32; - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let lo = v as u32; - let mut out = [0u8; 8]; - out[..4].copy_from_slice(&hi.to_le_bytes()); - out[4..].copy_from_slice(&lo.to_le_bytes()); - out - } - - #[test] - fn relative_alarm_value_on_idletime_resolves_against_current_idle() { - use std::time::Duration; - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Pre-condition: already idle 5s. - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(5); - - // CreateAlarm relative-value=10_000 → wait_value should resolve - // to current_idle (~5_000) + 10_000 = ~15_000. - let alarm_id: u32 = 0x2000_0002; - let mut body = Vec::new(); - body.extend_from_slice(&alarm_id.to_le_bytes()); - let mask: u32 = x11sync::CA_COUNTER - | x11sync::CA_VALUE_TYPE - | x11sync::CA_VALUE - | x11sync::CA_TEST_TYPE - | x11sync::CA_DELTA - | x11sync::CA_EVENTS; - body.extend_from_slice(&mask.to_le_bytes()); - body.extend_from_slice(&x11sync::IDLETIME_COUNTER.to_le_bytes()); - body.extend_from_slice(&x11sync::VALUE_TYPE_RELATIVE.to_le_bytes()); // u32 - body.extend_from_slice(&xsync_i64(10_000)); // value = 10_000 relative - body.extend_from_slice(&x11sync::TEST_POSITIVE_TRANSITION.to_le_bytes()); - body.extend_from_slice(&xsync_i64(0)); // delta = 0 - body.push(1); // events = true - body.extend_from_slice(&[0u8; 3]); - - let header = RequestHeader { - opcode: 142, - data: x11sync::CREATE_ALARM, - length_units: u32::try_from(2 + body.len() / 4).unwrap(), - }; - let _ = handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let alarm = state.sync_alarms.get(&alarm_id).expect("alarm exists"); - assert!( - alarm.wait_value >= 14_500 && alarm.wait_value <= 16_000, - "wait_value ≈ current_idle(5000) + 10000 = 15000; got {}", - alarm.wait_value - ); - } - - #[test] - fn create_alarm_on_idletime_with_comparison_already_true_fires_immediately() { - // Xorg sync.c:1772-1775 — create-time trigger eval passes - // (old=current, new=current). PositiveTransition requires - // `old < wait <= new` so it cannot fire on a same-value pair; - // only Comparison test types can fire at create time. - // PositiveComparison fires when `new >= wait`, which is - // exactly the "client opens an alarm while user is already - // idle past the threshold" smoke we want to verify. - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Pre-condition: already idle past the alarm threshold. - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); - - let alarm_id: u32 = 0x2000_0001; - let mut body = Vec::new(); - body.extend_from_slice(&alarm_id.to_le_bytes()); - let mask: u32 = x11sync::CA_COUNTER - | x11sync::CA_VALUE_TYPE - | x11sync::CA_VALUE - | x11sync::CA_TEST_TYPE - | x11sync::CA_DELTA - | x11sync::CA_EVENTS; - body.extend_from_slice(&mask.to_le_bytes()); - body.extend_from_slice(&x11sync::IDLETIME_COUNTER.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // value_type = Absolute - body.extend_from_slice(&xsync_i64(60_000)); // value = 60_000 - body.extend_from_slice(&x11sync::TEST_POSITIVE_COMPARISON.to_le_bytes()); - body.extend_from_slice(&xsync_i64(0)); // delta = 0 → goes Inactive on fire - body.push(1); // events = true - body.extend_from_slice(&[0u8; 3]); - - let header = RequestHeader { - opcode: 142, - data: x11sync::CREATE_ALARM, - length_units: u32::try_from(2 + body.len() / 4).unwrap(), - }; - let _ = handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let bytes = read_all_available(&mut peer); - // AlarmNotify event: type = SYNC_FIRST_EVENT(83) + ALARM_NOTIFY_KIND(1) = 84 - assert!( - bytes.contains(&84), - "AlarmNotify must fire at create-time for an already-idle PositiveComparison alarm; got {:?}", - bytes - ); - // Comparison + delta=0 transitions to Inactive on fire. - assert_eq!( - state.sync_alarms[&alarm_id].state, - x11sync::ALARM_STATE_INACTIVE - ); - } - - #[test] - fn create_alarm_on_idletime_with_pos_transition_does_not_fire_at_create() { - // Companion test: PositiveTransition cannot fire at create-time - // (Xorg sync.c:1772-1775 — old==new). The alarm sits Active - // waiting for the post-poll evaluator or input wake to drive - // the (old, new) pair across the threshold. - use std::time::Duration; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); - - let alarm_id: u32 = 0x2000_0003; - let mut body = Vec::new(); - body.extend_from_slice(&alarm_id.to_le_bytes()); - let mask: u32 = x11sync::CA_COUNTER - | x11sync::CA_VALUE_TYPE - | x11sync::CA_VALUE - | x11sync::CA_TEST_TYPE - | x11sync::CA_DELTA - | x11sync::CA_EVENTS; - body.extend_from_slice(&mask.to_le_bytes()); - body.extend_from_slice(&x11sync::IDLETIME_COUNTER.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&xsync_i64(60_000)); - body.extend_from_slice(&x11sync::TEST_POSITIVE_TRANSITION.to_le_bytes()); - body.extend_from_slice(&xsync_i64(0)); - body.push(1); - body.extend_from_slice(&[0u8; 3]); - - let header = RequestHeader { - opcode: 142, - data: x11sync::CREATE_ALARM, - length_units: u32::try_from(2 + body.len() / 4).unwrap(), - }; - let _ = handle_sync_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &body, - ); - - let bytes = read_all_available(&mut peer); - assert!( - !bytes.contains(&84), - "PositiveTransition with old==new at create-time must not fire" - ); - assert_eq!( - state.sync_alarms[&alarm_id].state, - x11sync::ALARM_STATE_ACTIVE, - "alarm stays Active, waiting for evaluator/input to drive the transition" - ); - } - - #[test] - fn suspend_release_resets_idletime_last_evaluated_and_per_device_baselines() { - use std::time::Duration; - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - // Pre-seed: stale idletime cache from before suspend. - state - .idletime_last_evaluated - .insert(x11sync::IDLETIME_COUNTER, 999_999); - state - .per_device_last_activity - .insert(3, std::time::Instant::now() - Duration::from_secs(120)); - - // Insert a suspending client, then drain via Suspend(false). - state.screensaver.suspend_counts.insert(ClientId(1), 1); - let header = RequestHeader { - opcode: 150, - data: x11screensaver::SUSPEND, - length_units: 2, - }; - let _ = handle_screen_saver_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(1), - header, - &[0u8, 0, 0, 0], - ); - - // The drain hit the (drained && empty && SS=Off && DPMS=On) guard - // and must have reset both IDLETIME bookkeeping fields. - assert!( - state.idletime_last_evaluated.is_empty(), - "idletime_last_evaluated must be cleared on suspend release" - ); - let vck_baseline = state - .per_device_last_activity - .get(&3) - .copied() - .expect("per_device_last_activity[3] still present"); - let elapsed = std::time::Instant::now().duration_since(vck_baseline); - assert!( - elapsed < Duration::from_millis(100), - "per_device_last_activity[3] must be reset to ~now; got elapsed {elapsed:?}" - ); - } - - /// Per X11 spec (Xorg `dix/enterleave.c:606` → - /// `CoreEnterLeaveEvents` → `CoreEnterNotifies` → - /// `DeliverEventsToWindow`): grab-activation crossing events - /// flow through the normal event-delivery path, which filters - /// by the client's per-window event-mask selection. xts's - /// `GrabPointer` test opens a fresh connection, creates a - /// grab window WITHOUT selecting `EnterWindowMask` (0x10), and - /// expects the next thing on the wire after sending GrabPointer - /// to be the reply (opcode 1). Pre-fix yserver's - /// `emit_core_grab_activation_crossings` fanned `EnterNotify` - /// (event type 7) unconditionally to the grabber via - /// `fanout_event_to_clients(&[client_id], …)` regardless of - /// mask, so the event landed on the wire BEFORE the reply - /// and the test reported `wanted REPLY - X_GrabPointer , got - /// EVENT - EnterNotify` (xts Xproto run 2026-05-31-11:13:07: - /// 1 FAIL on `GrabPointer` + 1 FAIL on `GrabKeyboard` + 8 - /// UNRESOLVED on `AllowEvents` / `ChangeActivePointerGrab`). - /// Marco / GTK3 popups still receive the crossings because - /// they select `EnterWindowMask` on their popup windows. - #[test] - fn grab_pointer_skips_synthesised_crossing_when_mask_unselected() { - const CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x100_0007; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - // Create the grab window WITHOUT EnterWindowMask selected - // (mirrors xts's fresh CreateWindow). - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - - // GrabPointer body: window(4) event-mask(2) pointer-mode(1) - // keyboard-mode(1) confine-to(4) cursor(4) time(4) = 20. - // event-mask=0, modes async, confine_to=None, cursor=None, - // time=CurrentTime. - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&GRAB_WIN.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); // event-mask - body.push(0); // pointer-mode async - body.push(0); // keyboard-mode async - body.extend_from_slice(&0u32.to_le_bytes()); // confine-to None - body.extend_from_slice(&0u32.to_le_bytes()); // cursor None - body.extend_from_slice(&0u32.to_le_bytes()); // time CurrentTime - - handle_grab_pointer( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(11), - RequestHeader { - opcode: 26, - data: 0, // owner_events false - length_units: 6, - }, - &body, - ) - .expect("handle_grab_pointer"); - - peer.set_nonblocking(true).unwrap(); - let mut tmp = [0u8; 1024]; - let mut wire = Vec::new(); - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - // First 32-byte chunk must be the reply (opcode 1), NOT an - // EnterNotify (event type 7). - assert!( - wire.len() >= 32, - "GrabPointer must produce at least the reply on the wire", - ); - assert_ne!( - wire[0] & 0x7f, - 7, - "Pre-fix: EnterNotify (type 7) landed on the wire before \ - the GrabPointer reply because crossings were unconditionally \ - fanned to the grabber regardless of EnterWindowMask. xts \ - reports this as `wanted REPLY - X_GrabPointer , got EVENT - \ - EnterNotify` and marks dependent tests UNRESOLVED.", - ); - assert_eq!( - wire[0], 1, - "GrabPointer must put the reply (opcode 1) first on the wire \ - when the grabber has not selected EnterWindowMask", - ); - // No EnterNotify anywhere — the grabber didn't select it. - let enter_notifies = wire.chunks_exact(32).filter(|c| c[0] & 0x7f == 7).count(); - assert_eq!( - enter_notifies, 0, - "EnterNotify must not be delivered to a grabber that didn't \ - select EnterWindowMask on the grab window", - ); - } - - /// Positive companion to the test above: when the grabber HAS - /// selected `EnterWindowMask` on the grab window (the - /// marco / GTK3 popup-menu pattern), the synthesised crossing - /// must still fire. The grab fix is "respect the event-mask - /// filter", not "drop crossings entirely". - #[test] - fn grab_pointer_emits_crossing_when_grabber_selected_enter_mask() { - const CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x100_0008; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - // marco/GTK3 popup pattern: the pointer is over the panel (the - // root here), NOT over the popup being grabbed — grab - // activation must emit Enter(NotifyGrab) on the popup for - // GTK3's hover machinery. (With the pointer already inside the - // grab window Xorg emits nothing: DoEnterLeaveEvents from==to.) - state.pointer_root = (500, 500); - state - .clients - .get_mut(&CLIENT_ID) - .unwrap() - .event_masks - .insert(ResourceId(GRAB_WIN), 0x10); - - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&GRAB_WIN.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); - body.push(0); - body.push(0); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - - handle_grab_pointer( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(13), - RequestHeader { - opcode: 26, - data: 0, - length_units: 6, - }, - &body, - ) - .expect("handle_grab_pointer"); - - peer.set_nonblocking(true).unwrap(); - let mut tmp = [0u8; 1024]; - let mut wire = Vec::new(); - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - let enter_notifies = wire.chunks_exact(32).filter(|c| c[0] & 0x7f == 7).count(); - assert!( - enter_notifies >= 1, - "EnterNotify must still fire to a grabber that selected \ - EnterWindowMask (marco/GTK3 popup-menu pattern)", - ); - } - - /// Symmetric to the activation test: xts case 116 - /// (`pUngrabPointer-1.(A)`) opens a connection with NO event - /// mask selected, grabs+ungrabs, and verifies the server - /// sends NOTHING. Pre-fix `emit_core_grab_deactivation_crossing` - /// fanned `LeaveNotify` unconditionally to the ungrabber; the - /// test reported `wanted NOTHING, got EVENT - LeaveNotify`. - /// Mirror fix: the deactivation crossing must respect - /// `LeaveWindowMask` (0x20) on the prior grab window. - #[test] - fn ungrab_pointer_skips_synthesised_leave_when_mask_unselected() { - const CLIENT_ID: u32 = 1; - const GRAB_WIN: u32 = 0x100_0009; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(CLIENT_ID), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(GRAB_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(GRAB_WIN)); - - // Seed an active grab so handle_ungrab_pointer has - // something to deactivate (mirrors xts's GrabPointer → - // UngrabPointer sequence). - state.active_pointer_grab = Some(crate::server::ActivePointerGrab { - owner: ClientId(CLIENT_ID), - grab_window: ResourceId(GRAB_WIN), - event_mask: 0, - cursor: ResourceId(0), - time: 0, - owner_events: false, - via_xi2: false, - implicit: false, - passive: false, - xi2_mask: 0, - }); - - handle_ungrab_pointer( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(17), - &[0u8; 4], - ) - .expect("handle_ungrab_pointer"); - - peer.set_nonblocking(true).unwrap(); - let mut tmp = [0u8; 1024]; - let mut wire = Vec::new(); - loop { - match peer.read(&mut tmp) { - Ok(0) => break, - Ok(n) => wire.extend_from_slice(&tmp[..n]), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, - Err(_) => break, - } - } - let leave_notifies = wire.chunks_exact(32).filter(|c| c[0] & 0x7f == 8).count(); - assert_eq!( - leave_notifies, 0, - "UngrabPointer from a client that did not select \ - LeaveWindowMask must not produce a LeaveNotify on the \ - wire (xts case 116 / `pUngrabPointer-1.(A)`)", - ); - assert!( - wire.is_empty(), - "UngrabPointer with no event mask selected must produce \ - NOTHING on the wire; got {} bytes: {:?}", - wire.len(), - &wire[..wire.len().min(64)], - ); - } - - /// xts5 Xlib4 (`EWin.mc`) creates a window, destroys it, then - /// invokes each window-manipulation request on the freed xid and - /// expects a `BadWindow` protocol error back. Before this fix, - /// every handler silently returned `RequestOutcome::Handled`, - /// causing ~24 FAILs across the Xlib4 cluster - /// (`Got Success, Expecting BadWindow`). - /// - /// One test per affected handler so a regression names the - /// specific request rather than a single bundled failure. - #[test] - fn window_handlers_on_freed_xid_return_bad_window() { - use std::io::Read; - const APP: u32 = 200; - const BAD: u32 = 0x0080_dead; - - // (opcode, header.data, body, label, requires_body_len) - let cases: &[(u8, u8, Vec, &str)] = &[ - ( - 1, - 24, - create_window_body_with_parent(BAD), - "CreateWindow(parent)", - ), - ( - 2, - 0, - change_window_attributes_body(BAD), - "ChangeWindowAttributes", - ), - (4, 0, BAD.to_le_bytes().to_vec(), "DestroyWindow"), - (5, 0, BAD.to_le_bytes().to_vec(), "DestroySubwindows"), - (8, 0, BAD.to_le_bytes().to_vec(), "MapWindow"), - (9, 0, BAD.to_le_bytes().to_vec(), "MapSubwindows"), - (10, 0, BAD.to_le_bytes().to_vec(), "UnmapWindow"), - (11, 0, BAD.to_le_bytes().to_vec(), "UnmapSubwindows"), - (12, 0, configure_window_body(BAD), "ConfigureWindow"), - (13, 0, BAD.to_le_bytes().to_vec(), "CirculateWindow"), - ]; - - for (i, (opcode, data, body, label)) in cases.iter().enumerate() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP + i as u32); - let mut backend = RecordingBackend::new(); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body length fits"); - let seq = SequenceNumber((i + 1) as u16); - process_request( - &mut state, - &mut backend, - ClientId(APP + i as u32), - seq, - RequestHeader { - opcode: *opcode, - data: *data, - length_units, - }, - body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap_or_else(|e| { - panic!("{label}: expected 32-byte error reply, got {e:?}"); - }); - assert_eq!( - buf[0], 0, - "{label}: byte 0 = error class (0); got {}", - buf[0] - ); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_WINDOW, - "{label}: expected BadWindow (3) for freed xid; got error code {}", - buf[1], - ); - // bytes [4..8] = error_value (the bad xid) - let bad_value = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]); - assert_eq!( - bad_value, BAD, - "{label}: error_value must echo the freed window xid" - ); - // byte [10] = major_opcode (this is the request that errored) - assert_eq!( - buf[10], *opcode, - "{label}: BadWindow error must carry the request's \ - major opcode (expected {opcode}); got {}", - buf[10], - ); - } - } - - fn create_window_body_with_parent(parent_xid: u32) -> Vec { - // ProcCreateWindow body (header.data carries depth): - // wid u32, parent u32, x i16, y i16, width u16, height u16, - // border_width u16, class u16, visual u32, value_mask u32, … - // Use class=CopyFromParent(0), visual=CopyFromParent(0), no - // attributes — the parent BadWindow check fires first. - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&0x0080_0001u32.to_le_bytes()); // new wid (will not be used) - body.extend_from_slice(&parent_xid.to_le_bytes()); - body.extend_from_slice(&0i16.to_le_bytes()); // x - body.extend_from_slice(&0i16.to_le_bytes()); // y - body.extend_from_slice(&10u16.to_le_bytes()); // width - body.extend_from_slice(&10u16.to_le_bytes()); // height - body.extend_from_slice(&0u16.to_le_bytes()); // border_width - body.extend_from_slice(&0u16.to_le_bytes()); // class - body.extend_from_slice(&0u32.to_le_bytes()); // visual - body.extend_from_slice(&0u32.to_le_bytes()); // value_mask - body - } - - fn change_window_attributes_body(window_xid: u32) -> Vec { - // ProcChangeWindowAttributes body: window u32, value_mask u32, - // values… No values needed — the window BadWindow check - // fires before attribute application. - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&window_xid.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // value_mask - body - } - - fn configure_window_body(window_xid: u32) -> Vec { - // ProcConfigureWindow body: window u32, value_mask u16, pad - // u16, values… No values needed — BadWindow check fires - // before mask is read. - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&window_xid.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); // value_mask - body.extend_from_slice(&0u16.to_le_bytes()); // pad - body - } - - // ── Border attribute validation (#133, plan step 1.3 / 1.4) ──────── - - const CWA_BORDER_PIXMAP: u32 = 0x0004; - const CWA_BORDER_PIXEL: u32 = 0x0008; - - /// CreateWindow body with an explicit class/visual and a value list. - /// `depth` travels in `header.data`, not the body. - fn border_create_body(wid: u32, parent: u32, value_mask: u32, values: &[u32]) -> Vec { - let mut body = Vec::with_capacity(28 + values.len() * 4); - body.extend_from_slice(&wid.to_le_bytes()); - body.extend_from_slice(&parent.to_le_bytes()); - body.extend_from_slice(&0i16.to_le_bytes()); // x - body.extend_from_slice(&0i16.to_le_bytes()); // y - body.extend_from_slice(&10u16.to_le_bytes()); // width - body.extend_from_slice(&10u16.to_le_bytes()); // height - body.extend_from_slice(&0u16.to_le_bytes()); // border_width - body.extend_from_slice(&1u16.to_le_bytes()); // class = InputOutput - body.extend_from_slice(&0u32.to_le_bytes()); // visual = CopyFromParent - body.extend_from_slice(&value_mask.to_le_bytes()); - for v in values { - body.extend_from_slice(&v.to_le_bytes()); - } - body - } - - fn border_cwa_body(window: u32, value_mask: u32, values: &[u32]) -> Vec { - let mut body = Vec::with_capacity(8 + values.len() * 4); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&value_mask.to_le_bytes()); - for v in values { - body.extend_from_slice(&v.to_le_bytes()); - } - body - } - - fn run_border_request(state: &mut ServerState, opcode: u8, depth: u8, body: &[u8]) { - run_border_request_recording(state, opcode, depth, body); - } - - /// Same as `run_border_request` but hands back what the backend - /// saw, for the #133 step 2 (P3) forward-path assertions. - fn run_border_request_recording( - state: &mut ServerState, - opcode: u8, - depth: u8, - body: &[u8], - ) -> Vec { - let mut backend = RecordingBackend::new(); - process_request( - state, - &mut backend, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode, - data: depth, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - None, - ) - .expect("process_request"); - backend.calls() - } - - /// Pick the border-source forward out of a recorded call list. - fn border_forwards(calls: &[RecordedCall]) -> Vec<(u32, u32, Vec)> { - calls - .iter() - .filter_map(|c| match c { - RecordedCall::ChangeSubwindowAttributes { - host_xid, - value_mask, - values, - } if value_mask & (CWA_BORDER_PIXMAP | CWA_BORDER_PIXEL) != 0 => { - Some((*host_xid, *value_mask, values.clone())) - } - _ => None, - }) - .collect() - } - - fn assert_error_code(bytes: &[u8], expected: u8, what: &str) { - assert!( - bytes.len() >= 32, - "{what}: expected a 32-byte error reply, got {} bytes: {:02x?}", - bytes.len(), - bytes - ); - assert_eq!(bytes[0], 0, "{what}: expected an Error reply"); - assert_eq!(bytes[1], expected, "{what}: wrong error code"); - } - - fn assert_no_error(bytes: &[u8], what: &str) { - assert!( - bytes.is_empty() || bytes[0] != 0, - "{what}: expected no error, got {:02x?}", - bytes - ); - } - - /// Xorg `dix/window.c:818` — a depth that differs from the parent's - /// with NO border attribute is BadMatch, because the inherited border - /// (`:879`) would carry the parent's depth. This is why awesome sends - /// `border-pixel=0x00000000` on every depth-32 CreateWindow. - #[test] - fn create_window_depth_differs_without_border_attribute_is_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, 0, &[]); - run_border_request(&mut state, 1, 32, &body); - let bytes = read_all_available(&mut peer); - assert_error_code( - &bytes, - x11::error::BAD_MATCH, - "depth 32 under depth-24 parent", - ); - } - - /// The same request WITH `CWBorderPixel` is legal — the awesome - /// pattern. - #[test] - fn create_window_depth_differs_with_border_pixel_is_accepted() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, CWA_BORDER_PIXEL, &[0]); - run_border_request(&mut state, 1, 32, &body); - let bytes = read_all_available(&mut peer); - assert_no_error(&bytes, "depth 32 with border-pixel"); - assert!( - state.resources.window(ResourceId(0x0080_0001)).is_some(), - "window should have been created" - ); - } - - /// `CWBorderPixmap` = `CopyFromParent` (xid 0) requires matching - /// depths (`dix/window.c:1254`). - #[test] - fn create_window_border_pixmap_copy_from_parent_depth_mismatch_is_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, CWA_BORDER_PIXMAP, &[0]); - run_border_request(&mut state, 1, 32, &body); - let bytes = read_all_available(&mut peer); - assert_error_code( - &bytes, - x11::error::BAD_MATCH, - "CopyFromParent border across depths", - ); - } - - /// A border pixmap xid that names nothing is BadPixmap. - #[test] - fn create_window_border_pixmap_unknown_xid_is_bad_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let body = border_create_body( - 0x0080_0001, - ROOT_WINDOW.0, - CWA_BORDER_PIXMAP, - &[0x0099_9999], - ); - run_border_request(&mut state, 1, 24, &body); - let bytes = read_all_available(&mut peer); - assert_error_code(&bytes, x11::error::BAD_PIXMAP, "stale border pixmap"); - } - - /// A real border pixmap of the wrong depth is BadMatch - /// (`dix/window.c:1275`). - #[test] - fn create_window_border_pixmap_depth_mismatch_is_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: ResourceId(0x0080_1200), - drawable: ROOT_WINDOW, - width: 4, - height: 4, - depth: 1, - }, - ); - let body = border_create_body( - 0x0080_0001, - ROOT_WINDOW.0, - CWA_BORDER_PIXMAP, - &[0x0080_1200], - ); - run_border_request(&mut state, 1, 24, &body); - let bytes = read_all_available(&mut peer); - assert_error_code(&bytes, x11::error::BAD_MATCH, "depth-1 border on depth-24"); - } - - /// With both bits set the pixel wins and the pixmap is never - /// resolved — Xorg clears `CWBorderPixmap` from the mask before the - /// ddx layer sees it (`dix/window.c:1298`). So a bogus pixmap xid - /// alongside a pixel must NOT error. - #[test] - fn create_window_border_pixel_overrides_pixmap_and_skips_its_validation() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let body = border_create_body( - 0x0080_0001, - ROOT_WINDOW.0, - CWA_BORDER_PIXMAP | CWA_BORDER_PIXEL, - &[0x0099_9999, 0x00ff_0000], - ); - run_border_request(&mut state, 1, 24, &body); - let bytes = read_all_available(&mut peer); - assert_no_error(&bytes, "pixel overrides a bogus pixmap"); - assert_eq!( - state - .resources - .window(ResourceId(0x0080_0001)) - .map(|w| w.border), - Some(crate::resources::BorderSource::Pixel(0x00ff_0000)), - ); - } - - #[test] - fn change_window_attributes_border_pixmap_unknown_xid_is_bad_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_window(&mut state, ResourceId(0x0080_0001), ROOT_WINDOW, 10, 10); - let body = border_cwa_body(0x0080_0001, CWA_BORDER_PIXMAP, &[0x0099_9999]); - run_border_request(&mut state, 2, 0, &body); - let bytes = read_all_available(&mut peer); - assert_error_code(&bytes, x11::error::BAD_PIXMAP, "CWA stale border pixmap"); - } - - #[test] - fn change_window_attributes_border_pixmap_depth_mismatch_is_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_window(&mut state, ResourceId(0x0080_0001), ROOT_WINDOW, 10, 10); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: ResourceId(0x0080_1200), - drawable: ROOT_WINDOW, - width: 4, - height: 4, - depth: 1, - }, - ); - let body = border_cwa_body(0x0080_0001, CWA_BORDER_PIXMAP, &[0x0080_1200]); - run_border_request(&mut state, 2, 0, &body); - let bytes = read_all_available(&mut peer); - assert_error_code(&bytes, x11::error::BAD_MATCH, "CWA border depth mismatch"); - } - - /// The awesome request shape: a 16-byte CWA carrying ONLY - /// `CWBorderPixel`. Before #133 this parsed into a struct where every - /// field was `None` and did nothing. - #[test] - fn change_window_attributes_border_pixel_only_installs_the_pixel() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - seed_window(&mut state, ResourceId(0x0080_0001), ROOT_WINDOW, 10, 10); - let body = border_cwa_body(0x0080_0001, CWA_BORDER_PIXEL, &[0xffff_0000]); - run_border_request(&mut state, 2, 0, &body); - let bytes = read_all_available(&mut peer); - assert_no_error(&bytes, "CWA border-pixel only"); - assert_eq!( - state - .resources - .window(ResourceId(0x0080_0001)) - .map(|w| w.border), - Some(crate::resources::BorderSource::Pixel(0xffff_0000)), - ); - } - - /// #133 step 2 (P3) — THE test for the forward path. The awesome - /// request shape (a CWA carrying only `CWBorderPixel`) must reach - /// the backend as a `change_subwindow_attributes` with the real X11 - /// CW bit `0x08` and the pixel value. Before step 2 a border change - /// reached the backend by no route at all: the only CWA forward - /// fired on a background change. - #[test] - fn change_window_attributes_border_pixel_forwards_to_backend() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - let host_xid = state - .resources - .window(win) - .and_then(|w| w.host_xid) - .expect("seed_window assigns a host xid") - .as_raw(); - - let body = border_cwa_body(win.0, CWA_BORDER_PIXEL, &[0xffff_0000]); - let calls = run_border_request_recording(&mut state, 2, 0, &body); - assert_no_error(&read_all_available(&mut peer), "CWA border-pixel only"); - assert_eq!( - border_forwards(&calls), - vec![(host_xid, CWA_BORDER_PIXEL, vec![0xffff_0000])], - "CWBorderPixel must forward as mask 0x08 with the pixel" - ); - } - - /// A border TILE forwards as `CWBorderPixmap` (`0x04`) carrying the - /// pixmap's HOST xid, not the client-visible one — same primitive - /// hand-off as a background pixmap, so the `yserver` crate never - /// needs `resources::BorderSource`. - #[test] - fn change_window_attributes_border_pixmap_forwards_host_xid() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - let host_xid = state - .resources - .window(win) - .and_then(|w| w.host_xid) - .expect("host xid") - .as_raw(); - let tile = ResourceId(0x0080_1300); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: tile, - drawable: ROOT_WINDOW, - width: 8, - height: 8, - depth: 24, - }, - ); - assert!( - state.resources.set_pixmap_host_xid( - tile, - crate::backend::PixmapHandle::from_raw(0x9999_0001).expect("non-zero") - ), - "tile pixmap must exist" - ); - - let body = border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]); - let calls = run_border_request_recording(&mut state, 2, 0, &body); - assert_no_error(&read_all_available(&mut peer), "CWA border-pixmap"); - assert_eq!( - border_forwards(&calls), - vec![(host_xid, CWA_BORDER_PIXMAP, vec![0x9999_0001])], - ); - } - - /// #143 — THE regression gate for the awesome border flicker. - /// - /// awesome recolours a focused/unfocused frame with a CWA carrying - /// only `CWBorderPixel`. We repainted the ring into the redirect - /// backing but reported no protocol DAMAGE for it, so picom — which - /// partial-repaints from `EXT_buffer_age` — kept one ring colour per - /// back buffer and alternated between them at frame rate. Xorg - /// reports it from `ChangeWindowAttributes` itself: `borderClip − - /// winSize` → `PaintWindow(..., PW_BORDER)` (`dix/window.c:1581-1589`) - /// → `PolyFillRect` on the window pixmap (`mi/miexpose.c:448-471`, - /// `:558`) → `damagePolyFillRect` (`miext/damage/damage.c:1194`). - /// - /// Geometry is the captured one: 1276×704 at `border_width = 2`. - #[test] - fn change_window_attributes_border_pixel_damages_the_ring() { - use crate::server::DamageObject; - use yserver_protocol::x11::xfixes::RegionRect; - const DAMAGE_XID: u32 = 0x0080_9143; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 1276, 704); - if let Some(w) = state.resources.window_mut(win) { - w.border_width = 2; - } - assert!( - state.resources.map_window(win).mapping_changed, - "window must map" - ); - // Raw level: `area` on the wire then carries the real rect - // instead of the NonEmpty full-extent substitute, so the test - // can prove the negative origin survives the i16 encoding. - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: win, - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let body = border_cwa_body(win.0, CWA_BORDER_PIXEL, &[0x0000_ff00]); - run_border_request(&mut state, 2, 0, &body); - - let rects = state - .damage_objects - .get(&DAMAGE_XID) - .expect("damage object") - .rects - .clone(); - assert_eq!( - rects, - vec![ - RegionRect { - x: -2, - y: -2, - width: 1280, - height: 2 - }, - RegionRect { - x: -2, - y: 0, - width: 2, - height: 704 - }, - RegionRect { - x: 1276, - y: 0, - width: 2, - height: 704 - }, - RegionRect { - x: -2, - y: 704, - width: 1280, - height: 2 - }, - ], - "a border-source change must damage the whole ring, including the \ - negative-origin top and left strips", - ); - - // And it must reach the client as real DamageNotify events, - // with the negative origin intact on the wire (`area.x` is - // INT16 at byte 16). - let bytes = read_all_available(&mut peer); - let notifies: Vec<&[u8]> = bytes - .chunks_exact(32) - .filter(|c| c[0] == crate::nested::DAMAGE_FIRST_EVENT) - .collect(); - assert_eq!( - notifies.len(), - 4, - "one DamageNotify per ring strip at ReportLevel Raw", - ); - let areas: Vec<(i16, i16, u16, u16)> = notifies - .iter() - .map(|c| { - ( - i16::from_le_bytes([c[16], c[17]]), - i16::from_le_bytes([c[18], c[19]]), - u16::from_le_bytes([c[20], c[21]]), - u16::from_le_bytes([c[22], c[23]]), - ) - }) - .collect(); - assert!( - areas.contains(&(-2, -2, 1280, 2)), - "the top strip must arrive at a NEGATIVE origin, got {areas:?}", - ); - assert!( - areas.contains(&(-2, 0, 2, 704)), - "the left strip must arrive at a NEGATIVE x, got {areas:?}", - ); - } - - /// The ring damage follows Xorg's two gates and no others: nothing - /// for an unbordered window (`HasBorder(pWin)`, `dix/window.c:1586`) - /// and nothing for a non-viewable one (`pWin->viewable`, same line). - #[test] - fn change_window_attributes_border_pixel_damages_nothing_unbordered_or_unmapped() { - use crate::server::DamageObject; - const DAMAGE_XID: u32 = 0x0080_9144; - for (bw, map) in [(0u16, true), (2, false)] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 64, 64); - if let Some(w) = state.resources.window_mut(win) { - w.border_width = bw; - } - if map { - assert!( - state.resources.map_window(win).mapping_changed, - "window must map" - ); - } - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: win, - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let body = border_cwa_body(win.0, CWA_BORDER_PIXEL, &[0x0000_ff00]); - run_border_request(&mut state, 2, 0, &body); - assert_no_error(&read_all_available(&mut peer), "CWA border-pixel"); - - assert!( - state.damage_objects[&DAMAGE_XID].rects.is_empty(), - "bw={bw} mapped={map}: no ring to report", - ); - } - } - - /// #143, the resize half. `5d7270c1` reported the ring on a - /// border-source change and on backing activation; a RESIZE - /// repaints it too — `rotate_redirected_backing_on_resize` - /// reallocates and `allocate_redirected_backing` paints the new - /// ring — and reported nothing, so a partial-repaint compositor - /// (picom on `EXT_buffer_age`) kept a ring at the OLD extent in one - /// back buffer and the new one in the other. The bottom and right - /// strips are the ones that move when a window is resized about a - /// fixed origin, which is exactly the observed fingerprint: those - /// two edges flickered at awesome's ~1 Hz clock tick and settled - /// gone. - /// - /// Xorg reports it: `compReallocPixmap` reallocates whenever the - /// bordered extent differs (`composite/compalloc.c:698`) and that - /// branch alone calls `compSetPixmap` (`:700`), whose visitor - /// queues `compRepaintBorder` for `bw != 0` - /// (`composite/compwindow.c:137-139`) — a `PolyFillRect` on the - /// window pixmap (`mi/miexpose.c:558`) that `damagePolyFillRect` - /// (`miext/damage/damage.c:1194`) reports. - /// - /// bw = 2 and the captured 1276x704, shrunk and grown. - #[test] - fn configure_window_resize_damages_the_ring_at_the_new_geometry() { - use crate::{ - resources::RedirectedBacking, - server::{CompositeRedirectMode, DamageObject, RedirectRecord}, - }; - use yserver_protocol::x11::xfixes::RegionRect; - const DAMAGE_XID: u32 = 0x0080_9145; - const BW: u16 = 2; - // (old_w, old_h, new_w, new_h, label) - for (old_w, old_h, new_w, new_h, label) in [ - (1276u16, 704u16, 636u16, 348u16, "shrink"), - (636, 348, 1276, 704, "grow"), - ] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, old_w, old_h); - if let Some(w) = state.resources.window_mut(win) { - w.border_width = BW; - w.redirected_backing = Some(RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(0x0050_0001), - width: old_w + 2 * BW, - height: old_h + 2 * BW, - depth: 24, - }); - } - assert!( - state.resources.map_window(win).mapping_changed, - "window must map" - ); - state.composite_redirects.insert( - (win, false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); - // ReportLevel Raw, so `rects` keeps the real strips instead - // of the NonEmpty full-extent substitute. - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: win, - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - // ConfigureWindow, CWWidth | CWHeight. - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&win.0.to_le_bytes()); - body.extend_from_slice(&0x000cu16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&u32::from(new_w).to_le_bytes()); - body.extend_from_slice(&u32::from(new_h).to_le_bytes()); - run_border_request(&mut state, 12, 0, &body); - - let rects = state.damage_objects[&DAMAGE_XID].rects.clone(); - let bw = i16::try_from(BW).unwrap(); - let ring = [ - RegionRect { - x: -bw, - y: -bw, - width: new_w + 2 * BW, - height: BW, - }, - RegionRect { - x: -bw, - y: 0, - width: BW, - height: new_h, - }, - RegionRect { - x: i16::try_from(new_w).unwrap(), - y: 0, - width: BW, - height: new_h, - }, - RegionRect { - x: -bw, - y: i16::try_from(new_h).unwrap(), - width: new_w + 2 * BW, - height: BW, - }, - ]; - assert_eq!( - rects.get(..4), - Some(&ring[..]), - "{label}: a resize must damage the whole ring at the NEW \ - geometry, before the full-extent configure damage, and the \ - top/left strips carry NEGATIVE origins; got {rects:?}", - ); - // The bottom and right strips are the ones whose position - // MOVED — the #143 fingerprint. Spell them out so a - // regression that reports the ring at the OLD extent fails - // here and not only on the ordering assert above. - assert!( - rects.contains(&ring[2]) && rects.contains(&ring[3]), - "{label}: the right and bottom strips must sit at the NEW \ - extent ({new_w}x{new_h}), not the old one ({old_w}x{old_h})", - ); - assert!( - rects.contains(&RegionRect { - x: 0, - y: 0, - width: new_w, - height: new_h, - }), - "{label}: the pre-existing full-extent configure damage must \ - still fire alongside the ring", - ); - - // And it reaches the client, negative origins intact on the - // wire (`area.x`/`area.y` are INT16 at bytes 16..20). - let bytes = read_all_available(&mut peer); - let areas: Vec<(i16, i16, u16, u16)> = bytes - .chunks_exact(32) - .filter(|c| c[0] == crate::nested::DAMAGE_FIRST_EVENT) - .map(|c| { - ( - i16::from_le_bytes([c[16], c[17]]), - i16::from_le_bytes([c[18], c[19]]), - u16::from_le_bytes([c[20], c[21]]), - u16::from_le_bytes([c[22], c[23]]), - ) - }) - .collect(); - for r in &ring { - assert!( - areas.contains(&(r.x, r.y, r.width, r.height)), - "{label}: ring strip {r:?} must arrive as a DamageNotify, got {areas:?}", - ); - } - } - } - - /// The resize ring damage follows the same two Xorg gates as the - /// border-source one — nothing at `bw == 0` (`HasBorder(pWin)`) and - /// nothing for a non-viewable window (`pWin->viewable`, - /// `dix/window.c:1586`) — so an unbordered resize keeps reporting - /// exactly the one full-extent rect it always did. - #[test] - fn configure_window_resize_damages_no_ring_unbordered_or_unmapped() { - use crate::{ - resources::RedirectedBacking, - server::{CompositeRedirectMode, DamageObject, RedirectRecord}, - }; - use yserver_protocol::x11::xfixes::RegionRect; - const DAMAGE_XID: u32 = 0x0080_9146; - for (bw, map) in [(0u16, true), (2, false)] { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 128, 64); - if let Some(w) = state.resources.window_mut(win) { - w.border_width = bw; - w.redirected_backing = Some(RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(0x0050_0001), - width: 128 + 2 * bw, - height: 64 + 2 * bw, - depth: 24, - }); - } - if map { - assert!( - state.resources.map_window(win).mapping_changed, - "window must map" - ); - } - state.composite_redirects.insert( - (win, false), - RedirectRecord { - mode: CompositeRedirectMode::Manual, - owner: ClientId(1), - }, - ); - state.damage_objects.insert( - DAMAGE_XID, - DamageObject { - owner: ClientId(1), - drawable: win, - level: 0, - rects: Vec::new(), - pending_notify_fired: false, - last_reported_geometry: None, - }, - ); - - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&win.0.to_le_bytes()); - body.extend_from_slice(&0x000cu16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&64u32.to_le_bytes()); - body.extend_from_slice(&32u32.to_le_bytes()); - run_border_request(&mut state, 12, 0, &body); - assert_no_error(&read_all_available(&mut peer), "ConfigureWindow resize"); - - let expected: Vec = if map { - vec![RegionRect { - x: 0, - y: 0, - width: 64, - height: 32, - }] - } else { - Vec::new() - }; - assert_eq!( - state.damage_objects[&DAMAGE_XID].rects, expected, - "bw={bw} mapped={map}: no ring to report on a resize", - ); - } - } - - /// A tile with no host storage degrades to the pixel bit with a - /// defined value, mirroring the background block: a backend that - /// cannot sample the tile is better off with a solid colour than - /// with a dangling xid. - #[test] - fn change_window_attributes_border_pixmap_without_host_storage_degrades_to_pixel() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - let host_xid = state - .resources - .window(win) - .and_then(|w| w.host_xid) - .expect("host xid") - .as_raw(); - let tile = ResourceId(0x0080_1301); - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - pixmap: tile, - drawable: ROOT_WINDOW, - width: 8, - height: 8, - depth: 24, - }, - ); - - let body = border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]); - let calls = run_border_request_recording(&mut state, 2, 0, &body); - assert_no_error(&read_all_available(&mut peer), "hostless border tile"); - assert_eq!( - border_forwards(&calls), - vec![(host_xid, CWA_BORDER_PIXEL, vec![0])], - ); - } - - /// A CWA changing background AND border produces BOTH forwards — - /// the border block is a sibling of the background block, not a - /// replacement, and each carries only its own bits. - #[test] - fn change_window_attributes_background_and_border_forward_separately() { - const CWA_BACK_PIXEL: u32 = 0x0002; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let win = ResourceId(0x0080_0001); - seed_window(&mut state, win, ROOT_WINDOW, 10, 10); - let host_xid = state - .resources - .window(win) - .and_then(|w| w.host_xid) - .expect("host xid") - .as_raw(); - - // Value list in ascending mask-bit order: back-pixel, then - // border-pixel. - let body = border_cwa_body( - win.0, - CWA_BACK_PIXEL | CWA_BORDER_PIXEL, - &[0x0000_00ff, 0x00ff_0000], - ); - let calls = run_border_request_recording(&mut state, 2, 0, &body); - assert_no_error(&read_all_available(&mut peer), "bg + border in one CWA"); - let cwa: Vec<_> = calls - .iter() - .filter_map(|c| match c { - RecordedCall::ChangeSubwindowAttributes { - host_xid, - value_mask, - values, - } => Some((*host_xid, *value_mask, values.clone())), - _ => None, - }) - .collect(); - assert_eq!( - cwa, - vec![ - (host_xid, CWA_BACK_PIXEL, vec![0x0000_00ff]), - (host_xid, CWA_BORDER_PIXEL, vec![0x00ff_0000]), - ], - "background forward first, then the border forward" - ); - } - - /// CreateWindow forwards the INITIAL border source too. Without it - /// a window created with a border pixel that is never changed again - /// would leave the backend mirror with no source at all — and - /// CreateWindow inherits the parent's border (`dix/window.c:879`), - /// so even a client supplying no border attribute can start out - /// with a non-default one. - #[test] - fn create_window_forwards_the_initial_border_source() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, CWA_BORDER_PIXEL, &[0x00ff_0000]); - let calls = run_border_request_recording(&mut state, 1, 24, &body); - assert_no_error(&read_all_available(&mut peer), "create with border pixel"); - let host_xid = state - .resources - .window(ResourceId(0x0080_0001)) - .and_then(|w| w.host_xid) - .expect("created window has a host xid") - .as_raw(); - assert_eq!( - border_forwards(&calls), - vec![(host_xid, CWA_BORDER_PIXEL, vec![0x00ff_0000])], - ); - } - - /// xts5 Xlib4 `XChangeWindowAttributes` 22-25 / Xlib4 - /// `XCreateWindow` 20-22 set a CWBackPixmap / CWColormap / - /// CWCursor value to a freed xid and expect BadPixmap / - /// BadColormap / BadCursor. Mirrors Xorg's per-attribute - /// `dixLookupResource` order in `dix/window.c::CreateWindow` and - /// `ChangeWindowAttributes`. - #[test] - fn change_window_attributes_with_stale_value_returns_specific_bad_error() { - use std::io::Read; - const APP: u32 = 300; - const WIN: u32 = 0x0090_0001; - const BAD_PIX: u32 = 0x0090_dead; - const BAD_CMAP: u32 = 0x0090_beef; - const BAD_CURS: u32 = 0x0090_face; - - // (mask, value, expected_error, label) - let cases: &[(u32, u32, u8, &str)] = &[ - ( - 0x0001, - BAD_PIX, - yserver_protocol::x11::error::BAD_PIXMAP, - "CWBackPixmap", - ), - ( - 0x2000, - BAD_CMAP, - yserver_protocol::x11::error::BAD_COLORMAP, - "CWColormap", - ), - ( - 0x4000, - BAD_CURS, - yserver_protocol::x11::error::BAD_CURSOR, - "CWCursor", - ), - ]; - - for (i, (mask, value, expected_err, label)) in cases.iter().enumerate() { - let mut state = ServerState::new(); - let app_id = APP + i as u32; - let mut peer = install_client(&mut state, app_id); - let mut backend = RecordingBackend::new(); - - // Create a live target window owned by this client so the - // BadWindow gate doesn't fire ahead of the value check. - let win = WIN + i as u32; - state.resources.create_window( - ClientId(app_id), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 10, - height: 10, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&win.to_le_bytes()); - body.extend_from_slice(&mask.to_le_bytes()); - body.extend_from_slice(&value.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body length fits"); - - process_request( - &mut state, - &mut backend, - ClientId(app_id), - SequenceNumber(1), - RequestHeader { - opcode: 2, - data: 0, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf).unwrap_or_else(|e| { - panic!("{label}: expected 32-byte error reply, got {e:?}"); - }); - assert_eq!( - buf[0], 0, - "{label}: byte 0 = error class (0); got {}", - buf[0] - ); - assert_eq!( - buf[1], *expected_err, - "{label}: expected error code {expected_err} for stale xid; got {}", - buf[1], - ); - let bad_value = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]); - assert_eq!( - bad_value, *value, - "{label}: error_value must echo the stale resource xid" - ); - assert_eq!( - buf[10], 2, - "{label}: error must carry the ChangeWindowAttributes \ - major opcode (2); got {}", - buf[10], - ); - } - } - - /// xts5 Xlib4 ConfigureWindow validations beyond BadWindow. - /// Mirrors Xorg `dix/window.c::ConfigureWindow:2203-2266` — every - /// check fires *before* any state mutation. - #[test] - fn configure_window_validates_inputonly_sibling_and_size() { - use std::io::Read; - const APP: u32 = 400; - const PARENT: u32 = 0x00a0_0001; - const INPUT_ONLY: u32 = 0x00a0_0002; - const SIB_A: u32 = 0x00a0_0003; - const SIB_B: u32 = 0x00a0_0004; - const ORPHAN: u32 = 0x00a0_0005; - const BAD_SIB: u32 = 0x00a0_dead; - const CW_X: u16 = 0x0001; - const CW_WIDTH: u16 = 0x0004; - const CW_HEIGHT: u16 = 0x0008; - const CW_BORDER_WIDTH: u16 = 0x0010; - const CW_SIBLING: u16 = 0x0020; - const CW_STACK_MODE: u16 = 0x0040; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - // Two siblings under PARENT and one orphan that's not their sibling. - for (id, parent, class) in [ - (PARENT, crate::resources::ROOT_WINDOW.0, 1u16), - (INPUT_ONLY, PARENT, 2u16), - (SIB_A, PARENT, 1u16), - (SIB_B, PARENT, 1u16), - (ORPHAN, crate::resources::ROOT_WINDOW.0, 1u16), - ] { - state.resources.create_window( - ClientId(APP), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(id), - parent: ResourceId(parent), - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - - // (label, body, expected_error) - let cases: Vec<(&str, Vec, u8)> = vec![ - ( - "InputOnly + CWBorderWidth → BadMatch", - build_configure_body(INPUT_ONLY, CW_BORDER_WIDTH, &[1u16.to_le_bytes()]), - yserver_protocol::x11::error::BAD_MATCH, - ), - ( - "CWSibling without CWStackMode → BadMatch", - build_configure_body( - SIB_A, - CW_SIBLING, - [SIB_B.to_le_bytes(); 1] - .iter() - .map(|b| { - let mut buf = [0u8; 2]; - buf.copy_from_slice(&b[..2]); - buf - }) - .collect::>() - .as_slice(), - ), - yserver_protocol::x11::error::BAD_MATCH, - ), - ( - "CWSibling with non-sibling → BadMatch", - build_configure_body_u32(SIB_A, CW_SIBLING | CW_STACK_MODE, ORPHAN, 0), - yserver_protocol::x11::error::BAD_MATCH, - ), - ( - "CWSibling with unknown xid → BadWindow", - build_configure_body_u32(SIB_A, CW_SIBLING | CW_STACK_MODE, BAD_SIB, 0), - yserver_protocol::x11::error::BAD_WINDOW, - ), - ( - "CWWidth=0 → BadValue", - build_configure_body(SIB_A, CW_WIDTH, &[0u16.to_le_bytes()]), - yserver_protocol::x11::error::BAD_VALUE, - ), - ( - "CWHeight=0 → BadValue", - build_configure_body(SIB_A, CW_HEIGHT, &[0u16.to_le_bytes()]), - yserver_protocol::x11::error::BAD_VALUE, - ), - ( - "CWX alone → no error (MOVE_WIN path)", - build_configure_body(SIB_A, CW_X, &[5u16.to_le_bytes()]), - 0, // 0 means: expect NO error reply - ), - ]; - - for (i, (label, body, expected_err)) in cases.iter().enumerate() { - let seq = SequenceNumber((i + 1) as u16); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body length fits"); - process_request( - &mut state, - &mut backend, - ClientId(APP), - seq, - RequestHeader { - opcode: 12, - data: 0, - length_units, - }, - body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - match peer.read_exact(&mut buf) { - Ok(()) => { - if *expected_err == 0 { - panic!("{label}: did not expect an error reply, got {buf:?}"); - } - assert_eq!(buf[0], 0, "{label}: byte 0 = error class (0)"); - assert_eq!( - buf[1], *expected_err, - "{label}: error code mismatch — got {}", - buf[1] - ); - } - Err(e) if *expected_err == 0 => { - // Expected — no error reply. - assert_eq!(e.kind(), std::io::ErrorKind::WouldBlock); - } - Err(e) => { - panic!("{label}: expected error reply with code {expected_err}, got {e:?}") - } - } - } - } - - fn build_configure_body(window_xid: u32, value_mask: u16, values: &[[u8; 2]]) -> Vec { - let mut body = Vec::with_capacity(8 + values.len() * 4); - body.extend_from_slice(&window_xid.to_le_bytes()); - body.extend_from_slice(&value_mask.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); // pad - for v in values { - body.extend_from_slice(v); - body.extend_from_slice(&0u16.to_le_bytes()); // each value is u32 on the wire - } - body - } - - fn build_configure_body_u32(window_xid: u32, value_mask: u16, v0: u32, v1: u32) -> Vec { - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&window_xid.to_le_bytes()); - body.extend_from_slice(&value_mask.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); // pad - body.extend_from_slice(&v0.to_le_bytes()); - body.extend_from_slice(&v1.to_le_bytes()); - body - } - - /// xts5 Xlib4 XCreateWindow CreateWindow class/border/depth rules: - /// parent InputOnly + child InputOutput → BadMatch (test 43), - /// InputOnly + non-zero border_width → BadMatch (test 31), - /// InputOnly + non-zero depth → BadMatch (test 44). - #[test] - fn create_window_validates_class_constraints() { - use std::io::Read; - const APP: u32 = 500; - const PARENT_IPO: u32 = 0x00b0_0001; - const PARENT_IPI: u32 = 0x00b0_0002; - const CHILD: u32 = 0x00b0_0003; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - - // One InputOutput parent and one InputOnly parent. - for (id, parent, class) in [ - (PARENT_IPO, crate::resources::ROOT_WINDOW.0, 1u16), - (PARENT_IPI, crate::resources::ROOT_WINDOW.0, 2u16), - ] { - state.resources.create_window( - ClientId(APP), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(id), - parent: ResourceId(parent), - x: 0, - y: 0, - width: 50, - height: 50, - border_width: 0, - class, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - } - - // (label, depth, parent, class, border_width, expected_err) - let cases: &[(&str, u8, u32, u16, u16, u8)] = &[ - ( - "parent InputOnly + class InputOutput", - 24, - PARENT_IPI, - 1, - 0, - yserver_protocol::x11::error::BAD_MATCH, - ), - ( - "class InputOnly + non-zero border_width", - 0, - PARENT_IPO, - 2, - 1, - yserver_protocol::x11::error::BAD_MATCH, - ), - ( - "class InputOnly + non-zero depth", - 24, - PARENT_IPO, - 2, - 0, - yserver_protocol::x11::error::BAD_MATCH, - ), - ]; - - for (i, (label, depth, parent, class, bw, expected_err)) in cases.iter().enumerate() { - let mut body = Vec::with_capacity(32); - body.extend_from_slice(&CHILD.to_le_bytes()); - body.extend_from_slice(&parent.to_le_bytes()); - body.extend_from_slice(&0i16.to_le_bytes()); // x - body.extend_from_slice(&0i16.to_le_bytes()); // y - body.extend_from_slice(&10u16.to_le_bytes()); // width - body.extend_from_slice(&10u16.to_le_bytes()); // height - body.extend_from_slice(&bw.to_le_bytes()); // border_width - body.extend_from_slice(&class.to_le_bytes()); // class - body.extend_from_slice(&0u32.to_le_bytes()); // visual = CopyFromParent - body.extend_from_slice(&0u32.to_le_bytes()); // value_mask - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); - let seq = SequenceNumber((i + 1) as u16); - process_request( - &mut state, - &mut backend, - ClientId(APP), - seq, - RequestHeader { - opcode: 1, - data: *depth, - length_units, - }, - &body, - None, - ) - .expect("process_request"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .unwrap_or_else(|e| panic!("{label}: expected error reply, got {e:?}")); - assert_eq!(buf[0], 0, "{label}: byte 0 = error class"); - assert_eq!( - buf[1], *expected_err, - "{label}: expected error code {expected_err}, got {}", - buf[1] - ); - assert_eq!( - buf[10], 1, - "{label}: BadMatch must carry CreateWindow opcode" - ); - } - } - - /// DRI3::BufferFromPixmap: when the backend's `dri3_export_pixmap` - /// returns Err (e.g. no exportable backing, Vulkan unavailable, or - /// any promotion failure), the dispatcher must emit `BadPixmap` - /// (error code 4) — matching Xorg `dri3/dri3_request.c:277`. - /// Previously this emitted `BadAlloc` (11). - #[test] - fn buffer_from_pixmap_export_failure_returns_bad_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // RecordingBackend does not override dri3_export_pixmap, so the - // default trait implementation returns Err("DRI3 export unsupported - // on this backend") — exactly the failure case we're testing. - let mut backend = RecordingBackend::new(); - - // Register a pixmap in the resource table with a valid host_xid so - // the handler reaches the dri3_export_pixmap call (not the - // BadDrawable path). - let pixmap_xid: u32 = 0x1000; - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(pixmap_xid), - drawable: ROOT_WINDOW, - width: 16, - height: 16, - }, - ); - assert!( - state.resources.set_pixmap_host_xid( - ResourceId(pixmap_xid), - crate::backend::PixmapHandle::from_raw(0xdead_cafe).unwrap(), - ), - "set_pixmap_host_xid must succeed" - ); - - // BufferFromPixmap body: 4-byte pixmap XID (little-endian). - let body = pixmap_xid.to_le_bytes().to_vec(); - - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(7), - RequestHeader { - opcode: 147, // DRI3_MAJOR_OPCODE - data: 3, // BUFFER_FROM_PIXMAP - length_units: 2, - }, - &body, - None, - ) - .expect("process_request should not hard-error"); - - assert!( - matches!(outcome, RequestOutcome::Handled), - "expected Handled, got {outcome:?}" - ); - - // Read the 32-byte X error packet from the peer socket. - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("BadPixmap error packet must be delivered to client"); - assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); - assert_eq!( - buf[1], - x11::error::BAD_PIXMAP, - "expected BadPixmap ({}), got {}", - x11::error::BAD_PIXMAP, - buf[1] - ); - } - - /// DRI3::BuffersFromPixmap (op 8): like op 3, a backend export - /// failure must emit `BadPixmap` (the modifier-aware multi-plane - /// reply shares op 3's error contract). The default RecordingBackend - /// returns Err from `dri3_export_pixmap_buffers`. - #[test] - fn buffers_from_pixmap_export_failure_returns_bad_pixmap() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - let pixmap_xid: u32 = 0x1000; - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(pixmap_xid), - drawable: ROOT_WINDOW, - width: 16, - height: 16, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - ResourceId(pixmap_xid), - crate::backend::PixmapHandle::from_raw(0xdead_cafe).unwrap(), - )); - - let body = pixmap_xid.to_le_bytes().to_vec(); - let outcome = process_request( - &mut state, - &mut backend, - ClientId(1), - SequenceNumber(7), - RequestHeader { - opcode: 147, // DRI3_MAJOR_OPCODE - data: 8, // BUFFERS_FROM_PIXMAP - length_units: 2, - }, - &body, - None, - ) - .expect("process_request should not hard-error"); - - assert!( - matches!(outcome, RequestOutcome::Handled), - "expected Handled, got {outcome:?}" - ); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("BadPixmap error packet must be delivered to client"); - assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); - assert_eq!( - buf[1], - x11::error::BAD_PIXMAP, - "expected BadPixmap ({}), got {}", - x11::error::BAD_PIXMAP, - buf[1] - ); - } - - #[test] - fn glx_extension_string_includes_tfp_only_when_capable() { - let with = glx_extension_string(true); - let without = glx_extension_string(false); - assert!(with.contains("GLX_EXT_texture_from_pixmap")); - assert!(!without.contains("GLX_EXT_texture_from_pixmap")); - // Base extensions always present. - assert!(with.contains("GLX_ARB_create_context")); - assert!(without.contains("GLX_ARB_create_context")); - } - - /// Xorg writes a space after **every** enabled extension - /// (`glx/extension_string.c:144-145`), so its GLX extension string - /// always ends with `' '` before the NUL. yserver's did not, and - /// `libGLX_nvidia` responds by losing the final token *and* dropping - /// `GLX_ARB_get_proc_address` from the client extension string — which - /// makes libepoxy abort and takes `kwin_x11` down with SIGABRT. - /// - /// Measured 2026-08-07; see - /// `docs/superpowers/specs/2026-08-07-glx-extension-string-terminator-design.md` - /// and `~/yserver-glx-logs/2026-08-07-terminator-evidence/`. - #[test] - fn glx_extension_string_is_space_terminated() { - for tfp_supported in [false, true] { - let s = glx_extension_string(tfp_supported); - assert!( - s.ends_with(' '), - "GLX extension string must end with Xorg's space terminator; \ - tfp_supported={tfp_supported} produced {s:?}" - ); - } - } - - /// Companion to `glx_extension_string_is_space_terminated`: the - /// terminator must not come at the cost of the token list. Green both - /// before and after that fix — this is a guard, not a regression test. - #[test] - fn glx_extension_string_tokens_match_advertised_constants() { - use yserver_protocol::x11::glx as g; - for tfp_supported in [false, true] { - let s = glx_extension_string(tfp_supported); - assert!( - !s.starts_with(' '), - "no leading separator; tfp_supported={tfp_supported} produced {s:?}" - ); - assert!( - !s.contains(" "), - "no doubled separator; tfp_supported={tfp_supported} produced {s:?}" - ); - let mut expected: Vec<&str> = g::SERVER_EXTENSIONS.split_whitespace().collect(); - expected.push(g::SGIX_FBCONFIG_EXTENSION); - if tfp_supported { - expected.push(g::TFP_EXTENSION); - } - let tokens: Vec<&str> = s.split_whitespace().collect(); - assert_eq!( - tokens, expected, - "token list must be the advertised constants, in order; \ - tfp_supported={tfp_supported}" - ); - } - } - - #[test] - fn fbconfigs_emit_bind_to_texture_pairs_in_xorg_order() { - use yserver_protocol::x11::glx as g; - let configs = synthesise_glx_fb_configs(true); - // All configs same length (wire encoder requirement). - let len = configs[0].len(); - assert!(configs.iter().all(|c| c.len() == len)); - - for c in &configs { - // Find the bind-to-texture block; it must appear as a contiguous run in this order. - let idx = c - .iter() - .position(|(k, _)| *k == g::GLX_BIND_TO_TEXTURE_RGB_EXT) - .expect("RGB present"); - let order = [ - g::GLX_BIND_TO_TEXTURE_RGB_EXT, - g::GLX_BIND_TO_TEXTURE_RGBA_EXT, - g::GLX_BIND_TO_MIPMAP_TEXTURE_EXT, - g::GLX_BIND_TO_TEXTURE_TARGETS_EXT, - g::GLX_Y_INVERTED_EXT, - ]; - for (i, key) in order.iter().enumerate() { - assert_eq!(c[idx + i].0, *key, "wrong order at offset {i}"); - } - // Values: - assert_eq!(c[idx + 2].1, 0, "MIPMAP must be 0/false"); - assert_eq!( - c[idx + 3].1, - g::GLX_DONT_CARE, - "BIND_TO_TEXTURE_TARGETS is GLX_DONT_CARE so it matches any \ - client-driver target bitmask (driConfigEqual)" - ); - assert_eq!( - c[idx + 4].1, - g::GLX_DONT_CARE, - "Y_INVERTED in FBConfig is GLX_DONT_CARE" - ); - } - - // Both depths advertise RGB=true RGBA=true, matching radeonsi's - // TFP configs (HW-verified). RGBA=true on depth-24 is correct: - // opaque windows sample as α=1. - let depth24 = configs - .iter() - .find(|c| c.iter().any(|(k, v)| *k == g::GLX_VISUAL_ID && *v == 0x102)) - .unwrap(); - let d24 = depth24 - .iter() - .position(|(k, _)| *k == g::GLX_BIND_TO_TEXTURE_RGB_EXT) - .unwrap(); - assert_eq!(depth24[d24].1, 1); // RGB true - assert_eq!(depth24[d24 + 1].1, 1); // RGBA true on depth-24 (match radeonsi) - - let depth32 = configs - .iter() - .find(|c| c.iter().any(|(k, v)| *k == g::GLX_VISUAL_ID && *v == 0x103)) - .unwrap(); - let d32 = depth32 - .iter() - .position(|(k, _)| *k == g::GLX_BIND_TO_TEXTURE_RGB_EXT) - .unwrap(); - assert_eq!(depth32[d32 + 1].1, 1); // RGBA true on depth-32 - } - - #[test] - fn fbconfigs_omit_bind_to_texture_when_tfp_unsupported() { - use yserver_protocol::x11::glx as g; - let configs = synthesise_glx_fb_configs(false); - assert!( - configs - .iter() - .all(|c| c.iter().all(|(k, _)| *k != g::GLX_BIND_TO_TEXTURE_RGB_EXT)) - ); - // Still equal length across configs. - let len = configs[0].len(); - assert!(configs.iter().all(|c| c.len() == len)); - } - - /// GLX Task 3.4: `glXCreatePixmap` records the X drawable in - /// `glx_drawables`, calls `acquire_glx_pixmap_export` on the backend, - /// and `glXDestroyPixmap` clears the entry and calls - /// `release_glx_pixmap_export`. - #[test] - fn glx_create_pixmap_records_x_drawable_and_destroy_clears_it() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Register an X pixmap in the resource table with a known host_xid. - let x_pixmap_xid: u32 = 0x2000; - let host_xid_raw: u32 = 0xdead_0001; - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(x_pixmap_xid), - drawable: ROOT_WINDOW, - width: 64, - height: 32, - }, - ); - assert!( - state.resources.set_pixmap_host_xid( - ResourceId(x_pixmap_xid), - crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), - ), - "set_pixmap_host_xid must succeed" - ); - - let glx_xid: u32 = 0x4000_0001; - let fbconfig: u32 = 0x101; - - // Build a GLX CREATE_PIXMAP request body: - // [screen(u32)][fbconfig(u32)][x_window(u32)][glx_window(u32)] - let mut create_body = Vec::new(); - create_body.extend_from_slice(&0u32.to_le_bytes()); // screen = 0 - create_body.extend_from_slice(&fbconfig.to_le_bytes()); - create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); - create_body.extend_from_slice(&glx_xid.to_le_bytes()); - - let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, // GLX_MAJOR_OPCODE - data: x11glx::CREATE_PIXMAP, // minor = 22 - length_units, - }, - &create_body, - None, - ) - .expect("process_request CREATE_PIXMAP"); - - // Verify the GlxDrawable was recorded. - let d = state - .glx_drawables - .get(&glx_xid) - .expect("GlxDrawable must be present after CreatePixmap"); - assert_eq!( - d.x_drawable, x_pixmap_xid, - "x_drawable must point to the X pixmap" - ); - assert_eq!(d.fbconfig, fbconfig); - - // Verify acquire was forwarded to the backend. - assert!( - backend - .calls() - .contains(&RecordedCall::AcquireGlxPixmapExport(host_xid_raw)), - "AcquireGlxPixmapExport must be recorded after CreatePixmap" - ); - - // Build a GLX DESTROY_PIXMAP request body: [glx_xid(u32)] - let destroy_body = glx_xid.to_le_bytes().to_vec(); - let length_units = u32::try_from(1 + destroy_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(2), - RequestHeader { - opcode: 148, - data: x11glx::DESTROY_PIXMAP, // minor = 23 - length_units, - }, - &destroy_body, - None, - ) - .expect("process_request DESTROY_PIXMAP"); - - // GlxDrawable must be removed. - assert!( - !state.glx_drawables.contains_key(&glx_xid), - "GlxDrawable must be removed after DestroyPixmap" - ); - - // Verify release was forwarded to the backend. - assert!( - backend - .calls() - .contains(&RecordedCall::ReleaseGlxPixmapExport(host_xid_raw)), - "ReleaseGlxPixmapExport must be recorded after DestroyPixmap" - ); - } - - // ─── GLX 1.0 CreateGLXPixmap / DestroyGLXPixmap, QueryContext, IsDirect ─── - // - // Expected wire behaviour is Xorg's, captured from Xvfb 21.1.24 - // (llvmpipe GLX) with an xcb probe on 2026-09-26. Xvfb's GLX visual 0x21 - // carries FBConfig 0x88; the yserver counterpart used below is - // ROOT_VISUAL 0x102 carrying FBConfig 0x101 (synthesise_glx_fb_configs). - // Error values, minors and the order in which the checks fire are - // Xvfb's, verbatim. - - const GLX_TEST_XID_BASE: u32 = 0x0020_0000; - const GLX_TEST_XID_MASK: u32 = 0x001f_ffff; - - /// A client whose XID range is `0x0020_0000 | 0x001f_ffff`, the range - /// Xvfb handed the capture probe, so `LEGAL_NEW_RESOURCE` is exercised. - fn glx_legacy_fixture() -> (ServerState, RecordingBackend, UnixStream) { - let mut state = ServerState::new(); - let peer = install_client(&mut state, 1); - let client = state.clients.get_mut(&1).expect("test client"); - client.resource_id_base = GLX_TEST_XID_BASE; - client.resource_id_mask = GLX_TEST_XID_MASK; - (state, RecordingBackend::new(), peer) - } - - fn glx_legacy_x_pixmap(state: &mut ServerState, xid: u32, depth: u8, host: Option) { - state.resources.create_pixmap( - ClientId(1), - CreatePixmapRequest { - depth, - pixmap: ResourceId(xid), - drawable: ROOT_WINDOW, - width: 64, - height: 32, - }, - ); - if let Some(host) = host { - assert!(state.resources.set_pixmap_host_xid( - ResourceId(xid), - crate::backend::PixmapHandle::from_raw(host).expect("non-zero host xid"), - )); - } - } - - fn glx_legacy_words(words: &[u32]) -> Vec { - words.iter().flat_map(|v| v.to_le_bytes()).collect() - } - - /// Run one request for `client` and return every byte it wrote. - fn glx_legacy_send_major( - state: &mut ServerState, - backend: &mut RecordingBackend, - peer: &mut UnixStream, - client: u32, - (opcode, minor): (u8, u8), - body: &[u8], - ) -> Vec { - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - process_request( - state, - backend, - ClientId(client), - SequenceNumber(7), - RequestHeader { - opcode, - data: minor, - length_units, - }, - body, - None, - ) - .expect("process_request"); - read_all_or_buffered(state, client, peer) - } - - /// Run one GLX request for `client` and return every byte it wrote. - fn glx_legacy_send( - state: &mut ServerState, - backend: &mut RecordingBackend, - peer: &mut UnixStream, - client: u32, - minor: u8, - body: &[u8], - ) -> Vec { - glx_legacy_send_major( - state, - backend, - peer, - client, - (crate::nested::GLX_MAJOR_OPCODE, minor), - body, - ) - } - - /// Assert `bytes` is exactly one X error with this code, bad value and - /// minor opcode on the GLX major opcode. - fn assert_glx_legacy_error(what: &str, bytes: &[u8], code: u8, value: u32, minor: u8) { - assert_eq!(bytes.len(), 32, "{what}: expected exactly one error packet"); - assert_eq!(bytes[0], 0, "{what}: expected an X error"); - assert_eq!(bytes[1], code, "{what}: error code"); - assert_eq!( - u32::from_le_bytes(bytes[4..8].try_into().unwrap()), - value, - "{what}: bad value" - ); - assert_eq!( - u16::from_le_bytes([bytes[8], bytes[9]]), - u16::from(minor), - "{what}: minor opcode" - ); - assert_eq!( - bytes[10], - crate::nested::GLX_MAJOR_OPCODE, - "{what}: major opcode" - ); - } - - fn create_glx_pixmap_body(screen: u32, visual: u32, pixmap: u32, glx_pixmap: u32) -> Vec { - glx_legacy_words(&[screen, visual, pixmap, glx_pixmap]) - } - - /// Decode the (attribute, value) pairs of a GetDrawableAttributes / - /// QueryContext reply, checking the header's length and count agree. - fn glx_legacy_reply_pairs(bytes: &[u8]) -> Vec<(u32, u32)> { - assert_eq!(bytes[0], 1, "expected a reply, got {bytes:02x?}"); - let length = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; - let n = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize; - assert_eq!(length, 2 * n, "reply length must be 2 * n"); - assert_eq!(bytes.len(), 32 + 8 * n, "reply size"); - (0..n) - .map(|i| { - let at = 32 + 8 * i; - ( - u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()), - u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()), - ) - }) - .collect() - } - - /// GLX 1.0 `glXCreateGLXPixmap` (minor 13) used to hit the - /// `GLXBadRenderRequest` catch-all, so Xlib's default handler killed the - /// app. It must create the same GLXPixmap record GLX 1.3 `CreatePixmap` - /// does (config = the visual's FBConfig), hold the export ref, report - /// Xorg's drawable attributes, and `DestroyGLXPixmap` (15) must release - /// the ref — also after the X pixmap was freed first (Xorg bumps the - /// pixmap refcount, glxcmds.c `DoCreateGLXPixmap`). - #[test] - fn glx10_create_glx_pixmap_records_pixmap_and_destroy_releases_it() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::glx as g; - - let (mut state, mut backend, mut peer) = glx_legacy_fixture(); - let pixmap = GLX_TEST_XID_BASE | 0x01; - let glx_pixmap = GLX_TEST_XID_BASE | 0x02; - let host = 0xdead_0001; - glx_legacy_x_pixmap(&mut state, pixmap, 24, Some(host)); - - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::CREATE_GLX_PIXMAP, - &create_glx_pixmap_body(0, crate::resources::ROOT_VISUAL.0, pixmap, glx_pixmap), - ); - assert!( - out.is_empty(), - "CreateGLXPixmap succeeds silently, got {out:02x?}" - ); - let record = state - .glx_drawables - .get(&glx_pixmap) - .expect("GLXPixmap recorded"); - assert_eq!(record.kind, crate::server::GlxDrawableKind::Pixmap); - assert_eq!(record.x_drawable, pixmap); - assert_eq!(record.fbconfig, 0x101, "the visual's FBConfig"); - assert_eq!(record.glx_export_host_xid, Some(host)); - assert!( - backend - .calls() - .contains(&RecordedCall::AcquireGlxPixmapExport(host)) - ); - - // Xvfb: 0x20d4=0 0x801d=64 0x801e=32 0x800c=0 0x20d6=0x20dd - // 0x801f=0 0x8013= 0x8010=GLX_PIXMAP_BIT - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::GET_DRAWABLE_ATTRIBUTES, - &glx_pixmap.to_le_bytes(), - ); - assert_eq!( - glx_legacy_reply_pairs(&out), - vec![ - (g::GLX_Y_INVERTED_EXT, 0), - (g::GLX_WIDTH, 64), - (g::GLX_HEIGHT, 32), - (g::GLX_SCREEN, 0), - (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_RECTANGLE_EXT), - (g::GLX_EVENT_MASK, 0), - (g::GLX_FBCONFIG_ID, 0x101), - (g::GLX_DRAWABLE_TYPE, g::GLX_PIXMAP_BIT), - ] - ); - - // FreePixmap first, then DestroyGLXPixmap: both Success on Xvfb. - let out = glx_legacy_send_major( - &mut state, - &mut backend, - &mut peer, - 1, - (54, 0), - &pixmap.to_le_bytes(), - ); - assert!(out.is_empty(), "FreePixmap: got {out:02x?}"); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::DESTROY_GLX_PIXMAP, - &glx_pixmap.to_le_bytes(), - ); - assert!( - out.is_empty(), - "DestroyGLXPixmap succeeds silently, got {out:02x?}" - ); - assert!(!state.glx_drawables.contains_key(&glx_pixmap)); - assert!( - backend - .calls() - .contains(&RecordedCall::ReleaseGlxPixmapExport(host)) - ); - } - - /// Every CreateGLXPixmap failure Xvfb produced, with its error code, - /// bad value and the precedence between checks: size, then the new - /// XID (`LEGAL_NEW_RESOURCE`), then the screen (GLXVND: BadMatch), then - /// the visual (BadValue), then the pixmap (core BadDrawable, or core - /// BadPixmap for a window). A failed request creates nothing. - #[test] - fn glx10_create_glx_pixmap_errors_match_xorg() { - use yserver_protocol::x11::{error, glx as g}; - - let (mut state, mut backend, mut peer) = glx_legacy_fixture(); - let pixmap = GLX_TEST_XID_BASE | 0x01; - let other_pixmap = GLX_TEST_XID_BASE | 0x03; - let existing_glx = GLX_TEST_XID_BASE | 0x04; - let fresh = GLX_TEST_XID_BASE | 0x05; - let vis = crate::resources::ROOT_VISUAL.0; - glx_legacy_x_pixmap(&mut state, pixmap, 24, None); - glx_legacy_x_pixmap(&mut state, other_pixmap, 32, None); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::CREATE_GLX_PIXMAP, - &create_glx_pixmap_body(0, vis, pixmap, existing_glx), - ); - assert!(out.is_empty()); - - let bad_id = error::BAD_ID_CHOICE; - let unknown = 0x5a_5a5a; - let root = ROOT_WINDOW.0; - let cases: &[(&str, [u32; 4], u8, u32)] = &[ - ( - "glx id in use", - [0, vis, pixmap, existing_glx], - bad_id, - existing_glx, - ), - ( - "glx id = X pixmap", - [0, vis, pixmap, other_pixmap], - bad_id, - other_pixmap, - ), - ( - "glx id out of range", - [0, vis, pixmap, 0x07f0_0001], - bad_id, - 0x07f0_0001, - ), - ("screen 1", [1, vis, pixmap, fresh], error::BAD_MATCH, 1), - ( - "unknown visual", - [0, 0xdead, pixmap, fresh], - error::BAD_VALUE, - 0xdead, - ), - // An FBConfig ID is not a GLX visual (Xvfb: its visual-less - // FBConfig 0x41 → BadValue 0x41). - ( - "visual-less fbconfig id", - [0, 0x104, pixmap, fresh], - error::BAD_VALUE, - 0x104, - ), - ( - "fbconfig id of a visual", - [0, 0x101, pixmap, fresh], - error::BAD_VALUE, - 0x101, - ), - ( - "screen 1 + bad visual", - [1, 0xdead, pixmap, fresh], - error::BAD_MATCH, - 1, - ), - ( - "root window as pixmap", - [0, vis, root, fresh], - error::BAD_PIXMAP, - root, - ), - ( - "unknown pixmap", - [0, vis, unknown, fresh], - error::BAD_DRAWABLE, - unknown, - ), - ( - "bad visual + bad pixmap", - [0, 0xdead, unknown, fresh], - error::BAD_VALUE, - 0xdead, - ), - ( - "bad pixmap + glx id in use", - [0, vis, unknown, existing_glx], - bad_id, - existing_glx, - ), - ]; - for (what, [screen, visual, pix, glx], code, value) in cases { - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::CREATE_GLX_PIXMAP, - &create_glx_pixmap_body(*screen, *visual, *pix, *glx), - ); - assert_glx_legacy_error(what, &out, *code, *value, g::CREATE_GLX_PIXMAP); - } - assert!(!state.glx_drawables.contains_key(&fresh)); - assert!(!state.glx_drawables.contains_key(&other_pixmap)); - assert_eq!(state.glx_drawables.len(), 1); - } - - /// Xorg does not compare the pixmap depth with the visual: Xvfb accepted - /// depth-32, depth-8 and depth-1 pixmaps for its depth-24 visual. - #[test] - fn glx10_create_glx_pixmap_accepts_any_pixmap_depth() { - use yserver_protocol::x11::glx as g; - - let (mut state, mut backend, mut peer) = glx_legacy_fixture(); - for (i, depth) in (0_u32..).zip([32_u8, 8, 1]) { - let pixmap = GLX_TEST_XID_BASE | (0x10 + i); - let glx_pixmap = GLX_TEST_XID_BASE | (0x20 + i); - glx_legacy_x_pixmap(&mut state, pixmap, depth, None); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::CREATE_GLX_PIXMAP, - &create_glx_pixmap_body(0, crate::resources::ROOT_VISUAL.0, pixmap, glx_pixmap), - ); - assert!(out.is_empty(), "depth {depth}: got {out:02x?}"); - assert!(state.glx_drawables.contains_key(&glx_pixmap)); - } - } - - /// DestroyGLXPixmap takes only a live GLX *pixmap*: anything else is - /// `GLXBadPixmap` with the XID as bad value (GLXVND's XID map, then - /// `validGlxDrawable`'s type check). GLX 1.0 and GLX 1.3 pixmaps are the - /// same resource type, so either destroy request frees either. - #[test] - fn glx10_destroy_glx_pixmap_errors_and_cross_version_destroy_match_xorg() { - use yserver_protocol::x11::glx as g; - - let (mut state, mut backend, mut peer) = glx_legacy_fixture(); - let bad_pixmap = crate::nested::GLX_FIRST_ERROR + g::ERROR_GLX_BAD_PIXMAP; - let pixmap = GLX_TEST_XID_BASE | 0x01; - glx_legacy_x_pixmap(&mut state, pixmap, 24, None); - let legacy = GLX_TEST_XID_BASE | 0x02; - let modern = GLX_TEST_XID_BASE | 0x03; - let glx_window = GLX_TEST_XID_BASE | 0x04; - let pbuffer = GLX_TEST_XID_BASE | 0x05; - let vis = crate::resources::ROOT_VISUAL.0; - - let mut send = |state: &mut ServerState, minor: u8, body: &[u8]| { - glx_legacy_send(state, &mut backend, &mut peer, 1, minor, body) - }; - let window_body = glx_legacy_words(&[0, 0x101, ROOT_WINDOW.0, glx_window]); - assert!(send(&mut state, g::CREATE_WINDOW, &window_body).is_empty()); - let pbuffer_body = glx_legacy_words(&[0, 0x101, pbuffer, 0]); - assert!(send(&mut state, g::CREATE_PBUFFER, &pbuffer_body).is_empty()); - - for (what, xid) in [ - ("unknown xid", 0x5a_5a5a), - ("X pixmap", pixmap), - ("GLX window", glx_window), - ("GLX pbuffer", pbuffer), - ] { - let out = send(&mut state, g::DESTROY_GLX_PIXMAP, &xid.to_le_bytes()); - assert_glx_legacy_error(what, &out, bad_pixmap, xid, g::DESTROY_GLX_PIXMAP); - } - assert!(state.glx_drawables.contains_key(&glx_window)); - assert!(state.glx_drawables.contains_key(&pbuffer)); - - // GLX 1.0 pixmap destroyed by GLX 1.3 DestroyPixmap; a second - // destroy through DestroyGLXPixmap is GLXBadPixmap. - let body = create_glx_pixmap_body(0, vis, pixmap, legacy); - assert!(send(&mut state, g::CREATE_GLX_PIXMAP, &body).is_empty()); - assert!(send(&mut state, g::DESTROY_PIXMAP, &legacy.to_le_bytes()).is_empty()); - assert!(!state.glx_drawables.contains_key(&legacy)); - let out = send(&mut state, g::DESTROY_GLX_PIXMAP, &legacy.to_le_bytes()); - assert_glx_legacy_error( - "destroyed twice", - &out, - bad_pixmap, - legacy, - g::DESTROY_GLX_PIXMAP, - ); - - // GLX 1.3 pixmap destroyed by GLX 1.0 DestroyGLXPixmap. - let body = glx_legacy_words(&[0, 0x101, pixmap, modern, 0]); - assert!(send(&mut state, g::CREATE_PIXMAP, &body).is_empty()); - assert!(send(&mut state, g::DESTROY_GLX_PIXMAP, &modern.to_le_bytes()).is_empty()); - assert!(!state.glx_drawables.contains_key(&modern)); - } - - /// CreateGLXPixmap, DestroyGLXPixmap, QueryContext and IsDirect are all - /// `REQUEST_SIZE_MATCH` in Xorg's GLXVND stubs: a short or long request - /// is core `BadLength`, and nothing is created. - #[test] - fn glx10_fixed_size_requests_reject_wrong_length() { - use yserver_protocol::x11::{error, glx as g}; - - let (mut state, mut backend, mut peer) = glx_legacy_fixture(); - let pixmap = GLX_TEST_XID_BASE | 0x01; - glx_legacy_x_pixmap(&mut state, pixmap, 24, None); - let mut long_create = create_glx_pixmap_body( - 0, - crate::resources::ROOT_VISUAL.0, - pixmap, - GLX_TEST_XID_BASE | 0x02, - ); - long_create.extend_from_slice(&[0; 4]); - let short_create = &long_create[..12]; - for (what, minor, body) in [ - ( - "CreateGLXPixmap long", - g::CREATE_GLX_PIXMAP, - long_create.as_slice(), - ), - ("CreateGLXPixmap short", g::CREATE_GLX_PIXMAP, short_create), - ("DestroyGLXPixmap long", g::DESTROY_GLX_PIXMAP, &[0; 8][..]), - ("DestroyGLXPixmap empty", g::DESTROY_GLX_PIXMAP, &[][..]), - ("QueryContext long", g::QUERY_CONTEXT, &[0; 8][..]), - ("QueryContext empty", g::QUERY_CONTEXT, &[][..]), - ("IsDirect long", g::IS_DIRECT, &[0; 8][..]), - ("IsDirect empty", g::IS_DIRECT, &[][..]), - ] { - let out = glx_legacy_send(&mut state, &mut backend, &mut peer, 1, minor, body); - assert_glx_legacy_error(what, &out, error::BAD_LENGTH, 0, minor); - } - assert!(state.glx_drawables.is_empty()); - } - - /// `QueryContext` (GLX_EXT_import_context) answers Xorg's five - /// attributes in Xorg's order (glxcmds.c `DoQueryContext`) for every - /// creation request, to any client, and `GLXBadContext` for an XID that - /// is not a live context. `IsDirect` reports the creation request's - /// `isDirect` and shares the `GLXBadContext` rule. - #[test] - fn glx_query_context_and_is_direct_match_xorg() { - use yserver_protocol::x11::glx as g; - - let (mut state, mut backend, mut peer) = glx_legacy_fixture(); - let mut peer2 = install_client(&mut state, 2); - let bad_context = crate::nested::GLX_FIRST_ERROR + g::ERROR_GLX_BAD_CONTEXT; - let root_visual = crate::resources::ROOT_VISUAL.0; - let ctx1 = GLX_TEST_XID_BASE | 0x11; - let ctx2 = GLX_TEST_XID_BASE | 0x12; - let ctx3 = GLX_TEST_XID_BASE | 0x13; - let ctx4 = GLX_TEST_XID_BASE | 0x14; - let ctx5 = GLX_TEST_XID_BASE | 0x15; - - let creates: [(u8, Vec); 5] = [ - // CreateContext: context visual screen share isDirect - (g::CREATE_CONTEXT, vec![ctx1, root_visual, 0, 0, 1]), - // CreateNewContext (visual-less FBConfig, share ctx1): - // context fbconfig screen renderType share isDirect - ( - g::CREATE_NEW_CONTEXT, - vec![ctx2, 0x104, 0, g::GLX_RGBA_TYPE, ctx1, 1], - ), - // CreateContextAttribsARB (share ctx1, GL 3.0): - // context fbconfig screen share isDirect numAttribs attribs - ( - g::CREATE_CONTEXT_ATTRIBS_ARB, - vec![ctx3, 0x101, 0, ctx1, 1, 2, 0x2091, 3, 0x2092, 0], - ), - // CreateContextAttribsARB with GLX_RENDER_TYPE = GLX_RGBA_TYPE. - ( - g::CREATE_CONTEXT_ATTRIBS_ARB, - vec![ - ctx4, - 0x101, - 0, - 0, - 1, - 1, - g::GLX_RENDER_TYPE, - g::GLX_RGBA_TYPE, - ], - ), - // CreateContext asking for an indirect context (isDirect 0). - (g::CREATE_CONTEXT, vec![ctx5, root_visual, 0, 0, 0]), - ]; - for (minor, words) in &creates { - let body = glx_legacy_words(words); - let out = glx_legacy_send(&mut state, &mut backend, &mut peer, 1, *minor, &body); - assert!(out.is_empty(), "create minor {minor}: got {out:02x?}"); - } - - let expect = |share: u32, visual: u32, fbconfig: u32| { - vec![ - (g::GLX_SHARE_CONTEXT_EXT, share), - (g::GLX_VISUAL_ID, visual), - (g::GLX_SCREEN, 0), - (g::GLX_FBCONFIG_ID, fbconfig), - (g::GLX_RENDER_TYPE, g::GLX_RGBA_TYPE), - ] - }; - for (ctx, share, visual, fbconfig) in [ - // Xvfb: 0x800a=0 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 - (ctx1, 0, root_visual, 0x101), - // Xvfb: 0x800a=ctx1 0x800b=0 0x800c=0 0x8013=0x41 0x8011=0x8014 - (ctx2, ctx1, 0, 0x104), - // Xvfb: 0x800a=ctx1 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 - (ctx3, ctx1, root_visual, 0x101), - // Xvfb: 0x800a=0 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 - (ctx4, 0, root_visual, 0x101), - // Xvfb +iglx: 0x800a=0 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 - (ctx5, 0, root_visual, 0x101), - ] { - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::QUERY_CONTEXT, - &ctx.to_le_bytes(), - ); - assert_eq!( - glx_legacy_reply_pairs(&out), - expect(share, visual, fbconfig), - "QueryContext(0x{ctx:x})" - ); - } - - // Another client may query and IsDirect it: that is what - // import_context is for. - let ctx1_body = ctx1.to_le_bytes(); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer2, - 2, - g::QUERY_CONTEXT, - &ctx1_body, - ); - assert_eq!(glx_legacy_reply_pairs(&out), expect(0, root_visual, 0x101)); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer2, - 2, - g::IS_DIRECT, - &ctx1_body, - ); - assert_eq!(out.len(), 32, "IsDirect reply is 32 bytes"); - assert_eq!(out[0], 1, "IsDirect reply"); - assert_eq!(&out[4..8], &[0; 4], "IsDirect reply length 0"); - assert_eq!(out[8], 1, "IsDirect(ctx1) = True"); - // Xvfb +iglx: IsDirect of a context created with isDirect 0 is 0. - // (Without +iglx Xorg refuses that CreateContext with BadValue.) - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::IS_DIRECT, - &ctx5.to_le_bytes(), - ); - assert_eq!((out.len(), out[0], out[8]), (32, 1, 0), "IsDirect(ctx5)"); - - let pixmap = GLX_TEST_XID_BASE | 0x01; - let glx_pixmap = GLX_TEST_XID_BASE | 0x02; - glx_legacy_x_pixmap(&mut state, pixmap, 24, None); - let body = create_glx_pixmap_body(0, root_visual, pixmap, glx_pixmap); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::CREATE_GLX_PIXMAP, - &body, - ); - assert!(out.is_empty()); - for (what, xid) in [ - ("unknown", 0x5a_5a5a), - ("GLX pixmap", glx_pixmap), - ("None", 0), - ] { - for minor in [g::QUERY_CONTEXT, g::IS_DIRECT] { - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - minor, - &xid.to_le_bytes(), - ); - assert_glx_legacy_error(what, &out, bad_context, xid, minor); - } - } - - let ctx2_body = ctx2.to_le_bytes(); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::DESTROY_CONTEXT, - &ctx2_body, - ); - assert!(out.is_empty()); - let out = glx_legacy_send( - &mut state, - &mut backend, - &mut peer, - 1, - g::QUERY_CONTEXT, - &ctx2_body, - ); - assert_glx_legacy_error( - "destroyed context", - &out, - bad_context, - ctx2, - g::QUERY_CONTEXT, - ); - } - - /// `GetDrawableAttributes` on a GLXPixmap/GLXWindow must report the - /// geometry of the *backing* X drawable. The GLX XID is a fresh - /// client-allocated id with no X resource behind it, so resolving the - /// geometry from the GLX XID itself always missed and fell through to - /// `unwrap_or((0, 0))`. Measured on the wire against `libGLX_nvidia` - /// (2026-08-03): a 64×32 backing drawable was reported as - /// `GLX_WIDTH`/`GLX_HEIGHT` = 0. Xorg reads `pGlxDraw->pDraw->width` / - /// `->height` (glxcmds.c:1891). Against the old logic this test FAILS - /// with 0×0. - #[test] - fn glx_drawable_attributes_report_backing_drawable_geometry() { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - let x_pixmap_xid: u32 = 0x2000; - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(x_pixmap_xid), - drawable: ROOT_WINDOW, - width: 64, - height: 32, - }, - ); - - let glx_xid: u32 = 0x4000_0001; - let fbconfig: u32 = 0x101; - let mut create_body = Vec::new(); - create_body.extend_from_slice(&0u32.to_le_bytes()); // screen = 0 - create_body.extend_from_slice(&fbconfig.to_le_bytes()); - create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); - create_body.extend_from_slice(&glx_xid.to_le_bytes()); - let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: g::CREATE_PIXMAP, - length_units, - }, - &create_body, - None, - ) - .expect("process_request CREATE_PIXMAP"); - - let attribs = drawable_attributes_for(&state, glx_xid); - let get = |key: u32| { - attribs - .iter() - .find(|(k, _)| *k == key) - .map(|(_, v)| *v) - .unwrap_or_else(|| panic!("attribute 0x{key:x} must be present")) - }; - assert_eq!(get(g::GLX_WIDTH), 64, "GLX_WIDTH must track the X pixmap"); - assert_eq!(get(g::GLX_HEIGHT), 32, "GLX_HEIGHT must track the X pixmap"); - assert_eq!( - get(g::GLX_FBCONFIG_ID), - fbconfig, - "a registered GLX drawable must report its real fbconfig" - ); - } - - /// Naked X window (GLX 1.2 pattern, no GLX record): Xorg skips the - /// whole `pGlxDraw` block — `GLX_FBCONFIG_ID` / `GLX_TEXTURE_TARGET_EXT` - /// / `GLX_EVENT_MASK` must be **absent**, not present-and-zero — and - /// still ends with `GLX_DRAWABLE_TYPE = GLX_WINDOW_BIT` - /// (glxcmds.c:1875-1914). Asserts exact set and order. - #[test] - fn glx_drawable_attributes_naked_window_matches_xorg() { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let client_id = ClientId(1); - let window_xid: u32 = 0x2000; - state.resources.create_window( - client_id, - CreateWindowRequest { - depth: 24, - window: ResourceId(window_xid), - parent: ROOT_WINDOW, - width: 64, - height: 32, - ..Default::default() - }, - ); - - let attribs = drawable_attributes_for(&state, window_xid); - assert_eq!( - attribs, - vec![ - (g::GLX_Y_INVERTED_EXT, 0), - (g::GLX_WIDTH, 64), - (g::GLX_HEIGHT, 32), - (g::GLX_SCREEN, 0), - (g::GLX_DRAWABLE_TYPE, g::GLX_WINDOW_BIT), - ], - "naked-window attribute set and order must match glxcmds.c:1889-1914" - ); - } - - /// Registered GLXWindow: the `pGlxDraw` block is present, in Xorg's - /// order (glxcmds.c:1894-1906), with `GLX_STEREO_TREE_EXT = 0` for - /// window-type drawables and `GLX_DRAWABLE_TYPE = GLX_WINDOW_BIT` last. - #[test] - fn glx_drawable_attributes_glx_window_matches_xorg() { - use crate::server::{GlxDrawable, GlxDrawableKind}; - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let client_id = ClientId(1); - let x_window: u32 = 0x2000; - state.resources.create_window( - client_id, - CreateWindowRequest { - depth: 24, - window: ResourceId(x_window), - parent: ROOT_WINDOW, - width: 64, - height: 32, - ..Default::default() - }, - ); - let glx_xid: u32 = 0x4000_0001; - state.glx_drawables.insert( - glx_xid, - GlxDrawable { - owner: client_id, - kind: GlxDrawableKind::Window, - x_drawable: x_window, - fbconfig: 0x101, - width: 0, - height: 0, - event_mask: 0, - glx_export_host_xid: None, - texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, - }, - ); - - let attribs = drawable_attributes_for(&state, glx_xid); - assert_eq!( - attribs, - vec![ - (g::GLX_Y_INVERTED_EXT, 0), - (g::GLX_WIDTH, 64), - (g::GLX_HEIGHT, 32), - (g::GLX_SCREEN, 0), - (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_2D_EXT), - (g::GLX_EVENT_MASK, 0), - (g::GLX_FBCONFIG_ID, 0x101), - (g::GLX_STEREO_TREE_EXT, 0), - (g::GLX_DRAWABLE_TYPE, g::GLX_WINDOW_BIT), - ], - "GLXWindow attribute set and order must match glxcmds.c:1889-1914" - ); - } - - /// Registered GLXPixmap: like GLXWindow but without - /// `GLX_STEREO_TREE_EXT` (window-only) and with - /// `GLX_DRAWABLE_TYPE = GLX_PIXMAP_BIT`. - #[test] - fn glx_drawable_attributes_glx_pixmap_matches_xorg() { - use crate::server::{GlxDrawable, GlxDrawableKind}; - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let client_id = ClientId(1); - let x_pixmap: u32 = 0x2000; - state.resources.create_pixmap( - client_id, - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(x_pixmap), - drawable: ROOT_WINDOW, - width: 64, - height: 32, - }, - ); - let glx_xid: u32 = 0x4000_0001; - state.glx_drawables.insert( - glx_xid, - GlxDrawable { - owner: client_id, - kind: GlxDrawableKind::Pixmap, - x_drawable: x_pixmap, - fbconfig: 0x101, - width: 0, - height: 0, - event_mask: 0, - glx_export_host_xid: None, - texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, - }, - ); - - let attribs = drawable_attributes_for(&state, glx_xid); - assert_eq!( - attribs, - vec![ - (g::GLX_Y_INVERTED_EXT, 0), - (g::GLX_WIDTH, 64), - (g::GLX_HEIGHT, 32), - (g::GLX_SCREEN, 0), - (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_2D_EXT), - (g::GLX_EVENT_MASK, 0), - (g::GLX_FBCONFIG_ID, 0x101), - (g::GLX_DRAWABLE_TYPE, g::GLX_PIXMAP_BIT), - ], - "GLXPixmap attribute set and order must match glxcmds.c:1889-1914" - ); - } - - /// Registered pbuffer: geometry from the record, - /// `GLX_PRESERVED_CONTENTS = 1` (pbuffer-only) and - /// `GLX_DRAWABLE_TYPE = GLX_PBUFFER_BIT`. - #[test] - fn glx_drawable_attributes_pbuffer_matches_xorg() { - use crate::server::{GlxDrawable, GlxDrawableKind}; - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let client_id = ClientId(1); - let glx_xid: u32 = 0x4000_0001; - state.glx_drawables.insert( - glx_xid, - GlxDrawable { - owner: client_id, - kind: GlxDrawableKind::Pbuffer, - x_drawable: glx_xid, - fbconfig: 0x101, - width: 64, - height: 32, - event_mask: 0, - glx_export_host_xid: None, - texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, - }, - ); - - let attribs = drawable_attributes_for(&state, glx_xid); - assert_eq!( - attribs, - vec![ - (g::GLX_Y_INVERTED_EXT, 0), - (g::GLX_WIDTH, 64), - (g::GLX_HEIGHT, 32), - (g::GLX_SCREEN, 0), - (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_2D_EXT), - (g::GLX_EVENT_MASK, 0), - (g::GLX_FBCONFIG_ID, 0x101), - (g::GLX_PRESERVED_CONTENTS, 1), - (g::GLX_DRAWABLE_TYPE, g::GLX_PBUFFER_BIT), - ], - "pbuffer attribute set and order must match glxcmds.c:1889-1914" - ); - } - - /// Request-level wire test: `GET_DRAWABLE_ATTRIBUTES` on a naked X - /// window must deliver a well-formed reply — `length = 2n` 4-byte - /// units, `numAttribs = n`, pairs in Xorg order — with no - /// `GLX_FBCONFIG_ID` anywhere in the payload. - #[test] - fn glx_get_drawable_attributes_naked_window_wire_reply() { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - let window_xid: u32 = 0x2000; - state.resources.create_window( - client_id, - CreateWindowRequest { - depth: 24, - window: ResourceId(window_xid), - parent: ROOT_WINDOW, - width: 64, - height: 32, - ..Default::default() - }, - ); - - let body = window_xid.to_le_bytes().to_vec(); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(7), - RequestHeader { - opcode: 148, - data: g::GET_DRAWABLE_ATTRIBUTES, - length_units, - }, - &body, - None, - ) - .expect("process_request GET_DRAWABLE_ATTRIBUTES"); - - let expected: [(u32, u32); 5] = [ - (g::GLX_Y_INVERTED_EXT, 0), - (g::GLX_WIDTH, 64), - (g::GLX_HEIGHT, 32), - (g::GLX_SCREEN, 0), - (g::GLX_DRAWABLE_TYPE, g::GLX_WINDOW_BIT), - ]; - let n = u32::try_from(expected.len()).expect("fits"); - - peer.set_nonblocking(true).unwrap(); - let mut header = [0u8; 32]; - peer.read_exact(&mut header) - .expect("reply header delivered"); - assert_eq!(header[0], 1, "byte 0 must be 1 (Reply)"); - assert_eq!(u16::from_le_bytes([header[2], header[3]]), 7, "sequence"); - assert_eq!( - u32::from_le_bytes([header[4], header[5], header[6], header[7]]), - 2 * n, - "length must be 2 * numAttribs 4-byte units" - ); - assert_eq!( - u32::from_le_bytes([header[8], header[9], header[10], header[11]]), - n, - "numAttribs" - ); - - let mut pairs = vec![0u8; (2 * n) as usize * 4]; - peer.read_exact(&mut pairs) - .expect("attribute pairs delivered"); - for (i, &(key, value)) in expected.iter().enumerate() { - let got_key = u32::from_le_bytes([ - pairs[i * 8], - pairs[i * 8 + 1], - pairs[i * 8 + 2], - pairs[i * 8 + 3], - ]); - let got_value = u32::from_le_bytes([ - pairs[i * 8 + 4], - pairs[i * 8 + 5], - pairs[i * 8 + 6], - pairs[i * 8 + 7], - ]); - assert_eq!((got_key, got_value), (key, value), "pair {i}"); - } - } - - #[test] - fn glx_vendor_names_query_answers_from_server_state() { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // The value the backend derived at startup, not the constant. - state.glx_vendor_names = "nvidia mesa".to_string(); - - // QueryServerString body: screen (u32), name (u32). - let mut body = Vec::new(); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&g::VENDOR_NAMES_EXT.to_le_bytes()); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(9), - RequestHeader { - opcode: 148, - data: g::QUERY_SERVER_STRING, - length_units, - }, - &body, - None, - ) - .expect("process_request QUERY_SERVER_STRING"); - - peer.set_nonblocking(true).unwrap(); - let mut header = [0u8; 32]; - peer.read_exact(&mut header) - .expect("reply header delivered"); - assert_eq!(header[0], 1, "byte 0 must be 1 (Reply)"); - assert_eq!(u16::from_le_bytes([header[2], header[3]]), 9, "sequence"); - - // Reply layout, read off encode_string_reply (glx.rs:267-291): - // 0 1 (Reply) 1 0 (pad) - // 2..4 sequence 4..8 length_units = padded / 4 - // 8..12 pad1 12..16 n (string length INCLUDING NUL) - // 16..32 pad3..pad6 then bytes + NUL + zero padding - // Note n sits at 12, not 8 -- offset 8 is pad1. The - // GetDrawableAttributes reply carries numAttribs at 8, which is a - // different reply shape; do not copy that offset here. - let n = u32::from_le_bytes([header[12], header[13], header[14], header[15]]); - assert_eq!(n as usize, "nvidia mesa".len() + 1, "n counts the NUL"); - - let padded = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize * 4; - assert_eq!(padded, 12, "11 bytes + NUL, already 4-aligned"); - let mut tail = vec![0u8; padded]; - peer.read_exact(&mut tail).expect("reply tail delivered"); - let s = String::from_utf8_lossy(&tail); - assert!( - s.starts_with("nvidia mesa"), - "arm must read state, not the VENDOR_NAMES constant; got {s:?}" - ); - } - - /// Error arm 1: a naked X **pixmap** (resolvable as a drawable but not - /// a window, no GLX record) gets the extension error `GLXBadDrawable` - /// (`GLX_FIRST_ERROR + 2`) — GLXVND forwards pixmaps because they carry - /// RC_DRAWABLE, then `dixLookupWindow` fails (glxcmds.c:1873-1880). - #[test] - fn glx_get_drawable_attributes_naked_pixmap_returns_glx_bad_drawable() { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - let pixmap_xid: u32 = 0x2000; - state.resources.create_pixmap( - client_id, - CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(pixmap_xid), - drawable: ROOT_WINDOW, - width: 64, - height: 32, - }, - ); - - let body = pixmap_xid.to_le_bytes().to_vec(); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: g::GET_DRAWABLE_ATTRIBUTES, - length_units, - }, - &body, - None, - ) - .expect("process_request should not hard-error"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("GLXBadDrawable error packet must be delivered"); - assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); - let expected_code = - crate::nested::GLX_FIRST_ERROR + yserver_protocol::x11::glx::ERROR_GLX_BAD_DRAWABLE; - assert_eq!( - buf[1], expected_code, - "expected GLXBadDrawable ({}), got {}", - expected_code, buf[1] - ); - } - - /// Error arm 2: an XID that is not a drawable at all gets **core - /// `BadDrawable` (9)** — GLXVND's XID-map lookup returns NULL and the - /// dispatch stub errors out before `DoGetDrawableAttributes` is ever - /// reached (glx/vnd_dispatch_stubs.c:456-472). The two error arms must - /// not be collapsed. - #[test] - fn glx_get_drawable_attributes_unknown_xid_returns_core_bad_drawable() { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - let unknown_xid: u32 = 0x9999; - let body = unknown_xid.to_le_bytes().to_vec(); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: g::GET_DRAWABLE_ATTRIBUTES, - length_units, - }, - &body, - None, - ) - .expect("process_request should not hard-error"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("core BadDrawable error packet must be delivered"); - assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); - assert_eq!( - buf[1], - yserver_protocol::x11::error::BAD_DRAWABLE, - "expected core BadDrawable (9), got {}", - buf[1] - ); - assert_eq!( - u16::from_le_bytes([buf[8], buf[9]]), - u16::from(g::GET_DRAWABLE_ATTRIBUTES), - "error must identify GLX::GetDrawableAttributes as the minor opcode" - ); - assert_eq!( - buf[10], - crate::nested::GLX_MAJOR_OPCODE, - "error must identify GLX as the major opcode" - ); - } - - /// Read the `contextTag` field (bytes 8..12) out of a 32-byte - /// `MakeCurrent` reply. - fn make_current_reply_tag(buf: &[u8; 32]) -> u32 { - u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]) - } - - /// Drive a `MakeCurrent`/`MakeContextCurrent` request and return the - /// 32-byte reply. `context` is placed at the minor-specific offset. - fn drive_make_current(minor: u8, context: u32) -> [u8; 32] { - use yserver_protocol::x11::glx as g; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Layouts (glxproto.h:225-233, :471-481), body-relative: - // minor 5 MakeCurrent: drawable, context, oldContextTag - // minor 26 MakeContextCurrent: oldContextTag, drawable, readdrawable, context - let mut body = Vec::new(); - if minor == g::MAKE_CURRENT { - body.extend_from_slice(&0x2000u32.to_le_bytes()); // drawable - body.extend_from_slice(&context.to_le_bytes()); // context - body.extend_from_slice(&0u32.to_le_bytes()); // oldContextTag - } else { - body.extend_from_slice(&0u32.to_le_bytes()); // oldContextTag - body.extend_from_slice(&0x2000u32.to_le_bytes()); // drawable - body.extend_from_slice(&0x2000u32.to_le_bytes()); // readdrawable - body.extend_from_slice(&context.to_le_bytes()); // context - } - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: minor, - length_units, - }, - &body, - None, - ) - .expect("process_request MakeCurrent"); - - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("MakeCurrent reply delivered"); - assert_eq!(buf[0], 1, "byte 0 must be 1 (Reply)"); - buf - } - - /// D6: the release form (`context == None`) must return - /// `contextTag = 0` — tag 0 is reserved by the protocol to mean "no - /// context current" (Xorg vndcmds.c:232-234, :271-273). Both minors. - #[test] - fn glx_make_current_release_returns_zero_tag() { - use yserver_protocol::x11::glx as g; - - let buf = drive_make_current(g::MAKE_CURRENT, 0); - assert_eq!( - make_current_reply_tag(&buf), - 0, - "MakeCurrent release must return contextTag = 0" - ); - } - - #[test] - fn glx_make_context_current_release_returns_zero_tag() { - use yserver_protocol::x11::glx as g; - - let buf = drive_make_current(g::MAKE_CONTEXT_CURRENT, 0); - assert_eq!( - make_current_reply_tag(&buf), - 0, - "MakeContextCurrent release must return contextTag = 0" - ); - } - - /// D6: a non-null context still gets a fresh non-zero tag, for both - /// minors (regression guard on the release fix). - #[test] - fn glx_make_current_non_null_context_returns_nonzero_tag() { - use yserver_protocol::x11::glx as g; - - let buf = drive_make_current(g::MAKE_CURRENT, 0x3000); - assert_ne!( - make_current_reply_tag(&buf), - 0, - "MakeCurrent with a context must return a non-zero tag" - ); - } - - #[test] - fn glx_make_context_current_non_null_context_returns_nonzero_tag() { - use yserver_protocol::x11::glx as g; - - let buf = drive_make_current(g::MAKE_CONTEXT_CURRENT, 0x3000); - assert_ne!( - make_current_reply_tag(&buf), - 0, - "MakeContextCurrent with a context must return a non-zero tag" - ); - } - - /// GLX Task 3.4 regression: the export ref must be released on - /// `glXDestroyPixmap` even when the client called X11 `FreePixmap` on - /// the underlying X pixmap FIRST (a common compositor ordering). The - /// release site must use the host_xid stored at acquire time, NOT a - /// re-resolution via `resources.pixmap(x_drawable)` (which is gone after - /// FreePixmap). Against the old re-resolving logic this test FAILS: - /// ReleaseGlxPixmapExport is never recorded → the export ref leaks. - #[test] - fn glx_destroy_releases_export_even_after_free_pixmap() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Register an X pixmap with a known host_xid. - let x_pixmap_xid: u32 = 0x3000; - let host_xid_raw: u32 = 0xdead_0002; - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: ResourceId(x_pixmap_xid), - drawable: ROOT_WINDOW, - width: 64, - height: 32, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - ResourceId(x_pixmap_xid), - crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), - )); - - let glx_xid: u32 = 0x4000_0003; - - // glXCreatePixmap — acquire. - let mut create_body = Vec::new(); - create_body.extend_from_slice(&0u32.to_le_bytes()); // screen - create_body.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig - create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); - create_body.extend_from_slice(&glx_xid.to_le_bytes()); - let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::CREATE_PIXMAP, - length_units, - }, - &create_body, - None, - ) - .expect("process_request CREATE_PIXMAP"); - assert!( - backend - .calls() - .contains(&RecordedCall::AcquireGlxPixmapExport(host_xid_raw)), - "AcquireGlxPixmapExport must be recorded" - ); - - // X11 FreePixmap on the underlying X pixmap BEFORE glXDestroyPixmap. - // This removes the pixmap from the resource table — any subsequent - // re-resolution of x_drawable→host_xid would fail. - let free_body = x_pixmap_xid.to_le_bytes().to_vec(); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(2), - RequestHeader { - opcode: 54, // FreePixmap - data: 0, - length_units: 2, - }, - &free_body, - None, - ) - .expect("process_request FreePixmap"); - // Sanity: the pixmap resource is really gone. - assert!( - state.resources.pixmap(ResourceId(x_pixmap_xid)).is_none(), - "X pixmap must be freed by FreePixmap" - ); - - // glXDestroyPixmap — must still release using the stored host_xid. - let destroy_body = glx_xid.to_le_bytes().to_vec(); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(3), - RequestHeader { - opcode: 148, - data: x11glx::DESTROY_PIXMAP, - length_units: 2, - }, - &destroy_body, - None, - ) - .expect("process_request DESTROY_PIXMAP"); - - assert!( - !state.glx_drawables.contains_key(&glx_xid), - "GlxDrawable must be removed after DestroyPixmap" - ); - // THE REGRESSION ASSERTION: release must fire despite the early FreePixmap. - assert!( - backend - .calls() - .contains(&RecordedCall::ReleaseGlxPixmapExport(host_xid_raw)), - "ReleaseGlxPixmapExport must be recorded even after the X pixmap was \ - freed before glXDestroyPixmap (no export-ref leak)" - ); - } - - /// GLX Task 3.4: `glXCreatePixmap` with a non-existent X pixmap XID - /// must reply with a GLXBadPixmap error rather than silently inserting. - #[test] - fn glx_create_pixmap_with_missing_x_pixmap_returns_glx_bad_pixmap() { - use yserver_protocol::x11::glx as x11glx; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Use an XID that was never registered. - let bad_x_pixmap_xid: u32 = 0x9999; - let glx_xid: u32 = 0x4000_0002; - - let mut create_body = Vec::new(); - create_body.extend_from_slice(&0u32.to_le_bytes()); // screen - create_body.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig - create_body.extend_from_slice(&bad_x_pixmap_xid.to_le_bytes()); - create_body.extend_from_slice(&glx_xid.to_le_bytes()); - let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); - - let outcome = process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::CREATE_PIXMAP, - length_units, - }, - &create_body, - None, - ) - .expect("process_request should not hard-error"); - assert!(matches!(outcome, RequestOutcome::Handled)); - - // Nothing inserted in glx_drawables. - assert!( - !state.glx_drawables.contains_key(&glx_xid), - "GlxDrawable must NOT be inserted when X pixmap does not exist" - ); - - // Error packet must be delivered: GLXBadPixmap = GLX_FIRST_ERROR + 3 = 172. - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - peer.read_exact(&mut buf) - .expect("GLXBadPixmap error packet must be delivered"); - assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); - let expected_code = - crate::nested::GLX_FIRST_ERROR + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP; - assert_eq!( - buf[1], expected_code, - "expected GLXBadPixmap ({}), got {}", - expected_code, buf[1] - ); - } - - /// GLX Task 3.5: `VendorPrivate` with vendor_code 1330 (`BindTexImageEXT`) - /// over a valid GLXPixmap must NOT be rejected with - /// `GLXUnsupportedPrivateRequest`; it must succeed (return `Handled` - /// with no error packet delivered to the client). - /// - /// Secondary assertion: an unknown vendor code still gets - /// `GLXUnsupportedPrivateRequest` (preservation of the fallthrough). - #[test] - fn bind_tex_image_ext_is_dispatched_not_rejected() { - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Register an X pixmap with a known host_xid — mirrors the - // Task 3.4 test setup so we can get a GlxDrawable into state. - let x_pixmap_xid: u32 = 0x2000; - let host_xid_raw: u32 = 0xdead_1330; - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: yserver_protocol::x11::ResourceId(x_pixmap_xid), - drawable: ROOT_WINDOW, - width: 32, - height: 32, - }, - ); - assert!( - state.resources.set_pixmap_host_xid( - yserver_protocol::x11::ResourceId(x_pixmap_xid), - crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), - ), - "set_pixmap_host_xid must succeed" - ); - - // First, call GLX::CreatePixmap to insert a GlxDrawable. - let glx_xid: u32 = 0x4000_0002; - let fbconfig: u32 = 0x101; - let mut create_body = Vec::new(); - create_body.extend_from_slice(&0u32.to_le_bytes()); // screen = 0 - create_body.extend_from_slice(&fbconfig.to_le_bytes()); - create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); - create_body.extend_from_slice(&glx_xid.to_le_bytes()); - let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::CREATE_PIXMAP, - length_units, - }, - &create_body, - None, - ) - .expect("process_request CREATE_PIXMAP"); - - // Build a VendorPrivate body for BindTexImageEXT (1330): - // [vendor_code=1330][context_tag=0][glx_drawable=glx_xid][buffer=GLX_FRONT_LEFT_EXT] - let mut bind_body = Vec::new(); - bind_body.extend_from_slice(&x11glx::VENDOR_CODE_BIND_TEX_IMAGE.to_le_bytes()); - bind_body.extend_from_slice(&0u32.to_le_bytes()); // context_tag - bind_body.extend_from_slice(&glx_xid.to_le_bytes()); - bind_body.extend_from_slice(&x11glx::GLX_FRONT_LEFT_EXT.to_le_bytes()); - let length_units = u32::try_from(1 + bind_body.len().div_ceil(4)).expect("fits"); - let outcome = process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(2), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE, // minor = 16 - length_units, - }, - &bind_body, - None, - ) - .expect("process_request VENDOR_PRIVATE BindTexImageEXT must not hard-error"); - assert!( - matches!(outcome, RequestOutcome::Handled), - "BindTexImageEXT must return Handled, got {outcome:?}" - ); - - // No error packet must be delivered to the client. - peer.set_nonblocking(true).unwrap(); - let mut buf = [0u8; 32]; - match peer.read(&mut buf) { - Ok(0) | Err(_) => { /* no data written — correct */ } - Ok(n) => { - assert_ne!( - buf[0], 0, - "BindTexImageEXT must not deliver an X11 error packet; \ - got {n} bytes, first byte={} (0=Error)", - buf[0] - ); - } - } - peer.set_nonblocking(false).unwrap(); - - // The unsupported-private rejection must still fire for unknown codes. - let mut unknown_body = Vec::new(); - unknown_body.extend_from_slice(&9999u32.to_le_bytes()); // unknown vendor code - unknown_body.extend_from_slice(&0u32.to_le_bytes()); - unknown_body.extend_from_slice(&0u32.to_le_bytes()); - unknown_body.extend_from_slice(&0u32.to_le_bytes()); - let length_units = u32::try_from(1 + unknown_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(3), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE, - length_units, - }, - &unknown_body, - None, - ) - .expect("process_request VENDOR_PRIVATE unknown must not hard-error"); - - // Error packet for the unknown vendor code. - peer.set_nonblocking(true).unwrap(); - let mut buf2 = [0u8; 32]; - peer.read_exact(&mut buf2) - .expect("GLXUnsupportedPrivateRequest error packet must be delivered"); - assert_eq!(buf2[0], 0, "byte 0 must be 0 (Error class)"); - let expected_unsupported = crate::nested::GLX_FIRST_ERROR - + yserver_protocol::x11::glx::ERROR_GLX_UNSUPPORTED_PRIVATE_REQUEST; - assert_eq!( - buf2[1], expected_unsupported, - "expected GLXUnsupportedPrivateRequest ({expected_unsupported}), got {}", - buf2[1] - ); - peer.set_nonblocking(false).unwrap(); - } - - /// GLX Task 3.5 regression (codex review): `BindTexImageEXT` / - /// `ReleaseTexImageEXT` must be DECOUPLED from the GLXPixmap LIFETIME - /// refcount (`glx_refs`). - /// - /// Bind uses the promote-only hook (`promote_pixmap_exportable`), - /// idempotently, taking NO lifetime ref — so repeated rebinds (the - /// normal TFP per-frame pattern) do not grow `glx_refs` and leak the - /// backing. Release is a lifetime no-op — it must NOT call - /// `release_glx_pixmap_export`, or a release without a matching bind - /// would tear the backing down while the GLXPixmap is still alive. - /// - /// Against the OLD acquire/release-based logic this test FAILS: the - /// three binds would record three `AcquireGlxPixmapExport` (and no - /// `PromotePixmapExportable`), and the release would record a - /// `ReleaseGlxPixmapExport`. - #[test] - fn bind_release_tex_image_do_not_touch_lifetime_refcount() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Register an X pixmap with a known host_xid. - let x_pixmap_xid: u32 = 0x2100; - let host_xid_raw: u32 = 0xdead_1331; - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: yserver_protocol::x11::ResourceId(x_pixmap_xid), - drawable: ROOT_WINDOW, - width: 32, - height: 32, - }, - ); - assert!( - state.resources.set_pixmap_host_xid( - yserver_protocol::x11::ResourceId(x_pixmap_xid), - crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), - ), - "set_pixmap_host_xid must succeed" - ); - - // glXCreatePixmap inserts the GlxDrawable and takes the ONE lifetime - // acquire ref (this is the legitimate AcquireGlxPixmapExport). - let glx_xid: u32 = 0x4000_0003; - let mut create_body = Vec::new(); - create_body.extend_from_slice(&0u32.to_le_bytes()); // screen - create_body.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig - create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); - create_body.extend_from_slice(&glx_xid.to_le_bytes()); - let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::CREATE_PIXMAP, - length_units, - }, - &create_body, - None, - ) - .expect("process_request CREATE_PIXMAP"); - - // Exactly one acquire (the lifetime ref) so far; no promote yet. - let after_create = backend.calls(); - assert_eq!( - after_create - .iter() - .filter(|c| matches!(c, RecordedCall::AcquireGlxPixmapExport(_))) - .count(), - 1, - "glXCreatePixmap must take exactly one lifetime acquire ref" - ); - let acquires_before_binds = after_create - .iter() - .filter(|c| matches!(c, RecordedCall::AcquireGlxPixmapExport(_))) - .count(); - let releases_before_binds = after_create - .iter() - .filter(|c| matches!(c, RecordedCall::ReleaseGlxPixmapExport(_))) - .count(); - - // Build a BindTexImageEXT VendorPrivate body. - let mut bind_body = Vec::new(); - bind_body.extend_from_slice(&x11glx::VENDOR_CODE_BIND_TEX_IMAGE.to_le_bytes()); - bind_body.extend_from_slice(&0u32.to_le_bytes()); // context_tag - bind_body.extend_from_slice(&glx_xid.to_le_bytes()); - bind_body.extend_from_slice(&x11glx::GLX_FRONT_LEFT_EXT.to_le_bytes()); - let bind_units = u32::try_from(1 + bind_body.len().div_ceil(4)).expect("fits"); - - // Bind THREE times (compositor per-frame / implicit-rebind pattern). - for seq in 2u16..=4 { - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(seq), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE, - length_units: bind_units, - }, - &bind_body, - None, - ) - .expect("process_request BindTexImageEXT"); - } - - let after_binds = backend.calls(); - // Each bind recorded a PromotePixmapExportable (the lightweight hook). - assert_eq!( - after_binds - .iter() - .filter(|c| matches!( - c, - RecordedCall::PromotePixmapExportable(h) if *h == host_xid_raw - )) - .count(), - 3, - "each BindTexImageEXT must record PromotePixmapExportable, not Acquire" - ); - // The binds must NOT have taken any extra lifetime ref. - assert_eq!( - after_binds - .iter() - .filter(|c| matches!(c, RecordedCall::AcquireGlxPixmapExport(_))) - .count(), - acquires_before_binds, - "BindTexImageEXT must NOT take a lifetime acquire ref (no leak on rebind)" - ); - assert_eq!( - after_binds - .iter() - .filter(|c| matches!(c, RecordedCall::ReleaseGlxPixmapExport(_))) - .count(), - releases_before_binds, - "BindTexImageEXT must NOT change the lifetime release count" - ); - - // Now ReleaseTexImageEXT — must be a lifetime no-op. - let mut rel_body = Vec::new(); - rel_body.extend_from_slice(&x11glx::VENDOR_CODE_RELEASE_TEX_IMAGE.to_le_bytes()); - rel_body.extend_from_slice(&0u32.to_le_bytes()); // context_tag - rel_body.extend_from_slice(&glx_xid.to_le_bytes()); - rel_body.extend_from_slice(&x11glx::GLX_FRONT_LEFT_EXT.to_le_bytes()); - let rel_units = u32::try_from(1 + rel_body.len().div_ceil(4)).expect("fits"); - process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(5), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE, - length_units: rel_units, - }, - &rel_body, - None, - ) - .expect("process_request ReleaseTexImageEXT"); - - // THE REGRESSION ASSERTION: release must NOT have dropped the - // lifetime ref — the backing survives until glXDestroyPixmap. - let after_release = backend.calls(); - assert_eq!( - after_release - .iter() - .filter(|c| matches!(c, RecordedCall::ReleaseGlxPixmapExport(_))) - .count(), - releases_before_binds, - "ReleaseTexImageEXT must NOT call release_glx_pixmap_export \ - (lifetime ref untouched; backing survives until glXDestroyPixmap)" - ); - } - - // ── RENDER::CreateAnimCursor (opcode 133 / minor 31) helpers ───────────── - - fn anim_cursor_body(cid: u32, elts: &[(u32, u32)]) -> Vec { - let mut b = cid.to_le_bytes().to_vec(); - for (cur, delay) in elts { - b.extend_from_slice(&cur.to_le_bytes()); - b.extend_from_slice(&delay.to_le_bytes()); - } - b - } - - fn seed_cursor(state: &mut ServerState, raw: u32, host: u32) { - state.resources.create_cursor(ClientId(1), ResourceId(raw)); - state.resources.set_cursor_host_xid( - ResourceId(raw), - crate::backend::CursorHandle::from_raw(host).unwrap(), - ); - } - - fn send_anim_cursor( - state: &mut ServerState, - backend: &mut RecordingBackend, - seq: u16, - body: &[u8], - ) { - process_request( - state, - backend, - ClientId(1), - SequenceNumber(seq), - RequestHeader { - opcode: 133, - data: 31, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - None, - ) - .expect("process_request"); - } - - #[test] - fn create_anim_cursor_empty_list_returns_bad_value() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let body = anim_cursor_body(0x4000, &[]); - send_anim_cursor(&mut state, &mut backend, 1, &body); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); - assert_eq!(bytes[1], x11::error::BAD_VALUE); - assert_eq!(&bytes[8..10], &31u16.to_le_bytes()); - assert_eq!(bytes[10], 133); - assert!(!state.resources.cursor_exists(ResourceId(0x4000))); - } - - #[test] - fn create_anim_cursor_odd_pairs_returns_bad_length() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_cursor(&mut state, 0x3000, 0x77); - // One full pair + 4 trailing bytes = not a multiple of 8. - let mut body = anim_cursor_body(0x4000, &[(0x3000, 50)]); - body.extend_from_slice(&0x3000u32.to_le_bytes()); - send_anim_cursor(&mut state, &mut backend, 1, &body); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32); - assert_eq!(bytes[1], x11::error::BAD_LENGTH); - assert_eq!(&bytes[8..10], &31u16.to_le_bytes()); - assert_eq!(bytes[10], 133); - assert!(!state.resources.cursor_exists(ResourceId(0x4000))); - } - - #[test] - fn create_anim_cursor_nested_anim_returns_bad_match() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_cursor(&mut state, 0x3000, 0x77); - // First anim cursor (fallback path on RecordingBackend). - let body = anim_cursor_body(0x4000, &[(0x3000, 50)]); - send_anim_cursor(&mut state, &mut backend, 1, &body); - let _ = read_all_available(&mut peer); // no error expected - assert!(state.resources.cursor_is_anim(ResourceId(0x4000))); - // Second anim cursor referencing the first → BadMatch. - let body2 = anim_cursor_body(0x4001, &[(0x4000, 50)]); - send_anim_cursor(&mut state, &mut backend, 2, &body2); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32); - assert_eq!(bytes[1], x11::error::BAD_MATCH); - // Xorg's AnimCursorCreate returns BadMatch without setting - // client->errorValue → value field must be zero. - assert_eq!(&bytes[4..8], &0u32.to_le_bytes()); - assert_eq!(&bytes[8..10], &31u16.to_le_bytes()); - assert_eq!(bytes[10], 133); - assert!(!state.resources.cursor_exists(ResourceId(0x4001))); - } - - #[test] - fn create_anim_cursor_fallback_aliases_first_frame_and_sets_anim() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - seed_cursor(&mut state, 0x3000, 0x77); - seed_cursor(&mut state, 0x3001, 0x78); - let body = anim_cursor_body(0x4000, &[(0x3000, 50), (0x3001, 75)]); - send_anim_cursor(&mut state, &mut backend, 1, &body); - let bytes = read_all_available(&mut peer); - assert!(bytes.is_empty(), "no error expected, got {bytes:02x?}"); - assert_eq!( - state.resources.cursor_host_xid(ResourceId(0x4000)), - Some(0x77) - ); - assert!(state.resources.cursor_is_anim(ResourceId(0x4000))); - } - - // ── GLX_SGIX_fbconfig dispatch tests ───────────────────────────────────── - - /// Build a VendorPrivateWithReply body for `GetFBConfigsSGIX` (vendor - /// code 65540): - /// [0..4] vendorCode - /// [4..8] pad1 = 0 - /// [8..12] screen = 0 - fn build_get_fb_configs_sgix_body(screen: u32) -> Vec { - use yserver_protocol::x11::glx as x11glx; - let mut body = Vec::new(); - body.extend_from_slice(&x11glx::VENDOR_CODE_GET_FB_CONFIGS_SGIX.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // pad1 - body.extend_from_slice(&screen.to_le_bytes()); - body - } - - /// `VendorPrivateWithReply` with vendor_code `GetFBConfigsSGIX` (65540) - /// must NOT be rejected with `GLXUnsupportedPrivateRequest`; it must - /// return a non-empty GetFBConfigs reply (real configs, not a stub). - #[test] - fn get_fb_configs_sgix_is_dispatched_not_rejected() { - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - let body = build_get_fb_configs_sgix_body(0); - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - - let outcome = process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE_WITH_REPLY, - length_units, - }, - &body, - None, - ) - .expect("process_request must not hard-error"); - - assert!( - matches!(outcome, RequestOutcome::Handled), - "GetFBConfigsSGIX must return Handled, got {outcome:?}" - ); - - // Must NOT deliver an error packet. - peer.set_nonblocking(true).unwrap(); - let bytes = read_all_available(&mut peer); - assert!( - !bytes.is_empty(), - "GetFBConfigsSGIX must deliver a reply packet" - ); - assert_ne!( - bytes[0], 0, - "byte 0 must not be 0 (Error); got {bytes:02x?}" - ); - // byte 0 = 1 (Reply), byte 8..12 = num_FB_configs > 0. - assert_eq!(bytes[0], 1, "byte 0 must be Reply type"); - let num_configs = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); - assert!( - num_configs > 0, - "GetFBConfigsSGIX must return at least one FBConfig, got {num_configs}" - ); - peer.set_nonblocking(false).unwrap(); - } - - /// `VendorPrivate` with vendor_code `CreateContextWithConfigSGIX` - /// (65541) must insert a `GlxContext` entry (no reply, no error). - #[test] - fn create_context_with_config_sgix_inserts_context() { - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - let context_xid: u32 = 0xABCD_0001; - let fbconfig: u32 = 0x101; - - // Build CreateContextWithConfigSGIX body: - // [0..4] vendorCode = 65541 - // [4..8] pad1 = 0 - // [8..12] context = context_xid - // [12..16] fbconfig = 0x101 - // [16..20] screen = 0 - // [20..24] renderType = 1 - // [24..28] shareList = 0 - // [28] isDirect = 1 - // [29..32] reserved = 0 - let mut body = Vec::new(); - body.extend_from_slice(&x11glx::VENDOR_CODE_CREATE_CONTEXT_WITH_CONFIG_SGIX.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // pad1 - body.extend_from_slice(&context_xid.to_le_bytes()); - body.extend_from_slice(&fbconfig.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // screen - body.extend_from_slice(&1u32.to_le_bytes()); // renderType - body.extend_from_slice(&0u32.to_le_bytes()); // shareList - body.push(1u8); // isDirect - body.push(0u8); // reserved1 - body.extend_from_slice(&0u16.to_le_bytes()); // reserved2 - - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - - let outcome = process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE, - length_units, - }, - &body, - None, - ) - .expect("process_request must not hard-error"); - - assert!( - matches!(outcome, RequestOutcome::Handled), - "CreateContextWithConfigSGIX must return Handled, got {outcome:?}" - ); - - // GlxContext must be inserted. - assert!( - state.glx_contexts.contains_key(&context_xid), - "GlxContext must be inserted for xid=0x{context_xid:x}" - ); - let ctx = &state.glx_contexts[&context_xid]; - assert_eq!(ctx.fbconfig, fbconfig, "fbconfig must be recorded"); - - // No error packet. - peer.set_nonblocking(true).unwrap(); - let bytes = read_all_available(&mut peer); - assert!( - bytes.is_empty(), - "CreateContextWithConfigSGIX must not deliver an error; got {bytes:02x?}" - ); - peer.set_nonblocking(false).unwrap(); - } - - /// `VendorPrivate` with vendor_code `CreateGLXPixmapWithConfigSGIX` - /// (65542) must insert a `GlxDrawable` entry and call - /// `acquire_glx_pixmap_export` — same semantics as `CREATE_PIXMAP`. - #[test] - fn create_glx_pixmap_with_config_sgix_inserts_drawable_and_acquires() { - use crate::backend::recording::RecordedCall; - use yserver_protocol::x11::glx as x11glx; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let client_id = ClientId(1); - - // Register an X pixmap with a known host_xid. - let x_pixmap_xid: u32 = 0x3000; - let host_xid_raw: u32 = 0xdead_5542; - state.resources.create_pixmap( - client_id, - yserver_protocol::x11::CreatePixmapRequest { - depth: 24, - pixmap: yserver_protocol::x11::ResourceId(x_pixmap_xid), - drawable: ROOT_WINDOW, - width: 64, - height: 64, - }, - ); - assert!( - state.resources.set_pixmap_host_xid( - yserver_protocol::x11::ResourceId(x_pixmap_xid), - crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), - ), - "set_pixmap_host_xid must succeed" - ); - - let glx_xid: u32 = 0x5000_0010; - let fbconfig: u32 = 0x101; - - // Build CreateGLXPixmapWithConfigSGIX body: - // [0..4] vendorCode = 65542 - // [4..8] pad1 = 0 - // [8..12] screen = 0 - // [12..16] fbconfig = 0x101 - // [16..20] pixmap = x_pixmap_xid - // [20..24] glxpixmap = glx_xid - let mut body = Vec::new(); - body.extend_from_slice( - &x11glx::VENDOR_CODE_CREATE_GLX_PIXMAP_WITH_CONFIG_SGIX.to_le_bytes(), - ); - body.extend_from_slice(&0u32.to_le_bytes()); // pad1 - body.extend_from_slice(&0u32.to_le_bytes()); // screen - body.extend_from_slice(&fbconfig.to_le_bytes()); - body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); - body.extend_from_slice(&glx_xid.to_le_bytes()); - - let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); - - let outcome = process_request( - &mut state, - &mut backend, - client_id, - SequenceNumber(1), - RequestHeader { - opcode: 148, - data: x11glx::VENDOR_PRIVATE, - length_units, - }, - &body, - None, - ) - .expect("process_request must not hard-error"); - - assert!( - matches!(outcome, RequestOutcome::Handled), - "CreateGLXPixmapWithConfigSGIX must return Handled, got {outcome:?}" - ); - - // GlxDrawable must be inserted. - assert!( - state.glx_drawables.contains_key(&glx_xid), - "GlxDrawable must be inserted for glx_xid=0x{glx_xid:x}" - ); - let drawable = &state.glx_drawables[&glx_xid]; - assert_eq!(drawable.x_drawable, x_pixmap_xid, "x_drawable must be set"); - assert_eq!(drawable.fbconfig, fbconfig, "fbconfig must be recorded"); - assert_eq!( - drawable.glx_export_host_xid, - Some(host_xid_raw), - "host_xid must be stored for later release" - ); - - // acquire_glx_pixmap_export must have been called (same as CREATE_PIXMAP). - assert!( - backend - .calls() - .contains(&RecordedCall::AcquireGlxPixmapExport(host_xid_raw)), - "AcquireGlxPixmapExport must be recorded" - ); - - // No error packet. - peer.set_nonblocking(true).unwrap(); - let bytes = read_all_available(&mut peer); - assert!( - bytes.is_empty(), - "CreateGLXPixmapWithConfigSGIX must not deliver an error; got {bytes:02x?}" - ); - peer.set_nonblocking(false).unwrap(); - } - - /// After both dispatch and extension-string advertisement are live, - /// the computed GLX extension string must advertise - /// `GLX_SGIX_fbconfig` as a whole token, under both TFP settings. - /// - /// This test used to re-implement `glx_extension_string`'s body and - /// assert against its own copy, so it would have passed even if the - /// builder were deleted. It calls the real function now. - #[test] - fn glx_extension_string_contains_sgix_fbconfig() { - use yserver_protocol::x11::glx as x11glx; - for tfp_supported in [false, true] { - let s = glx_extension_string(tfp_supported); - assert!( - s.split_whitespace() - .any(|token| token == x11glx::SGIX_FBCONFIG_EXTENSION), - "glx_extension_string must advertise GLX_SGIX_fbconfig as a \ - whole token; tfp_supported={tfp_supported} produced {s:?}" - ); - } - } - - // NOTE: the 3rd argument is the SEQUENCE number, not a client id — - // every request in these tests comes from ClientId(1). - fn send_xcmisc( - state: &mut ServerState, - backend: &mut RecordingBackend, - seq: u16, - minor: u8, - body: &[u8], - ) { - process_request( - state, - backend, - ClientId(1), - SequenceNumber(seq), - RequestHeader { - opcode: 152, - data: minor, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - None, - ) - .expect("process_request"); - } - - #[test] - fn xcmisc_get_version_replies_1_1() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // GetVersion body: client major(2), minor(2) — values ignored. - let body = [0u8, 0, 0, 0]; - send_xcmisc(&mut state, &mut backend, 1, 0, &body); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32, "fixed 32-byte reply, got {bytes:02x?}"); - assert_eq!(bytes[0], 1, "X_Reply"); - assert_eq!(&bytes[2..4], &1u16.to_le_bytes(), "sequence"); - assert_eq!(&bytes[8..10], &1u16.to_le_bytes(), "major=1"); - assert_eq!(&bytes[10..12], &1u16.to_le_bytes(), "minor=1"); - } - - #[test] - fn xcmisc_bad_length_and_unknown_minor() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // GetVersion with wrong body size → BadLength. - send_xcmisc(&mut state, &mut backend, 1, 0, &[0u8; 8]); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32); - assert_eq!(bytes[1], x11::error::BAD_LENGTH); - assert_eq!(bytes[10], 152, "major opcode"); - assert_eq!(&bytes[8..10], &0u16.to_le_bytes(), "minor 0 echoed"); - // Unknown minor 3 → BadRequest (Xorg dispatcher default). - send_xcmisc(&mut state, &mut backend, 2, 3, &[]); - let bytes = read_all_available(&mut peer); - assert!(bytes.len() >= 32); - assert_eq!(bytes[1], x11::error::BAD_REQUEST); - assert_eq!(&bytes[8..10], &3u16.to_le_bytes(), "minor 3 echoed"); - } - - #[test] - fn xcmisc_advertised_in_query_and_list_extensions() { - // QueryExtension "XC-MISC" → present with major 152; covered via - // extension_query_reply + advertised_extension_names directly - // (cheaper than wire round-trips; they are what the handlers use). - let mut backend = RecordingBackend::new(); - let reply = extension_query_reply("XC-MISC", &mut backend); - assert_eq!(reply, Some((152, 0, 0))); - assert!(advertised_extension_names(&mut backend).contains(&"XC-MISC")); - } - - #[test] - fn xcmisc_get_xid_range_skips_used_ids() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - // Give the test client a realistic base/mask (install_client - // defaults to base=0, mask=u32::MAX). - { - let c = state.clients.get_mut(&1).unwrap(); - c.resource_id_base = 0x0010_0000; - c.resource_id_mask = 0x000F_FFFF; - } - // Occupy the low end of the range. - for i in 0..4u32 { - state - .resources - .create_cursor(ClientId(1), ResourceId(0x0010_0000 + i)); - } - send_xcmisc(&mut state, &mut backend, 1, 1, &[]); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32); - assert_eq!(bytes[0], 1); - let start = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); - let count = u32::from_le_bytes(bytes[12..16].try_into().unwrap()); - assert_eq!(start, 0x0010_0004, "range starts after the used prefix"); - assert_eq!(count, 0x000F_FFFF - 4 + 1); - // Wrong length → BadLength. - send_xcmisc(&mut state, &mut backend, 2, 1, &[0u8; 4]); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_LENGTH); - } - - #[test] - fn xcmisc_get_xid_list_returns_free_ids() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - { - let c = state.clients.get_mut(&1).unwrap(); - c.resource_id_base = 0x0010_0000; - c.resource_id_mask = 0x000F_FFFF; - } - // Occupy ids 0,2 in the range; ask for 4 ids. - state - .resources - .create_cursor(ClientId(1), ResourceId(0x0010_0000)); - state - .resources - .create_cursor(ClientId(1), ResourceId(0x0010_0002)); - send_xcmisc(&mut state, &mut backend, 1, 2, &4u32.to_le_bytes()); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes.len(), 32 + 16, "32 header + 4 ids"); - let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); - assert_eq!(count, 4); - let length = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); - assert_eq!(length, 4, "reply length in words = id count"); - let ids: Vec = bytes[32..] - .chunks_exact(4) - .map(|c| u32::from_le_bytes(c.try_into().unwrap())) - .collect(); - assert_eq!( - ids, - vec![0x0010_0001, 0x0010_0003, 0x0010_0004, 0x0010_0005], - "skips occupied 0x...0 and 0x...2" - ); - // Huge count is clamped to the RANGE size, not allocated. Shrink - // the client's range first so the reply stays ~1 KiB — a 1M-id - // reply would block the test's unread socketpair (write_or_buffer - // does a synchronous write; OUTBOUND_CAP would trip the - // disconnect path). - state.clients.get_mut(&1).unwrap().resource_id_mask = 0xFF; - send_xcmisc(&mut state, &mut backend, 2, 2, &u32::MAX.to_le_bytes()); - let bytes = read_all_available(&mut peer); - let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); - assert_eq!(count, 0x100 - 2, "256-id range minus 2 occupied"); - // BadLength on wrong size. - send_xcmisc(&mut state, &mut backend, 3, 2, &[]); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_LENGTH); - } - - /// `RRSetScreenSize` with the cursor stranded off the shrunken screen - /// must trigger a `warp_pointer_root` call that clamps it inside. - /// Also verifies the basic success path and per-dimension errorValue. - #[test] - fn screen_shrink_warps_stranded_cursor_inside() { - use crate::randr::{RandrOutput, RandrState}; - - const CLIENT_ID: u32 = 1; - // One enabled 1920×1080 output at (0,0). - let outputs = vec![RandrOutput { - name: "eDP-1".into(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs(0, outputs); - // Park the cursor at (2000, 1500) — valid under the old larger screen. - state.pointer_root = (2000, 1500); - let mut backend = RecordingBackend::new(); - let _peer = install_client(&mut state, CLIENT_ID); - - // Build a SetScreenSize body: window(4) width(2) height(2) - // mm_width(4) mm_height(4). - fn build_body(width: u16, height: u16, mm_w: u32, mm_h: u32) -> Vec { - let mut b = Vec::with_capacity(16); - b.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - b.extend_from_slice(&width.to_le_bytes()); - b.extend_from_slice(&height.to_le_bytes()); - b.extend_from_slice(&mm_w.to_le_bytes()); - b.extend_from_slice(&mm_h.to_le_bytes()); - b - } - - let header = yserver_protocol::x11::RequestHeader { - opcode: 128, // RANDR major opcode - data: yserver_protocol::x11::randr::RR_SET_SCREEN_SIZE, - length_units: 5, - }; - - // Shrink to 1920×1080 (same as output — no crop) with real mm values. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &build_body(1920, 1080, 527, 296), - ) - .expect("valid shrink"); - - // RRSetScreenSize is void — no reply on the wire. - // The cursor at (2000, 1500) is outside 1920×1080, so a warp must fire. - assert_eq!( - backend.warped_to, - Some((1919, 1079)), - "cursor must be warped to (w-1, h-1) when stranded off-screen" - ); - // RandrState must reflect the new logical size. - assert_eq!(state.randr.screen_width, 1920); - assert_eq!(state.randr.screen_height, 1080); - assert_eq!(state.randr.width_mm, 527, "mm verbatim from client"); - assert_eq!(state.randr.height_mm, 296, "mm verbatim from client"); - } - - /// A compositor that renders through the Composite Overlay Window - /// typically backs it with DRI3/Present buffers. `RRSetScreenSize` - /// resizes the root and COW outside the normal `ConfigureWindow` path, - /// so it must still emit both core ConfigureNotify and - /// Present::ConfigureNotify for the materialized COW. Otherwise the - /// compositor can keep presenting its old smaller swap buffers after a - /// shrink-grow cycle, leaving the desktop in the upper-left corner while - /// input/RandR already use the full screen. - #[test] - fn screen_resize_notifies_materialized_cow_present_subscriber() { - use crate::{ - backend::WindowHandle, - randr::{RandrOutput, RandrState}, - resources::COMPOSITE_OVERLAY_WINDOW, - server::PresentEventSelection, - }; - use yserver_protocol::x11::present as x11present; - - const CLIENT_ID: u32 = 1; - const PRESENT_EID: u32 = 0x0010_0042; - - let outputs = vec![RandrOutput { - name: "DP-4".into(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1680, - height: 1050, - vrefresh: 100, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs(0, outputs); - let mut peer = install_client(&mut state, CLIENT_ID); - let mut backend = RecordingBackend::new(); - - state - .resources - .materialize_cow_resource(WindowHandle::from_raw_for_test(COMPOSITE_OVERLAY_WINDOW.0)); - state.materialize_cow_input_shape(); - state - .clients - .get_mut(&CLIENT_ID) - .unwrap() - .event_masks - .insert(COMPOSITE_OVERLAY_WINDOW, 0x0002_0000); - state.present_event_selections.insert( - PRESENT_EID, - PresentEventSelection { - owner: ClientId(CLIENT_ID), - window: COMPOSITE_OVERLAY_WINDOW, - event_mask: x11present::EVENT_MASK_CONFIGURE_NOTIFY, - }, - ); - assert_eq!( - crate::core_loop::fanout::subscribers_by_id( - &state, - COMPOSITE_OVERLAY_WINDOW, - 0x0002_0000, - ), - vec![ClientId(CLIENT_ID)], - "COW StructureNotify subscription visible before resize", - ); - assert_eq!( - state - .present_event_selections - .get(&PRESENT_EID) - .unwrap() - .window, - COMPOSITE_OVERLAY_WINDOW, - "Present Configure subscription visible before resize", - ); - - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - body.extend_from_slice(&3440u16.to_le_bytes()); - body.extend_from_slice(&1440u16.to_le_bytes()); - body.extend_from_slice(&910u32.to_le_bytes()); - body.extend_from_slice(&381u32.to_le_bytes()); - - let header = yserver_protocol::x11::RequestHeader { - opcode: 128, - data: yserver_protocol::x11::randr::RR_SET_SCREEN_SIZE, - length_units: 5, - }; - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &body, - ) - .expect("RRSetScreenSize grow"); - - assert_eq!(state.randr.screen_width, 3440, "RandR width updated"); - assert_eq!(state.randr.screen_height, 1440, "RandR height updated"); - let cow = state - .resources - .window(COMPOSITE_OVERLAY_WINDOW) - .expect("COW still materialized"); - assert_eq!(cow.width, 3440, "COW width updated"); - assert_eq!(cow.height, 1440, "COW height updated"); - assert_eq!( - crate::core_loop::fanout::subscribers_by_id( - &state, - COMPOSITE_OVERLAY_WINDOW, - 0x0002_0000, - ), - vec![ClientId(CLIENT_ID)], - "COW StructureNotify subscription still visible after resize", - ); - assert_eq!( - state - .present_event_selections - .get(&PRESENT_EID) - .unwrap() - .window, - COMPOSITE_OVERLAY_WINDOW, - "Present Configure subscription still visible after resize", - ); - assert_eq!( - state.clients.get(&CLIENT_ID).unwrap().outbound.len(), - 0, - "small COW resize notifications should not be stuck in outbound", - ); - - let bytes = read_all_available(&mut peer); - assert_eq!( - bytes.len(), - 32 + 40, - "COW subscriber should receive core ConfigureNotify plus \ - Present::ConfigureNotify only; got {bytes:?}", - ); - - let core = &bytes[..32]; - assert_eq!(core[0] & 0x7f, 22, "first event must be ConfigureNotify"); - assert_eq!( - u32::from_le_bytes(core[4..8].try_into().unwrap()), - COMPOSITE_OVERLAY_WINDOW.0, - "ConfigureNotify event window must be COW", - ); - assert_eq!( - u32::from_le_bytes(core[8..12].try_into().unwrap()), - COMPOSITE_OVERLAY_WINDOW.0, - "ConfigureNotify target window must be COW", - ); - assert_eq!(u16::from_le_bytes(core[20..22].try_into().unwrap()), 3440); - assert_eq!(u16::from_le_bytes(core[22..24].try_into().unwrap()), 1440); - - let present = &bytes[32..]; - assert_eq!(present[0], 35, "second event must be GenericEvent"); - assert_eq!(present[1], 145, "GenericEvent extension must be PRESENT"); - assert_eq!( - u16::from_le_bytes(present[8..10].try_into().unwrap()), - u16::from(x11present::EVENT_CONFIGURE_NOTIFY), - ); - assert_eq!( - u32::from_le_bytes(present[12..16].try_into().unwrap()), - PRESENT_EID, - ); - assert_eq!( - u32::from_le_bytes(present[16..20].try_into().unwrap()), - COMPOSITE_OVERLAY_WINDOW.0, - ); - assert_eq!( - u16::from_le_bytes(present[24..26].try_into().unwrap()), - 3440, - "Present ConfigureNotify width must track the grown COW", - ); - assert_eq!( - u16::from_le_bytes(present[26..28].try_into().unwrap()), - 1440, - "Present ConfigureNotify height must track the grown COW", - ); - assert_eq!( - u16::from_le_bytes(present[32..34].try_into().unwrap()), - 3440, - "Present pixmap width must ask Mesa/KWin to reallocate full-size buffers", - ); - assert_eq!( - u16::from_le_bytes(present[34..36].try_into().unwrap()), - 1440, - "Present pixmap height must ask Mesa/KWin to reallocate full-size buffers", - ); - - super::super::run::emit_screen_resize_window_notifications_if_outputs_caught_up( - &mut state, - Some((1680, 1050)), - ); - assert!( - read_all_available(&mut peer).is_empty(), - "a stale output bbox must not re-emit full-size configure notifications", - ); - - state.randr.outputs[0].width = 3440; - state.randr.outputs[0].height = 1440; - super::super::run::emit_screen_resize_window_notifications_if_outputs_caught_up( - &mut state, - Some((1680, 1050)), - ); - let caught_up = read_all_available(&mut peer); - assert_eq!( - caught_up.len(), - 32 + 40, - "matching output bbox must re-emit core and Present COW configure notifications", - ); - assert_eq!(caught_up[0] & 0x7f, 22); - assert_eq!(caught_up[32], 35); - assert_eq!( - u16::from_le_bytes(caught_up[32 + 32..32 + 34].try_into().unwrap()), - 3440, - ); - assert_eq!( - u16::from_le_bytes(caught_up[32 + 34..32 + 36].try_into().unwrap()), - 1440, - ); - - super::super::run::emit_screen_resize_window_notifications_if_outputs_caught_up( - &mut state, - Some((3440, 1440)), - ); - assert!( - read_all_available(&mut peer).is_empty(), - "an unchanged output bbox must not re-emit configure notifications", - ); - } - - /// `RRSetScreenSize` validation: crop check returns BadMatch; zero-mm - /// returns BadValue; out-of-range width/height each report the offending - /// dimension as errorValue. - #[test] - fn screen_set_size_validation_errors() { - use crate::randr::{RandrOutput, RandrState}; - use yserver_protocol::x11::randr as x11randr; - - const CLIENT_ID: u32 = 1; - let outputs = vec![RandrOutput { - name: "eDP-1".into(), - output_id: 1, - crtc_id: 2, - mode_id: 3, - connected: true, - x: 0, - y: 0, - width: 1920, - height: 1080, - vrefresh: 60, - timing: None, - mm_width: 0, - mm_height: 0, - mode_ids: vec![3], - num_preferred: 1, - }]; - let mut state = ServerState::new(); - state.randr = RandrState::from_outputs(0, outputs); - let mut backend = RecordingBackend::new(); - let mut peer = install_client(&mut state, CLIENT_ID); - - fn build_body(width: u16, height: u16, mm_w: u32, mm_h: u32) -> Vec { - let mut b = Vec::with_capacity(16); - b.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - b.extend_from_slice(&width.to_le_bytes()); - b.extend_from_slice(&height.to_le_bytes()); - b.extend_from_slice(&mm_w.to_le_bytes()); - b.extend_from_slice(&mm_h.to_le_bytes()); - b - } - - let header = yserver_protocol::x11::RequestHeader { - opcode: 128, - data: x11randr::RR_SET_SCREEN_SIZE, - length_units: 5, - }; - - // width=0 → out-of-range (< min=1) → BadValue with errorValue=0. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(1), - header, - &build_body(0, 1080, 527, 296), - ) - .unwrap(); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_VALUE, "width=0 → BadValue"); - // errorValue for the offending width is 0 (the bad width). - let ev = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); - assert_eq!(ev, 0u32, "errorValue = offending width"); - - // height=0 → out-of-range → BadValue with errorValue=height. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(2), - header, - &build_body(1920, 0, 527, 296), - ) - .unwrap(); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_VALUE, "height=0 → BadValue"); - let ev = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); - assert_eq!(ev, 0u32, "errorValue = offending height"); - - // Crop: 1280×720 crops the 1920×1080 output → BadMatch. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(3), - header, - &build_body(1280, 720, 527, 296), - ) - .unwrap(); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_MATCH, "crop → BadMatch"); - - // mm_width=0 → BadValue. - handle_randr_request( - &mut state, - &mut backend, - ClientId(CLIENT_ID), - SequenceNumber(4), - header, - &build_body(1920, 1080, 0, 296), - ) - .unwrap(); - let bytes = read_all_available(&mut peer); - assert_eq!(bytes[1], x11::error::BAD_VALUE, "mm_width=0 → BadValue"); - } - - // DRIFT 1 + Multi-monitor Bug A regression: the Bounding-shape mirror - // must distinguish three states via the Option API — - // unset → None (drop the entry; scene tracks live geometry — - // the multi-monitor Bug A fix), NOT the - // materialized default geometry rect; - // empty → Some(0) (explicit empty region — distinct from unset); - // concrete → Some(n) (the real rects). - #[test] - fn bounding_shape_mirror_distinguishes_unset_empty_and_concrete() { - use yserver_protocol::x11::shape as x11shape; - - const WINDOW_XID: u32 = 0x0010_0001; - const HOST_XID: u32 = 0x0040_0001; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 2560, - height: 1440, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed") - .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - - // No explicit Bounding shape set → mirror must push empty rects. - mirror_shape_to_host_state( - &state, - &mut backend, - None, - ResourceId(WINDOW_XID), - x11shape::KIND_BOUNDING, - ); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_BOUNDING, - rects: None, - } - ), - "unset Bounding shape must mirror None (drop backend entry), \ - not the materialized 2560x1440 default geometry rect, and NOT \ - an explicit empty region (Some(0)) — DRIFT 1 distinction", - ); - - // An explicitly-set EMPTY Bounding shape is a DISTINCT state from - // unset: it mirrors Some(0), not None. This is the DRIFT 1 fix — - // the old &[]-based API collapsed both to a zero-length call. - crate::nested::set_shape_rects( - &mut state, - ResourceId(WINDOW_XID), - x11shape::KIND_BOUNDING, - vec![], - ); - mirror_shape_to_host_state( - &state, - &mut backend, - None, - ResourceId(WINDOW_XID), - x11shape::KIND_BOUNDING, - ); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_BOUNDING, - rects: Some(0), - } - ), - "explicit EMPTY Bounding shape must mirror Some(0) (an empty \ - region), distinct from unset's None", - ); - - // After an explicit non-empty Bounding shape, mirror the concrete rect(s). - crate::nested::set_shape_rects( - &mut state, - ResourceId(WINDOW_XID), - x11shape::KIND_BOUNDING, - vec![yserver_protocol::x11::xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }], - ); - mirror_shape_to_host_state( - &state, - &mut backend, - None, - ResourceId(WINDOW_XID), - x11shape::KIND_BOUNDING, - ); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_BOUNDING, - rects: Some(1), - } - ), - "explicitly-set Bounding shape must mirror the concrete rect", - ); - } - - // #133: the CLIP mirror must make the same unset/empty/concrete - // distinction as Bounding. Before step 5 the scene only consulted the - // bounding shape, so freezing the geometry rect for an unset clip shape - // was inert; step 5 clips descendants to the parent's clip shape, and a - // frozen rect then truncates the children after the parent resizes. That - // is the wezterm white block: awesome resets its frame's clip shape at - // 820x583, the frame later becomes 608x734, and 168 rows of the client - // vanished. Input is deliberately NOT in the guard — it feeds the cursor - // hit-test, which wants a concrete region. - #[test] - fn clip_shape_mirror_leaves_an_unset_region_unmaterialized() { - use yserver_protocol::x11::shape as x11shape; - - const WINDOW_XID: u32 = 0x0010_0002; - const HOST_XID: u32 = 0x0040_0002; - - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - yserver_protocol::x11::ClientId(1), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WINDOW_XID), - parent: crate::resources::ROOT_WINDOW, - x: 0, - y: 0, - width: 820, - height: 583, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(WINDOW_XID)) - .expect("window installed") - .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); - - let mirror = |state: &ServerState, backend: &mut RecordingBackend, kind: u8| { - mirror_shape_to_host_state(state, backend, None, ResourceId(WINDOW_XID), kind); - }; - - mirror(&state, &mut backend, x11shape::KIND_CLIP); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_CLIP, - rects: None, - } - ), - "an unset Clip shape must mirror None, not the 820x583 geometry \ - rect that goes stale on the next resize", - ); - - // Input keeps materializing the default rect — the cursor hit-test - // consumes a concrete region and does not clip descendants. - mirror(&state, &mut backend, x11shape::KIND_INPUT); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_INPUT, - rects: Some(1), - } - ), - "an unset Input shape still mirrors the default geometry rect", - ); - - // An explicit EMPTY clip region is a distinct state from unset. - crate::nested::set_shape_rects( - &mut state, - ResourceId(WINDOW_XID), - x11shape::KIND_CLIP, - vec![], - ); - mirror(&state, &mut backend, x11shape::KIND_CLIP); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_CLIP, - rects: Some(0), - } - ), - "explicit EMPTY Clip shape mirrors Some(0), distinct from unset", - ); - - // And a real clip shape is still mirrored through. - crate::nested::set_shape_rects( - &mut state, - ResourceId(WINDOW_XID), - x11shape::KIND_CLIP, - vec![yserver_protocol::x11::xfixes::RegionRect { - x: 0, - y: 0, - width: 100, - height: 100, - }], - ); - mirror(&state, &mut backend, x11shape::KIND_CLIP); - assert_eq!( - backend.calls().last(), - Some( - &crate::backend::recording::RecordedCall::SetShapeRectangles { - host_xid: HOST_XID, - kind: x11shape::KIND_CLIP, - rects: Some(1), - } - ), - "explicitly-set Clip shape must mirror the concrete rect", - ); - } - - /// #94 fast-click acceptance: press withheld by muffin's sync XI2 - /// passive grab; the RELEASE arrives during the freeze and is queued; - /// XIAllowEvents(ReplayDevice) replays the press (installing the - /// implicit grab on the natural recipient) and the queue drain must - /// deliver the release UNDER that grab (Xorg PlayReleasedEvents → - /// DeliverGrabbedEvent) — not re-hit-test it. - #[test] - fn xi_replay_device_then_queued_release_follows_implicit_grab() { - use crate::{ - backend::Backend, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const WM: u32 = 1; - const APP: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0051; - const APP_WIN: u32 = 0x0020_0052; - const HOST_XID: u32 = 0xCAFE_0001; - - let mut state = ServerState::new(); - let _wm_peer = install_client(&mut state, WM); - let mut app_peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - app_peer.set_nonblocking(true).expect("nonblocking"); - - for (client, win) in [(WM, GRAB_WIN), (APP, APP_WIN)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - state - .clients - .get_mut(&APP) - .expect("app client") - .event_masks - .insert(ResourceId(APP_WIN), 0x0000_000c); // press|release - Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_XID) - .expect("register host xid"); - - // Frozen sync passive grab held by the WM, activating press stored, - // and the fast release already QUEUED (it arrived mid-freeze; the - // queue gate decremented buttons_down and withheld it). - set_test_pointer_grab(&mut state, WM, GRAB_WIN, true, false); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 1000, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); - } - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 1010, - state: 0x100, - ..press - }; - state - .sync_pending - .push_back(crate::server::PendingSyncEvent { - device: crate::xinput::DEVICEID_SLAVE_POINTER, - event: crate::server::QueuedInputEvent::HostPointer(release), - }); - - // XIAllowEvents(ReplayDevice) from the WM. - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&2u16.to_le_bytes()); // deviceid = master ptr - body.push(2); // mode = ReplayDevice - body.push(0); // pad - let header = yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }; - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(WM), - SequenceNumber(1), - header, - &body, - ) - .expect("allow events"); - - // The replayed press delivered to APP + the queued release drained - // UNDER the freshly-installed implicit grab. - let bytes = read_all_available(&mut app_peer); - let (mut saw_press, mut saw_release) = (false, false); - let mut off = 0usize; - while off + 32 <= bytes.len() { - match bytes[off] & 0x7F { - 4 => saw_press = true, - 5 => { - saw_release = true; - assert_eq!( - &bytes[off + 12..off + 16], - &APP_WIN.to_le_bytes(), - "queued release must deliver on the implicit grab window" - ); - } - _ => {} - } - off += 32; - } - assert!(saw_press, "replayed press must reach the natural target"); - assert!( - saw_release, - "queued release must follow the implicit grab owner (fast click)" - ); - assert!( - state.active_pointer_grab.is_none(), - "release completes the click — implicit grab torn down" - ); - } - - /// An implicit grab is a REAL grab for request purposes (Xorg shares - /// deviceGrab.grab): another client's GrabPointer during it fails - /// AlreadyGrabbed (events.c:5240-5243); the owner's GrabPointer - /// replaces it; the owner's UngrabPointer releases it (events.c:5155). - #[test] - fn implicit_grab_interacts_with_grab_requests_like_a_real_grab() { - use crate::server::ActivePointerGrab; - const OWNER: u32 = 1; - const INTRUDER: u32 = 2; - const WIN: u32 = 0x0010_0001; - - let mut state = ServerState::new(); - let mut backend = RecordingBackend::new(); - let mut owner_peer = install_client(&mut state, OWNER); - let mut intruder_peer = install_client(&mut state, INTRUDER); - owner_peer.set_nonblocking(true).unwrap(); - intruder_peer.set_nonblocking(true).unwrap(); - state.resources.create_window( - ClientId(OWNER), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(WIN)); - - let install_implicit = |state: &mut ServerState| { - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(OWNER), - grab_window: ResourceId(WIN), - event_mask: 0x000c, - cursor: ResourceId(0), - time: 1000, - owner_events: false, - via_xi2: false, - implicit: true, - passive: false, - xi2_mask: 0, - }); - state.last_pointer_grab_time = 1000; - }; - let grab_body = || { - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&WIN.to_le_bytes()); - body.extend_from_slice(&0u16.to_le_bytes()); // event-mask - body.push(1); // pointer-mode async - body.push(1); // keyboard-mode async - body.extend_from_slice(&0u32.to_le_bytes()); // confine-to - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&0u32.to_le_bytes()); // time CurrentTime - body - }; - let header = RequestHeader { - opcode: 26, - data: 0, - length_units: 6, - }; - let grab_status = |peer: &mut std::os::unix::net::UnixStream| -> u8 { - let wire = read_all_available(peer); - assert!(wire.len() >= 32, "expected a GrabPointer reply"); - assert_eq!(wire[0], 1, "reply, not an event/error"); - wire[1] - }; - - // (a) Another client's GrabPointer → AlreadyGrabbed, state untouched. - install_implicit(&mut state); - handle_grab_pointer( - &mut state, - &mut backend, - ClientId(INTRUDER), - SequenceNumber(1), - header, - &grab_body(), - ) - .expect("grab pointer"); - assert_eq!(grab_status(&mut intruder_peer), 1, "AlreadyGrabbed"); - assert!( - state - .active_pointer_grab - .is_some_and(|g| g.implicit && g.owner == ClientId(OWNER)), - "implicit grab untouched by the failed request" - ); - - // (b) The owner's GrabPointer replaces its implicit grab. - handle_grab_pointer( - &mut state, - &mut backend, - ClientId(OWNER), - SequenceNumber(2), - header, - &grab_body(), - ) - .expect("grab pointer"); - assert_eq!(grab_status(&mut owner_peer), 0, "GrabSuccess"); - assert!( - state.active_pointer_grab.is_some_and(|g| !g.implicit), - "explicit grab replaced the implicit one" - ); - - // (c) Owner's UngrabPointer releases its own implicit grab; a - // non-owner's UngrabPointer is a no-op. - install_implicit(&mut state); - let ungrab_body = 0u32.to_le_bytes(); // time CurrentTime - handle_ungrab_pointer( - &mut state, - &mut backend, - ClientId(INTRUDER), - SequenceNumber(3), - &ungrab_body, - ) - .expect("ungrab pointer"); - assert!( - state.active_pointer_grab.is_some(), - "non-owner UngrabPointer must not touch the implicit grab" - ); - handle_ungrab_pointer( - &mut state, - &mut backend, - ClientId(OWNER), - SequenceNumber(4), - &ungrab_body, - ) - .expect("ungrab pointer"); - assert!( - state.active_pointer_grab.is_none(), - "owner UngrabPointer releases the implicit grab (Xorg SameClient)" - ); - } - - /// #94 slow-click acceptance (the traced Cinnamon shape): muffin's - /// sync XI2 passive grab withholds the press; XIAllowEvents( - /// XIReplayDevice) re-delivers it to Steam (XI2-only selector), - /// installing the implicit grab; muffin then MUTATES THE TREE - /// (click-to-focus reparents/restacks) before the user releases. - /// The release must follow the implicit grab to Steam — pre-fix it - /// was re-hit-tested against the mutated tree and lost (steam.xtrace: - /// 164 XI2 presses vs 28 releases → stuck button). - #[test] - fn xi_replay_device_press_then_tree_mutation_release_follows_grab() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const WM: u32 = 1; - const APP: u32 = 2; - const GRAB_WIN: u32 = 0x0010_0051; // WM's passive-grab window - const APP_WIN: u32 = 0x0020_0052; // Steam-like, XI2-only selector - const FRAME_WIN: u32 = 0x0010_0060; // WM frame created mid-click - const COVER_WIN: u32 = 0x0010_0061; // WM window the release re-hits - const HOST_APP: u32 = 0xCAFE_0001; - const HOST_COVER: u32 = 0xCAFE_0002; - const XI2_MASTER: u16 = 2; - - let mut state = ServerState::new(); - let mut wm_peer = install_client(&mut state, WM); - let mut app_peer = install_client(&mut state, APP); - let mut backend = RecordingBackend::new(); - wm_peer.set_nonblocking(true).unwrap(); - app_peer.set_nonblocking(true).unwrap(); - - for (client, win) in [ - (WM, GRAB_WIN), - (APP, APP_WIN), - (WM, FRAME_WIN), - (WM, COVER_WIN), - ] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - // Steam shape: cooked XI2 buttons, NO core mask. - state - .clients - .get_mut(&APP) - .expect("app") - .xi2_masks - .insert((ResourceId(APP_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); - // The WM selects XI2 buttons on the covering window — a re-hit-test - // would deliver the release THERE. - state - .clients - .get_mut(&WM) - .expect("wm") - .xi2_masks - .insert((ResourceId(COVER_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); - Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP) - .expect("register app"); - Backend::register_top_level(&mut backend, None, ResourceId(COVER_WIN), HOST_COVER) - .expect("register cover"); - - // Frozen sync passive grab held by the WM, press stored. - set_test_pointer_grab(&mut state, WM, GRAB_WIN, true, false); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_APP, - detail: 1, - time: 1000, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - { - let f = state - .xi1_frozen - .entry(crate::xinput::DEVICEID_SLAVE_POINTER) - .or_default(); - f.state = crate::server::Xi1SyncState::FrozenWithEvent; - f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); - } - - // XIAllowEvents(ReplayDevice) from the WM. - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); - body.push(2); // ReplayDevice - body.push(0); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(WM), - SequenceNumber(1), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }, - &body, - ) - .expect("allow events"); - - let xge_events = |bytes: &[u8]| -> Vec<(u16, u32)> { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(( - u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), - u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), - )); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - assert!( - xge_events(&read_all_available(&mut app_peer)).contains(&(4, APP_WIN)), - "replayed press must reach APP as XI2 on its window" - ); - assert!( - state.active_pointer_grab.is_some_and(|g| g.implicit - && g.via_xi2 - && g.owner == ClientId(APP) - && g.grab_window == ResourceId(APP_WIN)), - "replayed press installs the via_xi2 implicit grab (#94 crux)" - ); - - // muffin-style mutation between press and release: reparent the - // app window into a WM frame and let a WM window cover the spot. - let _ = state - .resources - .reparent_window(yserver_protocol::x11::ReparentWindowRequest { - window: ResourceId(APP_WIN), - parent: ResourceId(FRAME_WIN), - x: 0, - y: 0, - }); - let _ = state.resources.map_window(ResourceId(APP_WIN)); - - // Natural release now resolves over the WM's covering window. - let xid_map = backend.xid_map().clone(); - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - host_xid: HOST_COVER, - time: 1200, - state: 0x100, - ..press - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - assert!( - xge_events(&read_all_available(&mut app_peer)).contains(&(5, APP_WIN)), - "release must follow the implicit grab to APP on the grab window" - ); - assert!( - !xge_events(&read_all_available(&mut wm_peer)) - .iter() - .any(|(evtype, _)| *evtype == 5), - "the grab captures the release away from the re-hit-tested window" - ); - assert!( - state.active_pointer_grab.is_none(), - "click complete — implicit grab torn down" - ); - } - - /// Xorg oracle from `steam-xorg.xtrace` connection 019 — the canonical - /// Steam-webhelper click. The client selects XI2 Button{Press,Release}+ - /// Motion on its window W (`XISelectEvents win=W device=0 mask=0x001c0ff2`), - /// receives the `ButtonPress`, then establishes its OWN grab on the master - /// pointer BEFORE the release (`XIGrabDevice grab_window=W device=2 - /// grab_mode=Async owner_events=true masks=0x001c0070`), and Xorg still - /// delivers the matching `ButtonRelease` to the client on W — press count - /// equals release count — after which the client `XIUngrabDevice`s. - /// - /// This encodes Xorg's observed behavior ONLY. On yserver a delivered - /// press installs an implicit pointer grab, and the client's mid-click - /// `XIGrabDevice` overwrites that slot; the question this pins is whether - /// the release survives that overlap the way it does under Xorg. - #[test] - fn xi_client_grab_device_mid_click_delivers_release_xorg_conn019() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const APP: u32 = 1; - const APP_WIN: u32 = 0x0044_000b; // window id shape from the trace - const HOST_APP: u32 = 0xCAFE_0001; - const XI2_MASTER: u16 = 2; - - let mut state = ServerState::new(); - let mut app_peer = install_client(&mut state, APP); - app_peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(APP), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(APP_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(APP_WIN)); - // Xorg XISelectEvents mask 0x001c0ff2 → Button{Press,Release}+Motion (+more). - state.clients.get_mut(&APP).expect("app").xi2_masks.insert( - (ResourceId(APP_WIN), XI2_MASTER), - (1 << 4) | (1 << 5) | (1 << 6), - ); - Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP) - .expect("register app"); - let xid_map = backend.xid_map().clone(); - - let xge = |bytes: &[u8]| -> Vec<(u16, u32)> { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(( - u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), - u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), - )); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - - // 1. ButtonPress @ W (Xorg: delivered to the selector on its window). - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_APP, - detail: 1, - time: 1000, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - let after_press = xge(&read_all_available(&mut app_peer)); - let presses = after_press.iter().filter(|(t, _)| *t == 4).count(); - assert!( - after_press.contains(&(4, APP_WIN)), - "Xorg: the ButtonPress is delivered to the XI2 selector on its own window" - ); - - // 2. Client's own XIGrabDevice on the master pointer, owner_events=true, - // grab_window=W, mask=Button{Press,Release}+Motion (Xorg masks=0x001c0070). - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&APP_WIN.to_le_bytes()); // grab_window - body.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime - body.extend_from_slice(&0u32.to_le_bytes()); // cursor = None - body.extend_from_slice(&2u16.to_le_bytes()); // device = master pointer - body.extend_from_slice(&[1, 1, 1, 0]); // async, async, owner_events=1, pad - body.extend_from_slice(&1u16.to_le_bytes()); // mask_len (one 4-byte unit) - body.extend_from_slice(&[0u8; 2]); // pad - body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber(2), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, // XIGrabDevice - length_units: 8, - }, - &body, - ) - .expect("XIGrabDevice"); - let _ = read_all_available(&mut app_peer); // drain grab reply, if any - - // 3. ButtonRelease @ W, still over W (Xorg: delivered to the client on W, - // even though the client established its own grab mid-click). - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 1100, - state: 0x100, - ..press - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - let after_release = xge(&read_all_available(&mut app_peer)); - let releases = after_release.iter().filter(|(t, _)| *t == 5).count(); - - assert!( - after_release.contains(&(5, APP_WIN)), - "Xorg: the ButtonRelease must still reach the client on its window even \ - though the client established its own XIGrabDevice mid-click \ - (steam-xorg.xtrace conn 019); got events {after_release:?}" - ); - assert_eq!( - presses, releases, - "Xorg: press count equals release count for the grab client \ - (presses={presses}, releases={releases})" - ); - - // 4. Client XIUngrabDevice(device=2) — grab released. - let mut ungrab = Vec::with_capacity(8); - ungrab.extend_from_slice(&0u32.to_le_bytes()); // time - ungrab.extend_from_slice(&2u16.to_le_bytes()); // device = master pointer - ungrab.extend_from_slice(&[0u8; 2]); // pad - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber(3), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 52, // XIUngrabDevice - length_units: 3, - }, - &ungrab, - ) - .expect("XIUngrabDevice"); - assert!( - state.active_pointer_grab.is_none(), - "after the client ungrabs, no pointer grab remains" - ); - } - - /// Xorg oracle: `steam-xorg.xtrace` conn 019 repeats the grab-dance click - /// (`ButtonPress → XIGrabDevice → ButtonRelease → XIUngrabDevice`) ~40 - /// times, and EVERY click delivers a matched press+release with no residue. - /// The GH #94 report ("several clicks before one registers, growing - /// backlog") is a state-accumulation symptom, so this drives the same - /// cycle N times and asserts each click stays balanced and leaves no - /// stuck grab / lingering pointer-button state behind. - #[test] - fn xi_repeated_grab_dance_clicks_stay_balanced_xorg_conn019() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const APP: u32 = 1; - const APP_WIN: u32 = 0x0044_000b; - const HOST_APP: u32 = 0xCAFE_0001; - const XI2_MASTER: u16 = 2; - - let mut state = ServerState::new(); - let mut app_peer = install_client(&mut state, APP); - app_peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(APP), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(APP_WIN), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(APP_WIN)); - state.clients.get_mut(&APP).expect("app").xi2_masks.insert( - (ResourceId(APP_WIN), XI2_MASTER), - (1 << 4) | (1 << 5) | (1 << 6), - ); - Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP) - .expect("register app"); - let xid_map = backend.xid_map().clone(); - - let xge = |bytes: &[u8]| -> Vec<(u16, u32)> { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(( - u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), - u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), - )); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - - let grab_body = |window: u32| { - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); - body.extend_from_slice(&[1, 1, 1, 0]); - body.extend_from_slice(&1u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); - body - }; - let ungrab_body = || { - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body - }; - - for i in 0..10u32 { - let seq = i * 4; - let base_time = 1000 + i * 100; - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_APP, - detail: 1, - time: base_time, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - press, - true, - false, - ); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber((seq + 2) as u16), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 8, - }, - &grab_body(APP_WIN), - ) - .expect("XIGrabDevice"); - - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: base_time + 50, - state: 0x100, - ..press - }; - let _ = pointer_event_fanout_to_state( - &mut state, - &mut backend, - &xid_map, - release, - true, - false, - ); - - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber((seq + 3) as u16), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 52, - length_units: 3, - }, - &ungrab_body(), - ) - .expect("XIUngrabDevice"); - - let evs = xge(&read_all_available(&mut app_peer)); - let presses = evs.iter().filter(|(t, _)| *t == 4).count(); - let releases = evs.iter().filter(|(t, _)| *t == 5).count(); - assert!( - evs.contains(&(4, APP_WIN)) && evs.contains(&(5, APP_WIN)), - "click {i}: both press and release must reach the client on its window; \ - got {evs:?}" - ); - assert_eq!( - (presses, releases), - (1, 1), - "click {i}: exactly one press and one release must be delivered — \ - balanced-but-duplicated (e.g. 2/2) is also a bug \ - (presses={presses}, releases={releases})" - ); - assert!( - state.active_pointer_grab.is_none(), - "click {i}: no stuck grab may accumulate between clicks" - ); - assert_eq!( - state.buttons_down, 0, - "click {i}: logical button state must return to 0 after the release" - ); - } - } - - /// Xorg oracle from the FAILING `cinnamon.xtrace` (one Steam click) + - /// `dix/events.c:5240`. The traced sequence that swallows the click: - /// muffin sync-passive-grabs the press, `XIAllowEvents(ReplayDevice)` - /// replays it to Steam; Steam (conn 105) `XIGrabDevice`s the master - /// pointer (device=2, grab_window=its own window, first, never ungrabs); - /// muffin (conn 026) THEN `XIGrabDevice`s the SAME master pointer - /// (device=2, different client); the ButtonRelease is delivered to - /// muffin, and Steam never sees it → the click never completes. - /// - /// Xorg rejects the second grab with `AlreadyGrabbed` - /// (`grab && !SameClient`, dix/events.c:5240), so the first grabber keeps - /// the device and the release follows it. This test encodes that rule: a - /// second client's `XIGrabDevice` while another client holds the pointer - /// grab must NOT steal it, and the release must reach the first grabber. - #[test] - fn xi_grab_device_by_other_client_must_not_steal_held_grab_cinnamon_xtrace() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const STEAM: u32 = 1; - const MUFFIN: u32 = 2; - const STEAM_WIN: u32 = 0x0260_000d; // conn 105 grab_window - const MUFFIN_WIN: u32 = 0x00e0_0011; // conn 026 grab_window - const HOST_STEAM: u32 = 0xCAFE_0001; - const XI2_MASTER: u16 = 2; - - let mut state = ServerState::new(); - let mut steam_peer = install_client(&mut state, STEAM); - let mut muffin_peer = install_client(&mut state, MUFFIN); - steam_peer.set_nonblocking(true).unwrap(); - muffin_peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - for (client, win, x) in [(STEAM, STEAM_WIN, 0i16), (MUFFIN, MUFFIN_WIN, 500i16)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - // Both select XI2 Button{Press,Release} on their own windows, so a - // misrouted release to muffin would be observable on its wire. - state - .clients - .get_mut(&STEAM) - .unwrap() - .xi2_masks - .insert((ResourceId(STEAM_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); - state - .clients - .get_mut(&MUFFIN) - .unwrap() - .xi2_masks - .insert((ResourceId(MUFFIN_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); - Backend::register_top_level(&mut backend, None, ResourceId(STEAM_WIN), HOST_STEAM) - .expect("register steam"); - let xid_map = backend.xid_map().clone(); - - let xge = |bytes: &[u8]| -> Vec<(u16, u32)> { - let mut found = Vec::new(); - let mut off = 0usize; - while off + 32 <= bytes.len() { - let advance = if bytes[off] == 35 { - found.push(( - u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), - u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), - )); - 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize - * 4 - } else { - 32 - }; - off += advance; - } - found - }; - let grab_body = |window: u32, owner_events: u8| { - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); // time - body.extend_from_slice(&0u32.to_le_bytes()); // cursor - body.extend_from_slice(&2u16.to_le_bytes()); // device = master pointer - body.extend_from_slice(&[1, 1, owner_events, 0]); - body.extend_from_slice(&1u16.to_le_bytes()); // mask_len - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); - body - }; - let do_grab = |state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - seq: u16, - window: u32, - owner_events: u8| { - handle_xi2_request( - state, - backend, - None, - ClientId(client), - SequenceNumber(seq), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 8, - }, - &grab_body(window, owner_events), - ) - .expect("XIGrabDevice"); - }; - - // Press @ STEAM_WIN (post-ReplayDevice replay to Steam): Steam gets it, - // installs the implicit grab. - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_STEAM, - detail: 1, - time: 0xa040, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - let _ = read_all_available(&mut steam_peer); - - // Steam grabs the master pointer FIRST (conn 105, never ungrabs). - do_grab(&mut state, &mut backend, STEAM, 10, STEAM_WIN, 1); - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(STEAM), ResourceId(STEAM_WIN))), - "precondition: Steam holds the master-pointer grab" - ); - - // Muffin then grabs the SAME master pointer (conn 026). Xorg: - // AlreadyGrabbed → rejected; Steam keeps the grab. - do_grab(&mut state, &mut backend, MUFFIN, 20, MUFFIN_WIN, 0); - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(STEAM), ResourceId(STEAM_WIN))), - "Xorg (dix/events.c:5240): a second client's XIGrabDevice while \ - another client holds the pointer grab must return AlreadyGrabbed \ - and must NOT steal the grab" - ); - // The rejected grab's reply must carry status=1 (AlreadyGrabbed) at - // byte offset 8 (xXIGrabDeviceReply). muffin has received nothing else - // yet (the press went to Steam), so its wire starts with this reply. - let muffin_reply = read_all_available(&mut muffin_peer); - assert!( - muffin_reply.len() >= 9 && muffin_reply[0] == 1 && muffin_reply[8] == 1, - "muffin's contending XIGrabDevice must reply AlreadyGrabbed(1) at \ - offset 8; got {:?}", - &muffin_reply[..muffin_reply.len().min(12)] - ); - - // Release over Steam's window — must reach the grab holder (Steam), - // not muffin. - let release = HostPointerEvent { - kind: PointerEventKind::ButtonRelease, - time: 0xa0e3, - state: 0x100, - ..press - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); - - let steam_evs = xge(&read_all_available(&mut steam_peer)); - let muffin_evs = xge(&read_all_available(&mut muffin_peer)); - assert!( - steam_evs.iter().any(|(t, _)| *t == 5), - "the ButtonRelease must be delivered to the grab holder (Steam); \ - got steam={steam_evs:?} muffin={muffin_evs:?}" - ); - assert!( - !muffin_evs.iter().any(|(t, _)| *t == 5), - "the release must NOT be stolen by the second (rejected) grabber; \ - muffin={muffin_evs:?}" - ); - } - - /// Cinnamon dialog acceptance pin. The shell activates a synchronous XI2 - /// passive pointer grab, then issues XIReplayDevice. Xorg transitions the - /// device to NOT_GRABBED before replay (`dix/events.c:1898`), so the app's - /// later XIGrabDevice must succeed without superseding a foreign grab. - #[test] - fn xi_dialog_grab_succeeds_over_foreign_passive_grab_cinnamon() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - server::PassiveButtonGrab, - }; - const SHELL: u32 = 1; - const APP: u32 = 2; - const GRAB_WIN: u32 = 0x0070_0003; - const APP_WIN: u32 = 0x0080_0003; // the app dialog's popup - const HOST_XID: u32 = 0xCAFE_0001; - - let mut state = ServerState::new(); - let _shell_peer = install_client(&mut state, SHELL); - let mut app_peer = install_client(&mut state, APP); - app_peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - for (client, win) in [(SHELL, GRAB_WIN), (APP, APP_WIN)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - state.button_grabs.push(PassiveButtonGrab { - owner: ClientId(SHELL), - grab_window: ResourceId(GRAB_WIN), - button: 1, - modifiers: 0x8000, - owner_events: false, - event_mask: (1 << 4) | (1 << 5), - pointer_mode: 0, - keyboard_mode: 1, - confine_to: ResourceId(0), - via_xi2: true, - }); - Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) - .expect("register"); - let xid_map = backend.xid_map().clone(); - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_XID, - detail: 1, - time: 0x1c33, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert!( - state.active_pointer_grab.is_some_and(|grab| { - grab.owner == ClientId(SHELL) && grab.passive && grab.via_xi2 - }) - ); - - let mut allow_body = Vec::with_capacity(8); - allow_body.extend_from_slice(&0u32.to_le_bytes()); - allow_body.extend_from_slice(&2u16.to_le_bytes()); - allow_body.push(2); // XIReplayDevice - allow_body.push(0); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(SHELL), - SequenceNumber(1), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 53, - length_units: 3, - }, - &allow_body, - ) - .expect("XIAllowEvents ReplayDevice"); - assert!( - !state - .active_pointer_grab - .is_some_and(|grab| grab.owner == ClientId(SHELL)), - "ReplayDevice must deactivate the foreign passive pointer grab" - ); - assert!( - !state - .active_keyboard_grab - .is_some_and(|grab| grab.owner == ClientId(SHELL)), - "no foreign keyboard grab is held at grab time" - ); - - let mut grab_body = Vec::with_capacity(28); - grab_body.extend_from_slice(&APP_WIN.to_le_bytes()); - grab_body.extend_from_slice(&0u32.to_le_bytes()); - grab_body.extend_from_slice(&0u32.to_le_bytes()); - grab_body.extend_from_slice(&2u16.to_le_bytes()); - grab_body.extend_from_slice(&[1, 1, 1, 0]); - grab_body.extend_from_slice(&1u16.to_le_bytes()); - grab_body.extend_from_slice(&[0u8; 2]); - grab_body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber(2), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 8, - }, - &grab_body, - ) - .expect("XIGrabDevice"); - let ptr_reply = read_all_available(&mut app_peer); - let reply_start = ptr_reply.len().saturating_sub(32); - assert!( - ptr_reply.len() >= 32 && ptr_reply[reply_start] == 1 && ptr_reply[reply_start + 8] == 0, - "pointer XIGrabDevice must return Success(0), not AlreadyGrabbed(1), \ - over a foreign passive grab; got {:?}", - &ptr_reply[..ptr_reply.len().min(12)] - ); - } - - /// Pure Xorg guard: an implicit grab held by another client is still an - /// active grab and must return AlreadyGrabbed. The real MATE combo works - /// because its deeper XI2 leaf delivery attributes the implicit grab to - /// the app itself, covered by `mate_combo_implicit_grab_attributed_to_app_leaf_xi2`. - #[test] - fn xi_grab_device_over_foreign_implicit_grab_returns_already_grabbed() { - use crate::server::ActivePointerGrab; - const CORE_ANCESTOR: u32 = 13; // implicit-grab owner (core-first) - const APP: u32 = 46; // the GTK app opening the combo - const IMPLICIT_WIN: u32 = 0x0050_069b; - const COMBO_WIN: u32 = 0x0150_0ac3; - - let mut state = ServerState::new(); - let mut app_peer = install_client(&mut state, APP); - let _anc_peer = install_client(&mut state, CORE_ANCESTOR); - app_peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - for (client, win) in [(CORE_ANCESTOR, IMPLICIT_WIN), (APP, COMBO_WIN)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: ResourceId(win), - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(ResourceId(win)); - } - - // A core-first implicit grab attributed to the ancestor's core client. - state.active_pointer_grab = Some(ActivePointerGrab { - owner: ClientId(CORE_ANCESTOR), - grab_window: ResourceId(IMPLICIT_WIN), - event_mask: 0x000c, - cursor: ResourceId(0), - time: 100, - owner_events: false, - via_xi2: false, - implicit: true, - passive: false, - xi2_mask: 0, - }); - - // The app's combo XIGrabDevice on the master pointer. - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&COMBO_WIN.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); - body.extend_from_slice(&[1, 1, 1, 0]); - body.extend_from_slice(&1u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber(1), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 8, - }, - &body, - ) - .expect("XIGrabDevice"); - - assert_eq!( - state.active_pointer_grab.map(|grab| grab.owner), - Some(ClientId(CORE_ANCESTOR)), - "the foreign implicit grab must remain untouched" - ); - let reply = read_all_available(&mut app_peer); - let reply_start = reply.len().saturating_sub(32); - assert!( - reply.len() >= 32 && reply[reply_start] == 1 && reply[reply_start + 8] == 1, - "grab over a foreign implicit grab must return AlreadyGrabbed(1); got {:?}", - &reply[..reply.len().min(12)] - ); - } - - /// MATE combo regression: Xorg's `DeliverDeviceEvents` walks from the - /// leaf toward root and tries XI2 before core at each window. An XI2 - /// selector on the app leaf therefore owns the implicit grab instead of - /// a core selector on its ancestor. The app's popup grab is SameClient. - #[test] - fn mate_combo_implicit_grab_attributed_to_app_leaf_xi2() { - use crate::{ - backend::Backend, - core_loop::pointer_fanout::pointer_event_fanout_to_state, - host_x11::{HostPointerEvent, PointerEventKind}, - resources::ROOT_VISUAL, - }; - const CORE_ANCESTOR: u32 = 13; - const APP: u32 = 46; - let parent = ResourceId(0x0050_069b); // core-ancestor selector window - let leaf = ResourceId(0x0150_0007); // the XI2 app's window (hit) - let combo = ResourceId(0x0150_0ac3); // the app's combo popup - const HOST_LEAF: u32 = 0xCAFE_0001; - const XI2_ALL_MASTER: u16 = 1; - - let mut state = ServerState::new(); - let _anc_peer = install_client(&mut state, CORE_ANCESTOR); - let mut app_peer = install_client(&mut state, APP); - app_peer.set_nonblocking(true).unwrap(); - let mut backend = RecordingBackend::new(); - - state.resources.create_window( - ClientId(CORE_ANCESTOR), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: parent, - parent: ROOT_WINDOW, - x: 0, - y: 0, - width: 200, - height: 200, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(parent); - for (client, win, par) in [(APP, leaf, parent), (APP, combo, ROOT_WINDOW)] { - state.resources.create_window( - ClientId(client), - yserver_protocol::x11::CreateWindowRequest { - depth: 24, - window: win, - parent: par, - x: 0, - y: 0, - width: 100, - height: 100, - border_width: 0, - class: 1, - visual: ROOT_VISUAL, - ..Default::default() - }, - ); - let _ = state.resources.map_window(win); - } - // Ancestor: CORE press|release. App leaf: XI2 under XIAllMasterDevices. - state - .clients - .get_mut(&CORE_ANCESTOR) - .unwrap() - .event_masks - .insert(parent, 0x0000_000c); - state - .clients - .get_mut(&APP) - .unwrap() - .xi2_masks - .insert((leaf, XI2_ALL_MASTER), (1 << 4) | (1 << 5)); - Backend::register_top_level(&mut backend, None, leaf, HOST_LEAF).expect("register"); - let xid_map = backend.xid_map().clone(); - - // Real click over the app's leaf. - let press = HostPointerEvent { - kind: PointerEventKind::ButtonPress, - host_xid: HOST_LEAF, - detail: 1, - time: 0x7e1b, - root_x: 10, - root_y: 10, - event_x: 10, - event_y: 10, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - }; - let _ = - pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); - assert_eq!( - state.active_pointer_grab.map(|grab| grab.owner), - Some(ClientId(APP)), - "the deeper XI2 leaf delivery must own the implicit grab" - ); - assert!( - state - .active_pointer_grab - .is_some_and(|grab| grab.implicit && grab.via_xi2) - ); - let _ = read_all_available(&mut app_peer); - - // The app opens its combo → XIGrabDevice on the master pointer. - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&combo.0.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&0u32.to_le_bytes()); - body.extend_from_slice(&2u16.to_le_bytes()); - body.extend_from_slice(&[1, 1, 1, 0]); - body.extend_from_slice(&1u16.to_le_bytes()); - body.extend_from_slice(&[0u8; 2]); - body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); - handle_xi2_request( - &mut state, - &mut backend, - None, - ClientId(APP), - SequenceNumber(1), - yserver_protocol::x11::RequestHeader { - opcode: 131, - data: 51, - length_units: 8, - }, - &body, - ) - .expect("XIGrabDevice"); - - assert_eq!( - state - .active_pointer_grab - .map(|grab| (grab.owner, grab.grab_window)), - Some((ClientId(APP), combo)), - "the app's SameClient XIGrabDevice must replace its implicit grab" - ); - let reply = read_all_available(&mut app_peer); - let reply_start = reply.len().saturating_sub(32); - assert!( - reply.len() >= 32 && reply[reply_start] == 1 && reply[reply_start + 8] == 0, - "combo grab reply must be Success (0), not AlreadyGrabbed (1); got {:?}", - &reply[..reply.len().min(12)] - ); - } - - #[test] - fn present_async_may_tear_bit_is_0x10() { - // presenttokens.h: PresentOptionAsyncMayTear = (1 << 4). - assert_eq!(0x10u32, 1u32 << 4); - // Stripping AsyncMayTear must NOT strip Suboptimal (0x8) or Async (0x1). - let opts = 0x1 | 0x8 | 0x10; - assert_eq!(opts & !0x10u32, 0x1 | 0x8); - } - - #[test] - fn xkb_get_kbd_by_name_also_broadcasts_legacy_mapping_notify() { - // Real `setxkbmap` loads a layout via XkbGetKeyboardByName (minor - // 23), not by writing `_XKB_RULES_NAMES`. A plain-X11 client (any - // WM that never calls XkbSelectEvents and only understands core - // events — e.g. one resolving keybinds via XKeysymToKeycode once - // at startup) relies on the legacy MappingNotify event to know - // when to re-resolve its keysym-based key grabs. Without it, the - // WM's shortcuts stay bound to the pre-switch keycodes forever - // even though per-keystroke translation (and thus typing) already - // reflects the new layout. - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // Stale ChangeKeyboardMapping row from before the switch — must - // not keep shadowing the freshly loaded keymap either. - state.keymap_overrides.insert(38, vec![0x0071]); - - let mut reply = vec![0u8; 32]; - reply[0] = 1; // X_Reply - assert!(crate::core_loop::xkb_select::use_extension( - &mut state, - ClientId(1), - &[1, 0, 0, 0] - )); - let mut backend = RecordingBackend::new().with_kbd_by_name_result( - reply, - Some(crate::backend::XkbNewKeyboardInfo { - min_keycode: 8, - max_keycode: 255, - old_min_keycode: 8, - old_max_keycode: 255, - changed: 0x0001, - }), - ); - - handle_xkb_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(1), - RequestHeader { - opcode: 136, - data: 23, - length_units: 2, - }, - &[], - ) - .expect("XkbGetKbdByName"); - - assert!( - state.keymap_overrides.is_empty(), - "a full XkbGetKeyboardByName load must drop stale ChangeKeyboardMapping rows too" - ); - - let bytes = read_all_available(&mut peer); - let mapping_notify_count = bytes - .chunks(32) - .filter( - |chunk| chunk.len() == 32 && chunk[0] == 34, /* MappingNotify */ - ) - .count(); - assert!( - mapping_notify_count >= 2, - "expected legacy MappingNotify(Keyboard) + MappingNotify(Modifier) \ - alongside XkbNewKeyboardNotify, got {mapping_notify_count} in {bytes:02x?}" - ); - let keyboard_mapping_notify = bytes - .chunks(32) - .find(|chunk| chunk.len() == 32 && chunk[0] == 34 && chunk[4] == 1); - assert!( - keyboard_mapping_notify.is_some(), - "expected a MappingNotify with request=Keyboard(1): {bytes:02x?}" - ); - } - - fn xkb_request( - state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - minor: u8, - body: &[u8], - ) { - handle_xkb_request( - state, - backend, - None, - ClientId(client), - SequenceNumber(1), - RequestHeader { - opcode: 136, - data: minor, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - ) - .expect("XKB request"); - } - - /// Xvfb 21.1.24, XkbUseExtension(1, 0) at sequence 2 from a - /// little-endian client: `01010200 00000000 01000000 00…` - /// (supported, server 1.0). - #[test] - fn xkb_use_extension_replies_like_xorg() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - handle_xkb_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 136, - data: 0, - length_units: 2, - }, - &[1, 0, 0, 0], - ) - .expect("XkbUseExtension"); - let reply = read_all_available(&mut peer); - let mut expected = [0u8; 32]; - expected[..10].copy_from_slice(&[1, 1, 2, 0, 0, 0, 0, 0, 1, 0]); - assert_eq!(reply, expected); - assert!(crate::core_loop::xkb_select::xkb_initialized( - &state, - ClientId(1) - )); - } - - /// yserver's XKB request parsers and reply encoders are little-endian - /// only, so a big-endian client is refused the way Xorg refuses a - /// client it can't serve: XkbUseExtension answers supported=False - /// (the bytes are Xvfb's big-endian answer to an unsupported version, - /// `01000002 00000000 00010000 00…`), and every other XKB request is - /// then BadAccess, as Xorg answers an uninitialised client (Xvfb: - /// GetState → BadAccess, value 0, minor 4). All of it in the client's - /// byte order. - #[test] - fn xkb_refuses_big_endian_clients_cleanly() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - state.clients.get_mut(&1).unwrap().byte_order = ClientByteOrder::BigEndian; - // XKB request bodies are not swapped: wantedMajor=1, wantedMinor=0 - // as a big-endian client sends them. - handle_xkb_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(2), - RequestHeader { - opcode: 136, - data: 0, - length_units: 2, - }, - &[0, 1, 0, 0], - ) - .expect("XkbUseExtension"); - let reply = read_all_available(&mut peer); - let mut expected = [0u8; 32]; - expected[..10].copy_from_slice(&[1, 0, 0, 2, 0, 0, 0, 0, 0, 1]); - assert_eq!(reply, expected); - assert!(!crate::core_loop::xkb_select::xkb_initialized( - &state, - ClientId(1) - )); - handle_xkb_request( - &mut state, - &mut backend, - None, - ClientId(1), - SequenceNumber(3), - RequestHeader { - opcode: 136, - data: 4, - length_units: 2, - }, - &[1, 0, 0, 0], - ) - .expect("XkbGetState"); - let err = read_all_available(&mut peer); - assert_eq!(err.len(), 32); - assert_eq!((err[0], err[1]), (0, x11::error::BAD_ACCESS)); - assert_eq!(&err[2..4], &[0, 3], "big-endian sequence"); - assert_eq!(&err[8..10], &[0, 4], "big-endian minor opcode"); - } - - /// Golden (`xorg-xkb-setmap-errors.txt`, Xvfb 21.1.24: `access`, - /// `access-getmap`, `access-selectevents`): an XKB request from a client - /// that never called XkbUseExtension answers BadAccess (value 0, minor = - /// the request's), and changes nothing; after UseExtension the same - /// requests go through. - #[test] - fn xkb_requests_need_use_extension() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let select_all = [0x00, 0x01, 0xff, 0x0f, 0, 0, 0xff, 0x0f, 0xff, 0, 0xff, 0]; - for (minor, body) in [ - (8u8, vec![0u8; 24]), - (1, select_all.to_vec()), - (9, vec![0; 32]), - ] { - xkb_request(&mut state, &mut backend, 1, minor, &body); - let err = read_all_available(&mut peer); - assert_eq!(err.len(), 32, "minor {minor}: one error"); - assert_eq!( - (err[0], err[1], &err[4..8], err[8], err[10]), - (0, x11::error::BAD_ACCESS, &[0u8, 0, 0, 0][..], minor, 136), - "minor {minor}" - ); - } - assert!( - state - .xkb_clients - .get(&1) - .is_none_or(|c| c.map_notify_mask == 0) - ); - xkb_request(&mut state, &mut backend, 1, 0, &[1, 0, 0, 0]); - assert!(crate::core_loop::xkb_select::xkb_initialized( - &state, - ClientId(1) - )); - let _ = read_all_available(&mut peer); - xkb_request(&mut state, &mut backend, 1, 1, &select_all); - assert!( - read_all_available(&mut peer).is_empty(), - "SelectEvents: no error" - ); - assert_eq!(state.xkb_clients[&1].map_notify_mask, 0xff); - } - - /// `ProcXkbUseExtension`: an unsupported version (2.0) leaves the client - /// uninitialised. - #[test] - fn xkb_use_extension_unsupported_version_stays_uninitialised() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - xkb_request(&mut state, &mut backend, 1, 0, &[2, 0, 0, 0]); - assert!(!crate::core_loop::xkb_select::xkb_initialized( - &state, - ClientId(1) - )); - } - - /// `XkbSendLegacyMapNotify` (xkb/xkbEvents.c): a MapNotify's core - /// MappingNotify goes to non-XKB clients and to XKB clients whose map - /// details include a change; a NewKeyboardNotify's only to non-XKB - /// clients. - #[test] - fn legacy_map_notify_filters_xkb_clients() { - use crate::core_loop::xkb_select::{ - LegacyCause, send_legacy_core_map_notify, xkb_select_events, - }; - let mut state = ServerState::new(); - let mut plain = install_client(&mut state, 1); - let mut xkb_keysyms = install_client(&mut state, 2); - let mut xkb_none = install_client(&mut state, 3); - xkb_select_events(&mut state, 2, 0x100, 0x0002); - xkb_select_events(&mut state, 3, 0x100, 0x0004); - let _ = send_legacy_core_map_notify(&mut state, LegacyCause::MapNotify, 0x0002, 8, 248); - let count = |b: Vec| b.chunks(32).filter(|e| e[0] == 34).count(); - assert_eq!(count(read_all_available(&mut plain)), 1); - assert_eq!(count(read_all_available(&mut xkb_keysyms)), 1); - assert_eq!(count(read_all_available(&mut xkb_none)), 0); - let _ = - send_legacy_core_map_notify(&mut state, LegacyCause::NewKeyboardNotify, 0x0001, 8, 248); - assert_eq!( - count(read_all_available(&mut plain)), - 2, - "Keyboard + Modifier" - ); - assert_eq!(count(read_all_available(&mut xkb_keysyms)), 0); - assert_eq!(count(read_all_available(&mut xkb_none)), 0); - } - - // ── Step 3 (window-storage lifecycle): Pictures on windows ────────── - - const PIC_A: u32 = 0x0030_0000; - const PIC_B: u32 = 0x0040_0000; - const PIC_WIN: u32 = PIC_A | 1; - const PIC_WIN_HOST: u32 = 0x00E0_0001; - const PIC_ON_WIN: u32 = PIC_B | 1; - const PIC_PIXMAP: u32 = PIC_B | 2; - const PIC_ON_PIXMAP: u32 = PIC_B | 3; - - fn picture_request( - state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - opcode: u8, - data: u8, - body: &[u8], - ) { - process_request( - state, - backend, - ClientId(client), - SequenceNumber(1), - RequestHeader { - opcode, - data, - length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), - }, - body, - None, - ) - .unwrap(); - } - - /// `(error code, bad value)` of every error queued on `peer`. - fn drain_errors(peer: &mut UnixStream) -> Vec<(u8, u32)> { - peer.set_nonblocking(true).unwrap(); - let mut out = Vec::new(); - let mut buf = [0u8; 32]; - while peer.read_exact(&mut buf).is_ok() { - if buf[0] == 0 { - out.push((buf[1], u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]))); - } - } - out - } - - fn create_render_picture( - state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - pic: u32, - drawable: u32, - ) { - let mut body = Vec::new(); - for v in [pic, drawable, 0, 0] { - body.extend_from_slice(&v.to_le_bytes()); - } - picture_request(state, backend, client, 133, 4, &body); - } - - fn render_fill(state: &mut ServerState, backend: &mut RecordingBackend, client: u32, dst: u32) { - let mut body = vec![1u8, 0, 0, 0]; - body.extend_from_slice(&dst.to_le_bytes()); - body.extend_from_slice(&[0xff; 8]); - for v in [0i16, 0] { - body.extend_from_slice(&v.to_le_bytes()); - } - for v in [8u16, 8] { - body.extend_from_slice(&v.to_le_bytes()); - } - picture_request(state, backend, client, 133, 26, &body); - } - - fn render_composite_pics( - state: &mut ServerState, - backend: &mut RecordingBackend, - client: u32, - src: u32, - dst: u32, - ) { - let mut body = vec![0u8; 32]; - body[0] = 3; - body[4..8].copy_from_slice(&src.to_le_bytes()); - body[12..16].copy_from_slice(&dst.to_le_bytes()); - body[28..30].copy_from_slice(&8u16.to_le_bytes()); - body[30..32].copy_from_slice(&8u16.to_le_bytes()); - picture_request(state, backend, client, 133, 8, &body); - } - - fn render_free(state: &mut ServerState, backend: &mut RecordingBackend, client: u32, pic: u32) { - picture_request(state, backend, client, 133, 7, &pic.to_le_bytes()); - } - - fn host_pic_of(state: &ServerState, pic: u32) -> u32 { - state - .resources - .picture(ResourceId(pic)) - .expect("picture exists") - .host_picture_xid - .expect("backed picture") - .as_raw() - } - - fn render_paints(backend: &RecordingBackend) -> Vec { - backend - .calls() - .into_iter() - .filter(|c| { - matches!( - c, - RecordedCall::RenderComposite { .. } - | RecordedCall::RenderFillRectangles { .. } - ) - }) - .collect() - } - - /// Client A owns a mapped top-level `PIC_WIN`; client B holds a Picture on it and - /// one on its own pixmap. - fn cross_client_picture_fixture() -> (ServerState, RecordingBackend, UnixStream, UnixStream) { - let mut state = ServerState::new(); - let peer_a = install_client(&mut state, 1); - let peer_b = install_client(&mut state, 2); - let mut backend = RecordingBackend::new(); - create_pic_test_window(&mut state, PIC_WIN, PIC_WIN_HOST); - state.resources.create_pixmap( - ClientId(2), - CreatePixmapRequest { - pixmap: ResourceId(PIC_PIXMAP), - drawable: ROOT_WINDOW, - width: 16, - height: 16, - depth: 24, - }, - ); - assert!(state.resources.set_pixmap_host_xid( - ResourceId(PIC_PIXMAP), - crate::backend::PixmapHandle::from_raw_for_test(0x00E0_0100), - )); - create_render_picture(&mut state, &mut backend, 2, PIC_ON_WIN, PIC_WIN); - create_render_picture(&mut state, &mut backend, 2, PIC_ON_PIXMAP, PIC_PIXMAP); - (state, backend, peer_a, peer_b) - } - - fn create_pic_test_window(state: &mut ServerState, xid: u32, host: u32) { - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(xid), - parent: ROOT_WINDOW, - width: 64, - height: 64, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(xid)) - .unwrap() - .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(host)); - let _ = state.resources.map_window(ResourceId(xid)); - } - - /// B's Picture on A's window is dead once the window is gone: every use and - /// its FreePicture are BadPicture, its pixmap Picture is untouched, and a new - /// window on the same xid and host storage does not revive it. - fn assert_window_picture_dead_after( - destroy: impl FnOnce(&mut ServerState, &mut RecordingBackend), - ) { - let bad_picture = crate::nested::RENDER_FIRST_ERROR + 1; - let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); - let host_on_win = host_pic_of(&state, PIC_ON_WIN); - let host_on_pixmap = host_pic_of(&state, PIC_ON_PIXMAP); - - destroy(&mut state, &mut backend); - - assert!(state.resources.picture(ResourceId(PIC_ON_WIN)).is_none()); - let freed: Vec = backend - .calls() - .into_iter() - .filter_map(|c| match c { - RecordedCall::RenderFreePicture { host_pic } => Some(host_pic), - _ => None, - }) - .collect(); - assert_eq!( - freed, - vec![host_on_win], - "only the window Picture's backend record is freed" - ); - assert_eq!(host_pic_of(&state, PIC_ON_PIXMAP), host_on_pixmap); - backend.calls.lock().unwrap().clear(); - - create_pic_test_window(&mut state, PIC_WIN, PIC_WIN_HOST); - render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); - render_composite_pics(&mut state, &mut backend, 2, PIC_ON_WIN, PIC_ON_PIXMAP); - render_free(&mut state, &mut backend, 2, PIC_ON_WIN); - assert_eq!( - drain_errors(&mut peer_b), - vec![(bad_picture, PIC_ON_WIN); 3], - "FillRectangles, Composite and FreePicture on the dead Picture", - ); - assert!(render_paints(&backend).is_empty()); - assert!( - !backend - .calls() - .iter() - .any(|c| matches!(c, RecordedCall::RenderFreePicture { .. })) - ); - - render_fill(&mut state, &mut backend, 2, PIC_ON_PIXMAP); - assert_eq!( - render_paints(&backend), - vec![RecordedCall::RenderFillRectangles { - host_dst: host_on_pixmap - }], - ); - assert!(drain_errors(&mut peer_b).is_empty()); - } - - #[test] - fn destroy_window_frees_other_clients_pictures_on_it() { - assert_window_picture_dead_after(|state, backend| { - picture_request(state, backend, 1, 4, 0, &PIC_WIN.to_le_bytes()); - }); - } - - #[test] - fn owner_disconnect_frees_other_clients_pictures_on_its_windows() { - assert_window_picture_dead_after(|state, backend| { - crate::core_loop::process_disconnect::process_disconnect(state, backend, ClientId(1)); - let _peer = install_client(state, 1); - }); - } - - #[test] - fn destroying_a_parent_frees_pictures_on_its_descendants() { - let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); - const CHILD: u32 = PIC_A | 2; - const PIC_ON_CHILD: u32 = PIC_B | 4; - state.resources.create_window( - ClientId(1), - CreateWindowRequest { - depth: 24, - window: ResourceId(CHILD), - parent: ResourceId(PIC_WIN), - width: 8, - height: 8, - class: 1, - visual: crate::resources::ROOT_VISUAL, - ..Default::default() - }, - ); - state - .resources - .window_mut(ResourceId(CHILD)) - .unwrap() - .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(0x00E0_0002)); - create_render_picture(&mut state, &mut backend, 2, PIC_ON_CHILD, CHILD); - assert!(state.resources.picture(ResourceId(PIC_ON_CHILD)).is_some()); - - picture_request(&mut state, &mut backend, 1, 4, 0, &PIC_WIN.to_le_bytes()); - - assert!(state.resources.picture(ResourceId(PIC_ON_CHILD)).is_none()); - assert!(state.resources.picture(ResourceId(PIC_ON_WIN)).is_none()); - assert!(state.resources.picture(ResourceId(PIC_ON_PIXMAP)).is_some()); - assert!(drain_errors(&mut peer_b).is_empty()); - } - - /// Xorg: an unviewable window's clipList is empty, so a Picture on it as the - /// destination draws nothing; the same Picture draws again after remap. - #[test] - fn window_picture_draws_nothing_while_unmapped_and_again_after_remap() { - let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); - let host_on_win = host_pic_of(&state, PIC_ON_WIN); - let host_on_pixmap = host_pic_of(&state, PIC_ON_PIXMAP); - let fill = RecordedCall::RenderFillRectangles { - host_dst: host_on_win, - }; - - render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); - assert_eq!(render_paints(&backend), vec![fill.clone()]); - backend.calls.lock().unwrap().clear(); - - picture_request(&mut state, &mut backend, 1, 10, 0, &PIC_WIN.to_le_bytes()); - render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); - render_composite_pics(&mut state, &mut backend, 2, PIC_ON_PIXMAP, PIC_ON_WIN); - assert!( - render_paints(&backend).is_empty(), - "unmapped: nothing drawn" - ); - // As a source the hidden window's contents are undefined, not an error. - render_composite_pics(&mut state, &mut backend, 2, PIC_ON_WIN, PIC_ON_PIXMAP); - assert_eq!( - render_paints(&backend), - vec![RecordedCall::RenderComposite { - host_src: host_on_win, - host_dst: host_on_pixmap, - }], - ); - backend.calls.lock().unwrap().clear(); - - picture_request(&mut state, &mut backend, 1, 8, 0, &PIC_WIN.to_le_bytes()); - render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); - assert_eq!(render_paints(&backend), vec![fill]); - assert!(drain_errors(&mut peer_b).is_empty()); - } - - /// A Picture on a redirected window names the window, not the backing it - /// has at creation time, so it follows backing rotations. - #[test] - fn create_picture_on_redirected_window_names_the_window() { - let mut state = ServerState::new(); - let _peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - create_pic_test_window(&mut state, PIC_WIN, PIC_WIN_HOST); - state - .resources - .window_mut(ResourceId(PIC_WIN)) - .unwrap() - .redirected_backing = Some(crate::resources::RedirectedBacking { - host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(0x00E0_0200), - width: 64, - height: 64, - depth: 24, - }); - create_render_picture(&mut state, &mut backend, 1, PIC_A | 5, PIC_WIN); - let host_drawables: Vec = backend - .calls() - .into_iter() - .filter_map(|c| match c { - RecordedCall::RenderCreatePicture { host_drawable, .. } => Some(host_drawable), - _ => None, - }) - .collect(); - assert_eq!( - host_drawables, - vec![crate::backend::AnyHandle::Window( - crate::backend::WindowHandle::from_raw_for_test(PIC_WIN_HOST) - )], - ); - assert_eq!( - state - .resources - .picture(ResourceId(PIC_A | 5)) - .unwrap() - .window, - Some(ResourceId(PIC_WIN)), - ); - } - - /// Xorg `compDestroyOverlayWindow` frees the overlay through DeleteWindow, so - /// Pictures on it are freed with it (`composite/compoverlay.c:167-172`). - #[test] - fn overlay_release_frees_pictures_on_the_overlay() { - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let mut backend = RecordingBackend::new(); - let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; - let mut body = vec![0u8; 4]; - body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 1, - yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, - &body, - ); - drain_errors(&mut peer); - create_render_picture(&mut state, &mut backend, 1, PIC_A | 6, cow.0); - assert!(state.resources.picture(ResourceId(PIC_A | 6)).is_some()); - body[0..4].copy_from_slice(&cow.0.to_le_bytes()); - dispatch_composite_minor( - &mut state, - &mut backend, - ClientId(1), - 2, - yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, - &body, - ); - assert!(state.resources.window(cow).is_none()); - assert!(state.resources.picture(ResourceId(PIC_A | 6)).is_none()); - } - - /// CreateConicalGradient registers a Picture: usable as a source without an - /// error (drawing with it stays unimplemented) and freeable. - #[test] - fn conical_gradient_picture_is_usable_as_source_and_freeable() { - let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); - const CONICAL: u32 = PIC_B | 9; - let mut body = Vec::new(); - body.extend_from_slice(&CONICAL.to_le_bytes()); - body.extend_from_slice(&[0u8; 16]); // center, angle, nstops = 0 - picture_request(&mut state, &mut backend, 2, 133, 36, &body); - assert!(state.resources.picture(ResourceId(CONICAL)).is_some()); - backend.calls.lock().unwrap().clear(); - render_composite_pics(&mut state, &mut backend, 2, CONICAL, PIC_ON_PIXMAP); - assert!( - render_paints(&backend).is_empty(), - "unbacked source draws nothing" - ); - render_free(&mut state, &mut backend, 2, CONICAL); - assert!(state.resources.picture(ResourceId(CONICAL)).is_none()); - assert!(drain_errors(&mut peer_b).is_empty()); - } - - /// A CreatePicture the backend could not back still succeeds at protocol level: - /// ops on the Picture are silent no-ops and FreePicture is valid. An id that was - /// never created is still BadPicture. - #[test] - fn unbacked_picture_ops_are_silent_no_ops() { - let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); - const UNBACKED: u32 = PIC_B | 10; - backend.render_create_picture_fails = true; - create_render_picture(&mut state, &mut backend, 2, UNBACKED, PIC_PIXMAP); - backend.render_create_picture_fails = false; - let st = state - .resources - .picture(ResourceId(UNBACKED)) - .expect("registered"); - assert!(st.host_picture_xid.is_none()); - backend.calls.lock().unwrap().clear(); - - render_fill(&mut state, &mut backend, 2, UNBACKED); - render_composite_pics(&mut state, &mut backend, 2, UNBACKED, PIC_ON_PIXMAP); - render_composite_pics(&mut state, &mut backend, 2, PIC_ON_PIXMAP, UNBACKED); - render_free(&mut state, &mut backend, 2, UNBACKED); - assert!(drain_errors(&mut peer_b).is_empty()); - assert!(state.resources.picture(ResourceId(UNBACKED)).is_none()); - assert!(backend.calls().iter().all(|c| !matches!( - c, - RecordedCall::RenderComposite { .. } - | RecordedCall::RenderFillRectangles { .. } - | RecordedCall::RenderFreePicture { .. } - ))); - - const NEVER: u32 = PIC_B | 11; - render_fill(&mut state, &mut backend, 2, NEVER); - assert_eq!( - drain_errors(&mut peer_b), - vec![(crate::nested::RENDER_FIRST_ERROR + 1, NEVER)], - ); - } - - /// Xorg dixLookupDrawable: CreatePicture on an unknown drawable is BadDrawable - /// and registers nothing. - #[test] - fn create_picture_on_unknown_drawable_is_bad_drawable() { - let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); - const PIC: u32 = PIC_B | 12; - create_render_picture(&mut state, &mut backend, 2, PIC, 0x00DE_AD00); - assert_eq!( - drain_errors(&mut peer_b), - vec![(x11::error::BAD_DRAWABLE, 0x00DE_AD00)], - ); - assert!(state.resources.picture(ResourceId(PIC)).is_none()); + bytes: &[u8], +) -> RequestOutcome { + crate::core_loop::fanout::record_outbound_telemetry(client_id, client.byte_order, bytes); + match client_io::write_or_buffer(client, bytes) { + Ok(WriteOutcome::Done | WriteOutcome::WouldBlock) => RequestOutcome::Handled, + Ok(WriteOutcome::Disconnect) => RequestOutcome::Disconnect(client_id), + Err(_) => RequestOutcome::Disconnect(client_id), } } diff --git a/crates/yserver-core/src/core_loop/process_request/colormaps.rs b/crates/yserver-core/src/core_loop/process_request/colormaps.rs new file mode 100644 index 000000000..5027bb2df --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/colormaps.rs @@ -0,0 +1,709 @@ +use crate::{ + access::{ + AccessMode, Creation, Decision, DenyError, RequestOpcodes, ResourceKind, ResourceTarget, + }, + core_loop::process_request::{ + RequestOutcome, emit_x11_error, write_to_client, xid_out_of_client_range, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, ResourceId, SequenceNumber}, +}; + +fn check_colormap_access( + state: &ServerState, + client_id: ClientId, + cmap: ResourceId, + mode: AccessMode, + access_request: RequestOpcodes, +) -> Option { + if !state.policies_installed() || client_id == crate::resources::SERVER_OWNER { + return None; + } + state.resources.colormap(cmap)?; + match state.check_resource( + client_id, + &ResourceTarget { + id: cmap, + kind: ResourceKind::Colormap, + creation: None, + }, + mode, + Some(access_request), + ) { + Decision::Allow => None, + Decision::Deny(error) => Some(error), + } +} + +/// StoreColors (89): always BadAccess on TrueColor (read-only) colormaps. +pub(super) fn handle_store_colors( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + debug!("client {} #{} StoreColors", client_id.0, sequence.0); + if let Some(cmap) = body.get(..4).map(|bytes| { + ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte colormap id"), + )) + }) && let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::WRITE, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 89); + } + emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 89) +} + +/// StoreNamedColor (90): same — TrueColor → BadAccess. +pub(super) fn handle_store_named_color( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + debug!("client {} #{} StoreNamedColor", client_id.0, sequence.0); + if let Some(cmap) = body.get(..4).map(|bytes| { + ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte colormap id"), + )) + }) && let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::WRITE, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 90); + } + emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 90) +} + +/// AllocColorCells (86): always BadAlloc on TrueColor visuals. +/// X11 spec: cells/planes can only be allocated from +/// DirectColor/PseudoColor/GrayScale colormaps. Our default +/// colormaps are TrueColor → always BadAlloc. +pub(super) fn handle_alloc_color_cells( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + debug!("client {} #{} AllocColorCells", client_id.0, sequence.0); + let cmap = ResourceId(u32::from_le_bytes( + body[..4] + .try_into() + .expect("fixed-length AllocColorCells colormap id"), + )); + if let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::ADD, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 86); + } + emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 86) +} + +/// AllocColorPlanes (87): same — TrueColor → BadAlloc. +pub(super) fn handle_alloc_color_planes( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + debug!("client {} #{} AllocColorPlanes", client_id.0, sequence.0); + let cmap = ResourceId(u32::from_le_bytes( + body[..4] + .try_into() + .expect("fixed-length AllocColorPlanes colormap id"), + )); + if let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::ADD, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 87); + } + emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 87) +} + +pub(super) fn handle_create_colormap( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 12 { + return Ok(RequestOutcome::Handled); + } + let mid = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + if state.resources.xid_in_use(mid) || xid_out_of_client_range(state, client_id, mid.0) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + mid.0, + 78, + ); + } + let window = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + if state.resources.window(window).is_some() + && let Decision::Deny(error) = state.check_resource( + client_id, + &ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + Some(access_request), + ) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 78); + } + if let Decision::Deny(error) = state.check_resource( + client_id, + &ResourceTarget { + id: mid, + kind: ResourceKind::Colormap, + creation: Some(Creation { + parent: Some(window), + owner: client_id, + }), + }, + AccessMode::CREATE, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 78); + } + let visual = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + state.resources.create_colormap(client_id, mid, visual); + debug!( + "client {} #{} CreateColormap 0x{:x}", + client_id.0, sequence.0, mid.0 + ); + Ok(RequestOutcome::Handled) +} + +/// CopyColormapAndFree (80): allocate new colormap, BadIDChoice on duplicate. +pub(super) fn handle_copy_colormap_and_free( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let mid = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + if state.resources.xid_in_use(mid) || xid_out_of_client_range(state, client_id, mid.0) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + mid.0, + 80, + ); + } + // Source colormap's visual; default to ROOT_VISUAL if unknown. + let src_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + if let Some(error) = check_colormap_access( + state, + client_id, + src_id, + AccessMode::READ | AccessMode::REMOVE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 80); + } + if let Decision::Deny(error) = state.check_resource( + client_id, + &ResourceTarget { + id: mid, + kind: ResourceKind::Colormap, + creation: Some(Creation { + parent: None, + owner: client_id, + }), + }, + AccessMode::CREATE, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 80); + } + let visual = state + .resources + .colormap(src_id) + .map(|c| c.visual) + .unwrap_or(crate::resources::ROOT_VISUAL); + state.resources.create_colormap(client_id, mid, visual); + debug!( + "client {} #{} CopyColormapAndFree 0x{:x}", + client_id.0, sequence.0, mid.0 + ); + Ok(RequestOutcome::Handled) +} + +/// ListInstalledColormaps (83): reply with 0 colormaps. +/// Emit `ColormapNotify(window, cmap, new=false, installed=…)` to every +/// window whose `attributes.colormap == cmap`, for clients subscribed +/// with the ColormapChange event mask bit (`1 << 23`). +fn emit_colormap_notify_for(state: &mut ServerState, cmap: ResourceId, installed: bool) { + let windows = state.resources.windows_with_colormap(cmap); + for w in windows { + let _dropped = crate::core_loop::fanout::emit_window_event_to_state( + state, + w, + 0x0080_0000, + |buf, seq, order| { + x11::encode_colormap_notify_event(buf, seq, order, w, cmap, false, installed); + }, + ); + } +} + +/// Restore the default colormap to the installed list if a prior +/// uninstall / free emptied it. X11 spec: "Initially, the default +/// colormap for a screen is installed" plus the server may implicitly +/// install required colormaps; ROOT_COLORMAP is the lone required +/// entry on our TrueColor setup. +fn ensure_default_colormap_installed(state: &mut ServerState) { + if !state.installed_colormaps.is_empty() { + return; + } + let root = crate::resources::ROOT_COLORMAP; + state.installed_colormaps.push(root); + emit_colormap_notify_for(state, root, true); +} + +/// InstallColormap (81): mark a colormap as installed and emit +/// `ColormapNotify(Installed)` on every window that uses it. On a +/// TrueColor server this is bookkeeping only — the hardware colormap +/// never actually changes — but clients (and xts) still observe the +/// notify chain. +pub(super) fn handle_install_colormap( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let cmap = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + debug!( + "client {} #{} InstallColormap 0x{:x}", + client_id.0, sequence.0, cmap.0 + ); + if state.resources.colormap(cmap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + cmap.0, + 81, + ); + } + if let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::INSTALL, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 81); + } + if state.installed_colormaps.contains(&cmap) { + return Ok(RequestOutcome::Handled); + } + // Capacity = `max_installed_maps = 1` (matches the SETUP advertise). + // Evict oldest to make room — its own `ColormapNotify(Uninstalled)` + // fans out before the new install's notify. + if !state.installed_colormaps.is_empty() { + let evicted = state.installed_colormaps.remove(0); + emit_colormap_notify_for(state, evicted, false); + } + state.installed_colormaps.push(cmap); + emit_colormap_notify_for(state, cmap, true); + Ok(RequestOutcome::Handled) +} + +/// FreeColormap (79): destroy the colormap resource. Uninstalls it +/// first if installed (emitting `ColormapNotify(Uninstalled)`). The +/// default colormap is not freeable — BadColor per spec. +pub(super) fn handle_free_colormap( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let cmap = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + debug!( + "client {} #{} FreeColormap 0x{:x}", + client_id.0, sequence.0, cmap.0 + ); + if cmap == crate::resources::ROOT_COLORMAP || state.resources.colormap(cmap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + cmap.0, + 79, + ); + } + if let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::DESTROY, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 79); + } + let was_installed = state.installed_colormaps.contains(&cmap); + state.installed_colormaps.retain(|c| *c != cmap); + if was_installed { + emit_colormap_notify_for(state, cmap, false); + } + state.resources.free_colormap(cmap); + ensure_default_colormap_installed(state); + Ok(RequestOutcome::Handled) +} + +/// UninstallColormap (82): symmetric to `InstallColormap`. Uninstalling +/// the default colormap is allowed but the server implicitly re-installs +/// it later when focus changes; we model the bookkeeping faithfully. +pub(super) fn handle_uninstall_colormap( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let cmap = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + debug!( + "client {} #{} UninstallColormap 0x{:x}", + client_id.0, sequence.0, cmap.0 + ); + if state.resources.colormap(cmap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + cmap.0, + 82, + ); + } + if let Some(error) = check_colormap_access( + state, + client_id, + cmap, + AccessMode::UNINSTALL, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 82); + } + let before = state.installed_colormaps.len(); + state.installed_colormaps.retain(|c| *c != cmap); + if state.installed_colormaps.len() == before { + return Ok(RequestOutcome::Handled); + } + emit_colormap_notify_for(state, cmap, false); + ensure_default_colormap_installed(state); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_list_installed_colormaps( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + // Body's window xid scopes the reply to the window's screen. + // yserver has a single screen so the list is server-global, but + // we still validate the xid — xts probes BadWindow on a freed xid. + let window = if body.len() >= 4 { + ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])) + } else { + ResourceId(0) + }; + debug!( + "client {} #{} ListInstalledColormaps 0x{:x}", + client_id.0, sequence.0, window.0 + ); + if state.resources.window(window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 83, + ); + } + if let Decision::Deny(error) = state.check_resource( + client_id, + &ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 83); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let installed = state.installed_colormaps.clone(); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + // Layout: reply(1) pad(1) seq(2) length=N(4) nColormaps u16(2) + // pad(22) colormaps u32[N] + // Length field counts u32 units past the 32-byte fixed header. + let length_units = u32::try_from(installed.len()).unwrap_or(0); + let mut buf = x11::fixed_reply(byte_order, sequence, 0, length_units); + let mut tmp = Vec::with_capacity(2); + x11::write_u16( + byte_order, + &mut tmp, + u16::try_from(installed.len()).unwrap_or(0), + ); + buf.extend_from_slice(&tmp); + buf.resize(32, 0); + for cmap in &installed { + let mut entry = Vec::with_capacity(4); + x11::write_u32(byte_order, &mut entry, cmap.0); + buf.extend_from_slice(&entry); + } + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_alloc_color( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + debug!("client {} #{} AllocColor", client_id.0, sequence.0); + let color = x11::alloc_color_request(body).unwrap_or_default(); + if let Some(cmap) = body.get(..4).map(|bytes| { + ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte colormap id"), + )) + }) && let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::ADD, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 84); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_alloc_color_reply(&mut buf, byte_order, sequence, color)?; + Ok(write_to_client(client, client_id, &buf)) +} + +/// FreeColors (88): release a client's color allocations. +/// +/// yserver currently exposes only fixed TrueColor visuals and does not retain +/// per-client references for the read-only colors returned by AllocColor / +/// AllocNamedColor. Validate the colormap and the Xorg-detectable BadValue +/// cases, then complete without a reply. Xorg additionally returns BadAccess +/// for unallocated or already-freed pixels; without allocation accounting, +/// yserver deliberately accepts those frees as a permissive no-op. +pub(super) fn handle_free_colors( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(prefix) = body.get(..8) else { + return Ok(RequestOutcome::Handled); + }; + let cmap = ResourceId(u32::from_le_bytes( + prefix[..4].try_into().expect("four-byte colormap id"), + )); + let plane_mask = u32::from_le_bytes(prefix[4..8].try_into().expect("four-byte plane mask")); + let mut pixels = body[8..] + .chunks_exact(4) + .map(|pixel| u32::from_le_bytes(pixel.try_into().expect("four-byte pixel"))); + let pixel_count = pixels.len(); + debug!( + "client {} #{} FreeColors cmap=0x{:x} plane_mask=0x{:08x} pixels={}", + client_id.0, sequence.0, cmap.0, plane_mask, pixel_count + ); + let Some(colormap) = state.resources.colormap(cmap) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + cmap.0, + 88, + ); + }; + if let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::REMOVE, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 88); + } + let Some(visual) = state.resources.visual(colormap.visual) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + cmap.0, + 88, + ); + }; + let valid_mask = visual.red_mask | visual.green_mask | visual.blue_mask | visual.alpha_mask; + if pixel_count != 0 && plane_mask & !valid_mask != 0 { + let first_pixel = pixels.clone().next().expect("non-empty pixel list"); + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + first_pixel | plane_mask, + 88, + ); + } + if let Some(invalid_pixel) = pixels.find(|pixel| pixel & !valid_mask != 0) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + invalid_pixel, + 88, + ); + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_alloc_named_color( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let name = x11::alloc_named_color_name(body); + let Some(color) = x11::lookup_color_name(&name) else { + // Unknown color name → BadName (Xorg), not a silent gray + // fallback that hands the client the wrong pixel. + debug!( + "client {} #{} AllocNamedColor unknown name {:?} -> BadName", + client_id.0, sequence.0, name + ); + return emit_x11_error(state, client_id, sequence, x11::error::BAD_NAME, 0, 85); + }; + if let Some(cmap) = body.get(..4).map(|bytes| { + ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte colormap id"), + )) + }) && let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::ADD, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 85); + } + debug!( + "client {} #{} AllocNamedColor {:?}", + client_id.0, sequence.0, name + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_alloc_named_color_reply(&mut buf, byte_order, sequence, color)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_query_colors( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let pixels = x11::query_colors_pixels(body); + debug!( + "client {} #{} QueryColors {} pixels", + client_id.0, + sequence.0, + pixels.len() + ); + if let Some(cmap) = body.get(..4).map(|bytes| { + ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte colormap id"), + )) + }) && let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::READ, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 91); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32 + pixels.len() * 8); + x11::write_query_colors_reply(&mut buf, byte_order, sequence, &pixels)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_lookup_color( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let name = x11::alloc_named_color_name(body); + let Some(color) = x11::lookup_color_name(&name) else { + // Unknown color name → BadName (Xorg), not a silent gray fallback. + debug!( + "client {} #{} LookupColor unknown name {:?} -> BadName", + client_id.0, sequence.0, name + ); + return emit_x11_error(state, client_id, sequence, x11::error::BAD_NAME, 0, 92); + }; + if let Some(cmap) = body.get(..4).map(|bytes| { + ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte colormap id"), + )) + }) && let Some(error) = + check_colormap_access(state, client_id, cmap, AccessMode::READ, access_request) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 92); + } + debug!( + "client {} #{} LookupColor {:?}", + client_id.0, sequence.0, name + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_lookup_color_reply(&mut buf, byte_order, sequence, color)?; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/composite_damage.rs b/crates/yserver-core/src/core_loop/process_request/composite_damage.rs new file mode 100644 index 000000000..7be931cc8 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/composite_damage.rs @@ -0,0 +1,728 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + damage_fanout::{accumulate_damage_full_to_state, report_existing_damage_to_state}, + process_request::{ + RequestOutcome, emit_x11_error_with_minor, + redirect::{BackingDamage, damage_restored_window, sync_redirect_backing}, + shape_xfixes::{ + drawable_full_rect_xfixes, format_region_rects, normalize_region_rects, + }, + write_to_client, + }, + }, + resources::{COMPOSITE_OVERLAY_WINDOW, ROOT_WINDOW}, + server::ServerState, +}; +use log::{debug, trace}; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +#[allow(clippy::too_many_arguments)] +pub(super) fn handle_composite_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, composite as x11composite}; + const COMPOSITE_MAJOR_OPCODE: u8 = 144; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + match minor { + x11composite::QUERY_VERSION => { + let _ = x11composite::parse_query_version(body); + let major = x11composite::MAJOR_VERSION; + let minor_ver = x11composite::MINOR_VERSION; + debug!( + "client {} #{} COMPOSITE::QueryVersion -> {}.{}", + client_id.0, sequence.0, major, minor_ver + ); + let reply = + x11composite::encode_query_version_reply(byte_order, sequence, major, minor_ver); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11composite::REDIRECT_WINDOW + | x11composite::REDIRECT_SUBWINDOWS + | x11composite::UNREDIRECT_WINDOW + | x11composite::UNREDIRECT_SUBWINDOWS => { + let Some((window_raw, update)) = x11composite::parse_window_update(body) else { + return Ok(RequestOutcome::Handled); + }; + let window = ResourceId(window_raw); + let subwindows = matches!( + minor, + x11composite::REDIRECT_SUBWINDOWS | x11composite::UNREDIRECT_SUBWINDOWS + ); + let redirect = matches!( + minor, + x11composite::REDIRECT_WINDOW | x11composite::REDIRECT_SUBWINDOWS + ); + let error = |state: &mut ServerState, code: u8| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + window_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ) + }; + let Some(parent) = state.resources.window(window).map(|w| w.parent) else { + return error(state, x11::error::BAD_WINDOW); + }; + // compositeproto: update=0 → Automatic, update=1 → Manual. An + // unredirect with any other value matches no record (BadValue + // below, as Xorg). + let mode = match update { + 0 => crate::server::CompositeRedirectMode::Automatic, + 1 => crate::server::CompositeRedirectMode::Manual, + _ => return error(state, x11::error::BAD_VALUE), + }; + // Xorg compRedirectWindow (composite/compalloc.c:145-150): the + // overlay window is never redirected and asking succeeds; the + // root has no parent to redirect into (BadMatch). Unredirect has + // no such checks: neither ever holds a record, so it BadValues. + if redirect && !subwindows { + if window == COMPOSITE_OVERLAY_WINDOW { + return Ok(RequestOutcome::Handled); + } + if parent == window { + return error(state, x11::error::BAD_MATCH); + } + } + let targets: Vec = if subwindows { + crate::core_loop::process_request::subwindows_redirect_targets(state, window) + } else { + vec![window] + }; + let before: Vec<_> = targets + .iter() + .map(|t| state.composite_redirects.window_mode(*t)) + .collect(); + let record = crate::server::RedirectRecord { + mode, + owner: client_id, + }; + let released = if !redirect && subwindows { + crate::core_loop::process_request::manual_subwindows_release_regions( + state, + client_id, + &[window], + ) + } else { + Vec::new() + }; + let redirects = &mut state.composite_redirects; + let ok = match (redirect, subwindows) { + // Only one Manual redirect per window or subwindows list, + // whichever client holds it (compalloc.c:155-158, :336-339): + // muffin probes RedirectWindow(frame, Manual) after its own + // RedirectSubwindows(root, Manual) and expects BadAccess. + (true, false) => redirects.redirect_window(window, record).is_ok(), + (true, true) => redirects + .redirect_subwindows(window, &targets, record) + .is_ok(), + (false, false) => redirects.unredirect_window(window, client_id, mode), + (false, true) => redirects.unredirect_subwindows(window, &targets, client_id, mode), + }; + debug!( + "client {} #{} COMPOSITE::{}Redirect{}(0x{:x}, mode={:?}) -> {} targets={}", + client_id.0, + sequence.0, + if redirect { "" } else { "Un" }, + if subwindows { "Subwindows" } else { "Window" }, + window_raw, + mode, + if ok { "ok" } else { "refused" }, + targets.len(), + ); + if !ok { + return error( + state, + if redirect { + x11::error::BAD_ACCESS + } else { + x11::error::BAD_VALUE + }, + ); + } + if mode == crate::server::CompositeRedirectMode::Manual { + crate::core_loop::process_request::clear_after_manual_subwindows_release( + state, backend, origin, &released, + ); + } + for (i, (target, before)) in targets.iter().zip(before).enumerate() { + let had_backing = state + .resources + .window(*target) + .is_some_and(|w| w.redirected_backing.is_some()); + sync_redirect_backing( + state, + backend, + origin, + *target, + before, + BackingDamage::Allocation, + ); + if had_backing && state.composite_redirects.window_mode(*target).is_none() { + damage_restored_window(state, *target, &targets[i + 1..]); + } + } + } + x11composite::CREATE_REGION_FROM_BORDER_CLIP => { + if let Some((region, window)) = x11composite::parse_u32_pair(body) { + let rects = vec![drawable_full_rect_xfixes(state, ResourceId(window))]; + state.xfixes_regions.insert( + region, + crate::server::XFixesRegion { + owner: client_id, + region: crate::region::Region::from_rects(&rects), + }, + ); + } + } + x11composite::NAME_WINDOW_PIXMAP => { + let Some((window_raw, pixmap_raw)) = x11composite::parse_u32_pair(body) else { + return Ok(RequestOutcome::Handled); + }; + let window = ResourceId(window_raw); + let pixmap = ResourceId(pixmap_raw); + debug!( + "client {} #{} COMPOSITE::NameWindowPixmap(window=0x{:x}, pixmap=0x{:x})", + client_id.0, sequence.0, window_raw, pixmap_raw, + ); + let snapshot = state.resources.window(window).map(|w| { + // Xorg compext.c:246 `if (!cw) return BadMatch;`. + let redirected = state.composite_redirects.window_mode(window).is_some(); + let (pixmap_width, pixmap_height) = w + .redirected_backing + .as_ref() + .map_or((w.width, w.height), |backing| { + (backing.width, backing.height) + }); + ( + w.host_xid, + pixmap_width, + pixmap_height, + w.depth, + redirected, + w.map_state, + ) + }); + let Some((host_xid, w_width, w_height, w_depth, redirected, map_state)) = snapshot + else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + }; + if !redirected { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + window_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + // Xorg's `ProcCompositeNameWindowPixmap` refuses a non-viewable + // window (composite/compext.c:241 `if (!pWin->viewable) return + // BadMatch;`) — a non-viewable window has no off-screen backing to + // name. We honoured it instead, so in issue #97 fastcompmgr got a + // valid pixmap for i3's unmapped frame and kept compositing a + // window that had left the workspace. + if map_state != crate::resources::MapState::Viewable { + debug!( + "client {} #{} COMPOSITE::NameWindowPixmap(window=0x{:x}) -> BadMatch \ + (map_state={map_state:?}, Xorg requires Viewable)", + client_id.0, sequence.0, window_raw, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + window_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + let Some(host_window_xid) = host_xid else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + pixmap_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + }; + if backend.composite_opcode().is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + pixmap_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + let host_pixmap_xid = match backend.name_window_pixmap(origin, host_window_xid) { + Ok(handle) => handle, + Err(err) => { + debug!( + "client {} #{} COMPOSITE::NameWindowPixmap(window=0x{:x}) -> Err: {err}", + client_id.0, sequence.0, window_raw, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + pixmap_raw, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + }; + state.resources.create_pixmap( + client_id, + x11::CreatePixmapRequest { + pixmap, + drawable: window, + width: w_width, + height: w_height, + depth: w_depth, + }, + ); + let _ = state.resources.set_pixmap_host_xid(pixmap, host_pixmap_xid); + state.resources.mark_pixmap_composite_name(pixmap); + if let Some(w) = state.resources.window_mut(window) { + w.composite_named_pixmaps + .push(crate::resources::NamedCompositePixmap { + client_pixmap: pixmap, + host_pixmap: host_pixmap_xid, + width: w_width, + height: w_height, + }); + } + } + x11composite::GET_OVERLAY_WINDOW => { + // Checked first, before anything else: a previous session's + // overlay could not be torn down and is still materialized + // with nobody owning it. Whatever we would hand this + // compositor is inherited state, so refuse. Sticky for the + // life of the process. + if state.cow_teardown_failed { + log::warn!( + "client {} #{} COMPOSITE::GetOverlayWindow refused: the \ + overlay is orphaned by a failed teardown", + client_id.0, + sequence.0, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + 0, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + let _window = x11composite::parse_window(body).unwrap_or(ROOT_WINDOW.0); + // Must return a distinct XID, not root. See COMPOSITE_OVERLAY_WINDOW + // for why — marco's compositor immediately calls XSelectInput on + // this XID and would otherwise wipe its own WM event mask on root. + let overlay = COMPOSITE_OVERLAY_WINDOW.0; + // Core owns the claim list; the backend counts nothing. Each + // Get records one claim owned by the calling client (Xorg's + // per-Get `CompOverlayClientRec`), and materializes the overlay + // whenever it does not exist, whatever the claims: a + // `DestroyWindow(COW)` leaves them (`compext.c:303`, + // `compwindow.c:624-626`). + // + // Transactional: on failure only this Get's claim goes + // (`compext.c:305`). + let exists = state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_some(); + state.cow_claims.push(client_id); + if !exists + && let Err(err) = + crate::core_loop::composite_overlay::materialize_overlay(state, backend, origin) + { + state.cow_claims.pop(); + log::warn!( + "client {} #{} COMPOSITE::GetOverlayWindow materialization failed: {err}", + client_id.0, + sequence.0, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + 0, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + debug!( + "client {} #{} COMPOSITE::GetOverlayWindow -> 0x{:x}", + client_id.0, sequence.0, overlay + ); + let reply = + x11composite::encode_get_overlay_window_reply(byte_order, sequence, overlay); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11composite::RELEASE_OVERLAY_WINDOW => { + debug!( + "client {} #{} COMPOSITE::ReleaseOverlayWindow", + client_id.0, sequence.0 + ); + // Ownership check, as Xorg's `ProcCompositeReleaseOverlayWindow` + // does via `compFindOverlayClient`: a client holding no claim + // gets BadMatch and nothing changes. Get and Release pair 1:1, + // so this drops exactly ONE of the caller's claims — never all + // of them, and never somebody else's. + let Some(claim_index) = state + .cow_claims + .iter() + .rposition(|owner| *owner == client_id) + else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + }; + if state.cow_claims.len() == 1 { + // Final release: tear down FIRST and keep the claim unless + // it succeeds. The claim is what keeps the overlay alive, + // so dropping it before the overlay is gone is precisely + // the leak. A COW already destroyed just loses the claim. + if let Err(err) = + crate::core_loop::composite_overlay::teardown_overlay(state, backend, origin) + { + log::warn!( + "client {} #{} COMPOSITE::ReleaseOverlayWindow teardown failed: {err}", + client_id.0, + sequence.0, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + 0, + u16::from(minor), + COMPOSITE_MAJOR_OPCODE, + ); + } + } + state.cow_claims.remove(claim_index); + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + COMPOSITE_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_damage_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::damage as x11damage; + let minor = header.data; + match minor { + x11damage::QUERY_VERSION => { + let (client_major, client_minor) = x11damage::parse_query_version(body) + .unwrap_or((x11damage::MAJOR_VERSION, x11damage::MINOR_VERSION)); + let major = x11damage::MAJOR_VERSION.min(client_major); + let minor_ver = if major < x11damage::MAJOR_VERSION { + client_minor + } else { + x11damage::MINOR_VERSION.min(client_minor) + }; + debug!( + "client {} #{} DAMAGE::QueryVersion -> {}.{}", + client_id.0, sequence.0, major, minor_ver + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let reply = + x11damage::encode_query_version_reply(byte_order, sequence, major, minor_ver); + return Ok(write_to_client(client, client_id, &reply)); + } + x11damage::CREATE => { + if let Some((damage, drawable, level)) = x11damage::parse_create(body) { + let drawable_id = ResourceId(drawable); + // DamageRegister prepends to the drawable's list + // (`miext/damage/damage.c:1482`). + state.damage_list_clock += 1; + let tick = state.damage_list_clock; + state.damage_objects.insert( + damage, + crate::server::DamageObject { + owner: client_id, + drawable: drawable_id, + level, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: tick, + created: tick, + }, + ); + debug!( + "client {} #{} DAMAGE::Create damage=0x{damage:x} drawable=0x{drawable:x} level={level}", + client_id.0, sequence.0, + ); + let seed_initial_damage = state + .resources + .window(drawable_id) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable) + || state + .resources + .composite_named_pixmap_owner_window(drawable_id) + .and_then(|window_id| state.resources.window(window_id)) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + if seed_initial_damage { + log::trace!( + target: "yserver_core::core_loop::damage_fanout", + "damage_create_seed_full: damage=0x{:x} drawable=0x{:x} level={}", + damage, + drawable, + level, + ); + let _dropped = accumulate_damage_full_to_state(state, drawable_id); + } + } else { + debug!( + "client {} #{} DAMAGE::Create parse_failed", + client_id.0, sequence.0 + ); + } + } + x11damage::DESTROY => { + if let Some(damage) = x11damage::parse_resource(body) { + let drawable = state.damage_objects.remove(&damage).map(|d| d.drawable.0); + debug!( + "client {} #{} DAMAGE::Destroy damage=0x{damage:x} drawable=0x{:x}", + client_id.0, + sequence.0, + drawable.unwrap_or(0), + ); + } else { + debug!( + "client {} #{} DAMAGE::Destroy parse_failed", + client_id.0, sequence.0 + ); + } + } + x11damage::ADD => { + if let Some((drawable, region)) = x11damage::parse_add(body) { + let rects = if region == 0 { + vec![drawable_full_rect_xfixes(state, ResourceId(drawable))] + } else { + state + .xfixes_regions + .get(®ion) + .map(crate::server::XFixesRegion::rects) + .unwrap_or_default() + }; + for damage in state.damage_objects.values_mut() { + if damage.drawable == ResourceId(drawable) { + damage.rects.extend(rects.clone()); + damage.rects = normalize_region_rects(std::mem::take(&mut damage.rects)); + } + } + } + debug!("client {} #{} DAMAGE::Add", client_id.0, sequence.0); + } + x11damage::SUBTRACT => { + if let Some((damage_id, repair, parts)) = x11damage::parse_subtract(body) { + // NonEmpty damage coalesces later paints without notifying + // again. Submit those writes before acknowledging/consuming + // the damage, not only before the initial DamageNotify. + backend.flush_before_damage_notify(); + // Per X11 DAMAGE spec (cf. Xorg damageext.c:419 + + // miext/damage/damage.c:1854): + // if repair == None: parts ← old damage; damage ← empty + // else: parts ← old ∩ repair; damage ← old − repair + // The repair region is a read-only input filter — NEVER + // overwrite it. Compositors (marco, picom, ...) feed + // `parts` into `SetPictureClipRectangles`; an empty + // parts collapses every subsequent composite to a no-op + // and the screen freezes. + let old_region = state + .damage_objects + .get(&damage_id) + .map(|d| crate::region::Region::from_rects(&d.rects)) + .unwrap_or_default(); + let old_damage = old_region.to_rects(); + let drawable = state + .damage_objects + .get(&damage_id) + .map(|d| d.drawable.0) + .unwrap_or(0); + let level = state + .damage_objects + .get(&damage_id) + .map(|d| d.level) + .unwrap_or(0); + let owner = state + .damage_objects + .get(&damage_id) + .map(|d| d.owner.0) + .unwrap_or(0); + let repair_region = state.xfixes_regions.get(&repair).map(|r| &r.region); + let (parts_region, new_damage) = match repair_region { + _ if repair == 0 => (old_region, Vec::new()), + None => (crate::region::Region::default(), old_damage.clone()), + Some(repair) => ( + old_region.intersect(repair), + old_region.subtract(repair).to_rects(), + ), + }; + let repair_rects = repair_region + .filter(|_| repair != 0) + .map(crate::region::Region::to_rects) + .unwrap_or_default(); + if parts != 0 { + let parts_owner = state + .xfixes_regions + .get(&parts) + .map_or(client_id, |region| region.owner); + state.xfixes_regions.insert( + parts, + crate::server::XFixesRegion { + owner: parts_owner, + region: parts_region, + }, + ); + } + if let Some(damage) = state.damage_objects.get_mut(&damage_id) { + damage.rects = new_damage; + damage.pending_notify_fired = false; + } + if repair != 0 + && level != x11damage::report_level::RAW_RECTANGLES + && state + .damage_objects + .get(&damage_id) + .is_some_and(|d| !d.rects.is_empty()) + { + let _dropped = report_existing_damage_to_state(state, damage_id); + } + let parts_owner = if parts == 0 { + 0 + } else { + state.xfixes_regions.get(&parts).map_or(0, |r| r.owner.0) + }; + trace!( + "client {} #{} DAMAGE::Subtract damage=0x{damage_id:x} drawable=0x{drawable:x} \ + owner={} level={} repair=0x{repair:x} parts=0x{parts:x} parts_owner={} \ + old_n={} old={} repair_n={} repair_rects={} parts_n={} parts_rects={} \ + new_n={} new_rects={}", + client_id.0, + sequence.0, + owner, + level, + parts_owner, + old_damage.len(), + format_region_rects(&old_damage), + repair_rects.len(), + format_region_rects(&repair_rects), + if parts == 0 { + 0 + } else { + state + .xfixes_regions + .get(&parts) + .map_or(0, |r| r.rects().len()) + }, + format_region_rects( + &state + .xfixes_regions + .get(&parts) + .map(crate::server::XFixesRegion::rects) + .unwrap_or_default() + ), + state + .damage_objects + .get(&damage_id) + .map_or(0, |d| d.rects.len()), + format_region_rects( + &state + .damage_objects + .get(&damage_id) + .map(|d| d.rects.clone()) + .unwrap_or_default() + ), + ); + } + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + } + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/drawing.rs b/crates/yserver-core/src/core_loop/process_request/drawing.rs new file mode 100644 index 000000000..e65a3ada6 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/drawing.rs @@ -0,0 +1,2059 @@ +use crate::{ + access::{AccessMode, Decision, DenyError, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext, params::FillState}, + core_loop::{ + damage_fanout::{accumulate_damage_full_to_state, accumulate_damage_to_state}, + process_request::{ + CopyAreaSubRect, RequestOutcome, background_paint_inhibited, emit_x11_error, + paint_window_background, + redirect::{ + current_bounding_in_parent, effective_redirect_mode_for_window, + redirected_ancestor_or_self, + }, + send_window_exposures, validate_drawable_and_gc, validate_drawable_only, + window_unviewable, write_to_client, zpixmap_expected_len, + }, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// Xorg's `miClearToBackground` region (`mi/miwindow.c:63-112`): the +/// requested rect (a zero width/height reaching the window edge) clipped +/// to the window's clip list, in its content space. +fn clear_area_region( + state: &ServerState, + request: x11::ClearAreaRequest, + w_width: u16, + w_height: u16, +) -> Vec { + let span = |offset: i16, requested: u16, extent: u16| -> (i32, i32) { + let lo = i32::from(offset); + let hi = if requested == 0 { + i32::from(extent) + } else { + lo + i32::from(requested) + }; + (lo.max(0), hi.min(i32::from(extent))) + }; + let (x1, x2) = span(request.x, request.width, w_width); + let (y1, y2) = span(request.y, request.height, w_height); + if x2 <= x1 || y2 <= y1 { + return Vec::new(); + } + let rect = x11::xfixes::RegionRect { + x: i16::try_from(x1).unwrap_or(i16::MAX), + y: i16::try_from(y1).unwrap_or(i16::MAX), + width: u16::try_from(x2 - x1).unwrap_or(u16::MAX), + height: u16::try_from(y2 - y1).unwrap_or(u16::MAX), + }; + let clip = crate::core_loop::clip_list::clip_list(state, request.window); + crate::core_loop::clip_list::intersect(&[rect], &clip) +} + +pub(super) fn handle_put_image( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + let Some(request) = x11::put_image_request(header.data, body) else { + return Ok(RequestOutcome::Handled); + }; + if request.width == 0 || request.height == 0 { + return Ok(RequestOutcome::Handled); + } + debug!( + "client {} #{} PutImage drawable=0x{:x} {}x{} dst=({},{}) depth={} fmt={:?}", + client_id.0, + sequence.0, + request.drawable.0, + request.width, + request.height, + request.dst_x, + request.dst_y, + request.depth, + request.format, + ); + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + request.drawable, + request.gc, + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 72); + } + let draw_state = state.resources.resolve_draw_state(request.gc); + let target = state.resources.host_drawable_target(request.drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + let (image_bytes, upload_depth) = match request.format { + x11::ImageFormat::ZPixmap => { + if request.left_pad != 0 || request.depth != target.depth() { + return Ok(RequestOutcome::Handled); + } + let Some(expected_len) = + zpixmap_expected_len(request.width, request.height, request.depth) + else { + return Ok(RequestOutcome::Handled); + }; + if request.data.len() < expected_len { + return Ok(RequestOutcome::Handled); + } + (request.data[..expected_len].to_vec(), request.depth) + } + x11::ImageFormat::XyBitmap => { + // XYBitmap is a single depth-1 source plane interpreted through + // the GC foreground/background pixels. This is the path used by + // XCreateBitmapFromData() and XCreatePixmapFromBitmapData(). + if request.depth != 1 { + return Ok(RequestOutcome::Handled); + } + let Some(expected_len) = + xybitmap_expected_len(request.width, request.height, request.left_pad) + else { + return Ok(RequestOutcome::Handled); + }; + if request.data.len() < expected_len { + return Ok(RequestOutcome::Handled); + } + let Some(bytes) = xybitmap_to_target_zpixmap( + &request.data[..expected_len], + request.width, + request.height, + request.left_pad, + target.depth(), + st.foreground, + st.background, + ) else { + return Ok(RequestOutcome::Handled); + }; + (bytes, target.depth()) + } + x11::ImageFormat::XyPixmap => { + // Depth-1 XYPixmap is a single bitmap plane and can be + // normalized through the same repack as XYBitmap. Higher + // depths need multi-plane composition and remain unsupported + // here for now. + if request.depth != 1 || target.depth() != 1 { + return Ok(RequestOutcome::Handled); + } + let Some(expected_len) = + xybitmap_expected_len(request.width, request.height, request.left_pad) + else { + return Ok(RequestOutcome::Handled); + }; + if request.data.len() < expected_len { + return Ok(RequestOutcome::Handled); + } + let Some(bytes) = xybitmap_to_zpixmap( + &request.data[..expected_len], + request.width, + request.height, + request.left_pad, + ) else { + return Ok(RequestOutcome::Handled); + }; + (bytes, request.depth) + } + x11::ImageFormat::Unknown(_) => { + return Ok(RequestOutcome::Handled); + } + }; + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + backend.put_image( + origin, + target.host_xid(), + upload_depth, + request.width, + request.height, + request.dst_x, + request.dst_y, + &image_bytes, + )?; + let _dropped = accumulate_damage_to_state( + state, + request.drawable, + request.dst_x, + request.dst_y, + request.width, + request.height, + ); + } + Ok(RequestOutcome::Handled) +} + +/// Bytes per scanline for X11 ZPixmap of `width` pixels at `depth`, +/// padded to the server's bitmap_scanline_pad of 32 bits. +pub(super) fn zpixmap_row_stride(width: u16, depth: u8) -> Option { + match depth { + 24 | 32 => usize::from(width).checked_mul(4), + 8 => usize::from(width).div_ceil(4).checked_mul(4), + 4 => usize::from(width).div_ceil(8).checked_mul(4), + 1 => usize::from(width).div_ceil(32).checked_mul(4), + _ => None, + } +} + +fn xybitmap_expected_len(width: u16, height: u16, left_pad: u8) -> Option { + let bits_per_row = usize::from(width).checked_add(usize::from(left_pad))?; + let stride_bytes = bits_per_row.div_ceil(32).checked_mul(4)?; + stride_bytes.checked_mul(usize::from(height)) +} + +pub(super) fn xybitmap_to_zpixmap( + data: &[u8], + width: u16, + height: u16, + left_pad: u8, +) -> Option> { + let bits_per_row = usize::from(width).checked_add(usize::from(left_pad))?; + let src_row_stride = bits_per_row.div_ceil(32).checked_mul(4)?; + if data.len() < src_row_stride.checked_mul(usize::from(height))? { + return None; + } + let dst_row_stride = zpixmap_row_stride(width, 1)?; + let mut out = vec![0u8; dst_row_stride.checked_mul(usize::from(height))?]; + let left_pad = usize::from(left_pad); + let width = usize::from(width); + for row in 0..usize::from(height) { + let src_row = &data[row * src_row_stride..(row + 1) * src_row_stride]; + let dst_row = &mut out[row * dst_row_stride..(row + 1) * dst_row_stride]; + for x in 0..width { + let src_bit = left_pad + x; + let src_byte = src_row[src_bit / 8]; + if (src_byte >> (src_bit % 8)) & 1 != 0 { + dst_row[x / 8] |= 1 << (x % 8); + } + } + } + Some(out) +} + +fn depth_plane_mask(depth: u8) -> u32 { + if depth >= 32 { + u32::MAX + } else { + (1u32 << depth) - 1 + } +} + +fn write_zpixmap_pixel(bytes: &mut [u8], width: usize, depth: u8, x: usize, y: usize, value: u32) { + let stride = zpixmap_row_stride(width as u16, depth).expect("validated target depth"); + match depth { + 1 => { + let byte = &mut bytes[y * stride + x / 8]; + let bit = 1u8 << (x % 8); + if value & 1 != 0 { + *byte |= bit; + } else { + *byte &= !bit; + } + } + 4 => { + let byte = &mut bytes[y * stride + x / 2]; + let nibble = (value & 0x0f) as u8; + if x.is_multiple_of(2) { + *byte = (*byte & 0xf0) | nibble; + } else { + *byte = (*byte & 0x0f) | (nibble << 4); + } + } + 8 => bytes[y * stride + x] = value as u8, + 24 | 32 => { + let off = y * stride + x * 4; + bytes[off..off + 4].copy_from_slice(&value.to_le_bytes()); + } + _ => {} + } +} + +pub(super) fn xybitmap_to_target_zpixmap( + data: &[u8], + width: u16, + height: u16, + left_pad: u8, + target_depth: u8, + fg: u32, + bg: u32, +) -> Option> { + let bits_per_row = usize::from(width).checked_add(usize::from(left_pad))?; + let src_row_stride = bits_per_row.div_ceil(32).checked_mul(4)?; + if data.len() < src_row_stride.checked_mul(usize::from(height))? { + return None; + } + let dst_row_stride = zpixmap_row_stride(width, target_depth)?; + let mut out = vec![0u8; dst_row_stride.checked_mul(usize::from(height))?]; + let left_pad = usize::from(left_pad); + let width = usize::from(width); + let fg = fg & depth_plane_mask(target_depth); + let bg = bg & depth_plane_mask(target_depth); + for row in 0..usize::from(height) { + let src_row = &data[row * src_row_stride..(row + 1) * src_row_stride]; + for x in 0..width { + let src_bit = left_pad + x; + let src_byte = src_row[src_bit / 8]; + let pixel = if (src_byte >> (src_bit % 8)) & 1 != 0 { + fg + } else { + bg + }; + write_zpixmap_pixel(&mut out, width, target_depth, x, row, pixel); + } + } + Some(out) +} + +pub(super) fn handle_image_text8( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + if let Some((drawable_raw, gc_id, text_body)) = x11::image_text8_data(body) { + let drawable = ResourceId(drawable_raw); + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 76); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + backend.image_text8( + origin, + target.host_xid(), + st.foreground, + st.background, + header.data, + text_body, + )?; + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!("client {} #{} ImageText8", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_image_text16( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + if let Some((drawable_raw, gc_id, text_body)) = x11::image_text8_data(body) { + let drawable = ResourceId(drawable_raw); + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 77); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + backend.image_text16( + origin, + target.host_xid(), + st.foreground, + st.background, + header.data, + text_body, + )?; + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!("client {} #{} ImageText16", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_get_image( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + debug!("client {} #{} GetImage", client_id.0, sequence.0); + let Some(req) = x11::get_image_request(header.data, body) else { + return Ok(RequestOutcome::Handled); + }; + // Validation per Xorg ProcGetImage: format ∈ {XYPixmap, ZPixmap} + // → BadValue; drawable must exist → BadDrawable; the rect must + // lie fully within the drawable (windows additionally must be + // viewable) → BadMatch. + if req.format != 1 && req.format != 2 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.format), + 73, + ); + } + let window = state.resources.window(req.drawable); + let pixmap = if window.is_none() { + state.resources.pixmap(req.drawable) + } else { + None + }; + if window.is_none() && pixmap.is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable.0, + 73, + ); + } + let drawable_kind = if window.is_some() { + ResourceKind::Window + } else { + ResourceKind::Pixmap + }; + if let Decision::Deny(error) = state.check_resource( + client_id, + &ResourceTarget { + id: req.drawable, + kind: drawable_kind, + creation: None, + }, + AccessMode::READ, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 73); + } + let rx0 = i32::from(req.x); + let ry0 = i32::from(req.y); + let rx1 = rx0 + i32::from(req.width); + let ry1 = ry0 + i32::from(req.height); + if let Some(w) = window { + // Windows: must be viewable; the rect may include the BORDER + // (xts XGetImage-7 reads (-1,-1)) but not extend past its + // outside edges; and — ignoring overlaps — the rect must be + // fully on the screen (XGetImage-15). Both → BadMatch. + let bw = i32::from(w.border_width); + let (ww, wh) = (i32::from(w.width), i32::from(w.height)); + let viewable = w.map_state == crate::resources::MapState::Viewable; + let in_window = rx0 >= -bw && ry0 >= -bw && rx1 <= ww + bw && ry1 <= wh + bw; + let (abs_x, abs_y) = state.resources.window_absolute_position(req.drawable); + let (root_w, root_h) = state + .resources + .window(crate::resources::ROOT_WINDOW) + .map_or((i32::MAX, i32::MAX), |r| { + (i32::from(r.width), i32::from(r.height)) + }); + // The bound is the pixmap the window draws into: the screen, or + // the backing of the nearest redirected window at or above it, + // which a window partly off the screen still has whole + // (`DoGetImage`, `dix/dispatch.c:2176-2210`). + let (bx, by, bwidth, bheight) = match redirected_ancestor_or_self(state, req.drawable) + .and_then(|r| state.resources.window(r).map(|w| (r, w))) + { + Some((r, rw)) => { + let (rx, ry) = state.resources.window_absolute_position(r); + let rbw = i32::from(rw.border_width); + ( + rx - rbw, + ry - rbw, + i32::from(rw.width) + 2 * rbw, + i32::from(rw.height) + 2 * rbw, + ) + } + None => (0, 0, root_w, root_h), + }; + let on_screen = abs_x + rx0 >= bx + && abs_y + ry0 >= by + && abs_x + rx1 <= bx + bwidth + && abs_y + ry1 <= by + bheight; + if !viewable || !in_window || !on_screen { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.drawable.0, + 73, + ); + } + } else if let Some(p) = pixmap { + if rx0 < 0 || ry0 < 0 || rx1 > i32::from(p.width) || ry1 > i32::from(p.height) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.drawable.0, + 73, + ); + } + } else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable.0, + 73, + ); + } + let byte_order = state + .clients + .get(&client_id.0) + .map_or(yserver_protocol::x11::ClientByteOrder::LittleEndian, |c| { + c.byte_order + }); + let host_xid = if req.drawable == ROOT_WINDOW { + Some(backend.window_id()) + } else { + state + .resources + .host_drawable_target(req.drawable) + .map(|t| t.host_xid()) + }; + let host_reply = host_xid.and_then(|xid| { + backend + .get_image( + origin, + xid, + req.format, + req.x, + req.y, + req.width.max(1), + req.height.max(1), + req.plane_mask, + ) + .ok() + .flatten() + }); + let buf: Vec = if let Some(bytes) = host_reply { + patch_get_image_reply_header(bytes, byte_order, sequence, crate::resources::ROOT_VISUAL.0) + } else { + let mut buf: Vec = Vec::with_capacity(64); + x11::write_get_image_reply( + &mut buf, + byte_order, + sequence, + &req, + crate::resources::ROOT_VISUAL.0, + )?; + buf + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn patch_get_image_reply_header( + mut bytes: Vec, + byte_order: x11::ClientByteOrder, + sequence: SequenceNumber, + visual: u32, +) -> Vec { + if bytes.len() < 32 { + return bytes; + } + let seq = match byte_order { + x11::ClientByteOrder::LittleEndian => sequence.0.to_le_bytes(), + x11::ClientByteOrder::BigEndian => sequence.0.to_be_bytes(), + }; + let len_words = u32::try_from((bytes.len() - 32) / 4).unwrap_or(u32::MAX); + let len = match byte_order { + x11::ClientByteOrder::LittleEndian => len_words.to_le_bytes(), + x11::ClientByteOrder::BigEndian => len_words.to_be_bytes(), + }; + let vis = match byte_order { + x11::ClientByteOrder::LittleEndian => visual.to_le_bytes(), + x11::ClientByteOrder::BigEndian => visual.to_be_bytes(), + }; + bytes[2..4].copy_from_slice(&seq); + bytes[4..8].copy_from_slice(&len); + bytes[8..12].copy_from_slice(&vis); + bytes +} + +/// Rewrite PolyText8/16 embedded font-change items (len == 255): +/// the wire carries the CLIENT font XID, the backend's font table is +/// keyed by HOST xids. Returns the translated body plus the last +/// font's client id (committed to the GC per X11 §8), or a `DenyError` +/// for an unresolved font (BadFont) or a resource-policy denial. +fn translate_poly_text_fonts( + state: &ServerState, + client_id: ClientId, + access_request: RequestOpcodes, + body: &[u8], + two_byte: bool, +) -> Result<(Vec, Option), DenyError> { + let mut out = body.to_vec(); + let mut last: Option = None; + let mut off = 12usize; + while off + 2 <= out.len() { + let len = out[off]; + if len == 255 { + if off + 5 > out.len() { + break; + } + let client_xid = + u32::from_be_bytes([out[off + 1], out[off + 2], out[off + 3], out[off + 4]]); + let Some(font) = state.resources.font(ResourceId(client_xid)) else { + return Err(DenyError { + code: x11::error::BAD_FONT, + value: client_xid, + }); + }; + if let Decision::Deny(error) = state.check_resource( + client_id, + &ResourceTarget { + id: ResourceId(client_xid), + kind: ResourceKind::Font, + creation: None, + }, + AccessMode::USE, + Some(access_request), + ) { + return Err(error); + } + out[off + 1..off + 5].copy_from_slice(&font.host_xid.as_raw().to_be_bytes()); + last = Some(ResourceId(client_xid)); + off += 5; + } else { + let n = usize::from(len); + off += 2 + if two_byte { 2 * n } else { n }; + } + } + Ok((out, last)) +} + +pub(super) fn handle_poly_text8( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((drawable_raw, gc_id, text_body)) = x11::poly_text_data(body) { + let drawable = ResourceId(drawable_raw); + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 74); + } + let (text_body, last_font) = + match translate_poly_text_fonts(state, client_id, access_request, text_body, false) { + Ok(pair) => pair, + Err(error) => { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 74); + } + }; + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + backend.poly_text8(origin, target.host_xid(), st.foreground, &text_body)?; + } + if let Some(font) = last_font { + state.resources.set_gc_font(ResourceId(gc_id), font); + super::fonts::release_unreferenced_fonts(state, backend, origin); + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!("client {} #{} PolyText8", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_text16( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((drawable_raw, gc_id, text_body)) = x11::poly_text_data(body) { + let drawable = ResourceId(drawable_raw); + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 75); + } + let (text_body, last_font) = + match translate_poly_text_fonts(state, client_id, access_request, text_body, true) { + Ok(pair) => pair, + Err(error) => { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 75); + } + }; + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + backend.poly_text16(origin, target.host_xid(), st.foreground, &text_body)?; + } + if let Some(font) = last_font { + state.resources.set_gc_font(ResourceId(gc_id), font); + super::fonts::release_unreferenced_fonts(state, backend, origin); + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!("client {} #{} PolyText16", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_point( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + if body.len() >= 8 { + let drawable = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let gc_id = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let points = &body[8..]; + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 64); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + if let Err(err) = (|| -> io::Result<()> { + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + backend.poly_point( + origin, + target.host_xid(), + st.foreground, + header.data, + points, + ) + })() { + log::warn!( + "client {} #{} PolyPoint backend error: {err}", + client_id.0, + sequence.0 + ); + } + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolyPoint drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_line( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + if let Some((gc_id, points)) = x11::poly_line_data(body) + && let Some(drawable) = x11::drawable_request_id(body) + { + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 65); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + let _ = backend.poly_line( + origin, + target.host_xid(), + st.foreground, + header.data, + points, + ); + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolyLine drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_segment( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((gc_id, segments)) = x11::poly_segment_data(body) + && let Some(drawable) = x11::drawable_request_id(body) + { + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 66); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + let _ = backend.poly_segment(origin, target.host_xid(), st.foreground, segments); + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolySegment drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_rectangle( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((gc_id, rectangles)) = x11::poly_fill_rectangle_data(body) + && let Some(drawable) = x11::drawable_request_id(body) + { + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 67); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + let _ = backend.poly_rectangle(origin, target.host_xid(), st.foreground, rectangles); + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolyRectangle drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_arc( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((gc_id, arcs)) = x11::poly_arc_data(body) + && let Some(drawable) = x11::drawable_request_id(body) + { + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 68); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + let _ = backend.poly_arc(origin, target.host_xid(), st.foreground, arcs); + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolyArc drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_fill_poly( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 12 { + let drawable = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let gc_id = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let coord_mode = body[9]; + let points = &body[12..]; + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 69); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + let needs_fill_reset = !matches!(st.fill, FillState::Solid); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_fill_state(origin, &st.fill)?; + backend.apply_draw_state(origin, &st)?; + let _ = backend.fill_poly(origin, target.host_xid(), st.foreground, coord_mode, points); + if needs_fill_reset { + let _ = backend.set_gc_fill_solid(origin); + } + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} FillPoly drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_fill_rectangle( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((gc_id, rectangles)) = x11::poly_fill_rectangle_data(body) + && let Some(drawable) = x11::drawable_request_id(body) + { + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 70); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + let needs_fill_reset = !matches!(st.fill, FillState::Solid); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_fill_state(origin, &st.fill)?; + backend.apply_draw_state(origin, &st)?; + let _ = + backend.poly_fill_rectangle(origin, target.host_xid(), st.foreground, rectangles); + if needs_fill_reset { + let _ = backend.set_gc_fill_solid(origin); + } + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolyFillRectangle drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_poly_fill_arc( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some((gc_id, arcs)) = x11::poly_fill_arc_data(body) + && let Some(drawable) = x11::drawable_request_id(body) + { + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + drawable, + ResourceId(gc_id), + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 71); + } + let draw_state = state.resources.resolve_draw_state(ResourceId(gc_id)); + let target = state.resources.host_drawable_target(drawable); + if let Some(target) = target { + let st = draw_state.unwrap_or_default(); + let needs_fill_reset = !matches!(st.fill, FillState::Solid); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_fill_state(origin, &st.fill)?; + backend.apply_draw_state(origin, &st)?; + let _ = backend.poly_fill_arc(origin, target.host_xid(), st.foreground, arcs); + if needs_fill_reset { + let _ = backend.set_gc_fill_solid(origin); + } + } + let _dropped = accumulate_damage_full_to_state(state, drawable); + } + debug!( + "client {} #{} PolyFillArc drawable=0x{:x}", + client_id.0, + sequence.0, + x11::drawable_request_id(body).map_or(0, |d| d.0), + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_clear_area( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + let exposures = header.data != 0; + if let Some(request) = x11::clear_area_request(body) { + // Validation per Xorg ProcClearToBackground: exposures must + // be a BOOL (0/1) → BadValue; the drawable must be a window + // → BadWindow; InputOnly windows can't be cleared → BadMatch. + if header.data > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 61, + ); + } + let Some(window) = state.resources.window(request.window) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + request.window.0, + 61, + ); + }; + if matches!(window.class, crate::resources::WindowClass::InputOnly) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + request.window.0, + 61, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::WRITE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 61); + } + let (w_width, w_height) = (window.width, window.height); + let region = clear_area_region(state, request, w_width, w_height); + paint_window_background(state, backend, origin, request.window, ®ion)?; + if exposures { + send_window_exposures(state, backend, origin, request.window, ®ion, false); + } + } + debug!( + "client {} #{} ClearArea drawable=0x{:x}", + client_id.0, + sequence.0, + x11::clear_area_request(body).map_or(0, |r| r.window.0), + ); + Ok(RequestOutcome::Handled) +} + +/// Drawable size in its own coordinate space (windows: interior +/// w×h; pixmaps: w×h). None for unknown resources. +fn drawable_size(state: &ServerState, id: ResourceId) -> Option<(u16, u16)> { + if let Some(w) = state.resources.window(id) { + return Some((w.width, w.height)); + } + state.resources.pixmap(id).map(|p| (p.width, p.height)) +} + +/// Source-availability split for CopyArea/CopyPlane (X11 §CopyArea; +/// Xorg miHandleExposures): the part of the requested source rect +/// outside the source drawable's bounds is not copied. Returns the +/// available source sub-rect (None when fully outside) and the +/// missing sub-rects translated to DESTINATION coordinates — each +/// becomes one GraphicsExpose; an empty list means NoExposure. +#[allow(clippy::type_complexity)] +pub(super) fn copy_area_source_split( + state: &ServerState, + src: ResourceId, + src_x: i16, + src_y: i16, + dst_x: i16, + dst_y: i16, + width: u16, + height: u16, +) -> ( + Option<(i16, i16, i16, i16, u16, u16)>, + Vec<(i16, i16, u16, u16)>, +) { + if window_unviewable(state, src) { + // Xorg: an unrealized window's clipList is empty, so nothing copies (micopy.c:282). + return (None, vec![(dst_x, dst_y, width, height)]); + } + let Some((sw, sh)) = drawable_size(state, src) else { + // Unknown source geometry: keep the old conservative + // behavior (copy as requested, no missing region). + return ( + Some((src_x, src_y, dst_x, dst_y, width, height)), + Vec::new(), + ); + }; + let rx0 = i32::from(src_x); + let ry0 = i32::from(src_y); + let rx1 = rx0 + i32::from(width); + let ry1 = ry0 + i32::from(height); + let ax0 = rx0.max(0); + let ay0 = ry0.max(0); + let ax1 = rx1.min(i32::from(sw)); + let ay1 = ry1.min(i32::from(sh)); + // Translate a source-coordinate sub-rect into dst coordinates. + let to_dst = |x0: i32, y0: i32, x1: i32, y1: i32| -> (i16, i16, u16, u16) { + let dx = i32::from(dst_x) + (x0 - rx0); + let dy = i32::from(dst_y) + (y0 - ry0); + ( + i16::try_from(dx).unwrap_or(i16::MAX), + i16::try_from(dy).unwrap_or(i16::MAX), + u16::try_from(x1 - x0).unwrap_or(0), + u16::try_from(y1 - y0).unwrap_or(0), + ) + }; + if ax1 <= ax0 || ay1 <= ay0 { + // Fully outside: nothing copies, the whole rect is exposed. + return (None, vec![to_dst(rx0, ry0, rx1, ry1)]); + } + let mut missing: Vec<(i16, i16, u16, u16)> = Vec::new(); + // Band decomposition of requested − available: top, bottom, + // left-of-middle, right-of-middle. + if ay0 > ry0 { + missing.push(to_dst(rx0, ry0, rx1, ay0)); + } + if ay1 < ry1 { + missing.push(to_dst(rx0, ay1, rx1, ry1)); + } + if ax0 > rx0 { + missing.push(to_dst(rx0, ay0, ax0, ay1)); + } + if ax1 < rx1 { + missing.push(to_dst(ax1, ay0, rx1, ay1)); + } + let avail = ( + i16::try_from(ax0).unwrap_or(0), + i16::try_from(ay0).unwrap_or(0), + i16::try_from(i32::from(dst_x) + (ax0 - rx0)).unwrap_or(i16::MAX), + i16::try_from(i32::from(dst_y) + (ay0 - ry0)).unwrap_or(i16::MAX), + u16::try_from(ax1 - ax0).unwrap_or(0), + u16::try_from(ay1 - ay0).unwrap_or(0), + ); + (Some(avail), missing) +} + +/// The region a CopyArea / CopyPlane exposes on its destination, in its +/// coordinates: Xorg's `miHandleExposures` (`mi/miexpose.c:120-305`), +/// step for step. The part of the source rect outside what the source +/// shows — its clip list under ClipByChildren, `NotClippedByChildren` +/// under IncludeInferiors, its extent for a pixmap — moved over the +/// destination and cut to what of it shows likewise, and to the GC's +/// client clip (which Xorg applies without the clip origin). Past +/// `RECTLIMIT` rects onto a window it is sent as its extents, unless the +/// source's shape does not hold the source rect. `None` when nothing is +/// exposed or there is nothing to do: Xorg's NULL return, NoExpose. +/// The flag says whether the region was reduced to its extents. +#[allow(clippy::too_many_arguments)] +fn copy_exposed_region( + state: &ServerState, + src: ResourceId, + dst: ResourceId, + draw_state: &crate::backend::DrawState, + graphics_exposures: bool, + (src_x, src_y): (i16, i16), + (width, height): (u16, u16), + (dst_x, dst_y): (i16, i16), +) -> Option<(Vec, bool)> { + use crate::core_loop::clip_list; + let dst_is_window = state.resources.window(dst).is_some(); + if !graphics_exposures && !dst_is_window { + return None; + } + let include_inferiors = matches!( + draw_state.subwindow_mode, + crate::backend::SubwindowMode::IncludeInferiors + ); + let src_box = x11::xfixes::RegionRect { + x: src_x, + y: src_y, + width, + height, + }; + let window_clip = |w: ResourceId| { + if include_inferiors { + clip_list::not_clipped_by_children(state, w) + } else { + clip_list::clip_list(state, w) + } + }; + let src_clip = if state.resources.window(src).is_some() { + let clip = window_clip(src); + if clip_list::contains(&clip, src_box) { + return None; + } + clip + } else { + let (w, h) = drawable_size(state, src)?; + let whole = x11::xfixes::RegionRect { + x: 0, + y: 0, + width: w, + height: h, + }; + if clip_list::contains(&[whole], src_box) { + return None; + } + vec![whole] + }; + let dst_clip = if dst == src { + src_clip.clone() + } else if dst_is_window { + window_clip(dst) + } else { + let (w, h) = drawable_size(state, dst)?; + vec![x11::xfixes::RegionRect { + x: 0, + y: 0, + width: w, + height: h, + }] + }; + let hidden = clip_list::subtract(&[src_box], &src_clip); + let moved = clip_list::translate( + hidden, + i32::from(dst_x) - i32::from(src_x), + i32::from(dst_y) - i32::from(src_y), + ); + let mut exposed = clip_list::intersect(&moved, &dst_clip); + if let crate::backend::ClipState::Rectangles { rects, .. } = &draw_state.clip { + let client: Vec = rects + .rectangles + .chunks_exact(8) + .map(|c| x11::xfixes::RegionRect { + x: i16::from_le_bytes([c[0], c[1]]), + y: i16::from_le_bytes([c[2], c[3]]), + width: u16::from_le_bytes([c[4], c[5]]), + height: u16::from_le_bytes([c[6], c[7]]), + }) + .collect(); + exposed = clip_list::intersect(&exposed, &client); + } + let mut extents = graphics_exposures && exposed.len() > clip_list::RECTLIMIT && dst_is_window; + if extents + && let Some(shape) = state + .shape_windows + .get(&src) + .and_then(|s| s.clip().or(s.bounding())) + && !clip_list::contains(&shape, src_box) + { + extents = false; + } + if exposed.is_empty() { + return None; + } + if extents { + exposed = vec![crate::nested::region_extents(&exposed)]; + } + Some((exposed, extents)) +} + +/// [`copy_exposed_region`]'s side effects: the destination window's +/// background over the region unless it is None (`miHandleExposures` +/// paints it, cut to the clip list when reduced to extents), and the +/// GraphicsExpose events, or one NoExpose, when the GC asks for them. +#[allow(clippy::too_many_arguments)] +fn finish_copy_exposures( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + dst: ResourceId, + dst_host: u32, + exposed: Option<(Vec, bool)>, + graphics_exposures: bool, + major_opcode: u8, +) -> io::Result<()> { + let rects = exposed.as_ref().map_or(&[][..], |(r, _)| r.as_slice()); + if let Some(window) = state.resources.window(dst) + && !window.background_none + && !rects.is_empty() + && !background_paint_inhibited(state, dst) + { + let paint = match &exposed { + Some((r, true)) => crate::core_loop::clip_list::intersect( + r, + &crate::core_loop::clip_list::clip_list(state, dst), + ), + _ => rects.to_vec(), + }; + for r in &paint { + backend.paint_window_background_rect(origin, dst_host, r.x, r.y, r.width, r.height)?; + } + let _dropped = + crate::core_loop::damage_fanout::accumulate_damage_region_to_state(state, dst, &paint); + } + if graphics_exposures { + let events: Vec<(i16, i16, u16, u16)> = rects + .iter() + .map(|r| (r.x, r.y, r.width, r.height)) + .collect(); + emit_copy_exposures(state, client_id, dst, &events, major_opcode); + } + Ok(()) +} + +/// Emit the CopyArea/CopyPlane graphics-exposures contract events to +/// the requesting client: one GraphicsExpose per missing dst-coord +/// sub-rect (count = number still to follow), or one NoExposure when +/// the source was fully available. Only called when the GC has +/// graphics-exposures=True; the events go to the REQUESTOR +/// unconditionally (not gated by any event mask). +fn emit_copy_exposures( + state: &mut ServerState, + client_id: ClientId, + dst: ResourceId, + missing: &[(i16, i16, u16, u16)], + major_opcode: u8, +) { + let Some(client) = state.clients.get_mut(&client_id.0) else { + return; + }; + let seq = SequenceNumber( + client + .last_sequence + .load(std::sync::atomic::Ordering::Relaxed), + ); + if missing.is_empty() { + let mut buf = Vec::with_capacity(32); + x11::encode_no_exposure_event(&mut buf, seq, client.byte_order, dst, 0, major_opcode); + let _ = write_to_client(client, client_id, &buf); + return; + } + let total = missing.len(); + for (i, (x, y, w, h)) in missing.iter().enumerate() { + let mut buf = Vec::with_capacity(32); + x11::encode_graphics_expose_event( + &mut buf, + seq, + client.byte_order, + dst, + u16::try_from(*x).unwrap_or(0), + u16::try_from(*y).unwrap_or(0), + *w, + *h, + 0, + u16::try_from(total - 1 - i).unwrap_or(0), + major_opcode, + ); + let _ = write_to_client(client, client_id, &buf); + } +} + +pub(super) fn handle_copy_area( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(request) = x11::copy_area_request(body) else { + return Ok(RequestOutcome::Handled); + }; + if request.width == 0 || request.height == 0 { + return Ok(RequestOutcome::Handled); + } + debug!( + "client {} #{} CopyArea src=0x{:x} dst=0x{:x} gc=0x{:x} src=({},{}) dst=({},{}) {}x{}", + client_id.0, + sequence.0, + request.src.0, + request.dst.0, + request.gc.0, + request.src_x, + request.src_y, + request.dst_x, + request.dst_y, + request.width, + request.height + ); + // Preserve the existing structural error order (src, GC/depth, then + // dst), while policy asks follow this request's target order: src, + // dst, GC. The first pass validates the GC but defers its access check. + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + request.src, + request.gc, + Some(AccessMode::READ), + None, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 62); + } + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + request.dst, + request.gc, + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 62); + } + let draw_state = state.resources.resolve_draw_state(request.gc); + let src = state.resources.host_drawable_target(request.src); + let dst = state.resources.host_drawable_target(request.dst); + if let (Some(src), Some(dst)) = (src.as_ref(), dst.as_ref()) { + let src_host = src.host_xid(); + let dst_host = dst.host_xid(); + if src.depth() != dst.depth() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + request.dst.0, + 62, + ); + } + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + // Clamp the copy to the AVAILABLE part of the source drawable + // (X11 §CopyArea): out-of-bounds source regions are never + // copied; they become the GraphicsExpose region below. + let (avail, exposed) = if window_unviewable(state, request.dst) { + // Xorg miDoCopy returns before copying or exposing: NoExpose (micopy.c:157). + (None, None) + } else { + let graphics_exposures = state + .resources + .gc(request.gc) + .is_some_and(|g| g.graphics_exposures); + ( + copy_area_source_split( + state, + request.src, + request.src_x, + request.src_y, + request.dst_x, + request.dst_y, + request.width, + request.height, + ) + .0, + copy_exposed_region( + state, + request.src, + request.dst, + &st, + graphics_exposures, + (request.src_x, request.src_y), + (request.width, request.height), + (request.dst_x, request.dst_y), + ), + ) + }; + let request = match avail { + Some((sx, sy, dx, dy, w, h)) => x11::CopyAreaRequest { + src_x: sx, + src_y: sy, + dst_x: dx, + dst_y: dy, + width: w, + height: h, + ..request + }, + None => x11::CopyAreaRequest { + width: 0, + height: 0, + ..request + }, + }; + // Stage 4d Manual-redirect fix (codex 2026-05-18): when the + // destination is a window, the X11 spec requires copy_area to + // honour (a) the GC's clip-mask if rectangular and (b) the + // `subwindow-mode=ClipByChildren` default by subtracting every + // mapped child window's geometry from the destination rect. + // + // Split in window-local coordinates before the backend translates + // each piece to backing space. + // ClipState::Pixmap (mask-pixmap clip) is out of scope for this + // fix and passes through untouched. + let copy_sub_rects = if request.width == 0 || request.height == 0 { + Vec::new() + } else { + copy_area_effective_dst_rects(state, request.dst, &st, &request) + }; + if copy_sub_rects.is_empty() { + debug!( + "client {} #{} CopyArea fully clipped, no backend call", + client_id.0, sequence.0, + ); + } + for sub in ©_sub_rects { + // src coords shift by the same delta the dst sub-rect + // shifted from the original dst_xy. + let sub_src_x = request + .src_x + .saturating_add(sub.x.saturating_sub(request.dst_x)); + let sub_src_y = request + .src_y + .saturating_add(sub.y.saturating_sub(request.dst_y)); + backend.copy_area( + origin, src_host, dst_host, sub_src_x, sub_src_y, sub.x, sub.y, sub.width, + sub.height, + )?; + } + let dst_id = request.dst; + // Damage per actually-copied sub-rect rather than the original + // full rect — avoids over-damaging the children's areas a + // ClipByChildren split just excluded. Skipped naturally when + // the slice is empty (fully-clipped copy). + for sub in ©_sub_rects { + let _dropped = + accumulate_damage_to_state(state, dst_id, sub.x, sub.y, sub.width, sub.height); + } + // Graphics-exposures contract (still fires when the copy was + // fully clipped — codex 2026-05-18 follow-up): the exposed + // destination gets its background, and GraphicsExpose per rect + // or one NoExposure go to the requestor unconditionally (not + // mask-gated). + let graphics_exposures = state + .resources + .gc(request.gc) + .is_some_and(|g| g.graphics_exposures); + finish_copy_exposures( + state, + backend, + origin, + client_id, + request.dst, + dst_host, + exposed, + graphics_exposures, + 62, + )?; + } + Ok(RequestOutcome::Handled) +} + +/// Compute the surviving destination sub-rectangles for an X11 +/// CopyArea request after applying: +/// +/// 1. GC rectangular clip-mask (`ClipState::Rectangles`). Empty or +/// completely-disjoint clip → empty Vec (spec-correct no-op). +/// `ClipState::Pixmap` is currently NOT honoured here (out of +/// scope for the Stage 4d fix — see the inline TODO below). +/// 2. `subwindow-mode == ClipByChildren` (X11 default): subtract +/// every mapped child window's geometry from the destination +/// rectangle. v2 collapses a redirected subtree into a single +/// backing pixmap, so this is the layer that prevents marco's +/// decoration copies into a frame window from clobbering the +/// reparented client child area. +/// +/// Pixmap destinations skip clipping entirely (no children to +/// subtract; rectangular clip already applies via the same path). +/// +/// Returns rectangles in the **destination window's** coordinate +/// space (matching the wire `dst_x` / `dst_y` units). +pub(super) fn copy_area_effective_dst_rects( + state: &crate::server::ServerState, + dst_id: ResourceId, + draw_state: &crate::backend::DrawState, + req: &yserver_protocol::x11::CopyAreaRequest, +) -> Vec { + let mut current: Vec = vec![CopyAreaSubRect { + x: req.dst_x, + y: req.dst_y, + width: req.width, + height: req.height, + }]; + let mut gc_clip_rects: Vec = Vec::new(); + // Step 1: GC rectangular clip-mask. `ClipState::None` is + // "no clip" (pass through); `ClipState::Pixmap` is the + // depth-1 mask form — TODO: rasterise to rect-band; for now + // pass through (mirrors v1's `intersect_with_current_clip` + // pixmap-clip skip). + if let crate::backend::ClipState::Rectangles { origin, rects } = &draw_state.clip { + gc_clip_rects = Vec::with_capacity(rects.rectangles.len() / 8); + for chunk in rects.rectangles.chunks_exact(8) { + let cx = i16::from_le_bytes([chunk[0], chunk[1]]).saturating_add(origin.0); + let cy = i16::from_le_bytes([chunk[2], chunk[3]]).saturating_add(origin.1); + let cw = u16::from_le_bytes([chunk[4], chunk[5]]); + let ch = u16::from_le_bytes([chunk[6], chunk[7]]); + if cw > 0 && ch > 0 { + gc_clip_rects.push(CopyAreaSubRect { + x: cx, + y: cy, + width: cw, + height: ch, + }); + } + } + current = current + .into_iter() + .flat_map(|r| { + gc_clip_rects + .iter() + .filter_map(move |c| intersect_sub_rects(r, *c)) + }) + .collect(); + if current.is_empty() { + log::debug!( + target: "yserver_core::core_loop", + "copy_area clip empty after GC clip dst=0x{:x} req=({},{}) {}x{} subwindow_mode={:?} gc_clip_rects={:?}", + dst_id.0, + req.dst_x, + req.dst_y, + req.width, + req.height, + draw_state.subwindow_mode, + gc_clip_rects, + ); + return current; + } + } + // Step 2: ClipByChildren. Only meaningful when: + // - dst is a window (pixmaps have no children), + // - subwindow-mode is ClipByChildren (default), + // - the window has mapped children. + let Some(dst_window) = state.resources.window(dst_id) else { + return current; + }; + if !matches!( + draw_state.subwindow_mode, + crate::backend::SubwindowMode::ClipByChildren + ) { + return current; + } + let child_rects: Vec = dst_window + .children + .iter() + .filter_map(|cid| { + let c = state.resources.window(*cid)?; + // Manually-redirected children don't claim the parent's + // pixmap real estate — the redirecting compositor (which + // may BE the parent's own client; see + // notification-area-applet for a live example) puts the + // children's pixels there itself. Subtracting them + // strips the compositor's own composite-target rect to + // empty, blocking the icons from reaching the parent's + // backing. Automatic-redirected children are still + // subtracted: under Automatic mode the X server + // auto-composites them into the parent's pixmap, so the + // parent's own paint must avoid those rects to stay + // out of the auto-composite's way. + let is_manual = matches!( + effective_redirect_mode_for_window(state, *cid), + Some(crate::server::CompositeRedirectMode::Manual) + ); + (c.class == crate::resources::WindowClass::InputOutput + && c.map_state == crate::resources::MapState::Viewable + && c.width > 0 + && c.height > 0 + && !is_manual) + .then(|| { + let rect = x11::xfixes::RegionRect { + x: c.x, + y: c.y, + width: c.width, + height: c.height, + }; + // A shaped child takes only its bounding shape out + // (Xorg subtracts its `borderSize`): GDK clips a + // native window inside a client-side one with it, and + // the parent's button bar outside it stays drawable. + crate::nested::intersect_regions( + &[rect], + ¤t_bounding_in_parent(state, *cid), + ) + }) + }) + .flatten() + .map(|r| CopyAreaSubRect { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + }) + .collect(); + if child_rects.is_empty() { + return current; + } + for child in &child_rects { + let mut next = Vec::new(); + for r in current { + next.extend(subtract_sub_rect(r, *child)); + } + current = next; + if current.is_empty() { + let redirect_mode = effective_redirect_mode_for_window(state, dst_id); + log::debug!( + target: "yserver_core::core_loop", + "copy_area clip empty after ClipByChildren dst=0x{:x} req=({},{}) {}x{} subwindow_mode={:?} \ + redirect_mode={:?} gc_clip_rects={:?} child_rects={:?}", + dst_id.0, + req.dst_x, + req.dst_y, + req.width, + req.height, + draw_state.subwindow_mode, + redirect_mode, + gc_clip_rects, + child_rects, + ); + return current; + } + } + current +} + +/// Rect ∩ rect. Returns `None` for disjoint or zero-area input. +fn intersect_sub_rects(a: CopyAreaSubRect, b: CopyAreaSubRect) -> Option { + let ax0 = i32::from(a.x); + let ay0 = i32::from(a.y); + let ax1 = ax0 + i32::from(a.width); + let ay1 = ay0 + i32::from(a.height); + let bx0 = i32::from(b.x); + let by0 = i32::from(b.y); + let bx1 = bx0 + i32::from(b.width); + let by1 = by0 + i32::from(b.height); + let ix0 = ax0.max(bx0); + let iy0 = ay0.max(by0); + let ix1 = ax1.min(bx1); + let iy1 = ay1.min(by1); + if ix0 >= ix1 || iy0 >= iy1 { + return None; + } + Some(CopyAreaSubRect { + x: i16::try_from(ix0).ok()?, + y: i16::try_from(iy0).ok()?, + width: u16::try_from(ix1 - ix0).ok()?, + height: u16::try_from(iy1 - iy0).ok()?, + }) +} + +/// `outer \ inner` → up to 4 disjoint sub-rectangles (top strip, +/// bottom strip, left middle, right middle). If `inner` doesn't +/// intersect `outer`, returns `[outer]` unchanged. +fn subtract_sub_rect(outer: CopyAreaSubRect, inner: CopyAreaSubRect) -> Vec { + let ox0 = i32::from(outer.x); + let oy0 = i32::from(outer.y); + let ox1 = ox0 + i32::from(outer.width); + let oy1 = oy0 + i32::from(outer.height); + let ix0 = i32::from(inner.x).max(ox0); + let iy0 = i32::from(inner.y).max(oy0); + let ix1 = (i32::from(inner.x) + i32::from(inner.width)).min(ox1); + let iy1 = (i32::from(inner.y) + i32::from(inner.height)).min(oy1); + if ix0 >= ix1 || iy0 >= iy1 { + return vec![outer]; + } + let mk = |x: i32, y: i32, w: i32, h: i32| -> Option { + Some(CopyAreaSubRect { + x: i16::try_from(x).ok()?, + y: i16::try_from(y).ok()?, + width: u16::try_from(w).ok()?, + height: u16::try_from(h).ok()?, + }) + }; + let mut out = Vec::with_capacity(4); + // Top strip + if oy0 < iy0 + && let Some(r) = mk(ox0, oy0, ox1 - ox0, iy0 - oy0) + { + out.push(r); + } + // Bottom strip + if iy1 < oy1 + && let Some(r) = mk(ox0, iy1, ox1 - ox0, oy1 - iy1) + { + out.push(r); + } + // Left middle + if ox0 < ix0 + && let Some(r) = mk(ox0, iy0, ix0 - ox0, iy1 - iy0) + { + out.push(r); + } + // Right middle + if ix1 < ox1 + && let Some(r) = mk(ix1, iy0, ox1 - ix1, iy1 - iy0) + { + out.push(r); + } + out +} + +pub(super) fn handle_copy_plane( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 28 { + return Ok(RequestOutcome::Handled); + } + let src = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let dst = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let gc = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let sx = i16::from_le_bytes([body[12], body[13]]); + let sy = i16::from_le_bytes([body[14], body[15]]); + let dx = i16::from_le_bytes([body[16], body[17]]); + let dy = i16::from_le_bytes([body[18], body[19]]); + let w = u16::from_le_bytes([body[20], body[21]]); + let h = u16::from_le_bytes([body[22], body[23]]); + let plane = u32::from_le_bytes([body[24], body[25], body[26], body[27]]); + if w == 0 || h == 0 { + return Ok(RequestOutcome::Handled); + } + // CopyPlane: dst.depth must match gc.depth; src can be any depth + // (the plane mask extracts a single bit from src). + if let Err((code, bad_value)) = + validate_drawable_only(state, client_id, access_request, src, AccessMode::READ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 63); + } + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + access_request, + dst, + gc, + Some(AccessMode::WRITE), + Some(AccessMode::USE), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 63); + } + let draw_state = state.resources.resolve_draw_state(gc); + let src_target = state.resources.host_drawable_target(src); + let dst_target = state.resources.host_drawable_target(dst); + if let (Some(srct), Some(dstt)) = (src_target, dst_target) { + let st = draw_state.unwrap_or_default(); + backend.apply_clip_state(origin, &st.clip)?; + backend.apply_draw_state(origin, &st)?; + // Clamp to the available source region (same contract as + // CopyArea — out-of-bounds source becomes GraphicsExpose). + let graphics_exposures = state.resources.gc(gc).is_some_and(|g| g.graphics_exposures); + let (avail, exposed) = if window_unviewable(state, dst) { + // Xorg miDoCopy returns before copying or exposing: NoExpose (micopy.c:157). + (None, None) + } else { + ( + copy_area_source_split(state, src, sx, sy, dx, dy, w, h).0, + copy_exposed_region( + state, + src, + dst, + &st, + graphics_exposures, + (sx, sy), + (w, h), + (dx, dy), + ), + ) + }; + if let Some((asx, asy, adx, ady, aw, ah)) = avail { + backend.copy_plane( + origin, + srct.host_xid(), + dstt.host_xid(), + asx, + asy, + adx, + ady, + aw, + ah, + plane, + )?; + let _dropped = accumulate_damage_to_state(state, dst, adx, ady, aw, ah); + } + // The same exposure contract as CopyArea (`miCopyPlane` hands its + // region to `miHandleExposures` too). + finish_copy_exposures( + state, + backend, + origin, + client_id, + dst, + dstt.host_xid(), + exposed, + graphics_exposures, + 63, + )?; + } + debug!( + "client {} #{} CopyPlane src=0x{:x} dst=0x{:x} src=({},{}) dst=({},{}) {}x{} plane=0x{:x}", + client_id.0, sequence.0, src.0, dst.0, sx, sy, dx, dy, w, h, plane, + ); + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/dri3.rs b/crates/yserver-core/src/core_loop/process_request/dri3.rs new file mode 100644 index 000000000..cfea4155c --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/dri3.rs @@ -0,0 +1,848 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{ + RequestOutcome, emit_x11_error_with_minor, send_reply_with_fd, write_to_client, + xid_out_of_client_range, + }, + fd::OwnedFd, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +pub(super) fn handle_dri3_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + attached_fd: Option, +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, dri3 as x11dri3}; + const DRI3_MAJOR_OPCODE: u8 = 147; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let caps = backend.dri3_capabilities(); + let minor = header.data; + match minor { + x11dri3::QUERY_VERSION => { + let (cmaj, cmin) = x11dri3::parse_query_version(body).unwrap_or((0, 0)); + // Server caps the version per Dri3Caps::version. Without + // syncobj support, version is (1, 3); fence_fd governs + // individual request availability rather than the version + // reply. + let server_major = caps.version.0; + let server_minor = caps.version.1; + let major = cmaj.min(server_major); + let minor = cmin.min(server_minor); + debug!( + "client {} #{} DRI3::QueryVersion client={cmaj}.{cmin} -> {major}.{minor}", + client_id.0, sequence.0 + ); + let reply = x11dri3::encode_query_version_reply(byte_order, sequence, major, minor); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11dri3::OPEN => { + let req = x11dri3::parse_open(body); + let drawable = req.map_or(0, |r| r.drawable); + match backend.dri3_open(drawable) { + Ok(fd) => { + debug!( + "client {} #{} DRI3::Open drawable=0x{drawable:x} -> fd={}", + client_id.0, + sequence.0, + crate::fd::AsRawFd::as_raw_fd(&fd) + ); + let reply = x11dri3::encode_open_reply(byte_order, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let raw = crate::fd::AsRawFd::as_raw_fd(&fd); + if let Err(e) = send_reply_with_fd(client, &reply, raw) { + log::warn!("DRI3::Open SCM_RIGHTS dispatch failed: {e}"); + return Ok(RequestOutcome::Disconnect(client_id)); + } + drop(fd); + return Ok(RequestOutcome::Handled); + } + Err(err) => { + debug!( + "client {} #{} DRI3::Open drawable=0x{drawable:x} -> BadAlloc ({err})", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + } + } + x11dri3::PIXMAP_FROM_BUFFER => { + let Some(req) = x11dri3::parse_pixmap_from_buffer(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + let Some(fd) = attached_fd else { + debug!( + "client {} #{} DRI3::PixmapFromBuffer no SCM_RIGHTS fd attached -> BadAlloc", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.pixmap, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + match backend.dri3_import_pixmap( + fd, + req.width, + req.height, + u32::from(req.stride), + 0, + // DRI3 1.0 carries no modifier. That means the layout is + // IMPLICIT, to be resolved from the buffer -- not linear. + // This line used to pass `0`, i.e. an explicit + // DRM_FORMAT_MOD_LINEAR, which is #138: Chrome hands us a + // TILED VA-API decode buffer here, we recorded it as + // linear, and `BuffersFromPixmap` then handed that lie + // back so Chrome sampled its own frame wrong. + crate::backend::Dri3ImportModifier::Implicit { size: req.size }, + req.depth, + req.bpp, + ) { + Ok(handle) => { + debug!( + "client {} #{} DRI3::PixmapFromBuffer pixmap=0x{:x} {}x{} stride={} depth={} bpp={} -> imported", + client_id.0, + sequence.0, + req.pixmap, + req.width, + req.height, + req.stride, + req.depth, + req.bpp, + ); + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(req.pixmap), + drawable: ResourceId(req.drawable), + width: req.width, + height: req.height, + depth: req.depth, + }, + ); + let _ = state + .resources + .set_pixmap_host_xid(ResourceId(req.pixmap), handle); + } + Err(err) => { + debug!( + "client {} #{} DRI3::PixmapFromBuffer pixmap=0x{:x} {}x{} stride={} depth={} bpp={} -> BadAlloc ({err})", + client_id.0, + sequence.0, + req.pixmap, + req.width, + req.height, + req.stride, + req.depth, + req.bpp, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.pixmap, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + } + } + x11dri3::PIXMAP_FROM_BUFFERS => { + let Some(req) = x11dri3::parse_pixmap_from_buffers(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + // Phase 4.2 scope: single-plane RGB only. num_buffers > 1 + // is wire-decoded (so logging is accurate) but rejected. + if req.num_buffers != 1 { + debug!( + "client {} #{} DRI3::PixmapFromBuffers num_buffers={} -> BadAlloc \ + (multi-plane out of scope for Phase 4.2)", + client_id.0, sequence.0, req.num_buffers + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.pixmap, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let Some(fd) = attached_fd else { + debug!( + "client {} #{} DRI3::PixmapFromBuffers no SCM_RIGHTS fd attached -> BadAlloc", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.pixmap, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + match backend.dri3_import_pixmap( + fd, + req.width, + req.height, + req.strides[0], + req.offsets[0], + crate::backend::Dri3ImportModifier::Explicit(req.modifier), + req.depth, + req.bpp, + ) { + Ok(handle) => { + debug!( + "client {} #{} DRI3::PixmapFromBuffers pixmap=0x{:x} {}x{} stride={} offset={} modifier=0x{:x} depth={} bpp={} -> imported", + client_id.0, + sequence.0, + req.pixmap, + req.width, + req.height, + req.strides[0], + req.offsets[0], + req.modifier, + req.depth, + req.bpp, + ); + // Register the X resource id so subsequent + // CopyArea / PresentPixmap can resolve it. Mirror + // what handle_create_pixmap does. + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(req.pixmap), + drawable: ResourceId(req.window), + width: req.width, + height: req.height, + depth: req.depth, + }, + ); + let _ = state + .resources + .set_pixmap_host_xid(ResourceId(req.pixmap), handle); + } + Err(err) => { + debug!( + "client {} #{} DRI3::PixmapFromBuffers pixmap=0x{:x} {}x{} stride={} offset={} modifier=0x{:x} depth={} bpp={} -> BadAlloc ({err})", + client_id.0, + sequence.0, + req.pixmap, + req.width, + req.height, + req.strides[0], + req.offsets[0], + req.modifier, + req.depth, + req.bpp, + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.pixmap, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + } + } + x11dri3::BUFFER_FROM_PIXMAP | x11dri3::BUFFERS_FROM_PIXMAP => { + // op 3 is the single-fd, no-modifier subset of op 8. mesa's + // loader_dri3 uses op 8 whenever the server advertises DRI3 >= 1.2, + // and a modifier-tiled backing is unusable without the modifier op + // 8 carries. yserver exports a single plane, so op 8 has nfd=1. + let op = if minor == x11dri3::BUFFER_FROM_PIXMAP { + Dri3ExportOp::BufferFromPixmap + } else { + Dri3ExportOp::BuffersFromPixmap + }; + let parsed = match op { + Dri3ExportOp::BufferFromPixmap => x11dri3::parse_buffer_from_pixmap(body), + Dri3ExportOp::BuffersFromPixmap => x11dri3::parse_buffers_from_pixmap(body), + }; + let Some(pixmap) = parsed else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + let host_xid = match state + .resources + .pixmap(yserver_protocol::x11::ResourceId(pixmap)) + .and_then(|p| p.host_xid.map(|h| h.as_raw())) + { + Some(h) => h, + None => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + pixmap, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + }; + let continuation = PendingDri3Export { + token: crate::backend::Dri3ExportToken(0), + op, + pixmap, + }; + return match backend.dri3_begin_export_pixmap_buffers(host_xid) { + Ok(crate::backend::Dri3ExportBegin::Ready(export)) => { + complete_dri3_export(state, client_id, sequence, continuation, Ok(export)) + } + Ok(crate::backend::Dri3ExportBegin::Pending(token)) => { + debug!( + "client {} #{} DRI3::{op:?} pixmap=0x{pixmap:x}: deferred while scanned out", + client_id.0, sequence.0 + ); + Ok(RequestOutcome::PendingDri3Export(PendingDri3Export { + token, + ..continuation + })) + } + Err(err) => { + complete_dri3_export(state, client_id, sequence, continuation, Err(err)) + } + }; + } + x11dri3::GET_SUPPORTED_MODIFIERS => { + let req = match x11dri3::parse_get_supported_modifiers(body) { + Some(r) => r, + None => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + }; + let (window_mods, screen_mods) = + backend.dri3_supported_modifiers(req.window, req.depth, req.bpp); + debug!( + "client {} #{} DRI3::GetSupportedModifiers w=0x{:x} d={} bpp={} -> window={:?} screen={:?}", + client_id.0, + sequence.0, + req.window, + req.depth, + req.bpp, + window_mods + .iter() + .map(|m| format!("0x{m:x}")) + .collect::>(), + screen_mods + .iter() + .map(|m| format!("0x{m:x}")) + .collect::>(), + ); + let reply = x11dri3::encode_get_supported_modifiers_reply( + byte_order, + sequence, + &window_mods, + &screen_mods, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + // Not gated on `caps.fence_fd`, which is the renderer's SYNC_FD + // semaphores (FDFromFence's export needs them): what a client + // sends here is Mesa's xshmfence, shared memory the backend maps + // without Vulkan, and Xorg takes it on every screen + // (`miSyncShmFenceFromFD`). Refused, every Vulkan swapchain on + // such a renderer (lavapipe) waited on its buffers for ever. + // + // The checks are Xorg's `proc_dri3_fence_from_fd`, in its order: + // the length, a new fence ID in the client's range + // (`LEGAL_NEW_RESOURCE`), the drawable, then the fd. A fd the + // backend can't take is BadValue and makes no fence, as + // `miSyncShmCreateFenceFromFd` when `xshmfence_map_shm` fails. + x11dri3::FENCE_FROM_FD => { + let Some(req) = x11dri3::parse_fence_from_fd(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + if xid_out_of_client_range(state, client_id, req.fence) || state.xid_occupied(req.fence) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + req.fence, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let drawable_exists = state.resources.window(ResourceId(req.drawable)).is_some() + || state.resources.pixmap(ResourceId(req.drawable)).is_some(); + if !drawable_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let Some(fd) = attached_fd else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.fence, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + if let Err(e) = backend.dri3_fence_from_fd(req.fence, fd) { + debug!( + "client {} #{} DRI3::FenceFromFD 0x{:x} -> BadValue ({e})", + client_id.0, sequence.0, req.fence + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.fence, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + debug!( + "client {} #{} DRI3::FenceFromFD 0x{:x} initially_triggered={}", + client_id.0, sequence.0, req.fence, req.initially_triggered + ); + state.sync_fences.insert( + req.fence, + crate::server::SyncFence { + owner: client_id, + triggered: req.initially_triggered, + }, + ); + } + x11dri3::FD_FROM_FENCE => { + if !caps.fence_fd { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_IMPLEMENTATION, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let Some(req) = x11dri3::parse_fd_from_fence(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + match backend.dri3_fd_from_fence(req.fence) { + Ok(fd) => { + let reply = x11dri3::encode_fd_from_fence_reply(byte_order, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let raw = crate::fd::AsRawFd::as_raw_fd(&fd); + if let Err(e) = send_reply_with_fd(client, &reply, raw) { + log::warn!("DRI3::FDFromFence SCM_RIGHTS dispatch failed: {e}"); + return Ok(RequestOutcome::Disconnect(client_id)); + } + drop(fd); + return Ok(RequestOutcome::Handled); + } + Err(e) => { + debug!( + "client {} #{} DRI3::FDFromFence 0x{:x} -> BadAlloc ({e})", + client_id.0, sequence.0, req.fence + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.fence, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + } + } + x11dri3::IMPORT_SYNCOBJ => { + if !caps.syncobj { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_IMPLEMENTATION, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let Some(req) = x11dri3::parse_import_syncobj(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + if xid_out_of_client_range(state, client_id, req.syncobj) + || state.xid_occupied(req.syncobj) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + req.syncobj, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let drawable_exists = state.resources.window(ResourceId(req.drawable)).is_some() + || state.resources.pixmap(ResourceId(req.drawable)).is_some(); + if !drawable_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let Some(fd) = attached_fd else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.syncobj, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + if let Err(e) = backend.dri3_import_syncobj(client_id, req.syncobj, fd) { + debug!( + "client {} #{} DRI3::ImportSyncobj 0x{:x} -> BadAlloc ({e})", + client_id.0, sequence.0, req.syncobj + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.syncobj, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + assert!( + state + .resources + .register_dri3_syncobj(ResourceId(req.syncobj), client_id), + "validated DRI3 syncobj XID became occupied before registration" + ); + debug!( + "client {} #{} DRI3::ImportSyncobj 0x{:x} -> imported", + client_id.0, sequence.0, req.syncobj + ); + } + x11dri3::FREE_SYNCOBJ => { + if !caps.syncobj { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_IMPLEMENTATION, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let Some(syncobj) = x11dri3::parse_free_syncobj(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + let Some(owner) = state.resources.dri3_syncobj_owner(ResourceId(syncobj)) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + syncobj, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + }; + if owner != client_id { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + syncobj, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + if let Err(e) = backend.dri3_free_syncobj(client_id, syncobj) { + let code = if e.kind() == std::io::ErrorKind::PermissionDenied { + debug!( + "client {} #{} DRI3::FreeSyncobj 0x{:x} -> BadAccess ({e})", + client_id.0, sequence.0, syncobj + ); + x11::error::BAD_ACCESS + } else { + debug!( + "client {} #{} DRI3::FreeSyncobj 0x{:x} -> BadValue ({e})", + client_id.0, sequence.0, syncobj + ); + x11::error::BAD_VALUE + }; + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + syncobj, + u16::from(header.data), + DRI3_MAJOR_OPCODE, + ); + } + let removed = state.resources.remove_dri3_syncobj(ResourceId(syncobj)); + debug_assert_eq!(removed, Some(client_id)); + // Pairs with the `-> imported` line above. A successful free was + // silent, so an import count could not be matched against a free + // count and "are retired swapchain syncobjs released?" was + // unanswerable from a capture — mpv scrubbing imports 6 per + // swapchain rebuild. + debug!( + "client {} #{} DRI3::FreeSyncobj 0x{:x} -> freed", + client_id.0, sequence.0, syncobj + ); + } + x11dri3::SET_DRM_DEVICE_IN_USE => { + // Acknowledged but ignored — single-GPU only per design §1. + debug!( + "client {} #{} DRI3::SetDRMDeviceInUse (single-GPU; ignored)", + client_id.0, sequence.0 + ); + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + DRI3_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// The DRI3 request a deferred export answers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dri3ExportOp { + /// op 3. + BufferFromPixmap, + /// op 8. + BuffersFromPixmap, +} + +/// Continuation of a DRI3 export the backend deferred. +#[derive(Debug, Clone, Copy)] +pub struct PendingDri3Export { + pub token: crate::backend::Dri3ExportToken, + pub op: Dri3ExportOp, + pub pixmap: u32, +} + +/// Send the reply (with the fd) or the error of one DRI3 export, now or +/// after a deferral. +pub(crate) fn complete_dri3_export( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + continuation: PendingDri3Export, + result: io::Result, +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, dri3 as x11dri3}; + const DRI3_MAJOR_OPCODE: u8 = 147; + let PendingDri3Export { op, pixmap, .. } = continuation; + let minor = match op { + Dri3ExportOp::BufferFromPixmap => x11dri3::BUFFER_FROM_PIXMAP, + Dri3ExportOp::BuffersFromPixmap => x11dri3::BUFFERS_FROM_PIXMAP, + }; + let export = match result { + Ok(export) => export, + Err(err) => { + // Xorg dri3/dri3_request.c:277 maps export failure to BadPixmap. + // BadDrawable is reserved for the unresolvable-XID case. Xorg + // returns BadAlloc when sending the fd fails; yserver disconnects + // instead, as a broken SCM_RIGHTS socket is unrecoverable. + debug!( + "client {} #{} DRI3::{op:?} pixmap=0x{pixmap:x} -> BadPixmap ({err})", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + pixmap, + u16::from(minor), + DRI3_MAJOR_OPCODE, + ); + } + }; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + debug!( + "client {} #{} DRI3::{op:?} pixmap=0x{pixmap:x} size={} {}x{} stride={} offset={} modifier=0x{:x} depth={} bpp={}", + client_id.0, + sequence.0, + export.size, + export.width, + export.height, + export.stride, + export.offset, + export.modifier, + export.depth, + export.bpp, + ); + let reply = match op { + // op 3's stride is CARD16. + Dri3ExportOp::BufferFromPixmap => x11dri3::encode_buffer_from_pixmap_reply( + byte_order, + sequence, + export.size, + export.width, + export.height, + u16::try_from(export.stride).unwrap_or(u16::MAX), + export.depth, + export.bpp, + ), + Dri3ExportOp::BuffersFromPixmap => x11dri3::encode_buffers_from_pixmap_reply( + byte_order, + sequence, + export.width, + export.height, + export.modifier, + export.depth, + export.bpp, + &[export.stride], + &[export.offset], + ), + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let raw = crate::fd::AsRawFd::as_raw_fd(&export.fd); + if let Err(e) = send_reply_with_fd(client, &reply, raw) { + log::warn!("DRI3::{op:?} SCM_RIGHTS dispatch failed: {e}"); + return Ok(RequestOutcome::Disconnect(client_id)); + } + drop(export.fd); + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/focus_pointer.rs b/crates/yserver-core/src/core_loop/process_request/focus_pointer.rs new file mode 100644 index 000000000..19af2acda --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/focus_pointer.rs @@ -0,0 +1,692 @@ +use crate::{ + access::{AccessMode, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext}, + core_loop::{ + fanout::{emit_window_event_to_state, emit_xi2_focus_event_to_state}, + process_request::{ + FOCUS_CHANGE_MASK, RequestOutcome, XI2_MAJOR_OPCODE, emit_x11_error, write_to_client, + xi::{XI1_ERROR_BAD_DEVICE, xi1_error}, + }, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// XIWarpPointer (XI 2.0 minor 41) — Xorg `ProcXIWarpPointer` +/// (Xi/xiwarppointer.c): core WarpPointer for one device, with FP16.16 +/// coordinates. Only a master pointer or a floating slave may be warped; +/// yserver's only candidate is the master pointer (2), whose sprite is the +/// core one, so this runs the core warp path with the XI source-rectangle +/// rule. +pub(super) fn handle_xi_warp_pointer( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // Length is gated to exactly 9 units above, so the body is 32 bytes. + let u32_at = |o: usize| u32::from_le_bytes([body[o], body[o + 1], body[o + 2], body[o + 3]]); + let fp1616_pixels = |o: usize| u32_at(o).cast_signed() / 65536; + let u16_at = |o: usize| u16::from_le_bytes([body[o], body[o + 1]]); + let deviceid = u16_at(28); + if deviceid != crate::xinput::DEVICEID_MASTER_POINTER { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(deviceid), + 41, + ); + } + let req = WarpRequest { + src: ResourceId(u32_at(0)), + dst: ResourceId(u32_at(4)), + src_x: fp1616_pixels(8), + src_y: fp1616_pixels(12), + src_w: u16_at(16), + src_h: u16_at(18), + dst_x: fp1616_pixels(20), + dst_y: fp1616_pixels(24), + }; + if let Some(bad) = warp_pointer_bad_window(state, &req) { + return xi1_error(state, client_id, sequence, x11::error::BAD_WINDOW, bad, 41); + } + if warp_pointer_src_allows(state, &req, WarpSrcRule::XInput2) { + apply_pointer_warp(state, backend, origin, &req); + } + debug!( + "client {} #{} XIWarpPointer dst=0x{:x} ({}, {})", + client_id.0, sequence.0, req.dst.0, req.dst_x, req.dst_y + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_get_input_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetInputFocus", client_id.0, sequence.0); + let focus = state.core_focus; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_get_input_focus_reply( + &mut buf, + byte_order, + sequence, + ResourceId(focus.raw), + focus.revert_to, + )?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_set_input_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if let Some(window) = x11::input_focus_window(body) { + // Validation per Xorg SetInputFocus (dix/events.c): revert_to + // ∈ {None, PointerRoot, Parent} else BadValue; a focus window + // (anything other than None(0)/PointerRoot(1)) must exist + // (BadWindow) and be viewable (BadMatch). + let revert_to = header.data; + if revert_to > 2 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(revert_to), + 42, + ); + } + if let Some((code, value)) = core_focus_window_error(state, window) { + return emit_x11_error(state, client_id, sequence, code, value, 42); + } + if window.0 > 1 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 42); + } + let time = body + .get(4..8) + .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + apply_core_input_focus(state, client_id, sequence, window, revert_to, time); + } + debug!("client {} #{} SetInputFocus", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// The window check of Xorg `SetInputFocus`: a focus other than +/// None(0)/PointerRoot(1) must be an existing window (BadWindow) that is +/// viewable (BadMatch). Returns `(error code, errorValue)`. +pub(crate) fn core_focus_window_error( + state: &ServerState, + window: ResourceId, +) -> Option<(u8, u32)> { + if window.0 <= 1 { + return None; + } + match state.resources.window(window) { + None => Some((x11::error::BAD_WINDOW, window.0)), + Some(w) if w.map_state != crate::resources::MapState::Viewable => { + Some((x11::error::BAD_MATCH, window.0)) + } + Some(_) => None, + } +} + +/// The rest of Xorg `SetInputFocus` for the master keyboard, whose focus +/// is the core focus (core SetInputFocus and XISetFocus on device 3 both +/// land here): the timestamp gate, the FocusOut/FocusIn chain, and the +/// new focus/revert_to/time. `window` has passed +/// [`core_focus_window_error`]. +pub(crate) fn apply_core_input_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + window: ResourceId, + revert_to: u8, + time: u32, +) { + // Xorg SetInputFocus: requests with a time LATER than the + // current time or EARLIER than the last focus time are + // silently ignored. + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.core_focus.time); + if time != 0 + && (crate::core_loop::xi1_focus::time_after(time, now) + || crate::core_loop::xi1_focus::time_after(state.core_focus.time, time)) + { + debug!( + "client {} #{} SetInputFocus ignored (time {time} outside [{}, {now}])", + client_id.0, sequence.0, state.core_focus.time + ); + return; + } + debug!( + "focus decision: client {} SetInputFocus 0x{:x} revert_to={revert_to}", + client_id.0, window.0 + ); + log::trace!( + target: "yserver::input::focus", + "SetInputFocus client={} window={} revert_to={revert_to}", + state.debug_client_label(client_id), + state.debug_window_label(window), + ); + let from_raw = state.core_focus.raw; + let to_raw = window.0; + if from_raw != to_raw { + // Xorg SetInputFocus (dix/events.c:4923): the focus transition + // is reported NotifyWhileGrabbed (3) while a keyboard grab is + // active, else NotifyNormal (0). bspwm focuses a newly-mapped + // window WHILE sxhkd's synchronous passive key grab is still + // active; emitting NotifyNormal there told GLFW/kitty it had + // genuinely taken focus mid-grab, and its focus state machine + // then ignored every typed key (the keys still routed + // correctly to its window — only the FocusIn mode was wrong). + // Mirrors the same gate in `revert_core_focus_from`. + let mode = if state.active_keyboard_grab.is_some() { + 3 // NotifyWhileGrabbed + } else { + 0 // NotifyNormal + }; + emit_core_focus_transition(state, from_raw, to_raw, mode); + } + state.core_focus = crate::server::CoreFocus { + raw: to_raw, + revert_to, + time: if time == 0 { now } else { time }, + }; + // Legacy mirror — the key fanout's `current_focus` and other + // readers still consult the per-client field; None/PointerRoot + // map to ROOT_WINDOW there (the fanout resolves PointerRoot + // through `state.core_focus` directly). + let mirror = match to_raw { + 0 | 1 => ROOT_WINDOW, + w => ResourceId(w), + }; + for c in state.clients.values_mut() { + c.focused_window = mirror; + } +} + +/// Focus revert when the focus window (or an ancestor) becomes +/// unviewable or is destroyed — Xorg `DeleteWindowFromAnyEvents` +/// (dix/events.c:5889-5931), reached from both `UnrealizeTree` +/// (unmap) and window deletion. Reverts per `revert_to`: None → +/// None; PointerRoot → PointerRoot; Parent → nearest viewable +/// ancestor, and `revert_to` collapses to RevertToNone. +pub(super) fn revert_core_focus_from( + state: &mut ServerState, + win: ResourceId, + dying: &[ResourceId], +) { + if state.core_focus.raw != win.0 || win == ROOT_WINDOW { + return; + } + let mode = if state.active_keyboard_grab.is_some() { + 3 // NotifyWhileGrabbed + } else { + 0 // NotifyNormal + }; + let (to_raw, new_revert) = match state.core_focus.revert_to { + 2 => { + // RevertToParent: the nearest surviving viewable ancestor + // (Xorg's `while (!parent->realized)` walk — `dying` + // marks windows in a subtree being destroyed, which are + // still Viewable at this point but won't survive). + let mut parent = state + .resources + .window(win) + .map_or(ROOT_WINDOW, |w| w.parent); + loop { + if parent == ROOT_WINDOW { + break; + } + let Some(w) = state.resources.window(parent) else { + parent = ROOT_WINDOW; + break; + }; + if w.map_state == crate::resources::MapState::Viewable && !dying.contains(&parent) { + break; + } + if w.parent == parent { + break; + } + parent = w.parent; + } + (parent.0, 0) + } + 1 => (1, state.core_focus.revert_to), + _ => (0, state.core_focus.revert_to), + }; + emit_core_focus_transition(state, win.0, to_raw, mode); + state.core_focus.raw = to_raw; + state.core_focus.revert_to = new_revert; + let mirror = match to_raw { + 0 | 1 => ROOT_WINDOW, + w => ResourceId(w), + }; + for c in state.clients.values_mut() { + c.focused_window = mirror; + } +} + +/// Unmap-side focus revert: fire `revert_core_focus_from` when the +/// focus window stopped being viewable (covers an unmapped ancestor — +/// Xorg unrealizes the whole tree and hits the focus check per child). +pub(super) fn revert_core_focus_if_unviewable(state: &mut ServerState) { + let raw = state.core_focus.raw; + if raw <= 1 { + return; + } + let viewable = state + .resources + .window(ResourceId(raw)) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + if !viewable { + revert_core_focus_from(state, ResourceId(raw), &[]); + } +} + +/// Emit the FocusOut/FocusIn chain for a core focus transition +/// (`crate::crossings::focus_transition_events`) through the normal +/// per-window event-mask filter, plus the matching XI2 focus events +/// on the endpoint windows. `mode` is the wire NotifyNormal(0) / +/// NotifyWhileGrabbed(3) / NotifyGrab(1) / NotifyUngrab(2) value. +pub(crate) fn emit_core_focus_transition( + state: &mut ServerState, + from_raw: u32, + to_raw: u32, + mode: u8, +) { + log::trace!( + target: "yserver::input::focus", + "FOCUS-EMIT from={} to={} mode={mode}", + state.debug_window_label(ResourceId(from_raw)), + state.debug_window_label(ResourceId(to_raw)), + ); + let pointer_win = crate::core_loop::key_fanout::deepest_window_at_pointer(state); + // Xorg DoFocusEvents (dix/enterleave.c:1557) short-circuits a + // same-window transition ONLY for non-grab modes: + // `if (from == to && mode != NotifyGrab && mode != NotifyUngrab) return;` + // For NotifyGrab/NotifyUngrab with from == to (the grab window is + // already the focus), CoreFocusEvents still runs and reaches + // CoreFocusNonLinear(W, W) — CommonAncestor(W,W) is W's parent, so + // both the Out/In endpoint events fire on W with NotifyNonlinear + // (the intermediate walks are empty). focus_transition_events + // returns nothing for from == to, so synthesize that pair here. + // (Grab windows are always real windows, so the None/PointerRoot + // same-window branch is unreachable from our call sites.) + let events = if from_raw == to_raw && (mode == 1 || mode == 2) && to_raw > 1 { + vec![ + crate::crossings::FocusEvent { + window: ResourceId(to_raw), + focus_in: false, + detail: crate::crossings::NOTIFY_NONLINEAR, + }, + crate::crossings::FocusEvent { + window: ResourceId(to_raw), + focus_in: true, + detail: crate::crossings::NOTIFY_NONLINEAR, + }, + ] + } else { + crate::crossings::focus_transition_events(state, from_raw, to_raw, pointer_win) + }; + let (ptr_x, ptr_y) = state.pointer_root; + for e in events { + let _dropped = + emit_window_event_to_state(state, e.window, FOCUS_CHANGE_MASK, |buf, seq, order| { + x11::encode_focus_event_with_mode_detail( + buf, seq, order, e.focus_in, e.window, mode, e.detail, + ); + }); + } + // Xorg DoFocusEvents: the whole core sequence, then the XI2 one + // (DeviceFocusEvents), which has its own windows. + for e in crate::crossings::device_focus_transition_events(state, from_raw, to_raw, pointer_win) + { + let evtype = if e.focus_in { 9 } else { 10 }; + let _dropped = emit_xi2_focus_event_to_state( + state, + e.window, + evtype, + XI2_MAJOR_OPCODE, + mode, + e.detail, + ptr_x, + ptr_y, + ); + } +} + +pub(super) fn handle_query_pointer( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let queried_window = if body.len() >= 4 { + ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])) + } else { + ROOT_WINDOW + }; + if state.resources.window(queried_window).is_some() + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: queried_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 38); + } + let pointer = backend.query_pointer(origin).ok().filter(|p| p.same_screen); + let reply_data = if let Some(pointer) = pointer { + // The KMS backend's PointerPosition carries cursor coordinates + // in root-absolute screen space (win_x/win_y are misnamed + // historical fields). Compute win-relative by subtracting the + // queried window's absolute origin. Without this xeyes (and + // any other client doing per-window pointer queries) sees + // win_x/win_y unchanged after the WM moves the window, so + // the iris locks to a fixed offset and stops tracking. + let (origin_x, origin_y) = state.resources.window_absolute_position(queried_window); + let root_x = pointer.win_x; + let root_y = pointer.win_y; + let win_x = i16::try_from(i32::from(root_x).saturating_sub(origin_x)).unwrap_or(i16::MAX); + let win_y = i16::try_from(i32::from(root_y).saturating_sub(origin_y)).unwrap_or(i16::MAX); + // Per X11 spec, `child` is the direct child of `queried_window` + // that contains the pointer, or None (0) if the pointer is on + // the queried window itself or on no descendant. Previously + // this was hardcoded to ROOT_WINDOW, which made GTK's + // QueryPointer-based hover/tooltip polling never see a + // transition between children — xfce4-panel spun 3500 times + // per second on QueryPointer, starving its event loop and + // dropping clicks on every panel applet. + let child = state + .direct_child_at(queried_window, win_x, win_y) + .unwrap_or(ResourceId(0)); + x11::QueryPointerReply { + root: ROOT_WINDOW, + child, + root_x, + root_y, + win_x, + win_y, + mask: pointer.mask, + } + } else { + x11::QueryPointerReply { + root: ROOT_WINDOW, + child: ResourceId(0), + ..Default::default() + } + }; + debug!( + "client {} #{} QueryPointer queried=0x{:x} -> root=({},{}) win=({},{}) child=0x{:x} mask=0x{:x}", + client_id.0, + sequence.0, + queried_window.0, + reply_data.root_x, + reply_data.root_y, + reply_data.win_x, + reply_data.win_y, + reply_data.child.0, + reply_data.mask, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_query_pointer_reply(&mut buf, byte_order, sequence, reply_data)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_warp_pointer( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 20 { + let rd16 = |o: usize| i16::from_le_bytes([body[o], body[o + 1]]); + let rdu16 = |o: usize| u16::from_le_bytes([body[o], body[o + 1]]); + let req = WarpRequest { + src: ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])), + dst: ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])), + src_x: i32::from(rd16(8)), + src_y: i32::from(rd16(10)), + src_w: rdu16(12), + src_h: rdu16(14), + dst_x: i32::from(rd16(16)), + dst_y: i32::from(rd16(18)), + }; + for window in [req.dst, req.src] { + if window.0 == 0 { + continue; + } + if state.resources.window(window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 41, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 41); + } + } + if !warp_pointer_src_allows(state, &req, WarpSrcRule::Core) { + debug!( + "client {} #{} WarpPointer no-op (pointer outside src rect)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + apply_pointer_warp(state, backend, origin, &req); + } + debug!("client {} #{} WarpPointer", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Which of Xorg's two source-rectangle tests a warp uses. Xorg keeps +/// two copies that differ in one term (see [`warp_pointer_src_allows`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum WarpSrcRule { + /// `ProcWarpPointer` (dix/events.c). + Core, + /// `ProcXIWarpPointer` (Xi/xiwarppointer.c). + XInput2, +} + +/// A decoded core `WarpPointer` or `XIWarpPointer`. The XI FP16.16 +/// coordinates are already converted to whole pixels the way Xorg does +/// it (`int src_x = stuff->src_x / (double)(1 << 16)`, which truncates +/// toward zero). +struct WarpRequest { + src: ResourceId, + dst: ResourceId, + src_x: i32, + src_y: i32, + src_w: u16, + src_h: u16, + dst_x: i32, + dst_y: i32, +} + +/// The first nonexistent window of a warp, in Xorg's lookup order: the +/// destination is looked up before the source in both ProcWarpPointer +/// and ProcXIWarpPointer. +fn warp_pointer_bad_window(state: &ServerState, req: &WarpRequest) -> Option { + [req.dst, req.src] + .into_iter() + .find(|w| w.0 != 0 && state.resources.window(*w).is_none()) + .map(|w| w.0) +} + +/// Whether the pointer is inside the warp's source rectangle, so the +/// warp goes ahead (always true without a source window). +/// +/// Ported term for term, including the XI copy's slip: its right-edge +/// test compares against 0 instead of the pointer x +/// (`winX + src_x + src_width < 0`, Xi/xiwarppointer.c), so an XI warp +/// ignores the right edge of the rectangle — only the window's own +/// extent (via the visibility test) bounds it. Both copies treat the +/// right/bottom edges as inclusive, and a zero width/height as "to the +/// window's edge". The core copy skips the visibility test for the root +/// window (`source->parent &&`); the XI copy always runs it. +fn warp_pointer_src_allows(state: &ServerState, req: &WarpRequest, rule: WarpSrcRule) -> bool { + if req.src.0 == 0 { + return true; + } + let (x, y) = ( + i32::from(state.pointer_root.0), + i32::from(state.pointer_root.1), + ); + let (win_x, win_y) = state.resources.window_absolute_position(req.src); + let left = win_x + req.src_x; + let top = win_y + req.src_y; + let right_limit = match rule { + WarpSrcRule::Core => x, + WarpSrcRule::XInput2 => 0, + }; + let outside = x < left + || y < top + || (req.src_w != 0 && left + i32::from(req.src_w) < right_limit) + || (req.src_h != 0 && top + i32::from(req.src_h) < y); + if outside { + return false; + } + let check_visibility = rule == WarpSrcRule::XInput2 || req.src != ROOT_WINDOW; + !check_visibility || point_in_window_is_visible(state, req.src, x, y) +} + +/// Xorg `PointInWindowIsVisible` (dix/window.c): the window is viewable +/// and the root point lies in its visible border-inclusive region and +/// input shape. The pointer hit test resolves exactly that — the point is +/// in `window`'s region iff the deepest window under it is `window` or +/// one of its inferiors. +fn point_in_window_is_visible(state: &ServerState, window: ResourceId, x: i32, y: i32) -> bool { + if window == ROOT_WINDOW { + return true; + } + let viewable = state + .resources + .window(window) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + if !viewable { + return false; + } + let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else { + return false; + }; + state + .root_pointer_target_at(x, y) + .is_some_and(|(hit, _, _)| { + hit == window || crate::core_loop::xi1_focus::is_ancestor(state, window, hit) + }) +} + +/// Move the sprite for a validated warp: relative to the destination +/// window's origin, or to the current position when there is none, +/// clamped to the screen like ProcWarpPointer/ProcXIWarpPointer, then +/// through the backend's absolute-motion path (which generates the +/// crossing and motion events a warp is specified to produce). Warps +/// bypass pointer barriers. +fn apply_pointer_warp( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + req: &WarpRequest, +) { + let (base_x, base_y) = if req.dst.0 == 0 { + ( + i32::from(state.pointer_root.0), + i32::from(state.pointer_root.1), + ) + } else { + state.resources.window_absolute_position(req.dst) + }; + let (root_w, root_h) = state + .resources + .window(ROOT_WINDOW) + .map_or((1, 1), |r| (i32::from(r.width), i32::from(r.height))); + let x = base_x + .saturating_add(req.dst_x) + .clamp(0, (root_w - 1).max(0)); + let y = base_y + .saturating_add(req.dst_y) + .clamp(0, (root_h - 1).max(0)); + if req.dst.0 != 0 { + // Proxy backends warp the host pointer relative to the host + // window (a no-op on KMS, which only uses `warp_pointer_root`). + let to_i16 = |v: i32| i16::try_from(v).unwrap_or(if v < 0 { i16::MIN } else { i16::MAX }); + if let Some(target) = state.resources.host_drawable_target(req.dst) { + let _ = backend.warp_pointer( + origin, + target.host_xid(), + to_i16(req.dst_x), + to_i16(req.dst_y), + ); + } + } + let prev = state.barrier_bypass; + state.barrier_bypass = true; + backend.warp_pointer_root(state, x, y); + state.barrier_bypass = prev; + crate::rootless::note_warp(state, x, y); +} diff --git a/crates/yserver-core/src/core_loop/process_request/fonts.rs b/crates/yserver-core/src/core_loop/process_request/fonts.rs new file mode 100644 index 000000000..ae2a6458d --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/fonts.rs @@ -0,0 +1,637 @@ +use crate::{ + access::{AccessMode, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext}, + core_loop::process_request::{RequestOutcome, emit_x11_error, write_to_client}, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, SequenceNumber}, +}; + +fn rewrite_reply_sequence(reply: &mut [u8], sequence: SequenceNumber) { + if reply.len() >= 4 { + let bytes = sequence.0.to_le_bytes(); + reply[2] = bytes[0]; + reply[3] = bytes[1]; + } +} + +/// GetFontPath (52): reply with 0 paths. +pub(super) fn handle_get_font_path( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetFontPath", client_id.0, sequence.0); + let paths = backend.font_path(); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + // Layout: reply(1) pad(1) seq(2) length(4) npaths u16(2) pad(22) + // then LISTofSTR (1 length byte + bytes each), padded to 4. + let mut buf = x11::fixed_reply(byte_order, sequence, 0, 0); + let mut tmp = Vec::with_capacity(2); + x11::write_u16( + byte_order, + &mut tmp, + u16::try_from(paths.len()).unwrap_or(0), + ); + buf.extend_from_slice(&tmp); + buf.resize(32, 0); + for p in &paths { + let bytes = p.as_bytes(); + let len = bytes.len().min(255); + buf.push(u8::try_from(len).unwrap_or(255)); + buf.extend_from_slice(&bytes[..len]); + } + while !buf.len().is_multiple_of(4) { + buf.push(0); + } + let units = u32::try_from((buf.len() - 32) / 4).unwrap_or(0); + let len_bytes = match byte_order { + yserver_protocol::x11::ClientByteOrder::LittleEndian => units.to_le_bytes(), + yserver_protocol::x11::ClientByteOrder::BigEndian => units.to_be_bytes(), + }; + buf[4..8].copy_from_slice(&len_bytes); + Ok(write_to_client(client, client_id, &buf)) +} + +/// SetFontPath (51): parse the STR list, hand it to the backend for +/// validation + install. Invalid element → BadValue (old path kept, +/// errorValue = offending element index, matching Xorg's +/// SetFontPathElements bad-element counter). +pub(super) fn handle_set_font_path( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if body.len() < 4 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + } + let npaths = u16::from_le_bytes([body[0], body[1]]); + let mut paths: Vec = Vec::with_capacity(usize::from(npaths)); + let mut off = 4usize; + for _ in 0..npaths { + let Some(&len) = body.get(off) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + }; + off += 1; + let end = off + usize::from(len); + let Some(bytes) = body.get(off..end) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + }; + paths.push(String::from_utf8_lossy(bytes).into_owned()); + off = end; + } + debug!( + "client {} #{} SetFontPath {:?}", + client_id.0, sequence.0, paths + ); + match backend.set_font_path(origin, &paths) { + Ok(()) => Ok(RequestOutcome::Handled), + Err(bad_index) => emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::try_from(bad_index).unwrap_or(0), + header.opcode, + ), + } +} + +pub(super) fn handle_list_fonts( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + if let Some(request) = x11::list_fonts_request(body) { + debug!( + "client {} #{} ListFonts max={} pattern={:?}", + client_id.0, sequence.0, request.max_names, request.pattern + ); + if let Ok(mut reply) = backend.list_fonts_proxy(origin, request.max_names, &request.pattern) + { + let names_returned = u16::from_le_bytes([reply[8], reply[9]]); + debug!( + "client {} #{} ListFonts → {} names", + client_id.0, sequence.0, names_returned + ); + rewrite_reply_sequence(&mut reply, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + } else { + debug!( + "client {} #{} ListFonts (unparsed)", + client_id.0, sequence.0 + ); + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_list_fonts_with_info( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + if let Some(request) = x11::list_fonts_request(body) { + debug!( + "client {} #{} ListFontsWithInfo max={} pattern={:?}", + client_id.0, sequence.0, request.max_names, request.pattern + ); + // Thread the atom interner so the backend can attach the FONT + // property (value = atom of the resolved XLFD) — XCreateFontSet + // resolves non-XLFD base names exclusively through it. Same + // disjoint-borrow pattern as handle_xkb_request. + let replies = { + let atoms = &mut state.atoms; + let mut intern = |name: &str| atoms.intern(name, false).0; + backend.list_fonts_with_info_proxy( + origin, + request.max_names, + &request.pattern, + &mut intern, + ) + }; + if let Ok(replies) = replies { + debug!( + "client {} #{} ListFontsWithInfo → {} replies (incl. terminator)", + client_id.0, + sequence.0, + replies.len() + ); + for mut reply in replies { + rewrite_reply_sequence(&mut reply, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + let outcome = write_to_client(client, client_id, &reply); + if matches!(outcome, RequestOutcome::Disconnect(_)) { + return Ok(outcome); + } + } + } + } else { + debug!( + "client {} #{} ListFontsWithInfo (unparsed)", + client_id.0, sequence.0 + ); + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_open_font( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(request) = x11::open_font_request(body) else { + debug!( + "client {} #{} OpenFont (parse failed)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + }; + debug!( + "client {} #{} OpenFont {:?}", + client_id.0, sequence.0, request.name + ); + let new_id = request.font.0; + let validation_failed = { + let handle = state.clients.get(&client_id.0).expect("client registered"); + !crate::server::IdAllocator::validate_owned( + new_id, + handle.resource_id_base, + handle.resource_id_mask, + ) || state.xid_occupied(request.font.0) + }; + if validation_failed { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + new_id, + 45, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.font, + kind: ResourceKind::Font, + creation: Some(crate::access::Creation { + parent: None, + owner: client_id, + }), + }, + AccessMode::CREATE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 45); + } + let host_result = match backend.open_font(origin, &request.name) { + Ok(pair) => Some(pair), + Err(err) if err.kind() == io::ErrorKind::NotFound => { + // Font-path resolution exhausted with no match → BadName + // (Xorg dix OpenFont semantics). KMS signals this with + // ErrorKind::NotFound; host-proxy failures use other + // kinds and keep the sentinel path below. + debug!( + "client {} OpenFont {:?}: no match on font path → BadName", + client_id.0, request.name + ); + return emit_x11_error(state, client_id, sequence, x11::error::BAD_NAME, 0, 45); + } + Err(err) => { + log::warn!( + "client {} OpenFont {:?} failed on host: {err}", + client_id.0, + request.name + ); + None + } + }; + // Even when the host font open failed, install the font ID locally + // so subsequent OpenFont calls on the same XID raise BadIDChoice + // (X11 spec: BadIDChoice fires on duplicate IDs regardless of + // whether the resource is actually backed). Use a sentinel host + // handle that drawing paths will recognise as "no glyph data". + let (host_handle, mut metrics) = host_result.unwrap_or_else(|| { + ( + crate::backend::FontHandle::from_raw(0xffff_ffff).expect("nonzero sentinel"), + x11::FontMetrics { + min_bounds: x11::CharInfo::default(), + max_bounds: x11::CharInfo::default(), + min_char_or_byte2: 0, + max_char_or_byte2: 0, + default_char: 0, + draw_direction: 0, + min_byte1: 0, + max_byte1: 0, + all_chars_exist: false, + font_ascent: 0, + font_descent: 0, + properties: Vec::new(), + named_properties: Vec::new(), + char_infos: Vec::new(), + }, + ) + }); + finish_font_properties(state, &request.name, &mut metrics); + state + .resources + .install_font(client_id, request.font, request.name, host_handle, metrics); + Ok(RequestOutcome::Handled) +} + +/// Open the server's default font, "fixed", as [`DEFAULT_FONT`] through the +/// same backend path `OpenFont` takes (Xorg `SetDefaultFont("fixed")`, +/// `dix/main.c:226`). Xorg treats a failure as fatal; so do the callers. +/// +/// [`DEFAULT_FONT`]: crate::resources::DEFAULT_FONT +pub fn install_default_font(state: &mut ServerState, backend: &mut dyn Backend) -> io::Result<()> { + const NAME: &str = "fixed"; + let (host_handle, mut metrics) = backend.open_font(None, NAME).map_err(|err| { + io::Error::new( + err.kind(), + format!("could not open default font {NAME:?}: {err}"), + ) + })?; + finish_font_properties(state, NAME, &mut metrics); + state.resources.install_font( + crate::resources::SERVER_OWNER, + crate::resources::DEFAULT_FONT, + NAME.to_string(), + host_handle, + metrics, + ); + Ok(()) +} + +/// Turn the font's properties into wire (atom, CARD32) pairs, synthesizing +/// them from the name when the backend supplied none. +fn finish_font_properties(state: &mut ServerState, name: &str, metrics: &mut x11::FontMetrics) { + // Properties read from the font file (BDF/PCF) arrive as + // named (String, value) pairs — convert to wire (atom, CARD32) + // pairs here where the atom table lives. String values are + // themselves atoms (BDF ATOM-typed properties). + if !metrics.named_properties.is_empty() { + let named = std::mem::take(&mut metrics.named_properties); + let mut out: Vec = Vec::with_capacity(named.len() * 8 + 8); + let mut has_font_prop = false; + for (prop, value) in &named { + if prop == "FONT" { + has_font_prop = true; + } + let name_atom = state.atoms.intern(prop, false).0; + let v: u32 = match value { + x11::FontPropValue::Card(c) => *c, + #[allow(clippy::cast_sign_loss)] + x11::FontPropValue::Int(i) => *i as u32, + x11::FontPropValue::Str(s) => state.atoms.intern(s, false).0, + }; + out.extend_from_slice(&name_atom.to_le_bytes()); + out.extend_from_slice(&v.to_le_bytes()); + } + // libX11's XCreateFontSet resolves non-XLFD base names + // exclusively through the FONT property (omGeneric.c) — + // always present on Xorg fonts; append if the file's + // property list lacked it. + if !has_font_prop { + let name_atom = state.atoms.intern("FONT", false).0; + let value_atom = state.atoms.intern(name, false).0; + out.extend_from_slice(&name_atom.to_le_bytes()); + out.extend_from_slice(&value_atom.to_le_bytes()); + } + metrics.properties = out; + } + // Backends that don't proxy to a real X server (KMS) can't + // populate font properties from upstream and return an empty + // properties vec. Synthesize the standard XLFD-derived + // properties (FOUNDRY, FAMILY_NAME, WEIGHT_NAME, ..., FONT) + // so apps that interrogate them — fvwm3 menu rendering, + // Xt/Athena widgets — don't silently skip text drawing. + if metrics.properties.is_empty() { + metrics.properties = synthesize_font_properties(&mut state.atoms, name); + log::debug!( + "OpenFont {:?}: synthesized {} property bytes ({} props), {} char_infos", + name, + metrics.properties.len(), + metrics.properties.len() / 8, + metrics.char_infos.len(), + ); + } +} + +/// Build a `FontProp` byte sequence (8 bytes per property: name atom + +/// CARD32 value) from an XLFD font name. String-typed properties get +/// their value interned as an atom; integer-typed properties carry +/// the int directly per the XLFD spec. +/// +/// XLFD components: +/// `-foundry-family-weight-slant-setwidth-addstyle-pixelsize-pointsize-resx-resy-spacing-avgwidth-charset-encoding` +fn synthesize_font_properties(atoms: &mut crate::server::AtomTable, xlfd: &str) -> Vec { + let parts: Vec<&str> = xlfd.split('-').collect(); + // Real XLFDs start with '-' so split yields an empty first element. + // Names that aren't proper XLFDs (e.g. "fixed", "cursor") get only a + // FONT property pointing at the literal string — better than empty. + let mut out: Vec = Vec::with_capacity(15 * 8); + + let put_string = + |atoms: &mut crate::server::AtomTable, out: &mut Vec, name: &str, value: &str| { + let name_atom = atoms.intern(name, false).0; + let value_atom = atoms.intern(value, false).0; + out.extend_from_slice(&name_atom.to_le_bytes()); + out.extend_from_slice(&value_atom.to_le_bytes()); + }; + let put_int = + |atoms: &mut crate::server::AtomTable, out: &mut Vec, name: &str, value: i32| { + let name_atom = atoms.intern(name, false).0; + out.extend_from_slice(&name_atom.to_le_bytes()); + out.extend_from_slice(&(value as u32).to_le_bytes()); + }; + + // FONT property always: the full XLFD as an atom value. + put_string(atoms, &mut out, "FONT", xlfd); + + // XLFD-shaped name: -foundry-family-weight-slant-setwidth-addstyle-pixel-point-resx-resy-spacing-avgwidth-charset-encoding + // parts[0] is the empty leading "" before the first '-'. + if parts.len() >= 15 { + put_string(atoms, &mut out, "FOUNDRY", parts[1]); + put_string(atoms, &mut out, "FAMILY_NAME", parts[2]); + put_string(atoms, &mut out, "WEIGHT_NAME", parts[3]); + put_string(atoms, &mut out, "SLANT", parts[4]); + put_string(atoms, &mut out, "SETWIDTH_NAME", parts[5]); + put_string(atoms, &mut out, "ADD_STYLE_NAME", parts[6]); + if let Ok(v) = parts[7].parse::() { + put_int(atoms, &mut out, "PIXEL_SIZE", v); + } + if let Ok(v) = parts[8].parse::() { + put_int(atoms, &mut out, "POINT_SIZE", v); + } + if let Ok(v) = parts[9].parse::() { + put_int(atoms, &mut out, "RESOLUTION_X", v); + } + if let Ok(v) = parts[10].parse::() { + put_int(atoms, &mut out, "RESOLUTION_Y", v); + } + put_string(atoms, &mut out, "SPACING", parts[11]); + if let Ok(v) = parts[12].parse::() { + put_int(atoms, &mut out, "AVERAGE_WIDTH", v); + } + put_string(atoms, &mut out, "CHARSET_REGISTRY", parts[13]); + put_string(atoms, &mut out, "CHARSET_ENCODING", parts[14]); + } + out +} + +/// Xorg `ProcCloseFont` (`dix/dispatch.c:1319`): an id that is not a font +/// (a GContext included) is BadFont; otherwise the id is freed and the +/// font goes once no GC holds it. The default font's id is no exception. +pub(super) fn handle_close_font( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(font) = x11::free_resource_id(body) else { + return Ok(RequestOutcome::Handled); + }; + if state.resources.font(font).is_none() { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, font.0, 46); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: font, + kind: ResourceKind::Font, + creation: None, + }, + AccessMode::DESTROY, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 46); + } + let _ = state.resources.close_font(font); + release_unreferenced_fonts(state, backend, origin); + debug!("client {} #{} CloseFont", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Close on the backend the fonts whose last reference (id or GC) just went. +pub(super) fn release_unreferenced_fonts( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, +) { + for host_xid in state.resources.take_released_fonts() { + let _ = backend.close_font(origin, host_xid); + } +} + +pub(super) fn handle_query_font( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + debug!("client {} #{} QueryFont", client_id.0, sequence.0); + let font_id = x11::drawable_request_id(body); + let Some(font_id) = font_id else { + // Unknown/invalid fontable → BadFont (Xorg), not a zeroed + // metrics reply that misleads the client into thinking the + // font loaded. + return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, 0, 47); + }; + let Some(kind) = state.resources.fontable(font_id).map(|_| { + if state.resources.gc(font_id).is_some() { + ResourceKind::Gc + } else { + ResourceKind::Font + } + }) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_FONT, + font_id.0, + 47, + ); + }; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: font_id, + kind, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 47); + } + let metrics = state + .resources + .fontable(font_id) + .expect("fontable was just resolved") + .metrics + .clone(); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(64); + x11::write_query_font_reply(&mut buf, byte_order, sequence, &metrics)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_query_text_extents( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + debug!("client {} #{} QueryTextExtents", client_id.0, sequence.0); + let req = x11::query_text_extents_request(header.data, body); + let Some(req) = req else { + // Unknown/invalid fontable → BadFont (Xorg), not zeroed extents. + return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, 0, 48); + }; + let Some(kind) = state.resources.fontable(req.fontable).map(|_| { + if state.resources.gc(req.fontable).is_some() { + ResourceKind::Gc + } else { + ResourceKind::Font + } + }) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_FONT, + req.fontable.0, + 48, + ); + }; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: req.fontable, + kind, + creation: None, + }, + AccessMode::GET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 48); + } + let extents = state + .resources + .fontable(req.fontable) + .expect("fontable was just resolved") + .metrics + .text_extents(&req.chars); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_query_text_extents_reply(&mut buf, byte_order, sequence, extents)?; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/gc_pixmap_cursor.rs b/crates/yserver-core/src/core_loop/process_request/gc_pixmap_cursor.rs new file mode 100644 index 000000000..07829951b --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/gc_pixmap_cursor.rs @@ -0,0 +1,1022 @@ +use crate::{ + access::{AccessMode, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext}, + core_loop::process_request::{ + FREE_CURSOR_OPCODE, FREE_GC_OPCODE, FREE_PIXMAP_OPCODE, RequestOutcome, emit_x11_error, + supported_pixmap_depth, validate_gc_only, write_to_client, xid_out_of_client_range, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +pub(super) fn handle_recolor_cursor( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let cursor = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + if !state.resources.cursor_exists(cursor) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + 96, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::WRITE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 96); + } + let fore = ( + u16::from_le_bytes([body[4], body[5]]), + u16::from_le_bytes([body[6], body[7]]), + u16::from_le_bytes([body[8], body[9]]), + ); + let back = ( + u16::from_le_bytes([body[10], body[11]]), + u16::from_le_bytes([body[12], body[13]]), + u16::from_le_bytes([body[14], body[15]]), + ); + if let Some(host_xid) = state.resources.cursor_host_xid(cursor) { + backend.recolor_cursor(origin, host_xid, fore, back)?; + } + debug!( + "client {} #{} RecolorCursor 0x{:x}", + client_id.0, sequence.0, cursor.0 + ); + Ok(RequestOutcome::Handled) +} + +/// SetDashes (58): replace the GC's dash pattern with the multi-byte +/// list supplied. Distinct from the single-byte `CPDashList` form in +/// `CreateGC` / `ChangeGC` (which can only set a uniform [n, n]). +/// +/// Wire: `gc u32, dash_offset u16, n u16, dashes u8[n]`. `n == 0` or +/// any `dashes[i] == 0` is `BadValue` per spec. +pub(super) fn handle_set_dashes( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let gc = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let dash_offset = u16::from_le_bytes([body[4], body[5]]); + let n = u16::from_le_bytes([body[6], body[7]]) as usize; + debug!( + "client {} #{} SetDashes gc=0x{:x} offset={} n={}", + client_id.0, sequence.0, gc.0, dash_offset, n + ); + if n == 0 { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 58); + } + let end = 8usize.saturating_add(n); + if body.len() < end { + return Ok(RequestOutcome::Handled); + } + let dashes = &body[8..end]; + // BadGC takes priority over BadValue when the GC id itself is + // bogus. Use the client-range check rather than `gc().is_some()` + // because other GC mutators (`set_clip_rectangles`, etc.) + // auto-vivify entries via `entry().or_insert_with`, so an + // invalid id can be present in the map from an earlier request. + if xid_out_of_client_range(state, client_id, gc.0) || state.resources.gc(gc).is_none() { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_GC, gc.0, 58); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: gc, + kind: ResourceKind::Gc, + creation: None, + }, + AccessMode::SET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 58); + } + if dashes.contains(&0) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 58); + } + state + .resources + .set_dashes(client_id, gc, dash_offset, dashes); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_create_cursor( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 28 { + let cursor_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + if state.resources.xid_in_use(cursor_id) + || xid_out_of_client_range(state, client_id, cursor_id.0) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + cursor_id.0, + 93, + ); + } + let source_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let mask_id = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let fore = ( + u16::from_le_bytes([body[12], body[13]]), + u16::from_le_bytes([body[14], body[15]]), + u16::from_le_bytes([body[16], body[17]]), + ); + let back = ( + u16::from_le_bytes([body[18], body[19]]), + u16::from_le_bytes([body[20], body[21]]), + u16::from_le_bytes([body[22], body[23]]), + ); + let hot_x = u16::from_le_bytes([body[24], body[25]]); + let hot_y = u16::from_le_bytes([body[26], body[27]]); + + for pixmap in [source_id, mask_id] { + if let Err((code, bad_value)) = super::validate_resource_if_present( + state, + client_id, + pixmap, + ResourceKind::Pixmap, + AccessMode::READ, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 93); + } + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor_id, + kind: ResourceKind::Cursor, + creation: Some(crate::access::Creation { + parent: None, + owner: client_id, + }), + }, + AccessMode::CREATE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 93); + } + + let src_host = state.resources.pixmap(source_id).and_then(|p| p.host_xid); + let mask_host = if mask_id.0 == 0 { + None + } else { + state.resources.pixmap(mask_id).and_then(|p| p.host_xid) + }; + state.resources.create_cursor(client_id, cursor_id); + if let Some(src_host) = src_host { + match backend.create_cursor(origin, src_host, mask_host, fore, back, hot_x, hot_y) { + Ok(handle) => { + state.resources.set_cursor_host_xid(cursor_id, handle); + } + Err(err) => { + log::warn!("client {} CreateCursor failed: {err}", client_id.0); + } + } + } + } + debug!("client {} #{} CreateCursor", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_create_glyph_cursor( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 28 + && let Some(cursor) = x11::create_glyph_cursor_id(body) + { + let new_id = cursor.0; + let validation_failed = { + let handle = state.clients.get(&client_id.0).expect("client registered"); + let owned = crate::server::IdAllocator::validate_owned( + new_id, + handle.resource_id_base, + handle.resource_id_mask, + ); + let in_use = state.xid_occupied(cursor.0); + !owned || in_use + }; + if validation_failed { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + new_id, + 94, + ); + } + + let source_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let mask_id = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let source_char = u16::from_le_bytes([body[12], body[13]]); + let mask_char = u16::from_le_bytes([body[14], body[15]]); + let fore = ( + u16::from_le_bytes([body[16], body[17]]), + u16::from_le_bytes([body[18], body[19]]), + u16::from_le_bytes([body[20], body[21]]), + ); + let back = ( + u16::from_le_bytes([body[22], body[23]]), + u16::from_le_bytes([body[24], body[25]]), + u16::from_le_bytes([body[26], body[27]]), + ); + + for font in [source_id, mask_id] { + if let Err((code, bad_value)) = super::validate_resource_if_present( + state, + client_id, + font, + ResourceKind::Font, + AccessMode::USE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 94); + } + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: Some(crate::access::Creation { + parent: None, + owner: client_id, + }), + }, + AccessMode::CREATE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 94); + } + + let src_host = state.resources.font(source_id).map(|f| f.host_xid); + let mask_host = if mask_id.0 == 0 { + None + } else { + state.resources.font(mask_id).map(|f| f.host_xid) + }; + + state.resources.create_glyph_cursor(client_id, cursor); + if let Some(src_host) = src_host { + match backend.create_glyph_cursor( + origin, + src_host, + mask_host, + source_char, + mask_char, + fore, + back, + ) { + Ok(handle) => { + state.resources.set_cursor_host_xid(cursor, handle); + } + Err(err) => { + log::warn!("client {} CreateGlyphCursor failed: {err}", client_id.0); + } + } + } else { + log::warn!( + "client {} CreateGlyphCursor: source font 0x{:x} unknown", + client_id.0, + source_id.0 + ); + } + } + debug!("client {} #{} CreateGlyphCursor", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_create_gc( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some(request) = x11::create_gc_request(body) { + let new_id = request.gc.0; + let validation_failed = { + let handle = state.clients.get(&client_id.0).expect("client registered"); + let owned = crate::server::IdAllocator::validate_owned( + new_id, + handle.resource_id_base, + handle.resource_id_mask, + ); + let in_use = state.xid_occupied(request.gc.0); + !owned || in_use + }; + if validation_failed { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + new_id, + 55, + ); + } + if let Some(bad) = unknown_gc_font(state, request.font) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, bad, 55); + } + let drawable_kind = if state.resources.window(request.drawable).is_some() { + Some(ResourceKind::Window) + } else if state.resources.pixmap(request.drawable).is_some() { + Some(ResourceKind::Pixmap) + } else { + None + }; + if let Some(kind) = drawable_kind + && let Err((code, bad_value)) = super::validate_resource_if_present( + state, + client_id, + request.drawable, + kind, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 55); + } + if let Err((code, bad_value)) = validate_gc_value_list_access( + state, + client_id, + access_request, + request.tile, + request.stipple, + request.font, + request.clip_mask, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 55); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.gc, + kind: ResourceKind::Gc, + creation: Some(crate::access::Creation { + parent: Some(request.drawable), + owner: client_id, + }), + }, + AccessMode::CREATE | AccessMode::SET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 55); + } + state.resources.create_gc(client_id, request); + } + debug!("client {} #{} CreateGC", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Host-free the pixmaps a GC change displaced once nothing else references +/// them — the client may have freed them while the GC still held them +/// (`handle_free_pixmap` defers that free). Same orphan rule as the +/// ChangeWindowAttributes release. +pub(super) fn release_displaced_gc_pixmaps( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + displaced: Vec, +) { + for handle in displaced { + if !state.resources.host_xid_still_referenced(handle) { + let _ = backend.free_pixmap(origin, handle.as_raw()); + state.resources.host_pixmap_freed(handle.as_raw()); + } + } +} + +/// GCFont naming no open font: Xorg `ChangeGCXIDs` (`dix/gc.c:430`) looks +/// every XID up before changing anything, so the request does nothing. +fn unknown_gc_font(state: &ServerState, font: Option) -> Option { + font.filter(|id| state.resources.font(*id).is_none()) + .map(|id| id.0) +} + +/// Authorize the resource operands in a CreateGC / ChangeGC value list. +fn validate_gc_value_list_access( + state: &ServerState, + client_id: ClientId, + access_request: RequestOpcodes, + tile: Option, + stipple: Option, + font: Option, + clip_mask: Option>, +) -> Result<(), (u8, u32)> { + for pixmap in [tile, stipple].into_iter().flatten() { + super::validate_resource_if_present( + state, + client_id, + pixmap, + ResourceKind::Pixmap, + AccessMode::READ, + access_request, + )?; + } + if let Some(font) = font { + super::validate_resource_if_present( + state, + client_id, + font, + ResourceKind::Font, + AccessMode::USE, + access_request, + )?; + } + if let Some(Some(pixmap)) = clip_mask { + super::validate_resource_if_present( + state, + client_id, + pixmap, + ResourceKind::Pixmap, + AccessMode::READ, + access_request, + )?; + } + Ok(()) +} + +pub(super) fn handle_change_gc( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + if let Some(request) = x11::change_gc_request(body) { + if let Err((code, bad_value)) = validate_gc_only( + state, + client_id, + access_request, + request.gc, + Some(AccessMode::SET_ATTR), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 56); + } + if let Some(bad) = unknown_gc_font(state, request.font) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_FONT, bad, 56); + } + if let Err((code, bad_value)) = validate_gc_value_list_access( + state, + client_id, + access_request, + request.tile, + request.stipple, + request.font, + request.clip_mask, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 56); + } + let displaced = state.resources.change_gc(client_id, request); + release_displaced_gc_pixmaps(state, backend, origin, displaced); + super::fonts::release_unreferenced_fonts(state, backend, origin); + } + debug!("client {} #{} ChangeGC", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_copy_gc( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 12 { + let src_gc = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let dst_gc = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let value_mask = u32::from_le_bytes([body[8], body[9], body[10], body[11]]); + if let Err((code, bad_value)) = super::validate_resource_if_present( + state, + client_id, + src_gc, + ResourceKind::Gc, + AccessMode::GET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 57); + } + if let Err((code, bad_value)) = super::validate_resource_if_present( + state, + client_id, + dst_gc, + ResourceKind::Gc, + AccessMode::SET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 57); + } + let displaced = state.resources.copy_gc(src_gc, dst_gc, value_mask); + release_displaced_gc_pixmaps(state, backend, origin, displaced); + super::fonts::release_unreferenced_fonts(state, backend, origin); + } + debug!("client {} #{} CopyGC", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_set_clip_rectangles( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let access_request = RequestOpcodes::for_request(header); + if let Some(request) = x11::set_clip_rectangles_request(header.data, body) { + if let Err((code, bad_value)) = validate_gc_only( + state, + client_id, + access_request, + request.gc, + Some(AccessMode::SET_ATTR), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 59); + } + let displaced = state.resources.set_clip_rectangles(client_id, request); + release_displaced_gc_pixmaps(state, backend, origin, displaced); + } + debug!("client {} #{} SetClipRectangles", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Xorg `ProcFreeGC` (`../xserver/dix/dispatch.c:1677`) resolves the id +/// with `dixLookupGC` -> `dixLookupResourceByType(X11_RESTYPE_GC)`, which +/// on a miss returns that resource type's `errorValue` — `BadGC` +/// (`../xserver/dix/resource.c:454`) — after setting `client->errorValue` +/// to the id exactly as sent. Silently succeeding is the same defect +/// class as #143 on FreePixmap: for a *checked void* request the error +/// packet is the only thing that can carry a higher sequence number back +/// to XCB, so swallowing it leaves every preceding checked request of +/// that client uncompleted. +pub(super) fn handle_free_gc( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(gc) = x11::free_resource_id(body) else { + debug!( + "client {} #{} FreeGC (parse failed)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + }; + if state.resources.gc(gc).is_none() { + debug!( + "client {} #{} FreeGC gc=0x{:x} unknown -> BadGC", + client_id.0, sequence.0, gc.0 + ); + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_GC, + gc.0, + FREE_GC_OPCODE, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: gc, + kind: ResourceKind::Gc, + creation: None, + }, + AccessMode::DESTROY, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, FREE_GC_OPCODE); + } + let displaced = state.resources.free_gc(gc); + release_displaced_gc_pixmaps(state, backend, origin, displaced); + super::fonts::release_unreferenced_fonts(state, backend, origin); + debug!( + "client {} #{} FreeGC gc=0x{:x} freed", + client_id.0, sequence.0, gc.0 + ); + Ok(RequestOutcome::Handled) +} + +/// Xorg `ProcFreeCursor` (`../xserver/dix/dispatch.c:3100`) looks the id +/// up with `dixLookupResourceByType(X11_RESTYPE_CURSOR)` and on a miss +/// sets `client->errorValue = stuff->id` and returns the type's +/// `errorValue`, `BadCursor` (`../xserver/dix/resource.c:466`). Same +/// checked-void-request reasoning as `handle_free_gc` above. +pub(super) fn handle_free_cursor( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(cursor) = x11::free_resource_id(body) else { + debug!( + "client {} #{} FreeCursor (parse failed)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + }; + if !state.resources.cursor_exists(cursor) { + debug!( + "client {} #{} FreeCursor cursor=0x{:x} unknown -> BadCursor", + client_id.0, sequence.0, cursor.0 + ); + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + FREE_CURSOR_OPCODE, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::DESTROY, + access_request, + ) { + return emit_x11_error( + state, + client_id, + sequence, + code, + bad_value, + FREE_CURSOR_OPCODE, + ); + } + let host_xid = state.resources.free_cursor(cursor); + if let Some(host_xid) = host_xid { + let _ = backend.free_cursor(origin, host_xid); + } + debug!( + "client {} #{} FreeCursor cursor=0x{:x} freed host_xid={host_xid:?}", + client_id.0, sequence.0, cursor.0 + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_create_pixmap( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let Some(request) = x11::create_pixmap_request(header.data, body) else { + debug!( + "client {} #{} CreatePixmap (parse failed)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + }; + debug!( + "client {} #{} CreatePixmap pid=0x{:x} depth={} {}x{} drawable=0x{:x}", + client_id.0, + sequence.0, + request.pixmap.0, + request.depth, + request.width, + request.height, + request.drawable.0, + ); + let new_id = request.pixmap.0; + let (owned, in_use, drawable_exists) = { + let handle = state.clients.get(&client_id.0).expect("client registered"); + let owned = crate::server::IdAllocator::validate_owned( + new_id, + handle.resource_id_base, + handle.resource_id_mask, + ); + let in_use = state.xid_occupied(request.pixmap.0); + let drawable_exists = state.resources.window(request.drawable).is_some() + || state.resources.pixmap(request.drawable).is_some(); + (owned, in_use, drawable_exists) + }; + if !owned || in_use { + log::warn!( + "client {} CreatePixmap BadIDChoice pid=0x{:x} ({})", + client_id.0, + new_id, + if !owned { "out-of-range" } else { "in-use" }, + ); + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + new_id, + 53, + ); + } + if !drawable_exists { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + request.drawable.0, + 53, + ); + } + let drawable_kind = if state.resources.window(request.drawable).is_some() { + ResourceKind::Window + } else { + ResourceKind::Pixmap + }; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.drawable, + kind: drawable_kind, + creation: None, + }, + AccessMode::GET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 53); + } + if !supported_pixmap_depth(request.depth) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(request.depth), + 53, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.pixmap, + kind: ResourceKind::Pixmap, + creation: Some(crate::access::Creation { + parent: Some(request.drawable), + owner: client_id, + }), + }, + AccessMode::CREATE, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 53); + } + let host_xid = match backend.create_pixmap(origin, request.depth, request.width, request.height) + { + Ok(handle) => Some(handle), + Err(err) => { + log::warn!("client {} host CreatePixmap failed: {err}", client_id.0); + None + } + }; + state.resources.create_pixmap(client_id, request); + if let Some(xid) = host_xid { + let updated = state.resources.set_pixmap_host_xid(request.pixmap, xid); + debug_assert!(updated, "pixmap was just inserted above"); + } + Ok(RequestOutcome::Handled) +} + +/// Xorg `ProcFreePixmap` (`../xserver/dix/dispatch.c:1529`) resolves the +/// id with `dixLookupResourceByType(X11_RESTYPE_PIXMAP)`; on a miss it +/// sets `client->errorValue = stuff->id` and returns that resource +/// type's `errorValue`, i.e. `BadPixmap` (`../xserver/dix/resource.c:448`) +/// — `None` (0) included, since 0 is simply an XID that is not a pixmap. +/// +/// #143: picom sends a deliberate `FreePixmap(drawable=None)` as a sync +/// barrier before every sleep (`x_prepare_for_sleep`, picom `src/x.c:1194`) +/// and *expects* `BadPixmap` back. XCB can only mark a checked **void** +/// request complete once it reads a packet carrying a higher sequence +/// number, and for a void request that packet is the error. Returning +/// silent success left picom's nine checked `ChangeWindowAttributes` +/// uncompleted, so `wm_handle_set_event_mask_reply` never fired and the +/// second half of its window import stalled ~10s (Xorg: ~120ms). +pub(super) fn handle_free_pixmap( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(pixmap) = x11::free_resource_id(body) else { + debug!( + "client {} #{} FreePixmap (parse failed)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + }; + if state.resources.pixmap(pixmap).is_none() { + debug!( + "client {} #{} FreePixmap pixmap=0x{:x} unknown -> BadPixmap", + client_id.0, sequence.0, pixmap.0 + ); + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + pixmap.0, + FREE_PIXMAP_OPCODE, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: pixmap, + kind: ResourceKind::Pixmap, + creation: None, + }, + AccessMode::DESTROY, + access_request, + ) { + return emit_x11_error( + state, + client_id, + sequence, + code, + bad_value, + FREE_PIXMAP_OPCODE, + ); + } + let Some(removed) = state.resources.free_pixmap(pixmap) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + pixmap.0, + FREE_PIXMAP_OPCODE, + ); + }; + if removed.composite_name { + // A name owns its own alias ref: a sibling name sharing the backing must not hide it. + let names: Vec<_> = removed.host_xid.into_iter().collect(); + let last = crate::core_loop::process_disconnect::release_removed_names( + state, backend, origin, &names, + ); + crate::core_loop::process_disconnect::free_orphaned_host_pixmaps( + state, + backend, + last.clone(), + &last, + None, + ); + debug!( + "client {} #{} FreePixmap pixmap=0x{:x} (window name) host_xid={:?}", + client_id.0, + sequence.0, + pixmap.0, + removed.host_xid.map(crate::backend::PixmapHandle::as_raw), + ); + return Ok(RequestOutcome::Handled); + } + let still_referenced = removed + .host_xid + // The BORDER reference is as load-bearing as the background one: + // `XCreatePixmap` → `XSetWindowBorderPixmap` → `XFreePixmap` is + // ordinary client code, and X11 keeps the storage alive because + // the window still names it (Xorg refcounts + // `pWin->border.pixmap`). Omitting it freed the host handle + // underneath a ring that was still sampling it (#133). All four + // release sites now share one rule. + .is_some_and(|xid| state.resources.host_xid_still_referenced(xid)); + if let Some(xid) = removed.host_xid + && !still_referenced + { + backend.free_pixmap(origin, xid.as_raw())?; + } + debug!( + "client {} #{} FreePixmap pixmap=0x{:x} freed host_xid={:?} retained={}", + client_id.0, + sequence.0, + pixmap.0, + removed.host_xid.map(crate::backend::PixmapHandle::as_raw), + still_referenced + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_query_best_size( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 4 { + let drawable = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let kind = if state.resources.window(drawable).is_some() { + Some(ResourceKind::Window) + } else if state.resources.pixmap(drawable).is_some() { + Some(ResourceKind::Pixmap) + } else { + None + }; + if let Some(kind) = kind + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: drawable, + kind, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 97); + } + } + let width = if body.len() >= 8 { + u16::from_le_bytes([body[4], body[5]]) + } else { + 0 + }; + let height = if body.len() >= 8 { + u16::from_le_bytes([body[6], body[7]]) + } else { + 0 + }; + debug!("client {} #{} QueryBestSize", client_id.0, sequence.0); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_query_best_size_reply(&mut buf, byte_order, sequence, width, height)?; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/get_image_reply_tests.rs b/crates/yserver-core/src/core_loop/process_request/get_image_reply_tests.rs new file mode 100644 index 000000000..a2eb71ad8 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/get_image_reply_tests.rs @@ -0,0 +1,16 @@ +use crate::core_loop::process_request::drawing::patch_get_image_reply_header; +use yserver_protocol::x11::{ClientByteOrder, SequenceNumber}; + +#[test] +fn patch_get_image_reply_header_honors_big_endian() { + let bytes = vec![0u8; 40]; + let patched = patch_get_image_reply_header( + bytes, + ClientByteOrder::BigEndian, + SequenceNumber(0x0102), + 0xA1B2_C3D4, + ); + assert_eq!(&patched[2..4], &0x0102u16.to_be_bytes()); + assert_eq!(&patched[4..8], &2u32.to_be_bytes()); + assert_eq!(&patched[8..12], &0xA1B2_C3D4u32.to_be_bytes()); +} diff --git a/crates/yserver-core/src/core_loop/process_request/glx.rs b/crates/yserver-core/src/core_loop/process_request/glx.rs new file mode 100644 index 000000000..7cd2e4ed4 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/glx.rs @@ -0,0 +1,1425 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::process_request::{ + RequestOutcome, emit_x11_error_with_minor, redirect::retarget_glx_pixmap_export, + write_to_client, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// Build the FBConfig list returned by `GetFBConfigs`. We synthesise +/// from each X visual (depth-24 RGB and depth-32 ARGB), double buffered, +/// plus one visual-less, single-buffered pixmap configuration for +/// QtWebEngine's native DMA-BUF import. All share depth=24 stencil=8 (the +/// universal default for OpenGL apps). The two visual-backed configurations +/// advertise GLX_PBUFFER_BIT so Chromium/ANGLE can allocate its offscreen +/// surface. +/// Resolve the attribute list for a `GetDrawableAttributes` reply, +/// mirroring Xorg's `DoGetDrawableAttributes` (glxcmds.c:1863-1914). +/// With no GLX record (a naked X window queried directly, the GLX 1.2 +/// pattern) the `pGlxDraw` block is skipped entirely — `GLX_FBCONFIG_ID`, +/// `GLX_TEXTURE_TARGET_EXT` and `GLX_EVENT_MASK` are absent, not zero. +pub(super) fn drawable_attributes_for(state: &ServerState, xid: u32) -> Vec<(u32, u32)> { + use yserver_protocol::x11::glx as g; + let drawable = state.glx_drawables.get(&xid); + // Resolve drawable geometry. For a pbuffer the size lives in the + // GlxDrawable record (from CreatePbuffer); otherwise read the real + // geometry of the backing X drawable from the resource store. Mesa's + // loader_dri3 reads GLX_WIDTH/GLX_HEIGHT here to size the buffer; + // without them it gets 0×0 and fails with "failed to create drawable". + // Xorg reports the same from pDraw->width/height (glxcmds.c:1891). + // A 0×0 pbuffer is treated as NOT a pbuffer here (matches the old + // size-keyed behaviour): its geometry falls through to the backing + // pixmap, which CREATE_PBUFFER clamps to max(1), so it reports 1×1. + let is_pbuffer = matches!( + drawable, + Some(d) if d.kind == crate::server::GlxDrawableKind::Pbuffer + && (d.width != 0 || d.height != 0) + ); + // A GLXWindow/GLXPixmap XID is a fresh client-allocated id with no X + // resource behind it — its geometry lives on the *backing* X drawable + // recorded at create time. Looking up the GLX XID itself always missed + // and reported 0×0. Xorg reads pGlxDraw->pDraw->width/height + // (glxcmds.c:1891). + let geometry_xid = match drawable { + Some(d) if !is_pbuffer => d.x_drawable, + _ => xid, + }; + let (width, height) = match drawable { + Some(d) if is_pbuffer => (d.width, d.height), + _ => state + .resources + .window(ResourceId(geometry_xid)) + .map(|w| (u32::from(w.width), u32::from(w.height))) + .or_else(|| { + state + .resources + .pixmap(ResourceId(geometry_xid)) + .map(|p| (u32::from(p.width), u32::from(p.height))) + }) + .unwrap_or((0, 0)), + }; + // Xorg's exact attribute set and order (glxcmds.c:1889-1914). + let mut attribs: Vec<(u32, u32)> = Vec::with_capacity(9); + attribs.push((g::GLX_Y_INVERTED_EXT, 0)); + attribs.push((g::GLX_WIDTH, width)); + attribs.push((g::GLX_HEIGHT, height)); + attribs.push((g::GLX_SCREEN, 0)); + if let Some(d) = drawable { + attribs.push((g::GLX_TEXTURE_TARGET_EXT, d.texture_target)); + attribs.push((g::GLX_EVENT_MASK, d.event_mask)); + attribs.push((g::GLX_FBCONFIG_ID, d.fbconfig)); + if d.kind == crate::server::GlxDrawableKind::Pbuffer { + attribs.push((g::GLX_PRESERVED_CONTENTS, 1)); + } + if d.kind == crate::server::GlxDrawableKind::Window { + attribs.push((g::GLX_STEREO_TREE_EXT, 0)); + } + } + // GLX_EXT_get_drawable_type — always last; Xorg's no-record + // fallthrough is GLX_WINDOW_BIT (glxcmds.c:1908-1910). + let drawable_type = match drawable.map(|d| d.kind) { + Some(crate::server::GlxDrawableKind::Pixmap) => g::GLX_PIXMAP_BIT, + Some(crate::server::GlxDrawableKind::Pbuffer) => g::GLX_PBUFFER_BIT, + Some(crate::server::GlxDrawableKind::Window) | None => g::GLX_WINDOW_BIT, + }; + attribs.push((g::GLX_DRAWABLE_TYPE, drawable_type)); + attribs +} + +/// GLX 1.2 visual configs in the legacy untagged form Mesa parses +/// via `__glXInitializeVisualConfigFromTags(!tagged_only)`. Mirrors +/// the visuals our setup-reply advertises (ROOT_VISUAL depth-24 +/// TrueColor RGB, ARGB_VISUAL depth-32 TrueColor RGBA). +/// +/// An X visual describes one GLX visual configuration. Do not publish the +/// same visual ID once as double-buffered and again as single-buffered: Mesa +/// cannot preserve that ambiguity when a context and window are selected +/// independently. ANGLE selected yserver's single-buffered config for its +/// context/pbuffer but the double-buffered config carrying the same visual for +/// its windows. Mesa then allocated a fake front buffer for every window. Xorg +/// gives those configurations distinct X visuals; until yserver exposes more +/// setup visuals, associate only the double-buffered configuration with each +/// real visual. +pub(super) fn synthesise_glx_visual_configs() -> Vec { + use yserver_protocol::x11::glx::VisualConfig; + // X11 visual class 4 == TrueColor, matching the class we put in the + // setup-reply visual list. + const TRUE_COLOR: u32 = 4; + let mut out: Vec = Vec::with_capacity(3); + for &(visual_id, alpha_bits, rgb_bits, stencil_bits) in &[ + // Must match the client driver's configs (see synthesise_glx_fb_configs): + // radeonsi advertises alpha-8 / 32-bit-buffer for both depths. + (0x102_u32, 8_u32, 32_u32, 8_u32), // ROOT_VISUAL — TrueColor (GL alpha 8) + (0x103_u32, 8_u32, 32_u32, 8_u32), // ARGB_VISUAL — TrueColor RGBA + (crate::resources::GLMARK_VISUAL.0, 8_u32, 32_u32, 0_u32), + ] { + out.push(VisualConfig { + visual_id, + visual_class: TRUE_COLOR, + rgba: true, + red_bits: 8, + green_bits: 8, + blue_bits: 8, + alpha_bits, + double_buffer: true, + stereo: false, + rgb_bits, + depth_bits: 24, + stencil_bits, + aux_buffers: 0, + level: 0, + }); + } + out +} + +/// Build the GLX extension string. The base extensions are always +/// present; `GLX_EXT_texture_from_pixmap` is appended only when the +/// backend confirmed at init that it can export a BGRA8 dma-buf. +/// `GLX_SGIX_fbconfig` is always appended: `GetFBConfigsSGIX`, +/// `CreateContextWithConfigSGIX` and `CreateGLXPixmapWithConfigSGIX` +/// are fully dispatched (VendorPrivate arms) — advertise-after-implement. +/// +/// **Every chunk is space-terminated, so the string ends with `' '`.** +/// This mirrors Xorg, which writes `' '` then `'\0'` after each enabled +/// extension (`glx/extension_string.c:144-145`). It is not cosmetic: +/// `libGLX_nvidia` loses the final token of an unterminated list — it +/// silently dropped the `GLX_SGIX_fbconfig` we advertise — and also +/// withholds `GLX_ARB_get_proc_address` from the client extension +/// string, which aborts libepoxy and crashes `kwin_x11`. Appending via +/// this closure keeps the invariant true for any extension added later. +pub(super) fn glx_extension_string(tfp_supported: bool) -> String { + let mut s = String::new(); + let mut push = |chunk: &str| { + s.push_str(chunk); + s.push(' '); + }; + push(yserver_protocol::x11::glx::SERVER_EXTENSIONS); + push(yserver_protocol::x11::glx::SGIX_FBCONFIG_EXTENSION); + if tfp_supported { + push(yserver_protocol::x11::glx::TFP_EXTENSION); + } + s +} + +pub(super) fn synthesise_glx_fb_configs(tfp_supported: bool) -> Vec> { + use yserver_protocol::x11::glx as g; + let mut out = Vec::with_capacity(4); + let depth = 24; + for &(visual_id, fbconfig_id, alpha_size, total_buffer_size, stencil) in &[ + // (X visual id, FBConfig id, alpha bits, total color buffer bits) + // + // These MUST match the client driver's __DRIconfig attributes + // exactly, or mesa's driConfigEqual rejects them all and GLX dri3 + // screen creation fails with "No matching fbConfigs or visuals + // found" (no direct GLX → no TFP). radeonsi advertises BOTH its + // depth-24 and depth-32 TrueColor configs as 8-bit-alpha, + // 32-bit-buffer (the GL backbuffer is BGRA8 regardless of the X + // visual's opacity), so we mirror that for both. The depth-24 X + // visual stays opaque on screen; the alpha is GL-side only. + (0x102_u32, 0x101_u32, 8_u32, 32_u32, 8_u32), // ROOT_VISUAL — TrueColor + // Preserve the IDs of the two double-buffered configurations while + // dropping the ambiguous single-buffered 0x102 and 0x104 entries. + (0x103_u32, 0x103_u32, 8_u32, 32_u32, 8_u32), // ARGB_VISUAL — TrueColor RGBA + ( + crate::resources::GLMARK_VISUAL.0, + 0x105_u32, + 8_u32, + 32_u32, + 0_u32, + ), + ] { + let mut config = vec![ + (g::GLX_VISUAL_ID, visual_id), + (g::GLX_FBCONFIG_ID, fbconfig_id), + (g::GLX_X_VISUAL_TYPE, g::GLX_TRUE_COLOR), + // PBUFFER_BIT is load-bearing for Chromium/ANGLE: it allocates + // its offscreen GL surface as a pbuffer and filters configs on + // this bit. Without it ANGLE's HW GL init fails and Chromium + // drops to SwiftShader (no WebGL accel → no Maps 3D). Firefox + // uses window surfaces and is unaffected either way. (#96) + ( + g::GLX_DRAWABLE_TYPE, + g::GLX_WINDOW_BIT | g::GLX_PIXMAP_BIT | g::GLX_PBUFFER_BIT, + ), + (g::GLX_RENDER_TYPE, g::GLX_RGBA_BIT), + (g::GLX_X_RENDERABLE, 1), + (g::GLX_BUFFER_SIZE, total_buffer_size), + (g::GLX_LEVEL, 0), + (g::GLX_DOUBLEBUFFER, 1), + (g::GLX_STEREO, 0), + (g::GLX_AUX_BUFFERS, 0), + (g::GLX_RED_SIZE, 8), + (g::GLX_GREEN_SIZE, 8), + (g::GLX_BLUE_SIZE, 8), + (g::GLX_ALPHA_SIZE, alpha_size), + (g::GLX_DEPTH_SIZE, depth), + (g::GLX_STENCIL_SIZE, stencil), + (g::GLX_ACCUM_RED_SIZE, 0), + (g::GLX_ACCUM_GREEN_SIZE, 0), + (g::GLX_ACCUM_BLUE_SIZE, 0), + (g::GLX_ACCUM_ALPHA_SIZE, 0), + (g::GLX_CONFIG_CAVEAT, g::GLX_NONE), + (g::GLX_TRANSPARENT_TYPE, g::GLX_NONE), + (g::GLX_SAMPLE_BUFFERS, 0), + (g::GLX_SAMPLES, 0), + // Pbuffer size caps — required alongside PBUFFER_BIT so ANGLE's + // glXGetFBConfigAttrib(GLX_MAX_PBUFFER_*) validation passes. + // 16384 comfortably exceeds any browser offscreen surface + // (ANGLE's init pbuffer is 1×1). Not compared by driConfigEqual. + (g::GLX_MAX_PBUFFER_WIDTH, 16384), + (g::GLX_MAX_PBUFFER_HEIGHT, 16384), + (g::GLX_MAX_PBUFFER_PIXELS, 16384 * 16384), + ]; + // Append bind-to-texture pairs in Xorg's exact reply order + // (glxcmds.c:1094-1100 / glxdricommon.c:165) when TFP is supported. + // + // These attributes are scalar-compared by mesa's driConfigEqual + // against the client driver's __DRIconfig (attribMap in + // src/glx/dri_common.c), so they MUST match what radeonsi + // advertises or the whole config is rejected and dri3 screen + // creation fails ("No matching fbConfigs or visuals found"). + // HW-verified on bee (radeonsi via Xwayland): every TFP config + // reports BIND_RGB=1, BIND_RGBA=1, and BIND_TARGETS=GLX_DONT_CARE. + // So advertise RGBA=1 for BOTH depths (depth-24 windows are + // opaque; the sample_view forces α=1, so an RGBA bind reads as + // opaque — correct) and DONT_CARE for targets (matches any + // driver target bitmask, as Xwayland itself does). + if tfp_supported { + config.push((g::GLX_BIND_TO_TEXTURE_RGB_EXT, 1)); + config.push((g::GLX_BIND_TO_TEXTURE_RGBA_EXT, 1)); + // MIPMAP: not backed, but pair MUST be present for contract. + config.push((g::GLX_BIND_TO_MIPMAP_TEXTURE_EXT, 0)); + config.push((g::GLX_BIND_TO_TEXTURE_TARGETS_EXT, g::GLX_DONT_CARE)); + // Y_INVERTED in FBConfig = GLX_DONT_CARE (differs from drawable-attributes + // where it is 0/GL_FALSE — do not confuse them; glxcmds.c:1093). + config.push((g::GLX_Y_INVERTED_EXT, g::GLX_DONT_CARE)); + } + out.push(config); + } + // QtWebEngine's GLXHelper chooses a single-buffered RGBA pixmap config + // before importing a native DMA-BUF through DRI3 (#152). Do not attach it + // to either real visual: #96 showed that Mesa can then pair the + // single-buffered config with a double-buffered window of the same visual, + // making it allocate a fake front buffer. A visual-less, pixmap-only + // config is sufficient for GLXPixmap and cannot be selected for windows + // or pbuffers. Keep the property count uniform: GetFBConfigs encodes one + // count for the whole reply. + let mut native_pixmap = out[0].clone(); + for (attribute, value) in &mut native_pixmap { + match *attribute { + g::GLX_VISUAL_ID => *value = 0, + g::GLX_FBCONFIG_ID => *value = 0x104, + g::GLX_X_VISUAL_TYPE => *value = g::GLX_NONE, + g::GLX_DRAWABLE_TYPE => *value = g::GLX_PIXMAP_BIT, + g::GLX_X_RENDERABLE => *value = 0, + g::GLX_DOUBLEBUFFER => *value = 0, + _ => {} + } + } + out.push(native_pixmap); + out +} + +pub(super) fn handle_glx_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, glx as x11glx}; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + match minor { + x11glx::QUERY_VERSION => { + let (cmaj, cmin) = x11glx::parse_query_version(body).unwrap_or((0, 0)); + let major = cmaj.min(x11glx::MAJOR_VERSION); + let minor = cmin.min(x11glx::MINOR_VERSION); + debug!( + "client {} #{} GLX::QueryVersion client={cmaj}.{cmin} -> {major}.{minor}", + client_id.0, sequence.0 + ); + let reply = x11glx::encode_query_version_reply(byte_order, sequence, major, minor); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::QUERY_SERVER_STRING => { + let req = x11glx::parse_query_server_string(body); + let name = req.map_or(0, |r| r.name); + // Build the extension string lazily so we only pay the + // allocation cost when the client actually asks for it. + let ext_string; + let s: &str = match name { + x11glx::STRING_VENDOR => "yserver", + x11glx::STRING_VERSION => "1.4", + x11glx::STRING_EXTENSIONS => { + ext_string = glx_extension_string(state.glx_tfp_supported); + &ext_string + } + // libglvnd vendor-neutral dispatch: tells the client which + // libGLX_.so drives this screen. Resolved once at + // startup from the render driver + // (`BackendCapabilities::from_backend`); every non-NVIDIA + // driver keeps `VENDOR_NAMES` ("mesa"), which is what stops + // libglvnd from falling back to a vendor that resolves to + // nothing on Asahi → NULL glXQueryExtensionsString → cogl + // SIGSEGV. Only queried because we advertise + // GLX_EXT_libglvnd. + x11glx::VENDOR_NAMES_EXT => &state.glx_vendor_names, + _ => "", + }; + debug!( + "client {} #{} GLX::QueryServerString name={name:#x} -> {s:?}", + client_id.0, sequence.0 + ); + let reply = x11glx::encode_string_reply(byte_order, sequence, s); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::QUERY_EXTENSIONS_STRING => { + // Per design §3.5 — list of GLX extensions Mesa probes for. + // Same list as the server string (opcode 19) — see + // `x11glx::SERVER_EXTENSIONS`. + let ext_string = glx_extension_string(state.glx_tfp_supported); + let reply = x11glx::encode_string_reply(byte_order, sequence, &ext_string); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::CLIENT_INFO | x11glx::SET_CLIENT_INFO_ARB | x11glx::SET_CLIENT_INFO_2_ARB => { + // Drop on the floor — Mesa sends one of these on connect + // carrying its GL/GLX/GLES versions; we don't act on them. + debug!( + "client {} #{} GLX::ClientInfo* minor={} body_len={}", + client_id.0, + sequence.0, + minor, + body.len() + ); + } + x11glx::IS_DIRECT => { + // Xorg answers the context's recorded isDirect and + // GLXBadContext for an XID that is not a context + // (glxcmds.c:702-726, glx/vnd_dispatch_stubs.c:509-525). Mesa's + // glXImportContextEXT sends this first and returns NULL for a + // direct context without ever sending QueryContext. + let context = match glx_request_context(state, body) { + Ok(context) => context, + Err((code, value)) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + }; + let is_direct = state.glx_contexts[&context].is_direct; + let reply = x11glx::encode_is_direct_reply(byte_order, sequence, is_direct); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::GET_FB_CONFIGS => { + // Synthesise FBConfigs from each X visual × singleBuf / + // doubleBuf. Mesa picks one matching the app's request + // via glXChooseFBConfig. + let configs = synthesise_glx_fb_configs(state.glx_tfp_supported); + let config_refs: Vec<&[(u32, u32)]> = configs.iter().map(|c| c.as_slice()).collect(); + let reply = x11glx::encode_get_fb_configs_reply(byte_order, sequence, &config_refs); + debug!( + "client {} #{} GLX::GetFBConfigs -> {} configs × {} props", + client_id.0, + sequence.0, + config_refs.len(), + config_refs.first().map_or(0, |c| c.len()), + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::GET_VISUAL_CONFIGS => { + // Synthesise GLX visual configs from the X visuals our + // setup-reply advertises. Mesa's `glx_screen_init` calls + // `getVisualConfigs` *before* `getFBConfigs` and bails the + // entire DRI3 screen creation if we hand back zero + // visuals — even though FBConfigs would otherwise carry + // the same info. So we always emit at least one visual. + let visuals = synthesise_glx_visual_configs(); + let reply = x11glx::encode_get_visual_configs_reply(byte_order, sequence, &visuals); + debug!( + "client {} #{} GLX::GetVisualConfigs -> {} visuals", + client_id.0, + sequence.0, + visuals.len(), + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::CREATE_CONTEXT + | x11glx::CREATE_NEW_CONTEXT + | x11glx::CREATE_CONTEXT_ATTRIBS_ARB => { + // Allocate a GlxContext resource keyed by the client-chosen + // XID. We never execute server-side GL; the recorded config, + // share list, render type and isDirect flag are what + // QueryContext / IsDirect report back (Xorg DoCreateContext + // stores the same fields, glxcmds.c:318-325). + let Some(req) = x11glx::parse_create_context(minor, body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + crate::nested::GLX_MAJOR_OPCODE, + ); + }; + let (visual_id, fbconfig) = match req.config { + x11glx::ContextConfigRef::Visual(visual) => { + (visual, glx_visual_fbconfig(visual).unwrap_or(0)) + } + x11glx::ContextConfigRef::FbConfig(fbconfig) => { + (glx_fbconfig_visual(fbconfig), fbconfig) + } + }; + state.glx_contexts.insert( + req.context, + crate::server::GlxContext { + owner: client_id, + screen: req.screen, + visual_id, + fbconfig, + render_type: req.render_type, + share_list: req.share_list, + is_direct: req.is_direct, + }, + ); + debug!( + "client {} #{} GLX::CreateContext minor={minor} xid=0x{:x} fbconfig=0x{:x} \ + visual=0x{visual_id:x} share=0x{:x} direct={}", + client_id.0, sequence.0, req.context, fbconfig, req.share_list, req.is_direct + ); + } + x11glx::DESTROY_CONTEXT => { + let xid = if body.len() >= 4 { + u32::from_le_bytes([body[0], body[1], body[2], body[3]]) + } else { + 0 + }; + state.glx_contexts.remove(&xid); + debug!( + "client {} #{} GLX::DestroyContext xid=0x{:x}", + client_id.0, sequence.0, xid + ); + } + x11glx::MAKE_CURRENT | x11glx::MAKE_CONTEXT_CURRENT => { + // MakeCurrent is a *round-trip* request — Mesa's + // `glXMakeCurrent` blocks on the contextTag in the reply + // and labels every subsequent indirect rendering request + // with it. Direct-rendering clients only use the tag for + // dispatch identification, but the reply is still + // mandatory; without it libxcb stalls. + // + // The new context XID sits at a minor-specific offset + // (glxproto.h:225-233, :471-481), body-relative: + // minor 5 MakeCurrent: drawable, context, oldContextTag + // minor 26 MakeContextCurrent: oldContextTag, drawable, + // readdrawable, context + let context = if minor == x11glx::MAKE_CURRENT { + body.get(4..8) + } else { + body.get(12..16) + } + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .unwrap_or(0); + // The release form (context == None) returns contextTag = 0 — + // tag 0 is reserved by the protocol to mean "no context + // current" (server.rs documents this; Xorg vndcmds.c:232-234, + // :271-273). A malformed/short body also releases. + let tag = if context == 0 { + 0 + } else { + let tag = state.glx_next_context_tag; + state.glx_next_context_tag = state.glx_next_context_tag.wrapping_add(1).max(1); + tag + }; + let reply = x11glx::encode_make_current_reply(byte_order, sequence, tag); + debug!( + "client {} #{} GLX::MakeCurrent -> contextTag={tag}", + client_id.0, sequence.0 + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::WAIT_GL | x11glx::WAIT_X => { + // No-op for direct contexts. + debug!( + "client {} #{} GLX::Wait{}", + client_id.0, + sequence.0, + if minor == x11glx::WAIT_GL { "GL" } else { "X" } + ); + } + x11glx::CREATE_WINDOW | x11glx::CREATE_PIXMAP => { + let parsed = x11glx::parse_create_glx_window(body); + if let Some(req) = parsed { + // For CREATE_PIXMAP: validate the X pixmap exists. + // CREATE_WINDOW wraps an X window XID, which we don't + // validate here (windows have a different resource type). + if minor == x11glx::CREATE_PIXMAP + && state + .resources + .pixmap(yserver_protocol::x11::ResourceId(req.x_window)) + .is_none() + { + debug!( + "client {} #{} GLX::CreatePixmap glx_xid=0x{:x} \ + x_pixmap=0x{:x} not found -> GLXBadPixmap", + client_id.0, sequence.0, req.glx_window, req.x_window + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP, + req.x_window, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + + if minor == x11glx::CREATE_PIXMAP { + insert_glx_pixmap_record( + state, + backend, + client_id, + req.glx_window, + req.x_window, + req.fbconfig, + x11glx::GLX_TEXTURE_2D_EXT, + ); + } else { + state.glx_drawables.insert( + req.glx_window, + crate::server::GlxDrawable { + owner: client_id, + kind: crate::server::GlxDrawableKind::Window, + x_drawable: req.x_window, + fbconfig: req.fbconfig, + width: 0, + height: 0, + event_mask: 0, + glx_export_host_xid: None, + texture_target: x11glx::GLX_TEXTURE_2D_EXT, + }, + ); + } + + debug!( + "client {} #{} GLX::CreateDrawable minor={minor} \ + glx_xid=0x{:x} x_drawable=0x{:x} fbconfig=0x{:x}", + client_id.0, sequence.0, req.glx_window, req.x_window, req.fbconfig + ); + } else { + debug!( + "client {} #{} GLX::CreateDrawable minor={minor} (parse failed)", + client_id.0, sequence.0 + ); + } + } + x11glx::CREATE_PBUFFER => { + // Pbuffers have NO parent X drawable and carry their size in + // the request attribs — parse them with the dedicated parser + // (parse_create_glx_window would mis-read the layout). The + // stored width/height are reported back as GLX_WIDTH/GLX_HEIGHT + // from GetDrawableAttributes so Mesa can size the buffer; key + // the record by the pbuffer XID itself (it is its own drawable). + if let Some(req) = x11glx::parse_create_pbuffer(body) { + state.glx_drawables.insert( + req.pbuffer, + crate::server::GlxDrawable { + owner: client_id, + kind: crate::server::GlxDrawableKind::Pbuffer, + x_drawable: req.pbuffer, + fbconfig: req.fbconfig, + width: req.width, + height: req.height, + event_mask: 0, + glx_export_host_xid: None, + texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, + }, + ); + // #96 tier-2: back the pbuffer with a real GPU pixmap under its + // own XID, so DRI3 BuffersFromPixmap can export a dmabuf for it. + // ANGLE (Chromium) renders WebGL into this surface; with no BO + // it gets BadDrawable and WebGL produces nothing → Google Maps + // hides the 3D button. Depth comes from the fbconfig's visual. + let depth = glx_fbconfig_depth(req.fbconfig); + let pw = u16::try_from(req.width).unwrap_or(1).max(1); + let ph = u16::try_from(req.height).unwrap_or(1).max(1); + match backend.create_pixmap(origin, depth, pw, ph) { + Ok(handle) => { + state.resources.create_pixmap( + client_id, + x11::CreatePixmapRequest { + depth, + pixmap: ResourceId(req.pbuffer), + drawable: ROOT_WINDOW, + width: pw, + height: ph, + }, + ); + let updated = state + .resources + .set_pixmap_host_xid(ResourceId(req.pbuffer), handle); + debug_assert!(updated, "pbuffer backing pixmap was just inserted"); + } + Err(err) => log::warn!( + "client {} #{} GLX::CreatePbuffer host pixmap alloc failed: {err}", + client_id.0, + sequence.0 + ), + } + debug!( + "client {} #{} GLX::CreatePbuffer pbuffer=0x{:x} \ + fbconfig=0x{:x} {}x{}", + client_id.0, sequence.0, req.pbuffer, req.fbconfig, req.width, req.height + ); + } else { + debug!( + "client {} #{} GLX::CreatePbuffer (parse failed)", + client_id.0, sequence.0 + ); + } + } + x11glx::CREATE_GLX_PIXMAP => { + // GLX 1.0 glXCreateGLXPixmap: the visual-based counterpart of + // CreatePixmap. Checks run in Xorg's order — GLXVND's + // dispatch_CreateGLXPixmap (size, LEGAL_NEW_RESOURCE, screen → + // BadMatch; glx/vnd_dispatch_stubs.c:143-169), then + // __glXDisp_CreateGLXPixmap (visual → BadValue) and + // DoCreateGLXPixmap (dixLookupDrawable → BadDrawable, a window → + // BadPixmap; glxcmds.c:1198-1220, :1267-1280). Xorg compares + // neither the pixmap depth nor its visual with the config. + let glx_error = |state: &mut ServerState, code: u8, value: u32| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + crate::nested::GLX_MAJOR_OPCODE, + ) + }; + let Some(req) = x11glx::parse_create_glx_pixmap(body) else { + return glx_error(state, x11::error::BAD_LENGTH, 0); + }; + let owned = state.clients.get(&client_id.0).is_some_and(|c| { + crate::server::IdAllocator::validate_owned( + req.glx_pixmap, + c.resource_id_base, + c.resource_id_mask, + ) + }); + if !owned || state.xid_occupied(req.glx_pixmap) { + return glx_error(state, x11::error::BAD_ID_CHOICE, req.glx_pixmap); + } + // yserver has exactly one screen (screenInfo.numScreens == 1). + if req.screen != 0 { + return glx_error(state, x11::error::BAD_MATCH, req.screen); + } + let Some(fbconfig) = glx_visual_fbconfig(req.visual) else { + return glx_error(state, x11::error::BAD_VALUE, req.visual); + }; + if state.resources.pixmap(ResourceId(req.pixmap)).is_none() { + let code = if state.resources.window(ResourceId(req.pixmap)).is_some() { + x11::error::BAD_PIXMAP + } else { + x11::error::BAD_DRAWABLE + }; + return glx_error(state, code, req.pixmap); + } + // Xorg never runs determineTextureTarget for the GLX 1.0 form, + // so the target stays 0 and GetDrawableAttributes reports + // GLX_TEXTURE_RECTANGLE_EXT (glxcmds.c:1896-1897). + insert_glx_pixmap_record( + state, + backend, + client_id, + req.glx_pixmap, + req.pixmap, + fbconfig, + x11glx::GLX_TEXTURE_RECTANGLE_EXT, + ); + debug!( + "client {} #{} GLX::CreateGLXPixmap glx_xid=0x{:x} x_pixmap=0x{:x} \ + visual=0x{:x} fbconfig=0x{fbconfig:x}", + client_id.0, sequence.0, req.glx_pixmap, req.pixmap, req.visual + ); + } + x11glx::DESTROY_GLX_PIXMAP => { + // GLX 1.0 glXDestroyGLXPixmap. Only a live GLX pixmap — created + // by either CreateGLXPixmap or CreatePixmap, which Xorg keeps as + // the same GLX_DRAWABLE_PIXMAP type — may be destroyed; any other + // XID is GLXBadPixmap (glx/vnd_dispatch_stubs.c:189-205, + // glxcmds.c validGlxDrawable / DoDestroyDrawable). + let Some(xid) = x11glx::parse_single_xid(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + crate::nested::GLX_MAJOR_OPCODE, + ); + }; + let is_glx_pixmap = state + .glx_drawables + .get(&xid) + .is_some_and(|d| d.kind == crate::server::GlxDrawableKind::Pixmap); + if !is_glx_pixmap { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + x11glx::ERROR_GLX_BAD_PIXMAP, + xid, + u16::from(minor), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + // Release the export ref through the host xid stored at create + // time, never by re-resolving the X pixmap: it may already be + // freed (see the DESTROY_PIXMAP arm). + if let Some(record) = state.glx_drawables.remove(&xid) + && let Some(host_xid) = record.glx_export_host_xid + { + backend.release_glx_pixmap_export(host_xid); + } + debug!( + "client {} #{} GLX::DestroyGLXPixmap glx_xid=0x{xid:x}", + client_id.0, sequence.0 + ); + } + x11glx::DELETE_WINDOW | x11glx::DESTROY_PIXMAP | x11glx::DESTROY_PBUFFER => { + let xid = if body.len() >= 4 { + u32::from_le_bytes([body[0], body[1], body[2], body[3]]) + } else { + 0 + }; + // For DESTROY_PIXMAP: release the export-lifetime ref taken at + // CREATE_PIXMAP, using the host_xid resolved+stored at acquire + // time. Do NOT re-resolve via resources.pixmap(x_drawable) — the + // X pixmap may already be freed (FreePixmap-before-destroy), and + // re-resolution would return None and leak the ref forever. + let release_host_xid = if minor == x11glx::DESTROY_PIXMAP { + state + .glx_drawables + .get(&xid) + .and_then(|d| d.glx_export_host_xid) + } else { + None + }; + if let Some(host_xid) = release_host_xid { + backend.release_glx_pixmap_export(host_xid); + } + state.glx_drawables.remove(&xid); + // #96 tier-2: release the GPU pixmap that backed a pbuffer (allocated + // at CreatePbuffer under the pbuffer's own XID). + if minor == x11glx::DESTROY_PBUFFER + && let Some(pixmap) = state.resources.free_pixmap(ResourceId(xid)) + && let Some(host) = pixmap.host_xid + { + backend.free_pixmap(origin, host.as_raw())?; + } + debug!( + "client {} #{} GLX::DestroyDrawable minor={minor} glx_xid=0x{:x}", + client_id.0, sequence.0, xid + ); + } + x11glx::CHANGE_DRAWABLE_ATTRIBUTES => { + // body: [glx_drawable: u32][num_attribs: u32][attribs * (id, value)] + if body.len() >= 8 { + let xid = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + let num_attribs = u32::from_le_bytes([body[4], body[5], body[6], body[7]]) as usize; + if let Some(drawable) = state.glx_drawables.get_mut(&xid) { + // Xorg's ChangeDrawableAttributes is a switch with a + // single case: record GLX_EVENT_MASK, silently ignore + // everything else (glxcmds.c:1494-1503). + let mut p = 8; + for _ in 0..num_attribs { + if p + 8 > body.len() { + break; + } + let id = + u32::from_le_bytes([body[p], body[p + 1], body[p + 2], body[p + 3]]); + let val = u32::from_le_bytes([ + body[p + 4], + body[p + 5], + body[p + 6], + body[p + 7], + ]); + if id == x11glx::GLX_EVENT_MASK { + drawable.event_mask = val; + } + p += 8; + } + } + debug!( + "client {} #{} GLX::ChangeDrawableAttributes glx_xid=0x{:x} n={num_attribs}", + client_id.0, sequence.0, xid + ); + } + } + x11glx::GET_DRAWABLE_ATTRIBUTES => { + // body: [glx_drawable: u32]. Mirrors Xorg's four-way + // behaviour, where GLXVND is the front door: a registered + // GLX drawable gets the full reply; a naked X window (the + // GLX 1.2 pattern — Mesa's `pixmap_from_buffer` + + // `glXMakeCurrent(window, ctx)` queries the X window XID + // directly) gets the reply without the pGlxDraw block; a + // naked X pixmap is forwarded by GLXVND (pixmaps carry + // RC_DRAWABLE) but fails dixLookupWindow → GLXBadDrawable; + // an XID that is not a drawable at all never reaches + // DoGetDrawableAttributes → core BadDrawable + // (glx/vnd_dispatch_stubs.c:456-472, glxcmds.c:1873-1880). + let xid = if body.len() >= 4 { + u32::from_le_bytes([body[0], body[1], body[2], body[3]]) + } else { + 0 + }; + if !state.glx_drawables.contains_key(&xid) + && state.resources.window(ResourceId(xid)).is_none() + { + if state.resources.pixmap(ResourceId(xid)).is_some() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + x11glx::ERROR_GLX_BAD_DRAWABLE, + xid, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + xid, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + let attribs = drawable_attributes_for(state, xid); + let reply = + x11glx::encode_get_drawable_attributes_reply(byte_order, sequence, &attribs); + debug!( + "client {} #{} GLX::GetDrawableAttributes glx_xid=0x{:x} -> {} attribs", + client_id.0, + sequence.0, + xid, + attribs.len() + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::SWAP_BUFFERS => { + // Direct-rendering clients route swaps through DRI3 + + // Present, never through indirect GLX SwapBuffers. Indirect + // clients hitting this path can't be served (no server-side + // GL), but a no-op (rather than an error) keeps silly + // clients limping along. + debug!( + "client {} #{} GLX::SwapBuffers (no-op)", + client_id.0, sequence.0 + ); + } + x11glx::QUERY_CONTEXT => { + // GLX 1.3 QueryContext, the request behind + // glXImportContextEXT (GLX_EXT_import_context, which, like Xorg + // without +iglx, we do not advertise). Xorg's DoQueryContext reports five + // attributes, in this order, for a live context of ANY client + // (glxcmds.c:1659-1708); an XID that is not a context is + // GLXBadContext (glx/vnd_dispatch_stubs.c:492-508). + let context = match glx_request_context(state, body) { + Ok(context) => context, + Err((code, value)) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + }; + let ctx = &state.glx_contexts[&context]; + let attribs = [ + (x11glx::GLX_SHARE_CONTEXT_EXT, ctx.share_list), + (x11glx::GLX_VISUAL_ID, ctx.visual_id), + (x11glx::GLX_SCREEN, ctx.screen), + (x11glx::GLX_FBCONFIG_ID, ctx.fbconfig), + (x11glx::GLX_RENDER_TYPE, ctx.render_type), + ]; + let reply = x11glx::encode_query_context_reply(byte_order, sequence, &attribs); + debug!( + "client {} #{} GLX::QueryContext 0x{context:x} -> {attribs:x?}", + client_id.0, sequence.0 + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::VENDOR_PRIVATE | x11glx::VENDOR_PRIVATE_WITH_REPLY => { + // Dispatch known vendor codes; reject everything else with + // GLXUnsupportedPrivateRequest (modern Mesa direct-rendering + // never reaches this path). + // + // VendorPrivate body layout: + // [0..4] vendor_code (u32 LE) + // [4..8] context_tag (u32 LE, informational) + // [8..12] glx_drawable (u32 LE, GLXPixmap XID) + // [12..16] buffer (u32 LE, e.g. GLX_FRONT_LEFT_EXT) + let vendor_code = if body.len() >= 4 { + u32::from_le_bytes([body[0], body[1], body[2], body[3]]) + } else { + 0 + }; + match vendor_code { + x11glx::VENDOR_CODE_BIND_TEX_IMAGE => { + // glXBindTexImageEXT (indirect path, EXT completeness). + // Direct-context compositors (muffin) ride DRI3 and never + // hit this. For indirect contexts: resolve the GLXPixmap to + // its underlying X pixmap, ensure it is export-promoted + // (so any indirect GL texture sampling reads live content), + // and return success. BindTexImageEXT has no reply. + let glx_drawable = if body.len() >= 12 { + u32::from_le_bytes([body[8], body[9], body[10], body[11]]) + } else { + 0 + }; + debug!( + "client {} #{} GLX::BindTexImageEXT glx_drawable=0x{glx_drawable:x}", + client_id.0, sequence.0 + ); + if let Some(d) = state.glx_drawables.get(&glx_drawable) { + let x_drawable = d.x_drawable; + let stored_host_xid = d.glx_export_host_xid; + let current_host_xid = state + .resources + .pixmap(yserver_protocol::x11::ResourceId(x_drawable)) + .and_then(|p| p.host_xid.map(|h| h.as_raw())); + let host_xid_for_export = current_host_xid.or(stored_host_xid); + if let Some(current_host_xid) = current_host_xid + && stored_host_xid != Some(current_host_xid) + { + retarget_glx_pixmap_export( + state, + backend, + glx_drawable, + current_host_xid, + ); + } + // Ensure the backing is promoted to exportable storage so + // indirect GL texture sampling can read live content. + // + // CRITICAL: use promote_pixmap_exportable, NOT + // acquire_glx_pixmap_export. Bind is decoupled from the + // GLXPixmap LIFETIME refcount (glx_refs): TFP compositors + // rebind every frame / on damage (the spec allows rebind + // without an intervening release), so calling acquire here + // would grow glx_refs unboundedly and the backing would + // never tear down after glXDestroyPixmap. promote is + // idempotent (the engine short-circuits via is_exportable) + // and touches no refcount. The backing is already kept + // alive by glXCreatePixmap's acquire (glx_refs >= 1 until + // glXDestroyPixmap). + // + // TODO(glx-tfp): indirect texture *sampling* (serving + // glTexImage2D-equivalent data from the promoted backing) + // is not yet implemented; the bind succeeds so clients + // do not receive a protocol error, but the texture + // content will not be updated until indirect GL sampling + // is wired up. + if let Some(host_xid) = host_xid_for_export { + let _ = backend.promote_pixmap_exportable(host_xid); + } + // No reply for VENDOR_PRIVATE; for VENDOR_PRIVATE_WITH_REPLY + // send an empty success reply so the client does not block. + if minor == x11glx::VENDOR_PRIVATE_WITH_REPLY { + let reply = x11glx::encode_get_drawable_attributes_reply( + byte_order, + sequence, + &[], + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + } else { + debug!( + "client {} #{} GLX::BindTexImageEXT \ + glx_drawable=0x{glx_drawable:x} not found -> GLXBadPixmap", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP, + glx_drawable, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + } + x11glx::VENDOR_CODE_GET_FB_CONFIGS_SGIX => { + // glXGetFBConfigsSGIX (VendorPrivateWithReply, vendor + // code 65540). Proxied to synthesise_glx_fb_configs + // and encoded with the GLX 1.3 GetFBConfigsReply wire + // format — glxproto.h defines no separate SGIX reply + // struct; the extension reuses the same layout. + // + // Request body: + // [0..4] vendorCode (already read) + // [4..8] pad1 + // [8..12] screen — intentionally ignored (yserver is + // single-screen; configs are valid for any screen, + // same as the GLX 1.3 GET_FB_CONFIGS handler). + // GetFBConfigsSGIX is a reply-bearing call; if a malformed + // client sends it as plain VENDOR_PRIVATE (no reply expected) + // do NOT write a reply, or we desync its reply stream. + if minor != x11glx::VENDOR_PRIVATE_WITH_REPLY { + return Ok(RequestOutcome::Handled); + } + let configs = synthesise_glx_fb_configs(state.glx_tfp_supported); + let config_refs: Vec<&[(u32, u32)]> = + configs.iter().map(|c| c.as_slice()).collect(); + let reply = x11glx::encode_get_fb_configs_sgix_reply( + byte_order, + sequence, + &config_refs, + ); + debug!( + "client {} #{} GLX::GetFBConfigsSGIX -> {} configs × {} props", + client_id.0, + sequence.0, + config_refs.len(), + config_refs.first().map_or(0, |c| c.len()), + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11glx::VENDOR_CODE_CREATE_CONTEXT_WITH_CONFIG_SGIX => { + // glXCreateContextWithConfigSGIX (VendorPrivate, no + // reply, vendor code 65541). Proxied to the existing + // context-creation logic: insert a GlxContext record. + // + // Request body: + // [0..4] vendorCode + // [4..8] pad1 + // [8..12] context XID + // [12..16] fbconfig + // [16..20] screen + // [20..24] renderType + // [24..28] shareList + // [28] isDirect + // [29..32] reserved + if let Some(req) = x11glx::parse_create_context_with_config_sgix(body) { + state.glx_contexts.insert( + req.context, + crate::server::GlxContext { + owner: client_id, + screen: req.screen, + visual_id: glx_fbconfig_visual(req.fbconfig), + fbconfig: req.fbconfig, + render_type: req.render_type, + share_list: req.share_list, + is_direct: req.is_direct, + }, + ); + debug!( + "client {} #{} GLX::CreateContextWithConfigSGIX \ + xid=0x{:x} fbconfig=0x{:x}", + client_id.0, sequence.0, req.context, req.fbconfig + ); + } else { + debug!( + "client {} #{} GLX::CreateContextWithConfigSGIX \ + (body too short, parse failed)", + client_id.0, sequence.0 + ); + } + } + x11glx::VENDOR_CODE_CREATE_GLX_PIXMAP_WITH_CONFIG_SGIX => { + // glXCreateGLXPixmapWithConfigSGIX (VendorPrivate, no + // reply, vendor code 65542). Proxied to the existing + // CREATE_PIXMAP path: validate X pixmap, record the + // GlxDrawable, call acquire_glx_pixmap_export. + // + // Request body: + // [0..4] vendorCode + // [4..8] pad1 + // [8..12] screen + // [12..16] fbconfig + // [16..20] pixmap (X pixmap XID) + // [20..24] glxpixmap (GLXPixmap XID) + if let Some(req) = x11glx::parse_create_glx_pixmap_with_config_sgix(body) { + // Validate that the X pixmap exists. + if state + .resources + .pixmap(yserver_protocol::x11::ResourceId(req.pixmap)) + .is_none() + { + debug!( + "client {} #{} GLX::CreateGLXPixmapWithConfigSGIX \ + glx_xid=0x{:x} x_pixmap=0x{:x} not found -> GLXBadPixmap", + client_id.0, sequence.0, req.glx_pixmap, req.pixmap + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP, + req.pixmap, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + insert_glx_pixmap_record( + state, + backend, + client_id, + req.glx_pixmap, + req.pixmap, + req.fbconfig, + x11glx::GLX_TEXTURE_2D_EXT, + ); + + debug!( + "client {} #{} GLX::CreateGLXPixmapWithConfigSGIX \ + glx_xid=0x{:x} x_pixmap=0x{:x} fbconfig=0x{:x}", + client_id.0, sequence.0, req.glx_pixmap, req.pixmap, req.fbconfig + ); + } else { + debug!( + "client {} #{} GLX::CreateGLXPixmapWithConfigSGIX \ + (body too short, parse failed)", + client_id.0, sequence.0 + ); + } + } + x11glx::VENDOR_CODE_RELEASE_TEX_IMAGE => { + // glXReleaseTexImageEXT (indirect path, EXT completeness). + // + // CRITICAL: this is a LIFETIME no-op. It must NOT call + // release_glx_pixmap_export — that decrements the + // GLXPixmap's create-time lifetime ref (glx_refs), which + // glXDestroyPixmap owns. A release without a matching bind + // (or more releases than binds) would drive glx_refs to 0 + // and tear down the backing WHILE THE GLXPixmap IS STILL + // ALIVE. Release only ends the texture binding; since bind + // is promote-only (no refcount taken), there is nothing to + // undo here. The promoted storage stays promoted (cheap, + // and a likely-imminent rebind reuses it). Unknown GLXPixmap + // XIDs are silently ignored (no error — matches Xorg + // glx/glxcmds.c behaviour for stale release after destroy). + let glx_drawable = if body.len() >= 12 { + u32::from_le_bytes([body[8], body[9], body[10], body[11]]) + } else { + 0 + }; + debug!( + "client {} #{} GLX::ReleaseTexImageEXT glx_drawable=0x{glx_drawable:x} \ + (lifetime no-op)", + client_id.0, sequence.0 + ); + // No reply for VENDOR_PRIVATE; for VENDOR_PRIVATE_WITH_REPLY + // send an empty success reply. + if minor == x11glx::VENDOR_PRIVATE_WITH_REPLY { + let reply = + x11glx::encode_get_drawable_attributes_reply(byte_order, sequence, &[]); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + } + _ => { + // All other vendor codes are unsupported. + debug!( + "client {} #{} GLX::VendorPrivate \ + vendor_code={vendor_code} (rejected: GLXUnsupportedPrivateRequest)", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + + yserver_protocol::x11::glx::ERROR_GLX_UNSUPPORTED_PRIVATE_REQUEST, + 0, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + } + } + other => { + // Indirect-rendering opcodes 1..=198 + anything else we + // don't handle → GLXBadRequest. + debug!( + "client {} #{} GLX unsupported minor={other} -> GLXBadRequest", + client_id.0, sequence.0 + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::GLX_FIRST_ERROR + + yserver_protocol::x11::glx::ERROR_GLX_BAD_RENDER_REQUEST, + 0, + u16::from(header.data), + crate::nested::GLX_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// Record a GLXPixmap over the (already validated) X pixmap `x_pixmap` and +/// take its export-lifetime ref — the one resource model behind GLX 1.0 +/// `CreateGLXPixmap`, GLX 1.3 `CreatePixmap` and +/// `CreateGLXPixmapWithConfigSGIX`, as Xorg funnels all three through +/// `DoCreateGLXPixmap` (glxcmds.c:1198-1220). +/// +/// The host xid is resolved NOW and stored on the record so release is +/// robust to the X pixmap being freed (X11 `FreePixmap`) before the GLX +/// destroy / disconnect — re-resolving `x_drawable → host_xid` at release +/// time would fail once the resource is gone, leaking the ref forever. The +/// ref keeps the `ExportedBacking` entry (and its dmabuf fd) alive past an +/// early `FreePixmap`, the counterpart of Xorg's `pixmap->refcnt++`. +fn insert_glx_pixmap_record( + state: &mut ServerState, + backend: &mut dyn Backend, + owner: ClientId, + glx_pixmap: u32, + x_pixmap: u32, + fbconfig: u32, + texture_target: u32, +) { + let acquire_host_xid = state + .resources + .pixmap(ResourceId(x_pixmap)) + .and_then(|p| p.host_xid.map(|h| h.as_raw())); + state.glx_drawables.insert( + glx_pixmap, + crate::server::GlxDrawable { + owner, + kind: crate::server::GlxDrawableKind::Pixmap, + x_drawable: x_pixmap, + fbconfig, + width: 0, + height: 0, + event_mask: 0, + glx_export_host_xid: acquire_host_xid, + texture_target, + }, + ); + if let Some(host_xid) = acquire_host_xid { + backend.acquire_glx_pixmap_export(host_xid); + } +} + +/// The context XID of a `QueryContext` / `IsDirect` request, or the error +/// Xorg sends: `BadLength` for a body that is not exactly one XID +/// (`REQUEST_SIZE_MATCH`), `GLXBadContext` with the XID as bad value when +/// it names no live context (glx/vnd_dispatch_stubs.c:492-525). +fn glx_request_context(state: &ServerState, body: &[u8]) -> Result { + use yserver_protocol::x11::glx as g; + let Some(xid) = g::parse_single_xid(body) else { + return Err((x11::error::BAD_LENGTH, 0)); + }; + if state.glx_contexts.contains_key(&xid) { + Ok(xid) + } else { + Err(( + crate::nested::GLX_FIRST_ERROR + g::ERROR_GLX_BAD_CONTEXT, + xid, + )) + } +} + +/// The FBConfig behind a GLX *visual*, or `None` when `visual` is not one +/// of the GLX visuals `GetVisualConfigs` advertises. Mirrors Xorg's +/// `validGlxVisual`, which searches `pGlxScreen->visuals` only — an +/// FBConfig ID, or an X visual without a GLX config, is not a GLX visual +/// (glxcmds.c:90-107). `synthesise_glx_fb_configs` stays the single source +/// of the visual → FBConfig pairing. +pub(super) fn glx_visual_fbconfig(visual: u32) -> Option { + use yserver_protocol::x11::glx as g; + if !synthesise_glx_visual_configs() + .iter() + .any(|v| v.visual_id == visual) + { + return None; + } + synthesise_glx_fb_configs(false).iter().find_map(|cfg| { + cfg.iter() + .any(|(a, v)| *a == g::GLX_VISUAL_ID && *v == visual) + .then(|| { + cfg.iter() + .find(|(a, _)| *a == g::GLX_FBCONFIG_ID) + .map(|(_, v)| *v) + }) + .flatten() + }) +} + +/// The X visual of a synthesised FBConfig (`GLX_VISUAL_ID`), 0 for a +/// visual-less or unknown FBConfig — Xorg's `ctx->config->visualID`. +pub(super) fn glx_fbconfig_visual(fbconfig: u32) -> u32 { + use yserver_protocol::x11::glx as g; + synthesise_glx_fb_configs(false) + .iter() + .find(|cfg| { + cfg.iter() + .any(|(a, v)| *a == g::GLX_FBCONFIG_ID && *v == fbconfig) + }) + .and_then(|cfg| { + cfg.iter() + .find(|(a, _)| *a == g::GLX_VISUAL_ID) + .map(|(_, v)| *v) + }) + .unwrap_or(0) +} + +/// Depth (24 or 32) of a synthesised GLX FBConfig, derived from the X visual +/// it maps to (`ROOT_VISUAL` depth-24 / `ARGB_VISUAL` depth-32) — the single +/// source of truth is `synthesise_glx_fb_configs`, so this stays correct if +/// the config table changes. Defaults to 24 for an unknown fbconfig. +pub(super) fn glx_fbconfig_depth(fbconfig: u32) -> u8 { + use yserver_protocol::x11::glx as g; + synthesise_glx_fb_configs(false) + .iter() + .find(|cfg| { + cfg.iter() + .any(|(a, v)| *a == g::GLX_FBCONFIG_ID && *v == fbconfig) + }) + .and_then(|cfg| { + cfg.iter() + .find(|(a, _)| *a == g::GLX_VISUAL_ID) + .map(|(_, v)| *v) + }) + .map_or(24, |visual| { + if visual == crate::resources::ARGB_VISUAL.0 { + 32 + } else { + 24 + } + }) +} diff --git a/crates/yserver-core/src/core_loop/process_request/grabs.rs b/crates/yserver-core/src/core_loop/process_request/grabs.rs new file mode 100644 index 000000000..e7c891b99 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/grabs.rs @@ -0,0 +1,1814 @@ +use crate::{ + access::{AccessMode, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::Backend, + core_loop::{ + fanout::{emit_window_event_to_state, fanout_event_to_clients}, + key_fanout::replay_frozen_key_to_focus, + pointer_fanout::replay_frozen_pointer_event_to_state, + process_request::{ + RequestOutcome, XI2_MAJOR_OPCODE, emit_x11_error, + focus_pointer::emit_core_focus_transition, write_to_client, + }, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +pub(super) fn handle_allow_events( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + // Core AllowEvents modes (X11 spec): + // 0 AsyncPointer 1 SyncPointer 2 ReplayPointer + // 3 AsyncKeyboard 4 SyncKeyboard 5 ReplayKeyboard + // 6 AsyncBoth 7 SyncBoth + let mode = header.data; + if mode > 7 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mode), + 35, + ); + } + let time = body + .get(0..4) + .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + apply_allow_events(state, backend, client_id, sequence, mode, time) +} + +/// Map an XI2 `XIAllowEvents` mode + registry-classified target onto the +/// equivalent core `AllowSome` mode consumed by [`apply_allow_events`]. The +/// paired modes act on the OTHER device. Touch modes (`XIAcceptTouch`=6 / +/// `XIRejectTouch`=7) and anything unknown are unsupported → `None` (no-op). +/// XI2 mode constants per `X11/extensions/XI2.h`: AsyncDevice=0, +/// SyncDevice=1, ReplayDevice=2, AsyncPairedDevice=3, AsyncPair=4, +/// SyncPair=5. +pub(super) fn xi2_allow_mode_to_core(xi2_mode: u8, kbd: bool) -> Option { + // Core modes: 0 AsyncPointer 1 SyncPointer 2 ReplayPointer + // 3 AsyncKeyboard 4 SyncKeyboard 5 ReplayKeyboard + // 6 AsyncBoth 7 SyncBoth + Some(match xi2_mode { + 0 => u8::from(kbd) * 3, // XIAsyncDevice → Async{Pointer,Keyboard} + 1 => 1 + u8::from(kbd) * 3, // XISyncDevice → Sync{Pointer,Keyboard} + 2 => 2 + u8::from(kbd) * 3, // XIReplayDevice → Replay{Pointer,Keyboard} + 3 => u8::from(!kbd) * 3, // XIAsyncPairedDevice → async the PAIRED device + 4 => 6, // XIAsyncPair → AsyncBoth + 5 => 7, // XISyncPair → SyncBoth + _ => return None, // XIAcceptTouch / XIRejectTouch / unknown + }) +} + +/// XI2 AllowEvents for a slave device uses the exact device's freeze state; +/// paired modes use the opposite master returned by the registry attachment. +pub(super) fn apply_xi2_allow_events_for_slave( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + device_id: u16, + is_keyboard: bool, + xi_mode: u8, + time: u32, +) -> io::Result { + use crate::server::Xi1SyncState; + + if xi_mode > 5 { + return Ok(RequestOutcome::Handled); + } + let paired_id = crate::core_loop::pointer_fanout::xi1_other_input_device(state, device_id); + let target_id = if xi_mode == 3 { + let Some(paired_id) = paired_id else { + return Ok(RequestOutcome::Handled); + }; + paired_id + } else { + device_id + }; + let target_owner = crate::core_loop::pointer_fanout::xi1_device_grab_owner(state, target_id); + let target_state = state + .xi1_frozen + .get(&target_id) + .map_or(Xi1SyncState::Thawed, |freeze| freeze.state); + let target_other = state + .xi1_frozen + .get(&target_id) + .and_then(|freeze| freeze.other); + let is_frozen_by_client = target_owner == Some(client_id) + && target_state >= Xi1SyncState::FrozenNoEvent + || target_other == Some(client_id); + if !is_frozen_by_client { + return Ok(RequestOutcome::Handled); + } + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(if is_keyboard { + state.last_keyboard_grab_time + } else { + state.last_pointer_grab_time + }); + if time != 0 && crate::core_loop::xi1_focus::time_after(time, now) { + return Ok(RequestOutcome::Handled); + } + + let mut devices = Vec::with_capacity(2); + match xi_mode { + 0..=2 => devices.push(device_id), + 3 => devices.push(target_id), + 4 | 5 => { + devices.push(device_id); + if let Some(paired_id) = paired_id { + devices.push(paired_id); + } + } + _ => return Ok(RequestOutcome::Handled), + } + let new_state = match xi_mode { + 0 | 3 | 4 => Some(Xi1SyncState::Thawed), + 1 | 5 => Some(Xi1SyncState::FreezeNextEvent), + 2 => Some(Xi1SyncState::Thawed), + _ => None, + }; + for id in &devices { + if let Some(new_state) = new_state { + let freeze = state.xi1_frozen.entry(*id).or_default(); + freeze.state = new_state; + if freeze.other == Some(client_id) { + freeze.other = None; + } + if matches!(xi_mode, 0 | 3 | 4) { + freeze.stored = None; + } + } + } + + if xi_mode == 2 { + let stored = state + .xi1_frozen + .get_mut(&device_id) + .and_then(|freeze| freeze.stored.take()); + if let Some(crate::server::QueuedInputEvent::HostPointer(_)) = stored { + if let Some(grab) = state.xi2_pointer_grabs.get(&device_id) + && grab.owner == client_id + { + state.xi2_pointer_grabs.remove(&device_id); + state.reattach_xi2_slave(device_id); + } + if let Some(crate::server::QueuedInputEvent::HostPointer(event)) = stored { + let xid_map = backend.xid_map().clone(); + let _dropped = + crate::core_loop::pointer_fanout::replay_frozen_pointer_event_to_state( + state, backend, &xid_map, event, + ); + } + } else if let Some(crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + )) = stored + { + if state + .xi2_keyboard_grabs + .get(&device_id) + .is_some_and(|grab| grab.owner == client_id) + { + state.xi2_keyboard_grabs.remove(&device_id); + state.reattach_xi2_slave(device_id); + } + let _dropped = + crate::core_loop::key_fanout::replay_frozen_key_to_focus_after_transition( + state, + event, + master_transition_accepted, + ); + } else if let Some(crate::server::QueuedInputEvent::HostKey(event)) = stored { + if state + .xi2_keyboard_grabs + .get(&device_id) + .is_some_and(|grab| grab.owner == client_id) + { + state.xi2_keyboard_grabs.remove(&device_id); + state.reattach_xi2_slave(device_id); + } + let _dropped = crate::core_loop::key_fanout::replay_frozen_key_to_focus(state, event); + } + } + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_compute_freezes(state, backend, &xid_map); + debug!( + "client {} #{} XIAllowEvents slave device={} mode={}", + client_id.0, sequence.0, device_id, xi_mode + ); + Ok(RequestOutcome::Handled) +} + +/// Shared `AllowSome` implementation (Xorg `dix/events.c:1823`), driven by +/// BOTH core `AllowEvents` (mode straight from the request) AND XI2 +/// `XIAllowEvents` (mode mapped from the XI2 mode + deviceid; see +/// [`xi2_allow_mode_to_core`]). Routing the XI2 path through here — rather +/// than the old partial reimplementation in the XI2 handler — kills a +/// recurring class of divergence bugs where the XI2 copy mishandled modes +/// the core path got right (the desktop rubber-band = Async/Replay thaw +/// gap; the Cinnamon input freeze = `XISyncDevice`/mode-1 treated as a +/// no-op). `mode` is a CORE AllowEvents mode (0..=7); `time` is the +/// request timestamp. +pub(super) fn apply_allow_events( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + mode: u8, + time: u32, +) -> io::Result { + // Xorg AllowSome: the request is a no-op when its time is LATER + // than the current time or EARLIER than the client's grab time + // (XAllowEvents-12/13). Pointer modes gate on the pointer's grab + // time, keyboard and *Both modes on the keyboard's. + let grab_time = if matches!(mode, 0..=2) { + state.last_pointer_grab_time + } else { + state.last_keyboard_grab_time + }; + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(grab_time); + if time != 0 + && (crate::core_loop::xi1_focus::time_after(time, now) + || crate::core_loop::xi1_focus::time_after(grab_time, time)) + { + debug!( + "client {} #{} AllowEvents ignored (time {time} outside [{grab_time}, {now}])", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + debug!( + "client {} #{} AllowEvents mode={} frozen_pointer={} frozen_keyboard={}", + client_id.0, + sequence.0, + mode, + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .is_some_and(|f| f.stored.is_some()), + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .is_some_and(|f| f.stored.is_some()), + ); + + // Port of Xorg AllowSome (dix/events.c:1823). `thisDev` is the + // pointer for the pointer modes and the keyboard for the keyboard + // and *Both modes; the request is a no-op unless this client's + // grab holds the device frozen, or the device is synced on this + // client's behalf. + use crate::server::Xi1SyncState; + let dev_this = if matches!(mode, 0..=2) { + crate::xinput::DEVICEID_MASTER_POINTER + } else { + crate::xinput::DEVICEID_MASTER_KEYBOARD + }; + let grab_owner_of = |state: &ServerState, dev: u16| -> Option { + crate::core_loop::pointer_fanout::xi1_device_grab_owner(state, dev) + }; + let this_grabbed = grab_owner_of(state, dev_this) == Some(client_id); + let this_state = state + .xi1_frozen + .get(&dev_this) + .map_or(Xi1SyncState::Thawed, |f| f.state); + let this_synced = state.xi1_frozen.get(&dev_this).and_then(|f| f.other) == Some(client_id); + if !((this_grabbed && this_state >= Xi1SyncState::FrozenNoEvent) || this_synced) { + debug!( + "client {} #{} AllowEvents no-op (not frozen by this client: grabbed={this_grabbed} state={this_state:?} synced={this_synced})", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + + let pointer_replay = mode == 2; + let keyboard_replay = mode == 5; + + // State transitions per mode (Xorg AllowSome switch). The queued + // events play AFTER the transition so the freeze gate at fanout + // entry sees the new state: Async → events flow; Sync → + // FreezeNextEvent lets them flow until the next key/button trips + // the re-freeze (FreezeThisEventIfNeededForSyncGrab). + let set_state = |state: &mut ServerState, dev: u16, st: Xi1SyncState| { + let f = state.xi1_frozen.entry(dev).or_default(); + f.state = st; + if f.other == Some(client_id) { + f.other = None; + } + }; + let dev_ptr = crate::xinput::DEVICEID_MASTER_POINTER; + let dev_kbd = crate::xinput::DEVICEID_MASTER_KEYBOARD; + // Xorg AllowSome `othersFrozen`: the *Both modes (AsyncBoth / + // SyncBoth) only act when ANOTHER device this client grabbed is + // itself frozen (dix/events.c:1872, 1886 — `if (othersFrozen)`). + // Without this gate a client could thaw/re-freeze its own device + // via *Both even when no paired device is frozen, leaving later + // grabs in the wrong sync state. In the two-device model "others" + // relative to dev_this (keyboard, for *Both) is the pointer. + let others_frozen = { + let other = if dev_this == dev_kbd { + dev_ptr + } else { + dev_kbd + }; + grab_owner_of(state, other) == Some(client_id) + && state + .xi1_frozen + .get(&other) + .is_some_and(|f| f.state >= Xi1SyncState::FrozenNoEvent) + }; + match mode { + 0 | 2 => set_state(state, dev_ptr, Xi1SyncState::Thawed), + 1 => set_state(state, dev_ptr, Xi1SyncState::FreezeNextEvent), + 3 | 5 => set_state(state, dev_kbd, Xi1SyncState::Thawed), + 4 => set_state(state, dev_kbd, Xi1SyncState::FreezeNextEvent), + 6 if others_frozen => { + // AsyncBoth thaws every device this client's grabs froze. + for dev in [dev_ptr, dev_kbd] { + if grab_owner_of(state, dev) == Some(client_id) + || state.xi1_frozen.get(&dev).and_then(|f| f.other) == Some(client_id) + { + set_state(state, dev, Xi1SyncState::Thawed); + } + } + } + 7 if others_frozen => { + // SyncBoth arms FreezeBothNextEvent on the client's + // grabbed devices. + for dev in [dev_ptr, dev_kbd] { + if grab_owner_of(state, dev) == Some(client_id) + || state.xi1_frozen.get(&dev).and_then(|f| f.other) == Some(client_id) + { + set_state(state, dev, Xi1SyncState::FreezeBothNextEvent); + } + } + } + // *Both with no paired device frozen → no-op (Xorg). + 6 | 7 => {} + _ => {} + } + + // Withheld pointer events. The activating press of a sync passive + // grab was already delivered to the grab owner — only Replay + // re-delivers it (to the natural target, grab bypassed); the + // async/sync releases just drop it. The QUEUE (events that arrived + // during the freeze, delivered to nobody) plays through the normal + // pipeline on every pointer-side release — Xorg + // PlayReleasedEvents; with the grab still active they route to + // the grab owner. + let pointer_side = matches!(mode, 0 | 1 | 2 | 6 | 7); + let frozen_pointer = if pointer_side { + state + .xi1_frozen + .get_mut(&dev_ptr) + .and_then(|f| f.stored.take()) + } else { + None + }; + // NOT_GRABBED (Replay) deactivates a frozen-with-event grab on + // this device — passive AND explicit (Xorg dix/events.c:1898 calls + // DeactivateGrab regardless of grab kind). Async/Sync keep the + // grab until the natural button release. Without the explicit + // branch a GrabPointer(GrabModeSync) replays the frozen event but + // stays active → user-visible stuck grab. + let pointer_has_event = frozen_pointer.is_some(); + if pointer_replay && state.active_pointer_grab.is_some_and(|grab| grab.passive) { + // Xorg `DeactivatePointerGrab` → `DoEnterLeaveEvents(grab + // window → sprite, NotifyUngrab)` (dix/events.c:1711): mirror + // the activation chain emitted in pointer_fanout so the client's + // crossing state rebalances. The subsequent replay (below) + // re-delivers the press to the natural target, matching Xorg's + // ungrab-crossings-then-replayed-press order. Shared with the XI1 + // ReplayThisDevice path. + deactivate_passive_pointer_grab_crossings(state); + } else if pointer_replay + && pointer_has_event + && state + .active_pointer_grab + .is_some_and(|g| g.owner == client_id) + { + deactivate_core_pointer_grab(state, backend, client_id); + } + + let keyboard_side = matches!(mode, 3..=7); + let frozen_keyboard = if keyboard_side { + state + .xi1_frozen + .get_mut(&dev_kbd) + .and_then(|f| f.stored.take()) + } else { + None + }; + // The activating core key was already delivered to the grab owner. Its + // parallel XI1 form can be pending from the device enqueue path; Sync + // must not replay it and consume the allowance intended for the next + // physical key event. + if mode == 4 + && let Some( + crate::server::QueuedInputEvent::HostKey(event) + | crate::server::QueuedInputEvent::HostKeyTransition(event, _), + ) = frozen_keyboard.as_ref() + { + let press_evcode = + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; + if let Some(index) = state.sync_pending.iter().position(|pending| { + pending.device == dev_kbd + && matches!(&pending.event, crate::server::QueuedInputEvent::Xi1Routed(q) + if q.evcode == press_evcode && q.detail == event.keycode && q.time == event.time) + }) { + state.sync_pending.remove(index); + } + } + // GH #59: a synchronous passive key grab's activating press is + // recorded in BOTH the unified activating slot (`Xi1Freeze::stored`, + // taken above) AND the XI1 pending queue. Xorg's ComputeFreezes replays the stored + // activating event only for Replay*, never for Sync* + // (dix/events.c:1320-1370). On SyncKeyboard, drop that duplicate + // queued XI1 DeviceKeyPress so the closing `xi1_compute_freezes` + // doesn't replay the grab's own already-delivered press — that + // replay would trip FreezeNextEvent → FrozenWithEvent, consuming the + // SyncKeyboard allowance meant for the next *physical* event and + // withholding the terminating release (sxhkd's dead keyboard). + if keyboard_replay + && state + .active_keyboard_grab + .is_some_and(|g| g.owner == client_id) + { + let is_passive = matches!( + state.active_keyboard_grab.map(|g| g.source), + Some(crate::server::ActiveKeyboardGrabSource::PassiveKey { .. }) + ); + let kbd_has_event = frozen_keyboard.is_some() + || state + .sync_pending + .iter() + .any(|pending| pending.device == dev_kbd); + if is_passive { + state.active_keyboard_grab = None; + } else if kbd_has_event { + // Explicit GrabKeyboard(GrabModeSync): deactivate on replay + // too (Xorg NOT_GRABBED → DeactivateGrab), emitting the + // FocusOut(NotifyUngrab) chain. Else the grab stays stuck. + deactivate_core_keyboard_grab(state, client_id); + } + } + + if pointer_replay + && let Some(crate::server::QueuedInputEvent::HostPointer(event)) = frozen_pointer + { + // Snapshot the xid_map so we can release the immutable + // borrow on `backend` before pointer_event_fanout_to_state + // mutates `state`. The map is small (a few hundred entries) + // and AllowEvents-replay is rare, so the clone is cheap + // compared to the wire writes the fanout produces. + let xid_map = backend.xid_map().clone(); + // Deliver core and XI2 device events to the natural target on + // replay, but do not regenerate XI_RawButtonPress: raw events + // describe physical input and were delivered before the grab froze. + // The XI2 freeze-filter at pointer_fanout.rs:309-316 (cinnamon + // aea9b0f) restricts XI2 press to the grab owner ONLY + // during sync-passive-grab freeze; the natural target + // never received XI2 during the freeze. Trace evidence + // from MATE on silence (2026-05-28): marco activates + // passive grab on the panel, AllowEvents fires, mate-panel + // (only XI2 mask, no core mask) saw the queued release + // but no press → menu clicks dead. + let _dropped = replay_frozen_pointer_event_to_state(state, backend, &xid_map, event); + } + if keyboard_replay + && let Some(crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + )) = frozen_keyboard + { + let _dropped = crate::core_loop::key_fanout::replay_frozen_key_to_focus_after_transition( + state, + event, + master_transition_accepted, + ); + } else if keyboard_replay + && let Some(crate::server::QueuedInputEvent::HostKey(event)) = frozen_keyboard + { + let _dropped = replay_frozen_key_to_focus(state, event); + } + // ComputeFreezes: replay the per-device XI1 queues + withheld + // core keys now that the sync states changed (Xorg has ONE + // AllowSome for both protocols). + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_compute_freezes(state, backend, &xid_map); + Ok(RequestOutcome::Handled) +} + +/// Core pointer-grab event mask: ButtonPress..KeymapState — X.h +/// `PointerGrabMask`. Requests selecting bits outside this set get +/// `BadValue` (Xorg `ProcGrabPointer` / `ProcGrabButton` / +/// `ProcChangeActivePointerGrab`). +const POINTER_GRAB_MASK: u32 = 0x7FFC; +/// X.h `AnyModifier` — wire encoding 1<<15. +const ANY_MODIFIER: u16 = 0x8000; +/// X.h `AllModifiersMask` — Shift..Mod5, the 8 real modifier bits. +/// `modifiers` values outside this (other than `AnyModifier`) get +/// `BadValue` (Xorg `CheckGrabValues`). +const ALL_MODIFIERS_MASK: u16 = 0x00FF; + +pub(super) fn handle_grab_pointer( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let mut status: u8 = 0; + // Logged with the grab result so an input trace shows whether the + // client asked for pointer confinement at all — SDL's relative-mouse + // mode passes its own window as confine_to (#99). + let mut logged_grab_window = ResourceId(0); + let mut logged_confine_to = ResourceId(0); + if body.len() >= 20 { + // GrabPointer wire shape: header opcode/data/length, then + // window(4) event-mask(2) pointer-mode(1) keyboard-mode(1) + // confine-to(4) cursor(4) time(4). The `owner_events` BOOL + // lives in the request header's `data` byte (header.data), + // not in the body. + let owner_events = header.data != 0; + let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let event_mask = u16::from_le_bytes([body[4], body[5]]); + let confine_to = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let cursor = ResourceId(u32::from_le_bytes([body[12], body[13], body[14], body[15]])); + let time = u32::from_le_bytes([body[16], body[17], body[18], body[19]]); + logged_grab_window = grab_window; + logged_confine_to = confine_to; + // Validation, in Xorg's order (ProcGrabPointer → GrabDevice): + // eventMask → confine_to lookup → keyboard/pointer mode → + // owner_events → grab_window lookup → cursor lookup. + if u32::from(event_mask) & !POINTER_GRAB_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(event_mask), + 26, + ); + } + if confine_to.0 != 0 && state.resources.window(confine_to).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + confine_to.0, + 26, + ); + } + if confine_to.0 != 0 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: confine_to, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 26); + } + if body[7] > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(body[7]), + 26, + ); + } + if body[6] > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(body[6]), + 26, + ); + } + if header.data > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 26, + ); + } + if state.resources.window(grab_window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + grab_window.0, + 26, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: grab_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 26); + } + if cursor.0 != 0 && !state.resources.cursor_exists(cursor) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + 26, + ); + } + if cursor.0 != 0 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::USE, + RequestOpcodes::for_request(header), + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 26); + } + // Grab status, in Xorg GrabDevice's check order (X.h values: + // GrabSuccess 0, AlreadyGrabbed 1, GrabInvalidTime 2, + // GrabNotViewable 3, GrabFrozen 4). Failure leaves all grab + // state untouched. + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.last_pointer_grab_time); + let viewable = state + .resources + .window(grab_window) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + let confine_viewable = confine_to.0 == 0 + || state + .resources + .window(confine_to) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + let grabbed_by_other = state + .active_pointer_grab + .is_some_and(|grab| grab.owner != client_id); + // Frozen on behalf of another client's grab on the paired + // device (Xorg: sync.frozen && sync.other && !SameClient). + let frozen_by_other = state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .is_some_and(|f| f.frozen() && f.other.is_some_and(|c| c != client_id)); + if grabbed_by_other { + status = 1; // AlreadyGrabbed + } else if !viewable || !confine_viewable { + status = 3; // GrabNotViewable + } else if time != 0 + && (crate::core_loop::xi1_focus::time_after(state.last_pointer_grab_time, time) + || crate::core_loop::xi1_focus::time_after(time, now)) + { + status = 2; // GrabInvalidTime + } else if frozen_by_other { + status = 4; // GrabFrozen + } else { + let prev_grab_window = state + .active_pointer_grab + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window); + state.set_pointer_grab(crate::server::ActivePointerGrab { + owner: client_id, + grab_window, + event_mask, + cursor, + time, + owner_events, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + state.last_pointer_grab_time = if time == 0 { now } else { time }; + // Core↔XI bridge (Xorg has ONE deviceGrab per device): a core + // sync grab freezes the device's XI1 event stream too — XTS + // XAllowDeviceEvents-3 freezes via XGrabPointer(GrabModeSync) + // and thaws via XAllowDeviceEvents. body[6]=pointer_mode, + // body[7]=keyboard_mode (0 = GrabModeSync). + crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( + state, + crate::xinput::DEVICEID_MASTER_POINTER, + client_id, + body[6] == 0, + body[7] == 0, + ); + // Xorg ActivatePointerGrab: DoEnterLeaveEvents(oldWin → + // grab window, NotifyGrab), where oldWin is the prior + // grab's window when re-grabbing, else the pointer window. + // marco's title-bar popup and GTK3 menus key off these. + let from_win = prev_grab_window + .unwrap_or_else(|| crate::core_loop::key_fanout::deepest_window_at_pointer(state)); + emit_core_pointer_grab_chain(state, from_win, grab_window, 1); + // ConfineCursorToWindow: record the confinement and pull + // the pointer inside the confine window if it is outside. + state.pointer_confine_to = confine_to; + confine_pointer_now(state, backend); + // Xorg ActivatePointerGrab installs the grab's cursor on the + // displayed sprite for the grab's duration (ImageMagick + // `import` grabs with a crosshair — #90). `cursor == None` + // (xid 0) means "no override"; per-window cursors show + // through. A re-grab by the same client with a new cursor + // replaces the override here. Resolved to a host cursor + // handle the same way XIChangeCursor does. + if cursor.0 == 0 { + let _ = backend.set_grab_cursor(None, None); + } else if let Some(host) = state.resources.cursor_host_xid(cursor) { + let _ = backend.set_grab_cursor(None, Some(host)); + } + } + } + debug!( + "client {} #{} GrabPointer status={status} window={:#x} confine_to={:#x}", + client_id.0, sequence.0, logged_grab_window.0, logged_confine_to.0 + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_grab_reply(&mut buf, byte_order, sequence, status)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_ungrab_pointer( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // Xorg ProcUngrabPointer: deactivate only when the request time is + // neither LATER than the current time nor EARLIER than the + // last-grab time, AND the active grab belongs to this client. + let time = body + .get(0..4) + .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.last_pointer_grab_time); + if time != 0 + && (crate::core_loop::xi1_focus::time_after(time, now) + || crate::core_loop::xi1_focus::time_after(state.last_pointer_grab_time, time)) + { + debug!( + "client {} #{} UngrabPointer ignored (time {time} outside [{}, {now}])", + client_id.0, sequence.0, state.last_pointer_grab_time + ); + return Ok(RequestOutcome::Handled); + } + let held_by_client = state + .active_pointer_grab + .is_some_and(|grab| grab.owner == client_id); + if !held_by_client { + debug!( + "client {} #{} UngrabPointer ignored (no grab held by client)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + deactivate_core_pointer_grab(state, backend, client_id); + debug!("client {} #{} UngrabPointer", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Tear down the active core pointer grab held by `client_id` — +/// shared by UngrabPointer and the unmap/destroy deactivation path +/// (Xorg `DeactivateGrab` reached from `DeleteWindowFromAnyEvents`). +/// Passive-grab NOT_GRABBED (Replay) teardown: clear the active passive +/// pointer grab and emit the `NotifyUngrab` crossing chain (grab window +/// → sprite), mirroring the activation chain from pointer_fanout. Does +/// NOT release any core↔XI grab bridge — the Replay path deliberately +/// omits `xi1_core_grab_bridge_release` (Xorg re-checks device grabs on +/// the replayed event). Shared by `apply_allow_events` and the XI1 +/// ReplayThisDevice path. +pub(super) fn deactivate_passive_pointer_grab_crossings(state: &mut ServerState) { + let prev_grab = state.active_pointer_grab.filter(|grab| grab.passive); + let prev_grab_window = prev_grab.map(|grab| grab.grab_window); + state.clear_pointer_grab(); + state.pointer_confine_to = ResourceId(0); + // Xorg DeactivatePointerGrab clears every `sync.other` held on the + // dying grab's behalf: a keyboard frozen by the button grab's sync + // keyboard mode thaws with it, or it stays frozen with no grab left + // to AllowEvents it. + // A core passive grab freezes the master pointer and holds its + // paired master keyboard (`xi1_check_grab_for_syncs`). + if let Some(grab) = prev_grab + && let Some(paired) = crate::core_loop::pointer_fanout::xi1_other_input_device( + state, + crate::xinput::DEVICEID_MASTER_POINTER, + ) + && let Some(kbd) = state.xi1_frozen.get_mut(&paired) + && kbd.other == Some(grab.owner) + { + kbd.other = None; + } + if let Some(prev) = prev_grab_window { + let to_win = crate::core_loop::key_fanout::deepest_window_at_pointer(state); + emit_core_pointer_grab_chain(state, prev, to_win, 2); // NotifyUngrab + } +} + +pub(super) fn deactivate_core_pointer_grab( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, +) { + state.pointer_confine_to = ResourceId(0); + let prev_grab_window = state + .active_pointer_grab + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window); + state.clear_pointer_grab(); + state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default() + .stored = None; + // Xorg DeactivatePointerGrab reverts the sprite from the grab + // cursor back to the per-window/default cursor. Clearing an + // override that was never set is a cheap no-op. + let _ = backend.set_grab_cursor(None, None); + // Core↔XI bridge: release any XI1-side hold the core grab placed. + crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( + state, + crate::xinput::DEVICEID_MASTER_POINTER, + client_id, + ); + if let Some(prev) = prev_grab_window { + // Xorg DeactivatePointerGrab: DoEnterLeaveEvents(grab window + // → pointer window, NotifyUngrab). + let to_win = crate::core_loop::key_fanout::deepest_window_at_pointer(state); + emit_core_pointer_grab_chain(state, prev, to_win, 2); + } +} + +/// Pull the pointer inside the current confinement rectangle when it +/// sits outside — Xorg `ConfineCursorToWindow` → `CheckPhysLimits` +/// (the warp generates motion/crossing events through the normal +/// input path). Used at grab activation and when the confine window +/// moves/resizes. +pub(crate) fn confine_pointer_now(state: &mut ServerState, backend: &mut dyn Backend) { + let win = state.pointer_confine_to; + if win.0 == 0 { + return; + } + let Some(w) = state.resources.window(win) else { + return; + }; + if w.map_state != crate::resources::MapState::Viewable { + return; + } + let (x0, y0) = state.resources.window_absolute_position(win); + let (x1, y1) = (x0 + i32::from(w.width), y0 + i32::from(w.height)); + let (px, py) = state.pointer_root; + let cx = i32::from(px).clamp(x0, (x1 - 1).max(x0)); + let cy = i32::from(py).clamp(y0, (y1 - 1).max(y0)); + if cx != i32::from(px) || cy != i32::from(py) { + debug!( + "confine_pointer_now: warping ({px},{py}) -> ({cx},{cy}) inside 0x{:x}", + win.0 + ); + backend.warp_pointer_root(state, cx, cy); + } +} + +/// Full Enter/Leave chain for pointer-grab activation/deactivation — +/// Xorg `ActivatePointerGrab`/`DeactivatePointerGrab` → +/// `DoEnterLeaveEvents(sprite.win ↔ grab window, NotifyGrab/Ungrab)`. +/// Events flow through the normal per-window mask filter (EnterWindow +/// 0x10 / LeaveWindow 0x20) to every selecting client, then the same chain +/// in XI2 form (`DeviceEnterLeaveEvents`), from the master pointer. +pub(crate) fn emit_core_pointer_grab_chain( + state: &mut ServerState, + from_win: ResourceId, + to_win: ResourceId, + mode: u8, +) { + if from_win == to_win { + return; + } + let chain = crate::crossings::normal_mode_crossings(state, from_win, to_win); + let (root_x, root_y) = state.pointer_root; + let server_time = state.timestamp_now(); + for e in &chain { + let (mask, enter) = match e.kind { + crate::crossings::CrossingKind::Enter => (0x10u32, true), + crate::crossings::CrossingKind::Leave => (0x20u32, false), + }; + let (ox, oy) = state.resources.window_absolute_position(e.window); + let event_x = i16::try_from(i32::from(root_x) - ox).unwrap_or(i16::MAX); + let event_y = i16::try_from(i32::from(root_y) - oy).unwrap_or(i16::MAX); + let focus = state.crossing_has_focus(e.window); + let _dropped = emit_window_event_to_state(state, e.window, mask, |buf, seq, order| { + let crossing = yserver_protocol::x11::CrossingEvent { + sequence: seq, + time: server_time, + root: ROOT_WINDOW, + event: e.window, + child: e.child, + root_x, + root_y, + event_x, + event_y, + state: 0, + detail: e.detail, + mode, + focus, + }; + if enter { + x11::encode_enter_notify_event(buf, order, crossing); + } else { + x11::encode_leave_notify_event(buf, order, crossing); + } + }); + } + for e in chain { + let evtype: u16 = match e.kind { + crate::crossings::CrossingKind::Enter => 7, + crate::crossings::CrossingKind::Leave => 8, + }; + // Xorg sends these before the grab is installed and after it is + // gone, so the window's selections get them, whatever the grab. + let targets = + crate::core_loop::pointer_fanout::xi2_master_selectors(state, e.window, evtype); + if targets.is_empty() { + continue; + } + let (ox, oy) = state.resources.window_absolute_position(e.window); + let event_x = i16::try_from(i32::from(root_x) - ox).unwrap_or(i16::MAX); + let event_y = i16::try_from(i32::from(root_y) - oy).unwrap_or(i16::MAX); + let focus = state.crossing_has_focus(e.window); + let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { + x11::encode_xi2_crossing_event( + buf, + order, + seq, + XI2_MAJOR_OPCODE, + evtype, + 2, + server_time, + ROOT_WINDOW, + e.window, + root_x, + root_y, + event_x, + event_y, + 0, + mode, + e.detail, + 2, + focus, + ); + }); + } +} + +pub(super) fn handle_grab_button( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if body.len() >= 20 { + let button = body[16]; + let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let event_mask = u32::from(u16::from_le_bytes([body[4], body[5]])); + let pointer_mode = body[6]; + let keyboard_mode = body[7]; + let confine_to = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let cursor = ResourceId(u32::from_le_bytes([body[12], body[13], body[14], body[15]])); + let owner_events = header.data != 0; + let modifiers = u16::from_le_bytes([body[18], body[19]]); + // Validation, in Xorg's ProcGrabButton order: pointer_mode → + // keyboard_mode → modifiers → owner_events → event_mask → + // grab_window → confine_to → cursor → conflicting-grab + // BadAccess (AddPassiveGrabToList). + if pointer_mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(pointer_mode), + 28, + ); + } + if keyboard_mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(keyboard_mode), + 28, + ); + } + if modifiers != ANY_MODIFIER && modifiers & !ALL_MODIFIERS_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(modifiers), + 28, + ); + } + if header.data > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 28, + ); + } + if event_mask & !POINTER_GRAB_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + event_mask, + 28, + ); + } + if state.resources.window(grab_window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + grab_window.0, + 28, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: grab_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 28); + } + if confine_to.0 != 0 && state.resources.window(confine_to).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + confine_to.0, + 28, + ); + } + if confine_to.0 != 0 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: confine_to, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 28); + } + if cursor.0 != 0 && !state.resources.cursor_exists(cursor) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + 28, + ); + } + if cursor.0 != 0 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::USE, + RequestOpcodes::for_request(header), + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 28); + } + // A passive grab that would override another client's grab on + // the same window is a BadAccess (Xorg GrabMatchesSecond via + // AddPassiveGrabToList): button details overlap when either + // side is AnyButton(0) or they are equal; modifiers likewise + // with AnyModifier. Core grabs only conflict with core grabs + // (grabtype mismatch never matches). + let conflicts = state.button_grabs.iter().any(|g| { + g.grab_window == grab_window + && g.owner != client_id + && !g.via_xi2 + && (g.button == button || g.button == 0 || button == 0) + && (g.modifiers == modifiers + || g.modifiers == ANY_MODIFIER + || modifiers == ANY_MODIFIER) + }); + if conflicts { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 28); + } + state.button_grabs.retain(|g| { + !(g.owner == client_id + && g.grab_window == grab_window + && g.button == button + && g.modifiers == modifiers) + }); + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: client_id, + grab_window, + button, + modifiers, + owner_events, + event_mask, + pointer_mode, + keyboard_mode, + confine_to, + via_xi2: false, + }); + debug!( + "client {} GrabButton window=0x{:x} button={} modifiers=0x{:x}", + client_id.0, grab_window.0, button, modifiers + ); + } + debug!("client {} #{} GrabButton", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_ungrab_button( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if body.len() >= 6 { + let button = header.data; + let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let modifiers = u16::from_le_bytes([body[4], body[5]]); + // Xorg ProcUngrabButton: modifiers BadValue → window BadWindow. + if modifiers != ANY_MODIFIER && modifiers & !ALL_MODIFIERS_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(modifiers), + 29, + ); + } + if state.resources.window(grab_window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + grab_window.0, + 29, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: grab_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::READ, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 29); + } + state.button_grabs.retain(|g| { + !(g.owner == client_id + && g.grab_window == grab_window + && (g.button == button || button == 0) + && (g.modifiers == modifiers || modifiers == 0x8000)) + }); + debug!( + "client {} UngrabButton window=0x{:x} button={} modifiers=0x{:x}", + client_id.0, grab_window.0, button, modifiers + ); + } + debug!("client {} #{} UngrabButton", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_change_active_pointer_grab( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() >= 12 { + let cursor = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let event_mask = u16::from_le_bytes([body[8], body[9]]); + // Xorg ProcChangeActivePointerGrab: eventMask BadValue → + // cursor BadCursor; both fire even when no grab is active. + if u32::from(event_mask) & !POINTER_GRAB_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(event_mask), + 30, + ); + } + if cursor.0 != 0 && !state.resources.cursor_exists(cursor) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + 30, + ); + } + if cursor.0 != 0 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::USE, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 30); + } + // Xorg ProcChangeActivePointerGrab: no-op when the request + // time is LATER than current or EARLIER than the grab time. + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.last_pointer_grab_time); + let time_ok = time == 0 + || (!crate::core_loop::xi1_focus::time_after(state.last_pointer_grab_time, time) + && !crate::core_loop::xi1_focus::time_after(time, now)); + if time_ok + && let Some(g) = state.active_pointer_grab.as_mut() + && g.owner == client_id + { + g.event_mask = event_mask; + g.cursor = cursor; + } + } + debug!( + "client {} #{} ChangeActivePointerGrab", + client_id.0, sequence.0 + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_grab_keyboard( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let mut status: u8 = 0; + if body.len() >= 12 { + let grab_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + // Validation per Xorg GrabDevice: keyboard_mode (body[9]) → + // pointer_mode (body[8]) → owner_events (header data byte) → + // grab_window lookup. + if body[9] > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(body[9]), + 31, + ); + } + if body[8] > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(body[8]), + 31, + ); + } + if header.data > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 31, + ); + } + if state.resources.window(grab_window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + grab_window.0, + 31, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: grab_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 31); + } + // Grab status, mirroring handle_grab_pointer (Xorg GrabDevice + // check order). Failure leaves all grab state untouched. + let time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.last_keyboard_grab_time); + let viewable = state + .resources + .window(grab_window) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + let grabbed_by_other = state + .active_keyboard_grab + .is_some_and(|g| g.owner != client_id); + let frozen_by_other = state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .is_some_and(|f| f.frozen() && f.other.is_some_and(|c| c != client_id)); + if grabbed_by_other { + status = 1; // AlreadyGrabbed + } else if !viewable { + status = 3; // GrabNotViewable + } else if time != 0 + && (crate::core_loop::xi1_focus::time_after(state.last_keyboard_grab_time, time) + || crate::core_loop::xi1_focus::time_after(time, now)) + { + status = 2; // GrabInvalidTime + } else if frozen_by_other { + status = 4; // GrabFrozen + } else { + let prev_grab_window = state + .active_keyboard_grab + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window); + state.active_keyboard_grab = Some(crate::server::ActiveKeyboardGrab { + owner: client_id, + grab_window, + source: crate::server::ActiveKeyboardGrabSource::Explicit, + owner_events: header.data != 0, + via_xi2: false, + xi2_mask: 0, + }); + state.last_keyboard_grab_time = if time == 0 { now } else { time }; + // Core↔XI bridge — see handle_grab_pointer. GrabKeyboard wire: + // window(4) time(4) pointer_mode(1) keyboard_mode(1); this + // device = keyboard, other = pointer. + crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( + state, + crate::xinput::DEVICEID_MASTER_KEYBOARD, + client_id, + body[9] == 0, + body[8] == 0, + ); + // Xorg ActivateKeyboardGrab: DoFocusEvents(oldWin → + // grab_window, NotifyGrab), where oldWin is the prior + // grab's window if one was active, else the focus. + let from_raw = prev_grab_window.map_or(state.core_focus.raw, |w| w.0); + emit_core_focus_transition(state, from_raw, grab_window.0, 1); + } + } + debug!( + "client {} #{} GrabKeyboard status={status}", + client_id.0, sequence.0 + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_grab_reply(&mut buf, byte_order, sequence, status)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_ungrab_keyboard( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // Time validation — see handle_ungrab_pointer (Xorg + // ProcUngrabKeyboard has the identical CompareTimeStamps gate). + let time = body + .get(0..4) + .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.last_keyboard_grab_time); + if time != 0 + && (crate::core_loop::xi1_focus::time_after(time, now) + || crate::core_loop::xi1_focus::time_after(state.last_keyboard_grab_time, time)) + { + debug!( + "client {} #{} UngrabKeyboard ignored (time {time} outside [{}, {now}])", + client_id.0, sequence.0, state.last_keyboard_grab_time + ); + return Ok(RequestOutcome::Handled); + } + deactivate_core_keyboard_grab(state, client_id); + debug!("client {} #{} UngrabKeyboard", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Tear down the active core keyboard grab held by `client_id` — +/// shared by UngrabKeyboard and the unmap/destroy deactivation path +/// (see [`deactivate_core_pointer_grab`]). +pub(super) fn deactivate_core_keyboard_grab(state: &mut ServerState, client_id: ClientId) { + let prev_grab_window = state + .active_keyboard_grab + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window); + if state + .active_keyboard_grab + .is_some_and(|g| g.owner == client_id) + { + state.active_keyboard_grab = None; + state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_KEYBOARD) + .or_default() + .stored = None; + // Core↔XI bridge: release any XI1-side hold the grab placed. + crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release( + state, + crate::xinput::DEVICEID_MASTER_KEYBOARD, + client_id, + ); + } + if let Some(prev) = prev_grab_window { + // Xorg DeactivateKeyboardGrab: DoFocusEvents(grab_window → + // focus, NotifyUngrab). + emit_core_focus_transition(state, prev.0, state.core_focus.raw, 2); + } +} + +/// Xorg `ReleaseActiveGrabs` (`dix/events.c:1995-2012`), from `CloseDownClient` +/// (`dix/dispatch.c:3496`): every device whose active grab is `client_id`'s +/// is deactivated as an explicit ungrab would, in device-list order (master +/// pointer, master keyboard, then the rest by id), so the survivors get the +/// `NotifyUngrab` crossings and focus events. Returns whether an XI 1.x +/// device grab was among them. +pub(crate) fn release_active_grabs( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, +) -> bool { + use crate::xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_MASTER_POINTER}; + if state + .active_pointer_grab + .is_some_and(|g| g.owner == client_id) + { + deactivate_core_pointer_grab(state, backend, client_id); + } + if state + .active_keyboard_grab + .is_some_and(|g| g.owner == client_id) + { + deactivate_core_keyboard_grab(state, client_id); + } + let owned = |dev: &u16, owner: ClientId| (owner == client_id).then_some(*dev); + let mut devices: Vec = (state.xi2_pointer_grabs.iter()) + .filter_map(|(dev, g)| owned(dev, g.owner)) + .chain((state.xi2_keyboard_grabs.iter()).filter_map(|(dev, g)| owned(dev, g.owner))) + .chain((state.xi1_active_grabs.iter()).filter_map(|(dev, g)| owned(dev, g.owner))) + .collect(); + devices.sort_unstable_by_key(|&dev| match dev { + DEVICEID_MASTER_POINTER => (0, dev), + DEVICEID_MASTER_KEYBOARD => (1, dev), + _ => (2, dev), + }); + devices.dedup(); + let mut released_xi1 = false; + for dev in devices { + if state.xi2_pointer_grabs.contains_key(&dev) { + super::xi::deactivate_xi2_device_grab( + state, backend, None, client_id, dev, false, false, + ); + } + if state.xi2_keyboard_grabs.contains_key(&dev) { + super::xi::deactivate_xi2_device_grab( + state, backend, None, client_id, dev, true, false, + ); + } + if state.xi1_active_grabs.contains_key(&dev) { + // As UngrabDevice does. + crate::core_loop::pointer_fanout::xi1_deactivate_device_grab(state, dev); + released_xi1 = true; + } + } + released_xi1 +} + +/// Xorg `DeleteWindowFromAnyEvents` grab leg: an active core grab +/// whose grab window stopped being viewable (unmap of it or an +/// ancestor, or destroy) deactivates. Call after the map-state / +/// resource changes have landed. +pub(super) fn release_core_grabs_for_unviewable( + state: &mut ServerState, + backend: &mut dyn Backend, +) { + let viewable = |state: &ServerState, w: ResourceId| { + state + .resources + .window(w) + .is_some_and(|win| win.map_state == crate::resources::MapState::Viewable) + }; + if let Some(grab) = state.active_pointer_grab + && (!viewable(state, grab.grab_window) + || (state.pointer_confine_to.0 != 0 && !viewable(state, state.pointer_confine_to))) + { + deactivate_core_pointer_grab(state, backend, grab.owner); + } + if let Some(g) = state.active_keyboard_grab + && !viewable(state, g.grab_window) + { + deactivate_core_keyboard_grab(state, g.owner); + } +} + +pub(super) fn handle_grab_key( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if let Some(req) = x11::parse_grab_key(body, header.data != 0) { + let grab_window = ResourceId(req.grab_window); + // Validation per Xorg ProcGrabKey: CheckGrabValues (modes, + // owner_events, modifiers) → keycode range → grab_window + // lookup → conflicting-grab BadAccess. + if req.keyboard_mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.keyboard_mode), + 33, + ); + } + if req.pointer_mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.pointer_mode), + 33, + ); + } + if header.data > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 33, + ); + } + if req.modifiers != ANY_MODIFIER && req.modifiers & !ALL_MODIFIERS_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.modifiers), + 33, + ); + } + // Keycode must be within the advertised [min_keycode, + // max_keycode] range (8..=255 — the setup reply's values) or + // AnyKey(0). + if req.keycode != 0 && req.keycode < 8 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.keycode), + 33, + ); + } + if state.resources.window(grab_window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + grab_window.0, + 33, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: grab_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 33); + } + // BadAccess when another client already holds an overlapping + // passive key grab on this window — see the GrabButton + // conflict check for the overlap rule. + let conflicts = state.key_grabs.iter().any(|g| { + g.grab_window == grab_window + && g.owner != client_id + && !g.via_xi2 + && (g.keycode == req.keycode || g.keycode == 0 || req.keycode == 0) + && (g.modifiers == req.modifiers + || g.modifiers == ANY_MODIFIER + || req.modifiers == ANY_MODIFIER) + }); + if conflicts { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 33); + } + state.key_grabs.retain(|g| { + !(g.owner == client_id + && g.grab_window == grab_window + && g.keycode == req.keycode + && g.modifiers == req.modifiers) + }); + state.key_grabs.push(crate::server::KeyGrab { + device_id: 0, + owner: client_id, + grab_window, + keycode: req.keycode, + modifiers: req.modifiers, + owner_events: req.owner_events, + pointer_mode: req.pointer_mode, + keyboard_mode: req.keyboard_mode, + via_xi2: false, + xi2_mask: 0, + }); + debug!( + "client {} GrabKey window=0x{:x} keycode={} modifiers=0x{:x}", + client_id.0, req.grab_window, req.keycode, req.modifiers + ); + } + debug!("client {} #{} GrabKey", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_ungrab_key( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if let Some(req) = x11::parse_ungrab_key(body, header.data) { + let grab_window = ResourceId(req.grab_window); + // Xorg ProcUngrabKey: window lookup → keycode range → + // modifiers BadValue. + if state.resources.window(grab_window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + grab_window.0, + 34, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: grab_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 34); + } + if req.keycode != 0 && req.keycode < 8 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.keycode), + 34, + ); + } + if req.modifiers != ANY_MODIFIER && req.modifiers & !ALL_MODIFIERS_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.modifiers), + 34, + ); + } + state.key_grabs.retain(|g| { + !(g.owner == client_id + && g.grab_window == grab_window + && (g.keycode == req.keycode || req.keycode == 0) + && (g.modifiers == req.modifiers || req.modifiers == 0x8000)) + }); + } + debug!("client {} #{} UngrabKey", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/input_ctl.rs b/crates/yserver-core/src/core_loop/process_request/input_ctl.rs new file mode 100644 index 000000000..00c2e27ee --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/input_ctl.rs @@ -0,0 +1,942 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::fanout_event_to_clients, + process_request::{ + RequestOutcome, emit_x11_error, write_to_client, xi::xi1_device_button_count, + }, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, SequenceNumber}, +}; + +pub(super) fn handle_query_keymap( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} QueryKeymap", client_id.0, sequence.0); + let keys_down = state.keys_down; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf = x11::fixed_reply(byte_order, sequence, 0, 2); + buf.extend_from_slice(&keys_down); + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_get_pointer_mapping( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetPointerMapping", client_id.0, sequence.0); + // Xorg reads PickPointer(client)->button->numButtons and its map + // (`dix/devices.c:1994-2016`). + let button_count = usize::from( + xi1_device_button_count(&state.xi_devices, crate::xinput::DEVICEID_MASTER_POINTER) + .unwrap_or(0), + ); + let map: Vec = (0..button_count) + .map(|index| { + state + .pointer_mapping_override + .as_ref() + .and_then(|mapping| mapping.get(index).copied()) + .unwrap_or_else(|| u8::try_from(index + 1).unwrap_or(u8::MAX)) + }) + .collect(); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + #[allow(clippy::cast_possible_truncation)] + let mut buf = x11::fixed_reply( + byte_order, + sequence, + map.len() as u8, + map.len().div_ceil(4) as u32, + ); + buf.extend_from_slice(&[0u8; 24]); + buf.extend_from_slice(&map); + while !buf.len().is_multiple_of(4) { + buf.push(0); + } + Ok(write_to_client(client, client_id, &buf)) +} + +/// Build a generic 32-byte stub reply: header + length(0) + zeros. +/// Caller fills `data` byte (offset 1) and any non-zero typed field. +fn stub_reply_32(byte_order: x11::ClientByteOrder, sequence: SequenceNumber, data: u8) -> Vec { + let mut buf = x11::fixed_reply(byte_order, sequence, data, 0); + buf.resize(32, 0); + buf +} + +/// GetKeyboardControl (103): 52-byte reply (length=5). Reflects +/// `ServerState::keyboard_control` (mirrors Xorg +/// `ProcGetKeyboardControl`, `dix/devices.c:2257`). +pub(super) fn handle_get_keyboard_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetKeyboardControl", client_id.0, sequence.0); + let kc = state.keyboard_control.clone(); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + // Layout: reply(1) global_auto_repeat(1) seq(2) length=5(4) + // led_mask u32(4) key_click_pct u8(1) bell_pct u8(1) + // bell_pitch u16(2) bell_duration u16(2) pad(2) + // auto_repeats u8[32] = 32 + 20 = 52 bytes + let mut buf = x11::fixed_reply(byte_order, sequence, u8::from(kc.global_auto_repeat), 5); + let mut tmp = Vec::with_capacity(4); + x11::write_u32(byte_order, &mut tmp, kc.led_mask); + buf.extend_from_slice(&tmp); + buf.push(kc.key_click_percent); + buf.push(kc.bell_percent); + tmp.clear(); + x11::write_u16(byte_order, &mut tmp, kc.bell_pitch); + buf.extend_from_slice(&tmp); + tmp.clear(); + x11::write_u16(byte_order, &mut tmp, kc.bell_duration); + buf.extend_from_slice(&tmp); + buf.extend_from_slice(&[0, 0]); // pad + buf.extend_from_slice(&kc.auto_repeats); + debug_assert_eq!(buf.len(), 52); + Ok(write_to_client(client, client_id, &buf)) +} + +/// ChangeKeyboardControl (102): value-mask driven update of +/// `ServerState::keyboard_control`. Mirrors Xorg +/// `DoChangeKeyboardControl` (`dix/devices.c:2050`): validate and +/// stage into a copy, commit only on full success. +pub(super) fn handle_change_keyboard_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + const KB_KEY_CLICK_PERCENT: u32 = 0x01; + const KB_BELL_PERCENT: u32 = 0x02; + const KB_BELL_PITCH: u32 = 0x04; + const KB_BELL_DURATION: u32 = 0x08; + const KB_LED: u32 = 0x10; + const KB_LED_MODE: u32 = 0x20; + const KB_KEY: u32 = 0x40; + const KB_AUTO_REPEAT_MODE: u32 = 0x80; + debug!( + "client {} #{} ChangeKeyboardControl", + client_id.0, sequence.0 + ); + if body.len() < 4 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + } + let mask = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + // Xorg BadLength: req_len must be exactly 2 + Ones(vmask) units. + if body.len() != 4 + 4 * mask.count_ones() as usize { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + } + let bad_value = |state: &mut ServerState, value: u32| { + emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + value, + header.opcode, + ) + }; + let mut ctrl = state.keyboard_control.clone(); + // Sentinel: "no KBLed/KBKey given" → led-mode / auto-repeat-mode + // apply to all leds / the global flag (Xorg DO_ALL). + let mut led: Option = None; + let mut key: Option = None; + let mut values = body[4..].chunks_exact(4); + let mut bit = 1u32; + while bit != 0 { + let item = bit & mask; + bit <<= 1; + if item == 0 { + continue; + } + let Some(raw) = values + .next() + .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) + else { + break; // unreachable: length validated above + }; + match item { + KB_KEY_CLICK_PERCENT => { + let t = raw as i8; + if t == -1 { + ctrl.key_click_percent = 0; // DEFAULT_KEYBOARD_CLICK + } else if !(0..=100).contains(&t) { + return bad_value(state, i32::from(t) as u32); + } else { + ctrl.key_click_percent = t as u8; + } + } + KB_BELL_PERCENT => { + let t = raw as i8; + if t == -1 { + ctrl.bell_percent = 50; // DEFAULT_BELL + } else if !(0..=100).contains(&t) { + return bad_value(state, i32::from(t) as u32); + } else { + ctrl.bell_percent = t as u8; + } + } + KB_BELL_PITCH => { + let t = raw as i16; + if t == -1 { + ctrl.bell_pitch = 400; // DEFAULT_BELL_PITCH + } else if t < 0 { + return bad_value(state, i32::from(t) as u32); + } else { + ctrl.bell_pitch = t as u16; + } + } + KB_BELL_DURATION => { + let t = raw as i16; + if t == -1 { + ctrl.bell_duration = 100; // DEFAULT_BELL_DURATION + } else if t < 0 { + return bad_value(state, i32::from(t) as u32); + } else { + ctrl.bell_duration = t as u16; + } + } + KB_LED => { + let l = raw as u8; + if !(1..=32).contains(&l) { + return bad_value(state, u32::from(l)); + } + if mask & KB_LED_MODE == 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + header.opcode, + ); + } + led = Some(l); + } + KB_LED_MODE => { + let t = raw as u8; + match (t, led) { + (0, None) => ctrl.led_mask = 0, + (0, Some(l)) => ctrl.led_mask &= !(1u32 << (l - 1)), + (1, None) => ctrl.led_mask = !0, + (1, Some(l)) => ctrl.led_mask |= 1u32 << (l - 1), + _ => return bad_value(state, u32::from(t)), + } + } + KB_KEY => { + let k = raw as u8; + // min_keycode advertised in the setup reply is 8; + // max is 255 so no upper check is reachable for a u8. + if k < 8 { + return bad_value(state, u32::from(k)); + } + if mask & KB_AUTO_REPEAT_MODE == 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + header.opcode, + ); + } + key = Some(k); + } + KB_AUTO_REPEAT_MODE => { + let t = raw as u8; + match (t, key) { + (0, None) => ctrl.global_auto_repeat = false, + (1, None) => ctrl.global_auto_repeat = true, + (2, None) => ctrl.global_auto_repeat = true, // DEFAULT_AUTOREPEAT + (0..=2, Some(k)) => { + let i = usize::from(k >> 3); + let m = 1 << (k & 7); + match t { + 0 => ctrl.auto_repeats[i] &= !m, + 1 => ctrl.auto_repeats[i] |= m, + _ => { + ctrl.auto_repeats[i] = (ctrl.auto_repeats[i] & !m) + | (crate::server::DEFAULT_AUTO_REPEATS[i] & m); + } + } + // Xorg XkbDisableComputedAutoRepeats: a mapping + // change no longer re-derives this key's repeat. + ctrl.auto_repeats_explicit[i] |= m; + } + _ => return bad_value(state, u32::from(t)), + } + } + _ => { + // Unknown mask bit: Xorg's default case → BadValue. + return bad_value(state, mask); + } + } + } + state.keyboard_control = ctrl; + Ok(RequestOutcome::Handled) +} + +/// Bell (104): validate percent (header data byte, INT8 −100..=100, +/// Xorg `ProcBell` `dix/devices.c:2288`). yserver has no audible +/// bell output; the request succeeds without side effects, like +/// Xorg on a bell-less device. +pub(super) fn handle_bell( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, +) -> io::Result { + let percent = header.data as i8; + debug!( + "client {} #{} Bell percent={}", + client_id.0, sequence.0, percent + ); + if !(-100..=100).contains(&percent) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + i32::from(percent) as u32, + header.opcode, + ); + } + Ok(RequestOutcome::Handled) +} + +/// ChangePointerControl (105): update `ServerState::pointer_control`. +/// Mirrors Xorg `ProcChangePointerControl` (`dix/devices.c:2326`): +/// stage into a copy, commit only on full success. +pub(super) fn handle_change_pointer_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + debug!( + "client {} #{} ChangePointerControl", + client_id.0, sequence.0 + ); + // Body: accel_num i16, accel_denom i16, threshold i16, + // do_accel u8, do_thresh u8 = 8 bytes. + if body.len() < 8 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + } + let accel_num = i16::from_le_bytes([body[0], body[1]]); + let accel_denom = i16::from_le_bytes([body[2], body[3]]); + let threshold = i16::from_le_bytes([body[4], body[5]]); + let do_accel = body[6]; + let do_thresh = body[7]; + let bad_value = |state: &mut ServerState, value: u32| { + emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + value, + header.opcode, + ) + }; + if do_accel > 1 { + return bad_value(state, u32::from(do_accel)); + } + if do_thresh > 1 { + return bad_value(state, u32::from(do_thresh)); + } + let mut ctrl = state.pointer_control.clone(); + if do_accel == 1 { + match accel_num { + -1 => ctrl.accel_numerator = 2, // DEFAULT_PTR_NUMERATOR + n if n < 0 => return bad_value(state, i32::from(n) as u32), + n => ctrl.accel_numerator = n as u16, + } + match accel_denom { + -1 => ctrl.accel_denominator = 1, // DEFAULT_PTR_DENOMINATOR + n if n <= 0 => return bad_value(state, i32::from(n) as u32), + n => ctrl.accel_denominator = n as u16, + } + } + if do_thresh == 1 { + match threshold { + -1 => ctrl.threshold = 4, // DEFAULT_PTR_THRESHOLD + n if n < 0 => return bad_value(state, i32::from(n) as u32), + n => ctrl.threshold = n as u16, + } + } + state.pointer_control = ctrl; + Ok(RequestOutcome::Handled) +} + +/// GetPointerControl (106): 32-byte reply reflecting +/// `ServerState::pointer_control` (Xorg `ProcGetPointerControl`, +/// `dix/devices.c:2405`). +pub(super) fn handle_get_pointer_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetPointerControl", client_id.0, sequence.0); + let pc = state.pointer_control.clone(); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf = x11::fixed_reply(byte_order, sequence, 0, 0); + let mut tmp = Vec::with_capacity(2); + x11::write_u16(byte_order, &mut tmp, pc.accel_numerator); + buf.extend_from_slice(&tmp); + tmp.clear(); + x11::write_u16(byte_order, &mut tmp, pc.accel_denominator); + buf.extend_from_slice(&tmp); + tmp.clear(); + x11::write_u16(byte_order, &mut tmp, pc.threshold); + buf.extend_from_slice(&tmp); + buf.resize(32, 0); + Ok(write_to_client(client, client_id, &buf)) +} + +/// SetPointerMapping (116): reply with status=0 + MappingNotify fanout. +pub(super) fn handle_set_pointer_mapping( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + debug!("client {} #{} SetPointerMapping", client_id.0, sequence.0); + let n = usize::from(header.data); + let Some(map) = body.get(..n) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 116); + }; + // Xorg ProcSetPointerMapping requires the selected pointer's button + // count and unique nonzero entries (`dix/devices.c:1904-1918`). + let current_len = usize::from( + xi1_device_button_count(&state.xi_devices, crate::xinput::DEVICEID_MASTER_POINTER) + .unwrap_or(0), + ); + if n != current_len { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 116, + ); + } + let mut seen = [false; 256]; + for &b in map { + if b != 0 { + if seen[usize::from(b)] { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(b), + 116, + ); + } + seen[usize::from(b)] = true; + } + } + state.pointer_mapping_override = Some(map.to_vec()); + // MappingNotify (request=2 = Pointer) to every connected client. + let targets: Vec = state.clients.keys().map(|id| ClientId(*id)).collect(); + let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { + let _ = x11::write_mapping_notify_event(buf, order, seq, 2, 0, 0); + }); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let buf = stub_reply_32(client.byte_order, sequence, 0); // status=Success + Ok(write_to_client(client, client_id, &buf)) +} + +/// SetModifierMapping (118): MappingNotify fanout, then reply. +pub(super) fn handle_set_modifier_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + debug!("client {} #{} SetModifierMapping", client_id.0, sequence.0); + let kpm = header.data; + let need = usize::from(kpm) * 8; + let Some(keycodes) = body.get(..need) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 118); + }; + // Xorg ProcSetModifierMapping: BadValue for a refused map, else the + // change_modmap status in the reply. + let status = match change_modifier_mapping(state, backend, origin, kpm, keycodes, None, |_| {}) + { + ModmapChangeOutcome::Success => 0, + ModmapChangeOutcome::Busy => 1, + ModmapChangeOutcome::BadValue(value) => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + value, + 118, + ); + } + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let buf = stub_reply_32(client.byte_order, sequence, status); + Ok(write_to_client(client, client_id, &buf)) +} + +/// Result of [`change_modifier_mapping`] (Xorg `change_modmap`'s return). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum ModmapChangeOutcome { + /// Applied (`MappingSuccess`). + Success, + /// A key that is or would be a modifier is down: nothing applied + /// (`MappingBusy`). + Busy, + /// Refused; the error value (Xorg `client->errorValue`). + BadValue(u32), +} + +/// Xorg's `change_modmap` (dix/inpututils.c) for SetModifierMapping and XI +/// SetDeviceModifierMapping (`xi_device`: the XI device; `None` = core). +/// +/// - `build_modmap_from_modkeymap`: row `i / kpm` of the request is modifier +/// `i / kpm`; a keycode listed twice is BadValue with value 0. +/// - `check_modmap_change`: a keycode outside the keycode range is BadValue +/// (value: the lowest such keycode); MappingBusy if a new modifier key is +/// down, or an old one is, where Xorg's loop over the old ones stops short +/// of the last keycode (255). +/// +/// Then the backend edits its XKB keymap's modmap and the events go out in +/// Xorg's order (`XkbApplyMappingChange` → `XkbSendNotification`): +/// XkbMapNotify, core MappingNotify(Modifier), XkbControlsNotify for per-key +/// repeat changes, XkbIndicatorMapNotify. A backend without an XKB keymap +/// gets the map stored for readback instead. An identical map still applies +/// and notifies, as on Xorg. Keyboard devices share the one keymap, so the XI +/// request changes it for every device (Xorg: the device, its master or +/// slaves). +/// +/// `on_applied` runs once the change took effect and before any notification +/// goes out: the XI request sends its DeviceMappingNotify there, so its +/// clients see it ahead of the XKB and core notifications, as on Xorg. +pub(super) fn change_modifier_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + kpm: u8, + keycodes: &[u8], + xi_device: Option, + on_applied: impl FnOnce(&mut ServerState), +) -> ModmapChangeOutcome { + const MIN_KEYCODE: usize = 8; + const MAX_KEYCODE: usize = 255; + let mut modmap = [0u8; 256]; + for (i, &kc) in keycodes.iter().enumerate() { + if kc == 0 { + continue; + } + if modmap[usize::from(kc)] != 0 { + return ModmapChangeOutcome::BadValue(0); + } + modmap[usize::from(kc)] = 1 << (i / usize::from(kpm.max(1))); + } + let down = |kc: usize| state.keys_down[kc >> 3] & (1 << (kc & 7)) != 0; + for (kc, _) in modmap.iter().enumerate().filter(|(_, m)| **m != 0) { + if !(MIN_KEYCODE..=MAX_KEYCODE).contains(&kc) { + return ModmapChangeOutcome::BadValue(u32::try_from(kc).unwrap_or(0)); + } + if down(kc) { + return ModmapChangeOutcome::Busy; + } + } + let current = xi_device + .and_then(|dev| state.xi1_modifier_map.get(&dev).cloned()) + .or_else(|| state.modifier_mapping_override.clone()) + .or_else(|| backend.get_modifier_mapping(origin).ok()); + if let Some((cur_kpm, cur_keys)) = current + && cur_keys.iter().take(8 * usize::from(cur_kpm)).any(|&kc| { + (MIN_KEYCODE..MAX_KEYCODE).contains(&usize::from(kc)) && down(usize::from(kc)) + }) + { + return ModmapChangeOutcome::Busy; + } + + // Xorg XkbSendLegacyMapNotify → XIShouldNotify: the core MappingNotify + // is for clients whose master keyboard changed. An XI request on a slave + // reaches the master only as its lastSlave, which the device an XI client + // remaps isn't on Xorg (XTEST drives a slave of its own there). + let core_notify = xi_device.is_none_or(|dev| dev == crate::xinput::DEVICEID_MASTER_KEYBOARD); + let Some(change) = backend.set_modifier_mapping(&modmap) else { + match xi_device { + Some(dev) => { + state.xi1_modifier_map.insert(dev, (kpm, keycodes.to_vec())); + } + None => state.modifier_mapping_override = Some((kpm, keycodes.to_vec())), + } + on_applied(state); + if core_notify { + let targets: Vec = state.clients.keys().map(|id| ClientId(*id)).collect(); + let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { + let _ = x11::write_mapping_notify_event(buf, order, seq, 0, 0, 0); + }); + } + return ModmapChangeOutcome::Success; + }; + crate::core_loop::xkb_layout::resync_xkb_announced(state, backend); + // The keymap is the one modifier map now: drop any stored readback. + state.modifier_mapping_override = None; + state.xi1_modifier_map.clear(); + on_applied(state); + let xkb_event_base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); + crate::core_loop::xkb_layout::send_xkb_map_notify(state, xkb_event_base, change.map_notify); + if core_notify { + // Xorg XkbSendLegacyMapNotify: MapNotify's changes decide who gets + // the core MappingNotify(Modifier). + crate::core_loop::xkb_select::send_legacy_core_map_notify( + state, + crate::core_loop::xkb_select::LegacyCause::MapNotify, + change.map_notify.changed, + change.map_notify.first_key_sym, + change.map_notify.n_key_syms, + ); + } + crate::core_loop::xkb_layout::send_keyboard_mapping_followups( + state, + xkb_event_base, + &change, + (crate::core_loop::xkb_layout::X_SET_MODIFIER_MAPPING, 0), + ); + ModmapChangeOutcome::Success +} + +pub(super) fn handle_change_keyboard_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let first_keycode = body.first().copied().unwrap_or(8); + let kpk = body.get(1).copied().unwrap_or(0); + let count = header.data; + // Xorg ProcChangeKeyboardMapping (dix/devices.c); BadLength is checked at dispatch. + if first_keycode < 8 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(first_keycode), + 100, + ); + } + // Xorg reports keySymsPerKeyCode as the error value for both conditions. + if u32::from(first_keycode) + u32::from(count) > 256 || kpk == 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(kpk), + 100, + ); + } + // XkbApplyMappingChange changes nothing (and notifies nothing) for zero keys. + if count == 0 { + return Ok(RequestOutcome::Handled); + } + // Body: first_keycode(1) keysyms_per_keycode(1) pad(2) then count × kpk CARD32 keysyms. + let xkb_change = apply_keymap_change( + state, + backend, + first_keycode, + kpk, + count, + &body[4.min(body.len())..], + ); + // Xorg's order (XkbSendNotification): XkbMapNotify, then the core + // MappingNotify (XkbSendLegacyMapNotify), then the ControlsNotify of a + // per-key repeat change and an IndicatorMapNotify. + let xkb_event_base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); + if let Some(change) = &xkb_change { + crate::core_loop::xkb_layout::send_xkb_map_notify(state, xkb_event_base, change.map_notify); + } + // The core MappingNotify (Xorg XkbSendLegacyMapNotify): every client + // but an XKB client that didn't select the change as a MapNotify detail. + legacy_keyboard_mapping_notify(state, xkb_change.as_ref(), first_keycode, count); + if let Some(change) = &xkb_change { + crate::core_loop::xkb_layout::send_keyboard_mapping_followups( + state, + xkb_event_base, + change, + (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), + ); + } + debug!( + "client {} #{} ChangeKeyboardMapping", + client_id.0, sequence.0 + ); + Ok(RequestOutcome::Handled) +} + +/// Hand the rows to the backend's XKB keymap (Xorg `XkbApplyMappingChange`), +/// else to `state.keymap_overrides`. Returns what the XKB keymap change did, +/// for the XKB notifications; `None` for the core-only store. +pub(super) fn apply_keymap_change( + state: &mut ServerState, + backend: &mut dyn Backend, + first_keycode: u8, + kpk: u8, + count: u8, + syms: &[u8], +) -> Option { + let n = usize::from(count) * usize::from(kpk); + let keysyms: Vec = syms + .chunks_exact(4) + .take(n) + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + let change = backend.change_keyboard_mapping(first_keycode, kpk, &keysyms); + crate::core_loop::xkb_layout::resync_xkb_announced(state, backend); + if change.is_none() { + store_keymap_overrides(state, first_keycode, kpk, count, syms); + } + change +} + +/// The core MappingNotify(Keyboard) of a keyboard mapping change, as Xorg's +/// `XkbSendLegacyMapNotify` sends it from the change's MapNotify: to every +/// client but an XKB-initialised one whose map details miss the change. +/// Without an XKB keymap (`None`) the change counts as KeySyms over the +/// request's keys. +pub(super) fn legacy_keyboard_mapping_notify( + state: &mut ServerState, + change: Option<&crate::backend::KeyboardMappingChange>, + first_keycode: u8, + count: u8, +) { + let (changed, first, num) = change.map_or((0x0002, first_keycode, count), |c| { + let m = c.map_notify; + (m.changed, m.first_key_sym, m.n_key_syms) + }); + crate::core_loop::xkb_select::send_legacy_core_map_notify( + state, + crate::core_loop::xkb_select::LegacyCause::MapNotify, + changed, + first, + num, + ); +} + +/// Install `count` keysym rows starting at `first_keycode` into +/// `state.keymap_overrides`, each row `kpk` keysyms wide, read from +/// `syms` as little-endian CARD32s (the wire is normalised to native +/// byte order before reaching here). Shared by core `ChangeKeyboardMapping` +/// (opcode 100) and XI1 `ChangeDeviceKeyMapping` (minor 25) — Xorg drives +/// both through the same `XkbApplyMappingChange`, so the device map and the +/// core map must stay one store. +fn store_keymap_overrides( + state: &mut ServerState, + first_keycode: u8, + kpk: u8, + count: u8, + syms: &[u8], +) { + for i in 0..usize::from(count) { + let mut row: Vec = Vec::with_capacity(usize::from(kpk)); + for j in 0..usize::from(kpk) { + let off = (i * usize::from(kpk) + j) * 4; + let Some(b) = syms.get(off..off + 4) else { + break; + }; + row.push(u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + } + #[allow(clippy::cast_possible_truncation)] + state + .keymap_overrides + .insert(first_keycode.wrapping_add(i as u8), row); + } +} + +/// Fetch the merged keyboard mapping for keycodes `[first_keycode, +/// first_keycode + keycode_count)`: the backend (host/KMS) keymap with +/// any `ChangeKeyboardMapping` rows layered on top. Returns +/// `(keysyms_per_keycode, keysyms)` where `keysyms.len() == +/// keycode_count * keysyms_per_keycode`. Shared by core +/// `GetKeyboardMapping` (opcode 101) and XI1 `GetDeviceKeyMapping` +/// (minor 24) — Xorg derives both from the same `XkbGetCoreMap`. +pub(super) fn fetch_merged_keymap( + state: &ServerState, + backend: &mut dyn Backend, + origin: Option, + first_keycode: u8, + keycode_count: u8, +) -> (u8, Vec) { + let proxied = backend + .get_keyboard_mapping(origin, first_keycode, keycode_count) + .ok(); + // Merge ChangeKeyboardMapping rows over the backend keymap. + { + let (mut kpc, mut keysyms) = proxied.unwrap_or((4, Vec::new())); + if keysyms.is_empty() { + keysyms = vec![0u32; usize::from(keycode_count) * usize::from(kpc)]; + } + let override_kpk = (0..keycode_count) + .filter_map(|i| { + state + .keymap_overrides + .get(&first_keycode.wrapping_add(i)) + .map(Vec::len) + }) + .max() + .unwrap_or(0); + if override_kpk > usize::from(kpc) { + // Widen each row to the override width. + let old = usize::from(kpc); + let mut widened = Vec::with_capacity(usize::from(keycode_count) * override_kpk); + for row in keysyms.chunks(old.max(1)) { + widened.extend_from_slice(row); + widened.extend(std::iter::repeat_n(0u32, override_kpk - row.len())); + } + keysyms = widened; + #[allow(clippy::cast_possible_truncation)] + { + kpc = override_kpk as u8; + } + } + let w = usize::from(kpc); + for i in 0..usize::from(keycode_count) { + #[allow(clippy::cast_possible_truncation)] + let kc = first_keycode.wrapping_add(i as u8); + if let Some(row) = state.keymap_overrides.get(&kc) { + for j in 0..w { + keysyms[i * w + j] = row.get(j).copied().unwrap_or(0); + } + } + } + (kpc, keysyms) + } +} + +pub(super) fn handle_get_keyboard_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + debug!("client {} #{} GetKeyboardMapping", client_id.0, sequence.0); + let first_keycode = body.first().copied().unwrap_or(8); + let keycode_count = body.get(1).copied().unwrap_or(0); + // Xorg ProcGetKeyboardMapping: first < min_keycode or first + + // count - 1 > max_keycode → BadValue. + if first_keycode < 8 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(first_keycode), + 101, + ); + } + if u32::from(first_keycode) + u32::from(keycode_count) > 256 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(first_keycode) + u32::from(keycode_count) - 1, + 101, + ); + } + let merged = fetch_merged_keymap(state, backend, origin, first_keycode, keycode_count); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(64); + x11::write_get_keyboard_mapping_reply_from_keysyms( + &mut buf, byte_order, sequence, merged.0, &merged.1, + )?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_get_modifier_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetModifierMapping", client_id.0, sequence.0); + let proxied = state + .modifier_mapping_override + .clone() + .or_else(|| backend.get_modifier_mapping(origin).ok()); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(64); + if let Some((kpm, keys)) = proxied { + x11::write_get_modifier_mapping_reply_with_keycodes( + &mut buf, byte_order, sequence, kpm, &keys, + )?; + } else { + x11::write_get_modifier_mapping_reply(&mut buf, byte_order, sequence)?; + } + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/largest_free_xid_gap_tests.rs b/crates/yserver-core/src/core_loop/process_request/largest_free_xid_gap_tests.rs new file mode 100644 index 000000000..12d55a5ac --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/largest_free_xid_gap_tests.rs @@ -0,0 +1,23 @@ +use crate::core_loop::process_request::misc::largest_free_xid_gap; + +#[test] +fn largest_free_xid_gap_cases() { + let base = 0x0010_0000u32; + let mask = 0x000F_FFFFu32; + let hi = base | mask; + // empty range → whole range (lo = base since base != 0) + assert_eq!(largest_free_xid_gap(base, mask, &[]), (base, mask + 1)); + // one used id at the start → gap after it + assert_eq!(largest_free_xid_gap(base, mask, &[base]), (base + 1, mask)); + // split: small gap low, big gap high → picks the big one + let used: Vec = (base..base + 10).chain([base + 12]).collect(); + assert_eq!( + largest_free_xid_gap(base, mask, &used), + (base + 13, hi - (base + 13) + 1) + ); + // fully exhausted → Xorg wire shape (0, 1) + let all: Vec = (base..=hi).collect(); // NOTE: 1M entries — fine in a test + assert_eq!(largest_free_xid_gap(base, mask, &all), (0, 1)); + // base 0 (hypothetical) excludes XID 0 + assert_eq!(largest_free_xid_gap(0, 0xFF, &[]), (1, 0xFF)); +} diff --git a/crates/yserver-core/src/core_loop/process_request/misc.rs b/crates/yserver-core/src/core_loop/process_request/misc.rs new file mode 100644 index 000000000..69d351b51 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/misc.rs @@ -0,0 +1,1051 @@ +use crate::{ + access::{AccessMode, Decision, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::Backend, + core_loop::{ + auth::HostChangeError, + host_access::{BadValue, SystemResolver, encode_entries}, + process_request::{ + RequestOutcome, emit_x11_error, emit_x11_error_with_minor, motion_history_range, + write_to_client, + }, + }, + server::{ClientState, ServerState}, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// Peer PID of a client's connection, as captured at setup. X-Resource +/// reports the same identity as `LocalClientPID`; Present uses it to apply +/// per-process scanout policy. `None` for TCP (no credentials) and where the +/// platform reports no pid (FreeBSD). +pub(super) fn client_peer_pid(client: &crate::server::ClientState) -> Option { + client.peer.cred.and_then(|cred| cred.pid) +} + +/// X-Resource (`Res`) extension. `QueryClients` returns the real list of +/// connected clients (their XID ranges); `QueryClientResources` returns +/// real per-type resource counts for a client (the two queries `xrestop` +/// leans on). `QueryClientPixmapBytes` computes live padded pixmap storage. +/// `QueryClientIds` reports ClientXID identities and, where the peer's +/// credentials carry one, its PID. `QueryResourceBytes` remains +/// empty until yserver keeps recursive resource-size accounting. +pub(super) fn handle_x_resource_request( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, x_resource as x11xres}; + + fn target_client_for_xid(state: &ServerState, xid: u32) -> Option { + state + .clients + .iter() + .find(|(_, client)| (xid & !client.resource_id_mask) == client.resource_id_base) + .map(|(id, _)| ClientId(*id)) + } + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + let reply = match minor { + x11xres::QUERY_VERSION => { + let (cmaj, cmin) = x11xres::parse_query_version(body).unwrap_or((0, 0)); + let major = u16::from(cmaj).min(x11xres::MAJOR_VERSION); + let minor_ver = u16::from(cmin).min(x11xres::MINOR_VERSION); + debug!( + "client {} #{} X-Resource::QueryVersion client={cmaj}.{cmin} -> {major}.{minor_ver}", + client_id.0, sequence.0 + ); + x11xres::encode_query_version_reply(byte_order, sequence, major, minor_ver) + } + x11xres::QUERY_CLIENTS => { + // Every connected client by its XID resource range + // (resource_base, resource_mask), sorted by client id for a + // deterministic reply. This is exactly what xrestop and other + // resource monitors read. + let mut entries: Vec<(u32, u32, u32)> = state + .clients + .iter() + .map(|(id, c)| (*id, c.resource_id_base, c.resource_id_mask)) + .collect(); + entries.sort_by_key(|(id, _, _)| *id); + let clients: Vec<(u32, u32)> = entries + .iter() + .map(|(_, base, mask)| (*base, *mask)) + .collect(); + debug!( + "client {} #{} X-Resource::QueryClients -> {} clients", + client_id.0, + sequence.0, + clients.len() + ); + x11xres::encode_query_clients_reply(byte_order, sequence, &clients) + } + x11xres::QUERY_CLIENT_RESOURCES => { + // body: xid(4). X-Resource identifies the target client by the + // xid's resource range (Xorg CLIENT_ID()), not by it being a + // live resource — xrestop passes the client's resource_base. + let xid = if body.len() >= 4 { + u32::from_le_bytes([body[0], body[1], body[2], body[3]]) + } else { + 0 + }; + let Some(target) = target_client_for_xid(state, xid) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + xid, + u16::from(minor), + header.opcode, + ); + }; + let pairs = state.resources.resource_counts_by_owner(target); + let types: Vec<(u32, u32)> = pairs + .iter() + .map(|(name, count)| (state.atoms.intern(name, false).0, *count)) + .collect(); + debug!( + "client {} #{} X-Resource::QueryClientResources xid=0x{xid:x} -> {} types", + client_id.0, + sequence.0, + types.len() + ); + x11xres::encode_query_client_resources_reply(byte_order, sequence, &types) + } + x11xres::QUERY_CLIENT_PIXMAP_BYTES => { + let xid = body + .get(0..4) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) + .unwrap_or(0); + let Some(target) = target_client_for_xid(state, xid) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + xid, + u16::from(minor), + header.opcode, + ); + }; + let bytes = state.resources.pixmap_bytes_by_owner(target); + debug!( + "client {} #{} X-Resource::QueryClientPixmapBytes xid=0x{xid:x} -> {bytes}", + client_id.0, sequence.0, + ); + x11xres::encode_query_client_pixmap_bytes_reply(byte_order, sequence, bytes) + } + x11xres::QUERY_CLIENT_IDS => { + let num_specs = body + .get(0..4) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) + .unwrap_or(0); + // Track the requested mask per client: Xorg applies each spec's + // mask to the clients that spec selects (`WillConstructMask`, + // Xext/xres.c), where mask 0 means "every identity". A client + // named by several specs gets the union. + let mut selected: Vec<(u32, u32)> = Vec::new(); + for spec in body + .get(4..) + .unwrap_or_default() + .chunks_exact(8) + .take(usize::try_from(num_specs).unwrap_or(usize::MAX)) + { + let requested = u32::from_le_bytes(spec[0..4].try_into().unwrap()); + let mask = u32::from_le_bytes(spec[4..8].try_into().unwrap()); + const KNOWN: u32 = x11xres::CLIENT_XID_MASK | x11xres::LOCAL_CLIENT_PID_MASK; + if mask != 0 && mask & KNOWN == 0 { + continue; + } + if requested == 0 { + selected.extend(state.clients.keys().map(|id| (*id, mask))); + } else if let Some(target) = target_client_for_xid(state, requested) { + selected.push((target.0, mask)); + } + } + selected.sort_unstable(); + let mut merged: Vec<(u32, u32)> = Vec::with_capacity(selected.len()); + for (id, mask) in selected { + match merged.last_mut() { + Some((prev, acc)) if *prev == id => *acc |= mask, + _ => merged.push((id, mask)), + } + } + + let mut entries = Vec::with_capacity(merged.len()); + for (id, mask) in merged { + let Some(client) = state.clients.get(&id) else { + continue; + }; + let base = client.resource_id_base; + // Xorg emits ClientXID first, then LocalClientPID. + if mask == 0 || mask & x11xres::CLIENT_XID_MASK != 0 { + entries.push(x11xres::ClientIdEntry::xid(base)); + } + if mask == 0 || mask & x11xres::LOCAL_CLIENT_PID_MASK != 0 { + // Omitted when the OS cannot supply a pid, exactly as Xorg + // skips the identity when GetClientPid returns -1. + if let Some(pid) = client_peer_pid(client) { + entries.push(x11xres::ClientIdEntry::pid(base, pid)); + } + } + } + debug!( + "client {} #{} X-Resource::QueryClientIds -> {} identities", + client_id.0, + sequence.0, + entries.len(), + ); + x11xres::encode_query_client_ids_reply(byte_order, sequence, &entries) + } + x11xres::QUERY_RESOURCE_BYTES => { + debug!( + "client {} #{} X-Resource::QueryResourceBytes -> 0 sizes (stub)", + client_id.0, sequence.0 + ); + x11xres::encode_query_resource_bytes_empty_reply(byte_order, sequence) + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &reply)) +} + +/// Returns `(major_opcode, first_event, first_error)` for an extension +/// the client just queried, or `None` if it isn't available. Mirrors +/// `nested::extension_query_reply` but operates on a live +/// `&mut dyn Backend` instead of `Option<&Arc>>`. +pub(super) fn extension_query_reply(name: &str, backend: &mut dyn Backend) -> Option<(u8, u8, u8)> { + use crate::nested::EXTENSIONS; + let ext = EXTENSIONS.iter().find(|ext| ext.name == name)?; + if !extension_available(ext, backend) { + return None; + } + if ext.availability == crate::nested::ExtensionAvailability::HostXkb { + let (_, first_event, first_error) = backend.xkb_info()?; + return Some((ext.major_opcode, first_event, first_error)); + } + Some((ext.major_opcode, ext.first_event, ext.first_error)) +} + +pub(super) fn extension_available( + ext: &crate::nested::ExtensionMetadata, + backend: &mut dyn Backend, +) -> bool { + use crate::nested::ExtensionAvailability; + match ext.availability { + ExtensionAvailability::Always => true, + ExtensionAvailability::HostRender => backend.render_opcode().is_some(), + ExtensionAvailability::HostXkb => backend.xkb_opcode().is_some(), + ExtensionAvailability::Dri3 => backend.dri3_capabilities().version != (0, 0), + ExtensionAvailability::Glx => backend.glx_available(), + ExtensionAvailability::Unix => cfg!(unix), + } +} + +/// Find the registered extension handler for a major opcode. Discovery +/// availability is deliberately not part of this lookup: dispatch is fixed +/// by the server's opcode table even when a backend hides the extension. +pub(super) fn extension_by_opcode(major: u8) -> Option<&'static crate::nested::ExtensionMetadata> { + crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.major_opcode == major) +} + +/// Release a reader waiting for the result of BIG-REQUESTS Enable. +pub(super) fn release_big_requests_reader(state: &ServerState, client_id: ClientId) { + if let Some(client) = state.clients.get(&client_id.0) + && let Some(tx) = client.reader_control.as_ref() + { + let _ = tx.send(crate::server::ReaderControl::IgnoreBigRequests); + } +} + +pub(super) fn advertised_extension_names(backend: &mut dyn Backend) -> Vec<&'static str> { + use crate::nested::EXTENSIONS; + EXTENSIONS + .iter() + .filter(|ext| extension_available(ext, backend)) + .map(|ext| ext.name) + .collect() +} + +pub(super) fn handle_grab_server( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + // Requests from another client are held by the core loop and therefore + // never reach this handler while a grab is active. Re-grabbing by the + // owner is idempotent, as in Xorg's ProcGrabServer. + if state.server_grab_owner.is_none() || state.server_grab_owner == Some(client_id) { + state.server_grab_owner = Some(client_id); + } + debug!("client {} #{} GrabServer", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_ungrab_server( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + // A non-owner cannot normally reach this handler: its request is parked + // behind the active grab. Keeping the ownership check makes direct unit + // calls and future dispatch changes fail closed. + if state.server_grab_owner == Some(client_id) { + state.server_grab_owner = None; + } + debug!("client {} #{} UngrabServer", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// The existing locality rule for changing the host list or access mode: +/// Xorg's `AuthorizedClient` without `-ac` (`os/access.c:1293-1307`). Callers +/// ask the `DixManageAccess` policy hook before applying this rule. +fn may_manage_access(client: &ClientState) -> bool { + client.is_local +} + +/// Who may list the hosts: anyone, as in Xorg (`dix/dispatch.c:3280-3283`). +/// The hook point for SECURITY's `DixReadAccess`. +fn may_read_access(_client: &ClientState) -> bool { + true +} + +/// ListHosts (110): `enabled` and the entries, newest first +/// (`dix/dispatch.c:3270-3304`). +pub(super) fn handle_list_hosts( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} ListHosts", client_id.0, sequence.0); + let handle = state.host_access.clone(); + let Some(client) = state.clients.get(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + if !may_read_access(client) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 110); + } + if let Decision::Deny(error) = state.check_server( + client_id, + AccessMode::READ, + Some(RequestOpcodes { + major: 110, + minor: 0, + }), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 110); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let (enabled, hosts) = handle.auth.list_hosts(handle.generation); + let (n_hosts, entries) = encode_entries(&hosts, byte_order); + let mut buf: Vec = Vec::with_capacity(32 + entries.len()); + x11::write_list_hosts_reply(&mut buf, byte_order, sequence, enabled, n_hosts, &entries)?; + Ok(write_to_client(client, client_id, &buf)) +} + +/// ChangeHosts (109): mode in `header.data`, then `family, pad, +/// length:CARD16, address`. Xorg's order: mode (`dix/dispatch.c:3253-3267`), +/// access, then family and address (`os/access.c:1313-1446`). `BadAccess` +/// carries 0; Xorg sends whatever `errorValue` the client had last. +pub(super) fn handle_change_hosts( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let mode = header.data; + debug!( + "client {} #{} ChangeHosts mode={mode}", + client_id.0, sequence.0 + ); + if mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mode), + 109, + ); + } + if let Decision::Deny(error) = state.check_server( + client_id, + AccessMode::MANAGE, + Some(RequestOpcodes { + major: 109, + minor: 0, + }), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 109); + } + let Some(client) = state.clients.get(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + if !may_manage_access(client) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 109); + } + // The generic length check already matched the request length to the + // address length; the body is little-endian here. + let (Some(&family), Some(len)) = (body.first(), body.get(2..4)) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 109); + }; + let len = u16::from_le_bytes([len[0], len[1]]); + let Some(addr) = body.get(4..4 + usize::from(len)) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 109); + }; + let handle = state.host_access.clone(); + let (code, value) = + match handle + .auth + .change_hosts(handle.generation, mode == 0, family, addr, &SystemResolver) + { + Ok(()) => return Ok(RequestOutcome::Handled), + Err(HostChangeError::Value(BadValue::Length)) => { + (x11::error::BAD_VALUE, u32::from(len)) + } + Err(HostChangeError::Value(BadValue::Family)) => { + (x11::error::BAD_VALUE, u32::from(family)) + } + Err(HostChangeError::Access) => (x11::error::BAD_ACCESS, 0), + }; + emit_x11_error(state, client_id, sequence, code, value, 109) +} + +/// SetAccessControl (111): mode 1 enables access control, 0 disables it +/// (`xhost -`/`xhost +`). Mode, then access (`dix/dispatch.c:3307-3317`, +/// `os/access.c:1616-1623`). Connected clients are not touched. +pub(super) fn handle_set_access_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, +) -> io::Result { + let mode = header.data; + debug!( + "client {} #{} SetAccessControl mode={mode}", + client_id.0, sequence.0 + ); + if mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mode), + 111, + ); + } + if let Decision::Deny(error) = state.check_server( + client_id, + AccessMode::MANAGE, + Some(RequestOpcodes { + major: 111, + minor: 0, + }), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 111); + } + let Some(client) = state.clients.get(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + if !may_manage_access(client) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 111); + } + let handle = state.host_access.clone(); + match handle.auth.set_access_enabled(handle.generation, mode == 1) { + Ok(()) => Ok(RequestOutcome::Handled), + Err(_) => emit_x11_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, 111), + } +} + +/// SetCloseDownMode (112): mode is in header.data. Valid values are +/// 0 (Destroy), 1 (RetainPermanent), 2 (RetainTemporary). Any other +/// value is BadValue. The stored mode is consulted by `process_disconnect` +/// to decide whether to free the client's resources or keep them +/// (with the original `owner: ClientId` intact) and record the client +/// as a zombie in `ServerState.zombie_clients`. +pub(super) fn handle_set_close_down_mode( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, +) -> io::Result { + debug!( + "client {} #{} SetCloseDownMode mode={}", + client_id.0, sequence.0, header.data + ); + if header.data > 2 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(header.data), + 112, + ); + } + if header.data == 0 { + state.close_down_modes.remove(&client_id.0); + } else { + state.close_down_modes.insert(client_id.0, header.data); + } + Ok(RequestOutcome::Handled) +} + +/// KillClient (113): resource ID lives in the first 4 bytes of `body`. +/// `resource == 0` is the spec-defined `AllTemporary` magic — destroy +/// every zombie client whose stored close-down mode is `RetainTemporary`. +/// Otherwise look up the resource's owner: if it's a live client, +/// force-disconnect them (their close-down mode still applies); if it's +/// a zombie, destroy that zombie's resources; if it's `SERVER_OWNER`, +/// noop; if the resource doesn't exist, BadValue. +pub(super) fn handle_kill_client( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let resource = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + debug!( + "client {} #{} KillClient resource=0x{:x}", + client_id.0, sequence.0, resource + ); + if resource == 0 { + let temp_zombies: Vec = state + .zombie_clients + .iter() + .filter_map(|(&id, &mode)| (mode == 2).then_some(id)) + .collect(); + for zid in temp_zombies { + // On `Err` the zombie stays recorded and the rest wait: the + // server is shutting down (`fatal_teardown`). + if crate::core_loop::process_disconnect::destroy_zombie_resources( + state, + backend, + ClientId(zid), + ) + .is_err() + { + break; + } + state.zombie_clients.remove(&zid); + } + return Ok(RequestOutcome::Handled); + } + let Some(owner) = state.resources.resource_owner(ResourceId(resource)) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + resource, + 113, + ); + }; + if state.policies_installed() { + let id = ResourceId(resource); + // Follow resource_owner's core-store order. In particular, do not + // widen KillClient's existing misses to colormaps or extension stores. + let kind = [ + ResourceKind::Window, + ResourceKind::Pixmap, + ResourceKind::Gc, + ResourceKind::Font, + ResourceKind::Cursor, + ResourceKind::Picture, + ResourceKind::GlyphSet, + ResourceKind::Dri3Syncobj, + ] + .into_iter() + .find(|kind| state.access_resource_owner(id, *kind).is_some()); + if let Some(kind) = kind + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id, + kind, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 113); + } + } + if owner == crate::resources::SERVER_OWNER { + // Server-reserved resource (root window, overlay, etc.). Noop. + return Ok(RequestOutcome::Handled); + } + if state.zombie_clients.contains_key(&owner.0) { + // On `Err` the zombie stays recorded; the server is shutting down. + if crate::core_loop::process_disconnect::destroy_zombie_resources(state, backend, owner) + .is_ok() + { + state.zombie_clients.remove(&owner.0); + } + return Ok(RequestOutcome::Handled); + } + if owner == client_id { + // X11 spec: KillClient targeting any of your own resources + // forces your own connection closed. Your stored close-down + // mode still applies — process_disconnect consults it. + return Ok(RequestOutcome::Disconnect(client_id)); + } + if state.clients.contains_key(&owner.0) { + // Force-disconnect the other client. Their close-down mode is + // honored: if they set RetainPermanent / RetainTemporary, + // their resources survive (they become a zombie) instead of + // being freed. + crate::core_loop::process_disconnect::process_disconnect(state, backend, owner); + } + Ok(RequestOutcome::Handled) +} + +/// GetMotionEvents (39): return bounded pointer history translated into the +/// requested window, filtering samples outside its border-inclusive bounds. +pub(super) fn handle_get_motion_events( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let Some(win) = state.resources.window(window) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 39, + ); + }; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 39); + } + let (width, height, border) = (win.width, win.height, win.border_width); + let (origin_x, origin_y) = state.resources.window_absolute_position(window); + let start = u32::from_le_bytes(body[4..8].try_into().expect("four bytes")); + let stop = u32::from_le_bytes(body[8..12].try_into().expect("four bytes")); + let border = i32::from(border); + let xmin = origin_x - border; + let ymin = origin_y - border; + let xmax = origin_x + i32::from(width) + border; + let ymax = origin_y + i32::from(height) + border; + let history: Vec<_> = motion_history_range(state, start, stop) + .into_iter() + .filter(|record| { + let x = i32::from(record.root_x); + let y = i32::from(record.root_y); + (xmin..xmax).contains(&x) && (ymin..ymax).contains(&y) + }) + .collect(); + debug!("client {} #{} GetMotionEvents", client_id.0, sequence.0); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let length_words = u32::try_from(history.len()) + .unwrap_or(u32::MAX) + .saturating_mul(2); + let mut buf = x11::fixed_reply(client.byte_order, sequence, 0, length_words); + x11::write_u32( + client.byte_order, + &mut buf, + u32::try_from(history.len()).unwrap_or(u32::MAX), + ); + buf.extend_from_slice(&[0u8; 20]); + for record in history { + x11::write_u32(client.byte_order, &mut buf, record.time); + x11::write_i16( + client.byte_order, + &mut buf, + i16::try_from(i32::from(record.root_x) - origin_x).unwrap_or(i16::MAX), + ); + x11::write_i16( + client.byte_order, + &mut buf, + i16::try_from(i32::from(record.root_y) - origin_y).unwrap_or(i16::MAX), + ); + } + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_ge_request( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, +) -> io::Result { + if header.data == 0 { + debug!("client {} #{} GEQueryVersion", client_id.0, sequence.0); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_ge_query_version_reply(&mut buf, byte_order, sequence)?; + return Ok(write_to_client(client, client_id, &buf)); + } + emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(header.data), + header.opcode, + ) +} + +pub(super) fn handle_big_requests_request( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, +) -> io::Result { + if header.data != 0 { + // Malformed minor — the reader thread parked waiting for an + // Apply / Ignore signal after sending the Enable through the + // channel; unblock it with `IgnoreBigRequests` so it doesn't + // deadlock. + release_big_requests_reader(state, client_id); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(header.data), + header.opcode, + ); + } + debug!("client {} #{} BigRequestsEnable", client_id.0, sequence.0); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + client.big_requests_enabled = true; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_big_requests_enable_reply( + &mut buf, + byte_order, + sequence, + x11::MAX_BIG_REQUEST_UNITS, + )?; + let outcome = write_to_client(client, client_id, &buf); + // Unblock the reader so subsequent requests use big-framing. + if let Some(tx) = client.reader_control.as_ref() { + let _ = tx.send(crate::server::ReaderControl::ApplyBigRequests); + } + Ok(outcome) +} + +pub(super) fn handle_query_extension( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + let name = x11::query_extension_name(body); + let mut extension = extension_query_reply(&name, backend); + if state.policies_installed() { + extension = extension.filter(|_| { + matches!( + state.check_extension_access( + client_id, + &name, + Some(RequestOpcodes { + major: 98, + minor: 0, + }), + ), + Decision::Allow + ) + }); + } + let (present, major_opcode, first_event, first_error) = extension + .map(|(major_opcode, first_event, first_error)| { + (true, major_opcode, first_event, first_error) + }) + .unwrap_or((false, 0, 0, 0)); + debug!( + "client {} #{} QueryExtension {:?} -> {}", + client_id.0, + sequence.0, + name, + if present { "present" } else { "absent" } + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_query_extension_reply( + &mut buf, + byte_order, + sequence, + present, + major_opcode, + first_event, + first_error, + )?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_list_extensions( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} ListExtensions", client_id.0, sequence.0); + let mut names = advertised_extension_names(backend); + if state.policies_installed() { + names.retain(|name| { + matches!( + state.check_extension_access( + client_id, + name, + Some(RequestOpcodes { + major: 99, + minor: 0, + }), + ), + Decision::Allow + ) + }); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32 + names.len() * 16); + x11::write_list_extensions_reply(&mut buf, byte_order, sequence, &names)?; + Ok(write_to_client(client, client_id, &buf)) +} + +/// Largest contiguous free run in `[max(base,1) .. base|mask]`, +/// given the SORTED+DEDUPED occupied ids in that range. Returns +/// Xorg's exact exhaustion wire shape `(0, 1)` when nothing is free +/// (dix/resource.c:733-737 zeroes min/max; the reply encodes +/// max-min+1 = 1; libxcb treats start 0 as exhausted). Largest-gap +/// is an implementation choice — the protocol promises only "a +/// contiguous range of unused IDs" (spec "GetXIDRange algorithm"). +pub(super) fn largest_free_xid_gap(base: u32, mask: u32, used_sorted: &[u32]) -> (u32, u32) { + let lo = base.max(1); // XID 0 is never allocatable + let hi = base | mask; + let mut best_start = 0u32; + let mut best_len = 0u64; + let mut cursor = lo; + for &u in used_sorted { + if u < lo { + continue; + } + if u > hi { + break; + } + if u > cursor { + let len = u64::from(u - cursor); + if len > best_len { + best_len = len; + best_start = cursor; + } + } + cursor = cursor.max(u.saturating_add(1)); + } + if cursor <= hi { + let len = u64::from(hi - cursor) + 1; + if len > best_len { + best_len = len; + best_start = cursor; + } + } + if best_len == 0 { + (0, 1) + } else { + #[allow(clippy::cast_possible_truncation)] + (best_start, best_len as u32) // len ≤ hi - lo + 1 ≤ hi ≤ u32::MAX + } +} + +/// XC-MISC (major opcode 152) — XID recycling for long-lived clients. +/// Spec docs/superpowers/specs/2026-06-12-xcmisc-design.md; Xorg ref +/// Xext/xcmisc.c. Length validation lives here because the top-level +/// exact-length table is core-opcode-only. +pub(super) fn handle_xcmisc_request( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::ClientByteOrder; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + match minor { + // GetVersion — req 8 bytes (client version, ignored). + 0 => { + if body.len() != 4 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + let mut buf: Vec = Vec::with_capacity(32); + x11::write_xcmisc_get_version_reply(&mut buf, byte_order, sequence)?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &buf)) + } + // GetXIDRange — req 4 bytes (header only). + 1 => { + if !body.is_empty() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + let Some((base, mask)) = state + .clients + .get(&client_id.0) + .map(|c| (c.resource_id_base, c.resource_id_mask)) + else { + return Ok(RequestOutcome::Handled); + }; + let used = state.used_xids_in(base, mask); + let (start_id, count) = largest_free_xid_gap(base, mask, &used); + log::info!( + "client {} XC-MISC GetXIDRange → start=0x{start_id:x} count={count} \ + ({} ids in use)", + client_id.0, + used.len(), + ); + let mut buf: Vec = Vec::with_capacity(32); + x11::write_xcmisc_get_xid_range_reply(&mut buf, byte_order, sequence, start_id, count)?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &buf)) + } + // GetXIDList — req 8 bytes: count(4). + 2 => { + if body.len() != 4 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + let want = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + let Some((base, mask)) = state + .clients + .get(&client_id.0) + .map(|c| (c.resource_id_base, c.resource_id_mask)) + else { + return Ok(RequestOutcome::Handled); + }; + // Clamp to the range size — never allocate + // client-controlled gigabytes (explicit Xorg deviation, + // spec "Edge cases"; Xorg would BadAlloc instead). + let limit = u64::from(want).min(u64::from(mask) + 1); + let mut ids: Vec = Vec::new(); + let lo = base.max(1); + let hi = base | mask; + let mut id = lo; + while ids.len() < limit as usize { + if !state.xid_occupied(id) { + ids.push(id); + } + if id == hi { + break; + } + id += 1; + } + log::info!( + "client {} XC-MISC GetXIDList want={want} → {} ids", + client_id.0, + ids.len(), + ); + let mut buf: Vec = Vec::with_capacity(32 + ids.len() * 4); + x11::write_xcmisc_get_xid_list_reply(&mut buf, byte_order, sequence, &ids)?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &buf)) + } + other => emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ), + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/present_ext.rs b/crates/yserver-core/src/core_loop/process_request/present_ext.rs new file mode 100644 index 000000000..cb8e17e95 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/present_ext.rs @@ -0,0 +1,3188 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + damage_fanout::accumulate_damage_to_state, + process_request::{ + PRESENT_ALL_OPTIONS, PresentDomainSelection, RANDR_BAD_CRTC, RequestOutcome, + SYNC_BAD_FENCE, XFIXES_BAD_REGION, emit_x11_error_with_minor, window_unviewable, + write_to_client, + }, + }, + server::{PendingPresentPixmap, PendingPresentRequest, ServerState}, +}; +use log::debug; +use std::{collections::HashMap, io}; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// Task 13 (spec §"Amendment 2026-08-01 — successor-gate relaxation"): +/// single source of truth for whether `successor` provably presents its +/// full source extent, and therefore may act as a scrap successor at +/// all. MANDATORY shared helper — used by BOTH +/// `present_supersession_covers` (the coverage gate below) and +/// `supersede_covered_pending_presents`'s decline-telemetry guard; they +/// must agree on what "cleared the gate" means, or the telemetry +/// mislabels every full-extent-region decline as a coverage failure. +/// +/// `None` (unchanged Xorg gate, `present_scmd.c:802`) always passes. +/// `Some(rects)` passes iff at least one single rect `r` contains the +/// full source extent, every term explicitly widened to `i32` (as +/// literally written in `i16`/`u16` this would not compile, and `u16` +/// arithmetic would wrap on negative `r.x`): +/// +/// ```text +/// i32::from(r.x) <= 0 +/// && i32::from(r.y) <= 0 +/// && i32::from(r.x) + i32::from(r.width) >= i32::from(src_width) +/// && i32::from(r.y) + i32::from(r.height) >= i32::from(src_height) +/// ``` +/// +/// (pixmap coordinates, before `x_off`/`y_off` translation — Xorg +/// installs the update region as a `CT_REGION` clip with +/// `GCClipXOrigin/GCClipYOrigin = x_off/y_off`, `present.c:76-92`.) A +/// zero-area rect can never satisfy both `>=` conditions, so +/// `Some([zero-area rect])` and `Some(empty)` both decline via `.any()` +/// on an iterator that is either empty or has no satisfying element. +/// Union coverage across multiple rects is deliberately NOT computed (no +/// observed client needs it — see the spec amendment's rejected- +/// alternative note): a multi-rect region whose union but no single rect +/// covers the extent declines, conservatively. +fn successor_presents_full_extent(successor: &PendingPresentPixmap) -> bool { + match &successor.update_rects { + None => true, + Some(rects) => rects.iter().any(|r| { + i32::from(r.x) <= 0 + && i32::from(r.y) <= 0 + && i32::from(r.x) + i32::from(r.width) >= i32::from(successor.src_width) + && i32::from(r.y) + i32::from(r.height) >= i32::from(successor.src_height) + }), + } +} + +/// Task 8 §Supersession coverage predicate (spec §Supersession; Xorg +/// verification item (d), `present_scmd.c:802`). `successor` is the +/// newly-arriving present `B`; `predecessor` is a candidate victim `A` +/// already sitting unexecuted in `present_pending_exec`. Pure — no state +/// mutation, so the arrival-time coverage scan +/// (`supersede_covered_pending_presents`) can call it as a `.filter()` +/// predicate. +/// +/// Destination-coordinate arithmetic in `i32`: offsets (`x_off`/`y_off`) +/// are `i16` and may be negative (a present whose window is partially +/// off-screen), and must NOT saturate the way `execute_present_pixmap_copy`'s +/// copy-time math does (`saturating_add`) — a saturated coordinate could +/// make an uncovered predecessor look covered. +/// +/// The **successor gate comes first**, via `successor_presents_full_extent` +/// (spec §"Amendment 2026-08-01 — successor-gate relaxation"): Xorg's +/// scrap loop (`present_scmd.c:802`, `if (!update && pixmap)`) attempts +/// scrap only when the successor carries no update region; yserver +/// additionally accepts a `Some(rects)` successor when one single rect +/// provably covers the full source extent (the NVIDIA-WSI shape — a +/// full-extent single-rect update region where Mesa attaches none). A +/// successor whose update region does not clear that gate — including +/// the documented zero-pixel `Some(empty)` present and any partial or +/// multi-rect-union-only region — never scraps anything, regardless of +/// predecessor geometry; this still dissolves the marco/picom +/// drag-sliver risk (a sliver successor's region never clears the gate). +/// +/// Given the gate passes, coverage is yserver's strictly conservative +/// addition on top of Xorg (which is geometry-blind): the predecessor's +/// footprint, in destination coordinates, must fit entirely inside the +/// successor's full-extent rect (top-left `(x_off, y_off)`, bottom-right +/// `(x_off plus src_width, y_off plus src_height)`) — source-pixmap- +/// bounded, not window-bounded, which matters mid-resize when Mesa +/// reallocates swapchain pixmaps on `PresentConfigureNotify`. A +/// predecessor with `update_rects == None` is covered iff its own +/// full-extent rect fits; `Some(rects)` iff every destination rect fits; +/// `Some(empty)` is trivially covered (no content, so nothing can fail +/// to fit — falls out of `.all()` on an empty iterator). +pub(super) fn present_supersession_covers( + successor: &PendingPresentPixmap, + predecessor: &PendingPresentPixmap, +) -> bool { + if !successor_presents_full_extent(successor) { + return false; + } + + let (succ_x, succ_y) = successor.request.offsets(); + let (succ_x, succ_y) = (i32::from(succ_x), i32::from(succ_y)); + let succ_right = succ_x + i32::from(successor.src_width); + let succ_bottom = succ_y + i32::from(successor.src_height); + + let fits = |x: i32, y: i32, w: i32, h: i32| -> bool { + x >= succ_x && y >= succ_y && x + w <= succ_right && y + h <= succ_bottom + }; + + let (pred_x_i16, pred_y_i16) = predecessor.request.offsets(); + let (pred_x, pred_y) = (i32::from(pred_x_i16), i32::from(pred_y_i16)); + match &predecessor.update_rects { + None => fits( + pred_x, + pred_y, + i32::from(predecessor.src_width), + i32::from(predecessor.src_height), + ), + Some(rects) => rects.iter().all(|r| { + // Evaluate exactly where the real copy lands + // (`execute_present_pixmap_copy`'s `x_off.saturating_add(rect.x)`, + // computed in `i16` — not unsaturated `i32` addition). Near + // `i16::MAX` the two disagree: an unsaturated `pred_x + r.x` + // can land past where the copy's saturated dest actually + // draws, so the predicate would judge "covered" at a + // position the copy never used (sliver loss). Saturate in + // `i16` first, exactly like the copy, then widen to `i32` + // only for the extent comparison. + fits( + i32::from(pred_x_i16.saturating_add(r.x)), + i32::from(pred_y_i16.saturating_add(r.y)), + i32::from(r.width), + i32::from(r.height), + ) + }), + } +} + +/// Task 8 §Supersession: build the `CompletedPresentEvent` a scrapped or +/// copy-failed entry would have produced had it reached +/// `execute_present_pixmap_copy`'s `enqueue_present_completion` call — +/// fields exactly as that function builds them (`host_xid` is the +/// client-visible pixmap XID, not the backend host xid, matching the +/// wire-event identity Mesa expects). +pub(super) fn completed_event_for_pending( + pending: &PendingPresentPixmap, +) -> crate::backend::CompletedPresentEvent { + crate::backend::CompletedPresentEvent { + client_id: pending.client_id, + serial: pending.request.serial(), + host_xid: pending.request.pixmap(), + dst_host_xid: pending.request.window(), + options: pending.masked_options, + present_id: pending.present_id, + window_generation: pending.window_generation, + crtc_id: pending.crtc_id, + crtc_epoch: pending.crtc_epoch, + msc_offset: pending.msc_offset, + completion_clock: None, + wake: pending.wake.clone(), + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + } +} + +/// IdleNotify-only half of `fire_present_completion_events_at`, fired +/// immediately at supersession scrap and at the copy-failure reroute +/// (Task 8) — deliberately NOT reusing `fire_present_completion_events_at` +/// itself, whose `CompleteNotify` half must NOT fire at this point (the +/// completion is parked for ordered delivery at the target MSC instead). +/// Modeled on the `IdleNotify` branch of that function: same selection +/// lookup, same `encode_idle_notify` call, gated on `IDLE_NOTIFY_MASK`. +fn fire_present_idle_notify_now( + state: &mut ServerState, + event: &crate::backend::CompletedPresentEvent, +) { + use crate::backend::PresentWake; + use yserver_protocol::x11::present as x11present; + + /// PRESENT major opcode. + const PRESENT_MAJOR_OPCODE: u8 = 145; + /// `PresentEventMaskIdleNotify`. + const IDLE_NOTIFY_MASK: u32 = 0x4; + + let window = ResourceId(event.dst_host_xid); + let pixmap_xid = event.host_xid; + let idle_fence = match &event.wake { + PresentWake::Pixmap { idle_fence_xid } => *idle_fence_xid, + PresentWake::PixmapSynced { + release_syncobj, .. + } => *release_syncobj, + }; + + let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); + for (eid, sel) in &state.present_event_selections { + if sel.window == window { + targets.push((*eid, sel.owner, sel.event_mask)); + } + } + + for (eid, owner, mask) in targets { + if mask & IDLE_NOTIFY_MASK == 0 { + continue; + } + let Some(client) = state.clients.get_mut(&owner.0) else { + continue; + }; + let byte_order = client.byte_order; + let seq = SequenceNumber( + client + .last_sequence + .load(std::sync::atomic::Ordering::Relaxed), + ); + let ev = x11present::encode_idle_notify( + byte_order, + seq, + PRESENT_MAJOR_OPCODE, + eid, + window.0, + event.serial, + pixmap_xid, + idle_fence, + ); + let _ = write_to_client(client, owner, &ev); + } +} + +/// Complete a covered, same-target Present as Skip after its source is no +/// longer allowed to be shown. The entry's producer wait and source pin are +/// owned by the caller; this handles the buffer wake and ordered wire +/// completion shared by arrival-time MSC scrap and a late fence waiter. +fn complete_pending_present_as_skip( + state: &mut ServerState, + backend: &mut dyn Backend, + pending: &PendingPresentPixmap, + target: u64, +) { + backend.note_present_skip(); + match &pending.wake { + crate::backend::PresentWake::Pixmap { idle_fence_xid } if *idle_fence_xid != 0 => { + if let Err(e) = backend.dri3_trigger_fence(*idle_fence_xid) { + log::warn!( + "PRESENT supersede: trigger idle fence 0x{idle_fence_xid:x} failed: {e}" + ); + } + crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); + } + crate::backend::PresentWake::PixmapSynced { + release, + release_syncobj, + release_value, + } => { + if let Err(e) = release.signal(*release_value) { + log::warn!( + "PRESENT supersede: signal release syncobj 0x{release_syncobj:x}@\ + {release_value} failed: {e}" + ); + } + } + _ => {} + } + let event = completed_event_for_pending(pending); + fire_present_idle_notify_now(state, &event); + state + .present_pending_complete + .push(crate::server::PendingPresentComplete { + event, + effective_target_msc: target, + mode: yserver_protocol::x11::present::COMPLETE_MODE_SKIP, + emit_idle: false, + }); +} + +/// Task 8 §Supersession: scan `present_pending_exec` for entries covered +/// by the newly-arriving successor `successor` and scrap them. Called in +/// BOTH Present::Pixmap and Present::PixmapSynced handlers right after +/// `pending` is fully built and after the successor's own +/// `arm_present_source_wait` / `arm_present_syncobj_wait` has already +/// succeeded (arm-before-scrap: see the comment at each call site) — +/// scrap happens at arrival regardless of whether the successor's own +/// source was ready or deferred, and regardless of its own park/execute +/// msc-due classification. +/// +/// Gated on the successor having a known effective target. A successor +/// with `effective_target_msc = None` never scraps because target +/// equivalence is not known. Victims are covered entries in +/// `present_pending_exec` for the same window, CRTC domain, and effective +/// target. Their target is classified at successor arrival with the same +/// general-clock/flip-in-flight classifier used by +/// `arrival_execute_or_park_present_pixmap`: `Park` victims are scrapped +/// whether waiting for MSC or their producer, while `ExecuteNow` victims +/// waiting for a source/acquire fence remain until that fence signals. +/// +/// `source_ready` records producer readiness, independently of MSC +/// parking. The ready `Pixmap` and `PixmapSynced` arrival paths insert +/// `source_ready: true, wait_id: None` only when the MSC classifier parks +/// them; the deferred source-pixmap and acquire-syncobj paths insert +/// `source_ready: false, wait_id: Some(_)`. When either wait resolves, +/// `drain_ready_present_pixmaps` runs the same MSC classifier before it +/// executes or parks the request. +pub(super) fn supersede_covered_pending_presents( + state: &mut ServerState, + backend: &mut dyn Backend, + successor: &PendingPresentPixmap, +) { + let Some(target) = successor.effective_target_msc else { + return; + }; + if !backend.present_supersedes_same_msc() { + return; + } + let window = successor.request.window(); + let (successor_msc_due, _, _) = + classify_present_pixmap_msc_due_at_arrival(state, backend, successor); + let mut victim_ids: Vec = Vec::new(); + for (&pid, entry) in &state.present_pending_exec { + if successor_msc_due != crate::present_scheduler::MscDue::Park + || entry.pending.request.window() != window + || entry.pending.crtc_id != successor.crtc_id + || entry.pending.crtc_epoch != successor.crtc_epoch + || entry.pending.effective_target_msc != Some(target) + { + continue; + } + if present_supersession_covers(successor, &entry.pending) { + victim_ids.push(pid); + } else if successor_presents_full_extent(successor) { + // Task 10 telemetry (spec §Telemetry / verification item (d)): + // the successor cleared the amended successor gate + // (`successor_presents_full_extent` — no update region, or a + // single rect covering the full source extent) but yserver's + // own extent-coverage check declined this candidate anyway — + // the empirical input for the future coverage-relaxation + // decision. Excluded here: successors whose update region + // does NOT clear the gate, which never even attempt scrap + // (the gate itself, `present_supersession_covers`'s first + // check) and would flood this log on every marco-style + // partial update. + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=supersede_declined by={} window=0x{:x} eff={}", + pace_instr_ms(), pid, successor.present_id, window, target + ); + } + } + + for pid in victim_ids { + let Some(entry) = state.present_pending_exec.remove(&pid) else { + continue; + }; + // 1. Cancel the source/acquire wait if armed, and release the + // entry's own source pin. + if let Some(wid) = entry.wait_id { + backend.finish_present_source_wait(wid); + state.present_wait_to_id.remove(&wid); + } + if let Some(pin) = entry.pin { + backend.release_present_source(pin); + } + // The entry never reached `enqueue_present_completion`; this is its + // sole buffer-release path. The X11 fence mirror is updated together + // with the wake so QueryFence cannot lag behind a released buffer. + complete_pending_present_as_skip(state, backend, &entry.pending, target); + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=superseded by={} window=0x{:x} eff={}", + pace_instr_ms(), pid, successor.present_id, window, target + ); + // The entry + side-map row are already gone (removed above); the + // Skip is queued by `complete_pending_present_as_skip`. + } +} + +/// Arm a `Present::Pixmap` successor's own source-pixmap wait, then scrap +/// covered pending entries — **in this order, never reversed**. The arm +/// is client-reachably fallible; scrap is not reversible (it releases +/// victims' buffers and fires their IdleNotify/Skip immediately). Running +/// scrap first and then having the arm fail would unwind via `?` with the +/// victims already destroyed and nothing committed to replace them, +/// leaving the window with no frame at the target MSC where Xorg would +/// still have shown the victim. Factored out (rather than inlined at the +/// call site) so a regression test can exercise the exact production +/// ordering instead of calling the two steps itself. +fn arm_present_pixmap_source_then_supersede( + state: &mut ServerState, + backend: &mut dyn Backend, + pending: &PendingPresentPixmap, +) -> std::io::Result { + let armed = + backend.arm_present_source_wait(pending.src_host_xid, pending.paint_dst_host_xid)?; + supersede_covered_pending_presents(state, backend, pending); + Ok(armed) +} + +/// `Present::PixmapSynced` counterpart of +/// `arm_present_pixmap_source_then_supersede`: arms the explicit acquire +/// syncobj wait before scrapping covered pending entries, for the same +/// reason (an unknown/invalid acquire syncobj makes this arm fail in a +/// way clients can trigger, and scrap must not run ahead of a still- +/// fallible arm). +pub(super) fn arm_present_pixmap_synced_source_then_supersede( + state: &mut ServerState, + backend: &mut dyn Backend, + acquire_syncobj: u32, + acquire_value: u64, + pending: &PendingPresentPixmap, +) -> std::io::Result { + let armed = backend.arm_present_syncobj_wait( + pending.src_host_xid, + pending.paint_dst_host_xid, + acquire_syncobj, + acquire_value, + )?; + supersede_covered_pending_presents(state, backend, pending); + Ok(armed) +} + +fn present_crtc_is_enabled(state: &ServerState, crtc_id: u32) -> bool { + crtc_id != 0 + && state + .randr + .enabled_outputs() + .any(|output| output.crtc_id == crtc_id) +} + +fn present_crtc_exists(state: &ServerState, crtc_id: u32) -> bool { + state + .randr + .outputs + .iter() + .any(|output| output.crtc_id == crtc_id) +} + +/// Select an enabled output by greatest intersection with `window`. +/// RANDR primary wins equal-area ties (including the all-zero fallback), +/// then the stable `randr.outputs` order wins. With no enabled outputs the +/// synthetic headless domain 0 preserves zero-device operation. +pub(super) fn default_present_crtc_for_window(state: &ServerState, window: ResourceId) -> u32 { + let Some(window_record) = state.resources.window(window) else { + return 0; + }; + let (window_x, window_y) = state.resources.window_absolute_position(window); + let window_right = window_x.saturating_add(i32::from(window_record.width)); + let window_bottom = window_y.saturating_add(i32::from(window_record.height)); + let primary = state.randr.primary_output; + + let mut best: Option<(u64, bool, u32)> = None; + for output in state.randr.enabled_outputs() { + let output_x = i32::from(output.x); + let output_y = i32::from(output.y); + let (footprint_w, footprint_h) = output.footprint(); + let output_right = output_x.saturating_add(i32::from(footprint_w)); + let output_bottom = output_y.saturating_add(i32::from(footprint_h)); + let width = window_right.min(output_right) - window_x.max(output_x); + let height = window_bottom.min(output_bottom) - window_y.max(output_y); + let area = if width > 0 && height > 0 { + u64::try_from(width).unwrap_or(0) * u64::try_from(height).unwrap_or(0) + } else { + 0 + }; + let is_primary = output.output_id == primary; + let replace = best.is_none_or(|(best_area, best_primary, _)| { + area > best_area || (area == best_area && is_primary && !best_primary) + }); + if replace { + best = Some((area, is_primary, output.crtc_id)); + } + } + best.map_or(0, |(_, _, crtc_id)| crtc_id) +} + +pub(crate) fn cached_present_crtc_clock( + state: &ServerState, + crtc_id: u32, + crtc_epoch: u64, +) -> crate::server::PresentCrtcClock { + state + .present_crtc_clocks + .get(&(crtc_id, crtc_epoch)) + .copied() + .unwrap_or_else(|| crate::server::PresentCrtcClock { + epoch: crtc_epoch, + ..crate::server::PresentCrtcClock::default() + }) +} + +/// Clock used both to decide when a Present completion is due and whether +/// its CRTC needs another tagged wake. Keep the arming pass aligned with the +/// completion sweep, including exact direct-scanout stamps and the immediate +/// fallback when no completion sample exists. +pub(crate) fn present_completion_due_clock( + state: &ServerState, + event: &crate::backend::CompletedPresentEvent, +) -> crate::backend::PresentClockSample { + present_completion_due_clock_for_domain( + state, + event.crtc_id, + event.crtc_epoch, + event.completion_clock, + ) +} + +pub(crate) fn present_completion_due_clock_for_domain( + state: &ServerState, + crtc_id: u32, + crtc_epoch: u64, + exact: Option, +) -> crate::backend::PresentClockSample { + let cached = cached_present_crtc_clock(state, crtc_id, crtc_epoch); + if cached.completion.msc > 0 { + cached.completion + } else if let Some(exact) = exact { + exact + } else { + crate::backend::PresentClockSample { + msc: cached.msc, + ust: cached.ust, + source: crate::backend::PresentClockSource::Immediate, + } + } +} + +/// Refresh one current physical clock epoch. A valid-but-Off CRTC and the +/// headless domain stay at zero; they are accepted but deliberately unpaced. +pub(crate) fn refresh_present_crtc_general_clock( + state: &mut ServerState, + backend: &mut dyn Backend, + crtc_id: u32, + crtc_epoch: u64, +) -> crate::server::PresentCrtcClock { + if crtc_id == 0 + || !present_crtc_is_enabled(state, crtc_id) + || backend.present_crtc_clock_epoch(crtc_id) != crtc_epoch + { + return cached_present_crtc_clock(state, crtc_id, crtc_epoch); + } + let (msc, ust) = backend.present_get_ust_msc(crtc_id); + let clock = state + .present_crtc_clocks + .entry((crtc_id, crtc_epoch)) + .or_insert_with(|| crate::server::PresentCrtcClock { + epoch: crtc_epoch, + ..crate::server::PresentCrtcClock::default() + }); + if msc > 0 { + clock.msc = msc; + clock.ust = ust; + } + *clock +} + +pub(crate) fn refresh_present_crtc_completion_clock( + state: &mut ServerState, + backend: &mut dyn Backend, + crtc_id: u32, + crtc_epoch: u64, + exact: Option, +) -> crate::backend::PresentClockSample { + let has_exact = exact.is_some(); + let sample = if let Some(exact) = exact { + exact + } else if crtc_id != 0 + && present_crtc_is_enabled(state, crtc_id) + && backend.present_crtc_clock_epoch(crtc_id) == crtc_epoch + { + backend.present_get_completion_clock(crtc_id) + } else { + return cached_present_crtc_clock(state, crtc_id, crtc_epoch).completion; + }; + advance_present_crtc_completion_clock(state, crtc_id, crtc_epoch, sample); + let cached = state + .present_crtc_clocks + .get(&(crtc_id, crtc_epoch)) + .copied() + .unwrap_or_else(|| crate::server::PresentCrtcClock { + epoch: crtc_epoch, + ..crate::server::PresentCrtcClock::default() + }); + if has_exact { sample } else { cached.completion } +} + +fn advance_present_crtc_completion_clock( + state: &mut ServerState, + crtc_id: u32, + crtc_epoch: u64, + sample: crate::backend::PresentClockSample, +) { + let clock = state + .present_crtc_clocks + .entry((crtc_id, crtc_epoch)) + .or_insert_with(|| crate::server::PresentCrtcClock { + epoch: crtc_epoch, + ..crate::server::PresentCrtcClock::default() + }); + let advances_cache = sample.msc > 0 + && (clock.completion.msc == 0 + || sample.msc == clock.completion.msc + || crate::present_scheduler::msc_is_after(sample.msc, clock.completion.msc)); + if advances_cache { + clock.completion = sample; + } +} + +pub(super) fn present_wire_clock( + raw: crate::backend::PresentClockSample, + msc_offset: u64, +) -> crate::backend::PresentClockSample { + crate::backend::PresentClockSample { + msc: raw.msc.wrapping_sub(msc_offset), + ..raw + } +} + +/// Bind a Present window to a CRTC clock while preserving Xorg's continuous +/// window MSC. `msc_offset` is defined by `wire_msc = raw_msc - offset`; +/// therefore a clock-domain switch applies `offset += new_raw - old_raw`. +fn bind_present_window_domain( + state: &mut ServerState, + backend: &mut dyn Backend, + window: u32, + crtc_id: u32, +) -> PresentDomainSelection { + let crtc_epoch = backend.present_crtc_clock_epoch(crtc_id); + let new_clock = refresh_present_crtc_general_clock(state, backend, crtc_id, crtc_epoch); + let previous = state.present_window_msc.get(&window).copied(); + + let next = match previous { + None => crate::server::PresentWindowMsc { + last_crtc: crtc_id, + last_crtc_epoch: crtc_epoch, + msc_offset: 0, + last_raw_msc: new_clock.msc, + }, + Some(mut window_clock) + if window_clock.last_crtc == crtc_id && window_clock.last_crtc_epoch == crtc_epoch => + { + if new_clock.msc > 0 { + window_clock.last_raw_msc = new_clock.msc; + } + window_clock + } + Some(mut window_clock) => { + let current_old_epoch = backend.present_crtc_clock_epoch(window_clock.last_crtc); + let old_raw = if current_old_epoch == window_clock.last_crtc_epoch { + let old_clock = refresh_present_crtc_general_clock( + state, + backend, + window_clock.last_crtc, + window_clock.last_crtc_epoch, + ); + if old_clock.msc > 0 { + old_clock.msc + } else { + window_clock.last_raw_msc + } + } else { + // The stable RANDR XID now names another physical counter. + // Never sample that replacement as the old side of the rebase. + let cached_old = cached_present_crtc_clock( + state, + window_clock.last_crtc, + window_clock.last_crtc_epoch, + ); + if cached_old.msc > 0 { + cached_old.msc + } else { + window_clock.last_raw_msc + } + }; + window_clock.msc_offset = window_clock + .msc_offset + .wrapping_add(new_clock.msc.wrapping_sub(old_raw)); + window_clock.last_crtc = crtc_id; + window_clock.last_crtc_epoch = crtc_epoch; + window_clock.last_raw_msc = new_clock.msc; + window_clock + } + }; + state.present_window_msc.insert(window, next); + PresentDomainSelection { + crtc_id, + crtc_epoch, + msc_offset: next.msc_offset, + raw_msc: new_clock.msc, + raw_ust: new_clock.ust, + } +} + +/// Resolve and bind a request domain. Explicit nonzero XIDs validate only +/// resource existence (Xorg accepts a valid-but-Off CRTC); implicit Pixmap +/// requests select by coverage every time, while NotifyMSC can request reuse +/// of the window's previous Present domain. +pub(super) fn select_present_domain( + state: &mut ServerState, + backend: &mut dyn Backend, + window: u32, + target_crtc: u32, + reuse_previous: bool, +) -> Result { + let crtc_id = if target_crtc != 0 { + if !present_crtc_exists(state, target_crtc) { + return Err(target_crtc); + } + target_crtc + } else if reuse_previous { + state.present_window_msc.get(&window).map_or_else( + || default_present_crtc_for_window(state, ResourceId(window)), + |c| c.last_crtc, + ) + } else { + default_present_crtc_for_window(state, ResourceId(window)) + }; + Ok(bind_present_window_domain(state, backend, window, crtc_id)) +} + +pub(super) fn effective_present_target_raw( + domain: PresentDomainSelection, + target_msc: u64, + divisor: u64, + remainder: u64, + options: u32, +) -> Option { + if domain.raw_msc == 0 { + return None; + } + // Xorg intentionally shifts only target_msc; divisor/remainder stay in + // the raw CRTC clock's residue class. + let effective = crate::present_scheduler::effective_target_msc( + target_msc.wrapping_add(domain.msc_offset), + domain.raw_msc, + divisor, + remainder, + options, + ); + // Xorg retains the target MSC even when an async request resolves to the + // current field. Besides being the protocol completion identity, that + // value groups same-target requests for supersession. `None` is reserved + // for a domain with no usable clock; collapsing current/past async targets + // to `None` makes the core park them behind an in-flight flip and prevents + // both core supersession and the backend's bounded successor queue. + Some(effective) +} + +/// Execute a batch of specific `present_pending_exec` entries by id — +/// shared by every msc-due execution site (the due-pass's normal +/// execute-due step, the idle-display fallback, the shared-wake +/// false/error fallback, and the blackout flush). Missing ids (already +/// resolved by a concurrent path) are silently skipped. Mirrors +/// `drain_ready_present_pixmaps`'s execute/release/mark_dirty sequence: +/// the entry pin is released after `execute_present_pixmap_copy` +/// regardless of success or failure, and `mark_dirty` fires only on +/// success. +pub(crate) fn execute_parked_present_ids( + state: &mut ServerState, + backend: &mut dyn Backend, + ids: &[u64], + trigger: &str, +) { + for &pid in ids { + let Some(entry) = state.present_pending_exec.remove(&pid) else { + continue; + }; + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=exec_due trigger={trigger} eff={:?}", + pace_instr_ms(), + pid, + entry.pending.effective_target_msc + ); + let ok = execute_present_pixmap_copy_or_reroute(state, backend, entry.pending); + if let Some(pin) = entry.pin { + backend.release_present_source(pin); + } + if ok { + backend.mark_dirty(); + } + } +} + +/// msc-due-pass (spec §msc-due; Task 7): re-classify every msc-parked +/// source-ready entry against the fresh general clock and execute +/// whatever just became due, then run the two fallback-ladder rungs that +/// are execution decisions rather than arming (the shared-wake arm lives in +/// `run::arm_present_idle_vblanks`, post-compose, alongside the other two +/// arms). Called at the top of `drain_present_completions`, which Task 4 +/// hoisted above `maybe_composite`, so an entry executed here is visible +/// to THIS iteration's compose. +pub(crate) fn drain_due_present_pending_exec(state: &mut ServerState, backend: &mut dyn Backend) { + // Sampled up front (not just inside the blackout branch below): an + // empty `present_pending_exec` must NOT short-circuit past the + // blackout flush, or DPMS-off with a display that never accumulates + // a msc-parked entry (flips keep retiring normally, so every arrival + // classifies ExecuteNow and the store stays empty) would leave + // `present_pending_complete` entries gated against a frozen + // completion clock with nothing left to ever call + // `fire_all_present_completions_now` — they'd park forever. The + // sweep inside that call still early-returns on an empty queue, so + // this costs nothing on the common (non-blackout) empty-store path. + let blackout = backend.present_scanout_blackout(); + if state.present_pending_exec.is_empty() && !blackout { + return; + } + let mut domains: Vec<(u32, u64)> = state + .present_pending_exec + .values() + .map(|entry| (entry.pending.crtc_id, entry.pending.crtc_epoch)) + .collect(); + domains.sort_unstable(); + domains.dedup(); + for &(crtc_id, crtc_epoch) in &domains { + if backend.present_crtc_clock_epoch(crtc_id) == crtc_epoch { + refresh_present_crtc_general_clock(state, backend, crtc_id, crtc_epoch); + } + } + + let due: Vec = state + .present_pending_exec + .iter() + .filter(|(_, e)| { + if !e.source_ready { + return false; + } + let epoch_current = + backend.present_crtc_clock_epoch(e.pending.crtc_id) == e.pending.crtc_epoch; + if !epoch_current { + // A stable RANDR XID now names a replacement raw counter. + // The saved raw target is meaningless there; fail open + // unpaced instead of arming/comparing against the new epoch. + return true; + } + let clock_msc = + cached_present_crtc_clock(state, e.pending.crtc_id, e.pending.crtc_epoch).msc; + matches!( + crate::present_scheduler::classify_msc_due( + e.pending.effective_target_msc, + clock_msc, + backend.present_flip_in_flight(e.pending.crtc_id), + ), + crate::present_scheduler::MscDue::ExecuteNow + ) + }) + .map(|(&pid, _)| pid) + .collect(); + execute_parked_present_ids(state, backend, &due, "drain"); + + // Idle-display fallback (spec §msc-due, flip-driven drivers only): a + // parked entry normally becomes due as flips advance the clock — the + // next flip retirement wakes this same due-pass and the `due` filter + // above catches it. But if the display is fully idle (no flip in + // flight AND nothing composing), the clock can never advance at all, + // so waiting would deadlock forever; execute immediately instead. + // Gated to `!present_absolute_vblank_arm_supported()` drivers only — + // on sequence-capable drivers an idle display still ticks via the + // tagged shared wake, and applying this fallback there would reintroduce + // the early-frame bug for mpv (spec §msc-due). + let idle_fallback: Vec = state + .present_pending_exec + .iter() + .filter(|(_, e)| { + e.source_ready + && e.pending.effective_target_msc.is_some() + && !backend.present_absolute_vblank_arm_supported(e.pending.crtc_id) + && backend.present_display_idle(e.pending.crtc_id) + }) + .map(|(&pid, _)| pid) + .collect(); + execute_parked_present_ids(state, backend, &idle_fallback, "idle_fallback"); + + // Blackout flush (spec Lifecycle §"DPMS-off / VT-away blackout"): + // checked unconditionally (not an `else` of the arm/idle-display + // rungs above) so it fires even while the clock is frozen — no flips, + // no sequence samples, `next_wakeup`'s scene deadline gated off, so + // nothing else here would ever unblock these entries. Only + // `source_ready` (msc-parked) entries are force-executed: a + // `source_ready == false` entry is still waiting on its OWN producer + // fence, a condition blackout does nothing to resolve, and forcing + // that copy would read whatever partial content the producer has + // written so far. + if blackout { + let blackout_ids: Vec = state + .present_pending_exec + .iter() + .filter(|(_, e)| e.source_ready) + .map(|(&pid, _)| pid) + .collect(); + execute_parked_present_ids(state, backend, &blackout_ids, "blackout"); + + // Both halves flush together: parked completions deliver too, + // ignoring the due check entirely (a frozen clock would + // otherwise never satisfy it — round-4 F1c). Stamped with the + // COMPLETION clock, not the general clock used for scheduling + // above — stamping/gate-release keeps its existing + // completion-clock provenance (spec "Loop-order and clock + // contract" item 2: scheduling and stamping are different + // concerns). + fire_all_present_completions_now(state, backend); + } +} + +fn accumulate_present_execution_damage( + state: &mut ServerState, + window: u32, + x_off: i16, + y_off: i16, + src_width: u16, + src_height: u16, + update_rects: Option<&[yserver_protocol::x11::xfixes::RegionRect]>, +) { + if let Some(rects) = update_rects { + for rect in rects { + let _dropped = accumulate_damage_to_state( + state, + ResourceId(window), + x_off.saturating_add(rect.x), + y_off.saturating_add(rect.y), + rect.width, + rect.height, + ); + } + } else { + let _dropped = accumulate_damage_to_state( + state, + ResourceId(window), + x_off, + y_off, + src_width, + src_height, + ); + } +} + +pub(super) fn execute_present_pixmap_copy( + state: &mut ServerState, + backend: &mut dyn Backend, + pending: PendingPresentPixmap, +) -> io::Result<()> { + let PendingPresentPixmap { + origin, + client_id, + request: req, + wake, + masked_options, + src_host_xid, + paint_dst_host_xid, + completion_dst_host_xid, + src_width, + src_height, + update_rects, + present_id, + window_generation, + crtc_id, + crtc_epoch, + msc_offset, + effective_target_msc, + } = pending; + let (serial, pixmap, window, x_off, y_off, valid, update) = match &req { + PendingPresentRequest::Pixmap(req) => ( + req.serial, req.pixmap, req.window, req.x_off, req.y_off, req.valid, req.update, + ), + PendingPresentRequest::PixmapSynced(req) => ( + req.serial, req.pixmap, req.window, req.x_off, req.y_off, req.valid, req.update, + ), + }; + + let variable_refresh = crate::properties::variable_refresh_property_enabled( + state + .atoms + .id_for("_VARIABLE_REFRESH") + .and_then(|atom| state.resources.window_property(ResourceId(window), atom)), + ); + + let candidate = crate::backend::PresentScanoutCandidate { + client_id: client_id.0, + client_pid: state + .clients + .get(&client_id.0) + .and_then(super::misc::client_peer_pid), + present_id, + crtc_id, + crtc_epoch, + src_pixmap_xid: pixmap, + dst_window_xid: window, + variable_refresh, + src_host_xid, + paint_dst_host_xid, + completion_dst_host_xid, + src_width, + src_height, + x_off, + y_off, + valid_region_xid: valid, + update_region_xid: update, + update_is_full: update_rects.is_none(), + explicit_sync: matches!(req, PendingPresentRequest::PixmapSynced(_)), + options: masked_options, + }; + let completion = crate::backend::CompletedPresentEvent { + client_id, + serial, + host_xid: pixmap, + dst_host_xid: window, + options: masked_options, + present_id, + window_generation, + crtc_id, + crtc_epoch, + msc_offset, + completion_clock: None, + wake, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }; + + if window_unviewable(state, ResourceId(window)) { + // Xorg: flip check fails on the empty clipList and the Copy clips to nothing, + // but idle and CompleteModeCopy are still delivered (present_execute.c:119-156). + if let Some(eff) = effective_target_msc { + state.present_complete_gate.insert( + present_id, + crate::server::PresentCompleteGate { + crtc_id, + crtc_epoch, + msc_offset, + effective_target_msc: eff, + owner: client_id, + dst_window_xid: window, + }, + ); + } + backend.enqueue_present_completion(completion, completion_dst_host_xid); + return Ok(()); + } + backend.note_present_scanout_candidate(candidate); + + // M2b attempts direct ownership before recording the fallback Copy. The + // completion gate must exist before the backend can own the page flip; + // on decline/error remove the provisional row so the unchanged Copy path + // below retains its historical "install only after successful Copy" + // failure semantics. + if let Some(eff) = effective_target_msc { + state.present_complete_gate.insert( + present_id, + crate::server::PresentCompleteGate { + crtc_id, + crtc_epoch, + msc_offset, + effective_target_msc: eff, + owner: client_id, + dst_window_xid: window, + }, + ); + } + match backend.try_present_direct(candidate, completion.clone()) { + Ok(true) => { + backend.note_present_pixmap(src_host_xid, paint_dst_host_xid); + accumulate_present_execution_damage( + state, + window, + x_off, + y_off, + src_width, + src_height, + update_rects.as_deref(), + ); + return Ok(()); + } + Ok(false) => {} + Err(error) => log::warn!( + "present direct submit failed, retaining Copy fallback (pid={present_id}): {error}" + ), + } + state.present_complete_gate.remove(&present_id); + + // PresentPixmap has no client GC. Clear every piece of draw state that a + // preceding request may have left bound before recording the copy. + let present_gc = crate::backend::DrawState::default(); + backend.apply_clip_state(origin, &present_gc.clip)?; + backend.apply_draw_state(origin, &present_gc)?; + + if let Some(rects) = &update_rects { + for rect in rects { + backend.copy_area( + origin, + src_host_xid, + paint_dst_host_xid, + rect.x, + rect.y, + x_off.saturating_add(rect.x), + y_off.saturating_add(rect.y), + rect.width, + rect.height, + )?; + } + } else { + backend.copy_area( + origin, + src_host_xid, + paint_dst_host_xid, + 0, + 0, + x_off, + y_off, + src_width, + src_height, + )?; + } + + backend.note_present_pixmap(src_host_xid, paint_dst_host_xid); + // Task 13 (spec §"Amendment 2026-08-01" — damage-arm dependency): + // re-keyed off `update_rects.is_none()`, not the raw `update` xid — + // an unresolvable region (`update != 0` but `update_rects == None`) + // must still damage full-extent, not nothing. Per-rect damage is + // translated by `x_off`/`y_off` exactly like the copy arm above + // (`x_off.saturating_add(rect.x)`), matching Xorg's `CT_REGION` clip- + // origin semantics (`present.c:76-92`). + accumulate_present_execution_damage( + state, + window, + x_off, + y_off, + src_width, + src_height, + update_rects.as_deref(), + ); + + // The direct attempt above removed its provisional gate when it declined + // ownership. Reinstall that gate only after the fallback Copy succeeded, + // preserving the historical copy-failure semantics. + if let Some(eff) = effective_target_msc { + state.present_complete_gate.insert( + present_id, + crate::server::PresentCompleteGate { + crtc_id, + crtc_epoch, + msc_offset, + effective_target_msc: eff, + owner: client_id, + dst_window_xid: window, + }, + ); + } + backend.enqueue_present_completion(completion, completion_dst_host_xid); + Ok(()) +} + +/// Finds older source/acquire waiters that this Present would cover if it +/// executes. Such entries stay pending until their producer fence signals, +/// then complete as Skip rather than painting over the newer frame. +fn covered_older_pending_wait_ids( + state: &ServerState, + successor: &PendingPresentPixmap, +) -> Vec { + let Some(target) = successor.effective_target_msc else { + return Vec::new(); + }; + state + .present_pending_exec + .iter() + .filter(|(pid, entry)| { + **pid < successor.present_id + && !entry.source_ready + && entry.wait_id.is_some() + && entry.pending.request.window() == successor.request.window() + && entry.pending.window_generation == successor.window_generation + && entry.pending.crtc_id == successor.crtc_id + && entry.pending.crtc_epoch == successor.crtc_epoch + && entry.pending.effective_target_msc == Some(target) + && present_supersession_covers(successor, &entry.pending) + }) + .map(|(pid, _)| *pid) + .collect() +} + +/// Task 8 §Supersession copy-failure reroute (round-4 F5). Wrapper +/// around `execute_present_pixmap_copy` used by ALL THREE execute sites +/// (`execute_parked_present_ids`, `arrival_execute_or_park_present_pixmap`'s +/// `ExecuteNow` arm, `drain_ready_present_pixmaps`'s `ExecuteNow` arm) — +/// pin release stays at the call sites, after this call, as today. +/// +/// Today a failing `execute_present_pixmap_copy` can only fail in +/// `apply_clip_state`/`apply_draw_state`/`copy_area` — all BEFORE the +/// completion gate is inserted and `enqueue_present_completion` runs, so +/// a failed copy leaves no gate row and no retained backend wake. Left +/// alone, that strands the client's buffer (never idled) and its +/// completion (never delivered) forever. On failure this wrapper: +/// releases the buffer by XID immediately (fence/syncobj + fence mirror, +/// mirroring scrap), fires `IdleNotify` now, and either parks a `Copy` +/// completion (`emit_idle: false`) in the ordered delivery queue when +/// `effective_target_msc` is `Some` (rides the same per-window hold-back +/// as everything else), or — when `None` (no clock, including +/// nested backends whose sweep never runs because `clock.msc == 0` +/// guards it) — delivers it inline, mirroring `run.rs`'s no-clock arm: a +/// `fire_due_present_completions` flush first (so this inline delivery +/// cannot overtake an already-due sibling), then `complete_present_with_clock` +/// with an Immediate clock sample built like `complete_present_now` does. +/// +/// Returns `true` iff the copy succeeded. +pub(super) fn execute_present_pixmap_copy_or_reroute( + state: &mut ServerState, + backend: &mut dyn Backend, + pending: PendingPresentPixmap, +) -> bool { + // Captured before the call below consumes `pending`. + let event = completed_event_for_pending(&pending); + let wake = pending.wake.clone(); + let effective_target_msc = pending.effective_target_msc; + let present_id = pending.present_id; + // A source/acquire waiter cannot be released before its producer + // signals. Remember covered older waiters only after this frame really + // executes; when those fences signal, they resolve as Skip instead of + // painting stale content over this newer frame. + let older_wait_ids = covered_older_pending_wait_ids(state, &pending); + + match execute_present_pixmap_copy(state, backend, pending) { + Ok(()) => { + for older_id in older_wait_ids { + if let Some(entry) = state.present_pending_exec.get_mut(&older_id) { + entry.superseded_by_executed_present_id = Some(present_id); + } + } + true + } + Err(e) => { + log::warn!("present copy failed, rerouting completion (pid={present_id}): {e}"); + // Accepted trade (Task 0 item (a) has the same shape for + // Xorg-parity scrap): on a multi-rect `update_rects` copy, a + // failure partway through may leave earlier rects' GPU reads + // of the source already recorded before the failing rect. By- + // XID buffer release below happens immediately regardless, so + // this is a WAR hazard against those already-recorded reads — + // a concurrent client write to the released buffer could race + // GPU work still reading it. Accepted because the alternative + // (holding the buffer/completion open indefinitely, hoping a + // retry never comes) strands the client's buffer and + // completion forever, which is strictly worse. + match wake { + crate::backend::PresentWake::Pixmap { idle_fence_xid } if idle_fence_xid != 0 => { + if let Err(e) = backend.dri3_trigger_fence(idle_fence_xid) { + log::warn!( + "PRESENT copy-failure: trigger idle fence 0x{idle_fence_xid:x} \ + failed: {e}" + ); + } + crate::core_loop::sync_await::fence_triggered(state, idle_fence_xid); + } + crate::backend::PresentWake::PixmapSynced { + release, + release_syncobj, + release_value, + } => { + if let Err(e) = release.signal(release_value) { + log::warn!( + "PRESENT copy-failure: signal release syncobj \ + 0x{release_syncobj:x}@{release_value} failed: {e}" + ); + } + } + _ => {} + } + fire_present_idle_notify_now(state, &event); + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=copy_failed eff={:?}", + pace_instr_ms(), present_id, effective_target_msc + ); + if let Some(target) = effective_target_msc { + state + .present_pending_complete + .push(crate::server::PendingPresentComplete { + event, + effective_target_msc: target, + mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: false, + }); + } else { + // No clock: no due-pass will ever drain a parked + // queue entry for this present, so deliver inline — + // mirroring run.rs's no-clock completion arm. Flush + // due-and-unblocked siblings first so this inline + // delivery cannot overtake an already-due one. + let clock = refresh_present_crtc_completion_clock( + state, + backend, + event.crtc_id, + event.crtc_epoch, + event.completion_clock, + ); + fire_due_present_completions_for_domain( + state, + backend, + event.crtc_id, + event.crtc_epoch, + clock, + ); + let cached = cached_present_crtc_clock(state, event.crtc_id, event.crtc_epoch); + let immediate = crate::backend::PresentClockSample { + msc: cached.msc, + ust: cached.ust, + source: crate::backend::PresentClockSource::Immediate, + }; + complete_present_with_clock( + state, + backend, + &event, + immediate, + yserver_protocol::x11::present::COMPLETE_MODE_COPY, + false, + ); + } + false + } + } +} + +/// Arrival-time msc-due evaluation (spec §msc-due; Task 7 Step 2) for a +/// present whose source is READY at request time — i.e. this runs at the +/// point today's code executed the copy unconditionally. Request drain +/// runs before the run-loop tail, so a lone present on an idle display +/// still executes right here at arrival; it never waits for the next +/// due-pass. `ExecuteNow` keeps today's immediate-copy path. `Park` inserts +/// a `source_ready: true, wait_id: None` entry (taking the entry pin) — +/// the due-pass (`drain_due_present_pending_exec`) picks it up later. +pub(super) fn arrival_execute_or_park_present_pixmap( + state: &mut ServerState, + backend: &mut dyn Backend, + present_id: u64, + pending: PendingPresentPixmap, +) { + let (due, clock_msc, flip_in_flight) = + classify_present_pixmap_msc_due_at_arrival(state, backend, &pending); + match due { + crate::present_scheduler::MscDue::ExecuteNow => { + let stage = match &pending.request { + PendingPresentRequest::Pixmap(_) => "source_ready", + PendingPresentRequest::PixmapSynced(_) => "acquire_ready", + }; + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage={stage}", + pace_instr_ms(), pending.present_id + ); + execute_present_pixmap_copy_or_reroute(state, backend, pending); + } + crate::present_scheduler::MscDue::Park => { + let reason = if flip_in_flight { + "flip_in_flight" + } else { + "future" + }; + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=parked_msc reason={reason} eff={:?} clock_msc={clock_msc}", + pace_instr_ms(), pending.present_id, pending.effective_target_msc + ); + let pin = backend.pin_present_source(pending.src_host_xid); + state.present_pending_exec.insert( + present_id, + crate::server::PendingPresentEntry { + pending, + source_ready: true, + superseded_by_executed_present_id: None, + wait_id: None, + pin, + }, + ); + } + } +} + +/// Shared arrival-time MSC classification for both the actual ready-source +/// path and supersession's decision about whether a fence waiter is parked +/// for a future target. Keep the general clock, epoch fallback, and in-flight +/// flip handling in one place so those decisions cannot drift apart. +fn classify_present_pixmap_msc_due_at_arrival( + state: &mut ServerState, + backend: &mut dyn Backend, + pending: &PendingPresentPixmap, +) -> (crate::present_scheduler::MscDue, u64, bool) { + let epoch_current = backend.present_crtc_clock_epoch(pending.crtc_id) == pending.crtc_epoch; + let clock_msc = if epoch_current { + refresh_present_crtc_general_clock(state, backend, pending.crtc_id, pending.crtc_epoch).msc + } else { + cached_present_crtc_clock(state, pending.crtc_id, pending.crtc_epoch).msc + }; + let flip_in_flight = epoch_current && backend.present_flip_in_flight(pending.crtc_id); + let due = if epoch_current { + crate::present_scheduler::classify_msc_due( + pending.effective_target_msc, + clock_msc, + flip_in_flight, + ) + } else { + crate::present_scheduler::MscDue::ExecuteNow + }; + (due, clock_msc, flip_in_flight) +} + +pub(crate) fn drain_ready_present_pixmaps(state: &mut ServerState, backend: &mut dyn Backend) { + let mut ready_wait_ids = backend.drain_ready_present_source_waits(); + // If multiple producer fences are ready in one backend drain, execute + // them in Present arrival order. If a newer one became ready in an + // earlier drain, its execution marks older still-waiting entries so they + // resolve as Skip when their own fence eventually signals. + ready_wait_ids.sort_by_key(|wait_id| { + state + .present_wait_to_id + .get(wait_id) + .copied() + .unwrap_or(u64::MAX) + }); + for wait_id in ready_wait_ids { + let present_id = state.present_wait_to_id.remove(&wait_id); + let entry = present_id.and_then(|pid| state.present_pending_exec.remove(&pid)); + let outcome = entry.map(|mut entry| { + let stage = match &entry.pending.request { + PendingPresentRequest::Pixmap(_) => "source_signaled", + PendingPresentRequest::PixmapSynced(_) => "acquire_signaled", + }; + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage={} wait_id={}", + pace_instr_ms(), entry.pending.present_id, stage, wait_id + ); + if let Some(newer_present_id) = entry.superseded_by_executed_present_id { + let target = entry + .pending + .effective_target_msc + .expect("only known same-target Presents are marked stale"); + complete_pending_present_as_skip(state, backend, &entry.pending, target); + if let Some(pin) = entry.pin { + backend.release_present_source(pin); + } + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=stale_wait_skip by={}", + pace_instr_ms(), entry.pending.present_id, newer_present_id + ); + return None; + } + let epoch_current = backend.present_crtc_clock_epoch(entry.pending.crtc_id) + == entry.pending.crtc_epoch; + let clock_msc = if epoch_current { + refresh_present_crtc_general_clock( + state, + backend, + entry.pending.crtc_id, + entry.pending.crtc_epoch, + ) + .msc + } else { + cached_present_crtc_clock( + state, + entry.pending.crtc_id, + entry.pending.crtc_epoch, + ) + .msc + }; + let flip_in_flight = + epoch_current && backend.present_flip_in_flight(entry.pending.crtc_id); + let due = if epoch_current { + crate::present_scheduler::classify_msc_due( + entry.pending.effective_target_msc, + clock_msc, + flip_in_flight, + ) + } else { + crate::present_scheduler::MscDue::ExecuteNow + }; + match due { + // The entry became source-ready AND is msc-due: execute now + // — releasing the ENTRY pin on both the success and + // failure path so a failing copy never leaks the pinned + // drawable. + crate::present_scheduler::MscDue::ExecuteNow => { + backend.begin_ready_present_destination_write(wait_id); + let ok = + execute_present_pixmap_copy_or_reroute(state, backend, entry.pending); + if let Some(pin) = entry.pin { + backend.release_present_source(pin); + } + Some(ok) + } + // Source-ready but not yet msc-due (Task 7 Step 2 combined + // vector): stays parked, now purely on msc-due — the WAIT + // pin still drops below (unconditional, as always), but + // the ENTRY pin stays held until the due-pass executes it. + crate::present_scheduler::MscDue::Park => { + let reason = if flip_in_flight { "flip_in_flight" } else { "future" }; + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=parked_msc reason={reason} eff={:?} clock_msc={clock_msc}", + pace_instr_ms(), entry.pending.present_id, entry.pending.effective_target_msc + ); + let pid = entry.pending.present_id; + entry.source_ready = true; + entry.wait_id = None; + state.present_pending_exec.insert(pid, entry); + None + } + } + }); + // The WAIT pin is distinct from the entry pin above and is + // released exactly here, as today — unconditionally, whether or + // not the entry was still present (an unknown-id backend report + // is a no-op guard). + backend.finish_present_source_wait(wait_id); + match outcome { + Some(Some(true)) => backend.mark_dirty(), + // Failure already logged + rerouted (by-XID release, IdleNotify, + // parked/inline completion) inside + // `execute_present_pixmap_copy_or_reroute`. + Some(Some(false)) => {} + Some(None) => {} + None => log::warn!("backend reported unknown Present source wait id {wait_id}"), + } + } +} + +/// Full-server shutdown: release every still-parked (pre-copy) entry in +/// the unified pending-present store. Mirrors the window-destroy teardown +/// loop's by-XID release exactly (same wake mechanism, same two distinct +/// pin releases) but with no window filter — every entry is stale once +/// there is no more request/vblank drain left to resolve it. Called once, +/// core-side, before the listening socket is torn down (yserver's +/// `lib.rs`, next to `signal_all_retained_present_wakes` which does the +/// analogous flush for the *post*-copy retained-wake population). +pub fn shutdown_drain_present_pending_exec(state: &mut ServerState, backend: &mut dyn Backend) { + for (_, entry) in std::mem::take(&mut state.present_pending_exec) { + match &entry.pending.wake { + crate::backend::PresentWake::Pixmap { idle_fence_xid } if *idle_fence_xid != 0 => { + if let Err(e) = backend.dri3_trigger_fence(*idle_fence_xid) { + log::warn!( + "PRESENT shutdown: trigger idle fence 0x{idle_fence_xid:x} failed: {e}" + ); + } + } + crate::backend::PresentWake::PixmapSynced { + release, + release_syncobj, + release_value, + } => { + if let Err(e) = release.signal(*release_value) { + log::warn!( + "PRESENT shutdown: signal release syncobj 0x{release_syncobj:x}@\ + {release_value} failed: {e}" + ); + } + } + _ => {} + } + if let Some(wid) = entry.wait_id { + backend.finish_present_source_wait(wid); + } + if let Some(pin) = entry.pin { + backend.release_present_source(pin); + } + } + state.present_wait_to_id.clear(); +} + +#[allow(clippy::too_many_arguments)] +fn present_remainder_invalid(divisor: u64, remainder: u64) -> bool { + (divisor == 0 && remainder != 0) || (divisor != 0 && remainder >= divisor) +} + +fn present_remainder_error_value(remainder: u64) -> u32 { + u32::try_from(remainder & u64::from(u32::MAX)).expect("masked to CARD32") +} + +/// Validate the resource/option/pacing tail shared by PresentPixmap and +/// PresentPixmapSynced, in Xorg `proc_present_pixmap_common` order. Drawable +/// and depth checks precede this helper; PixmapSynced's syncobj/point checks +/// precede the entire common path. `None` fence arguments model Synced's two +/// protocol-level `None` fences, while `Some(0)` is PresentPixmap's explicit +/// `None` XID. +#[allow(clippy::too_many_arguments)] +fn present_pixmap_common_validation_error( + state: &ServerState, + valid_region: u32, + update_region: u32, + target_crtc: u32, + wait_fence: Option, + idle_fence: Option, + options: u32, + divisor: u64, + remainder: u64, +) -> Option<(u8, u32)> { + if valid_region != 0 && !state.xfixes_regions.contains_key(&valid_region) { + return Some((XFIXES_BAD_REGION, valid_region)); + } + if update_region != 0 && !state.xfixes_regions.contains_key(&update_region) { + return Some((XFIXES_BAD_REGION, update_region)); + } + if target_crtc != 0 && !present_crtc_exists(state, target_crtc) { + return Some((RANDR_BAD_CRTC, target_crtc)); + } + if let Some(wait_fence) = wait_fence + && wait_fence != 0 + && !state.sync_fences.contains_key(&wait_fence) + { + return Some((SYNC_BAD_FENCE, wait_fence)); + } + if let Some(idle_fence) = idle_fence + && idle_fence != 0 + && !state.sync_fences.contains_key(&idle_fence) + { + return Some((SYNC_BAD_FENCE, idle_fence)); + } + if options & !PRESENT_ALL_OPTIONS != 0 { + return Some((x11::error::BAD_VALUE, options)); + } + if present_remainder_invalid(divisor, remainder) { + return Some(( + x11::error::BAD_VALUE, + present_remainder_error_value(remainder), + )); + } + None +} + +pub(super) fn handle_present_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, present as x11present}; + const PRESENT_MAJOR_OPCODE: u8 = 145; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + debug!( + "client {} #{} PRESENT dispatch minor={} body.len()={}", + client_id.0, + sequence.0, + minor, + body.len() + ); + match minor { + x11present::QUERY_VERSION => { + let _ = x11present::parse_query_version(body); + debug!( + "client {} #{} PRESENT::QueryVersion -> {}.{}", + client_id.0, + sequence.0, + x11present::MAJOR_VERSION, + x11present::MINOR_VERSION + ); + let reply = x11present::encode_query_version_reply( + byte_order, + sequence, + x11present::MAJOR_VERSION, + x11present::MINOR_VERSION, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11present::QUERY_CAPABILITIES => { + let target = x11present::parse_query_capabilities(body).unwrap_or(0); + let target_resource = ResourceId(target); + let crtc_id = if state.resources.window(target_resource).is_some() { + default_present_crtc_for_window(state, target_resource) + } else if present_crtc_exists(state, target) { + target + } else { + 0 + }; + let caps = backend.present_capabilities(target, crtc_id).encode(); + debug!( + "client {} #{} PRESENT::QueryCapabilities target=0x{target:x} -> 0x{caps:x}", + client_id.0, sequence.0 + ); + let reply = x11present::encode_query_capabilities_reply(byte_order, sequence, caps); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11present::SELECT_INPUT => { + if let Some(req) = x11present::parse_select_input(body) { + debug!( + "client {} #{} PRESENT::SelectInput eid=0x{:x} window=0x{:x} mask=0x{:x}", + client_id.0, sequence.0, req.eid, req.window, req.event_mask + ); + let window = ResourceId(req.window); + if state + .present_event_selections + .get(&req.eid) + .is_some_and(|selection| { + selection.owner != client_id || selection.window != window + }) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.eid, + u16::from(minor), + PRESENT_MAJOR_OPCODE, + ); + } + state + .present_event_selections + .entry(req.eid) + .and_modify(|selection| selection.event_mask = req.event_mask) + .or_insert(crate::server::PresentEventSelection { + owner: client_id, + window, + event_mask: req.event_mask, + }); + } else { + debug!( + "client {} #{} PRESENT::SelectInput parse failed body_len={}", + client_id.0, + sequence.0, + body.len() + ); + } + } + x11present::PIXMAP => { + let Some(req) = x11present::parse_pixmap(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + }; + // Phase 4.2.3: wait_fence / idle_fence are accepted. The + // dispatcher mirrors the result onto state.sync_fences via + // the XSync resource table for QueryFence / TriggerFence. + let window_exists = state.resources.window(ResourceId(req.window)).is_some(); + let pixmap_exists = state.resources.pixmap(ResourceId(req.pixmap)).is_some(); + let src = state.resources.host_drawable_target(ResourceId(req.pixmap)); + let dst = state.resources.host_drawable_target(ResourceId(req.window)); + let completion_host = state + .resources + .present_completion_host(ResourceId(req.window)); + if !window_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + if !pixmap_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.pixmap, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + if let ( + Some(crate::resources::HostDrawableTarget::Pixmap { + depth: src_depth, .. + }), + Some(dst), + ) = (&src, &dst) + && *src_depth != dst.depth() + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.pixmap, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + // Keep the full Xorg common validation path read-only. A rejected + // request must neither bind this window's Present domain nor + // allocate a new lifetime generation. + if let Some((error_code, error_value)) = present_pixmap_common_validation_error( + state, + req.valid, + req.update, + req.target_crtc, + Some(req.wait_fence), + Some(req.idle_fence), + req.options, + req.divisor, + req.remainder, + ) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error_code, + error_value, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + let domain = + match select_present_domain(state, backend, req.window, req.target_crtc, false) { + Ok(domain) => domain, + Err(crtc) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + crtc, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + }; + // Per design §4 AsyncMayTear silent-clear: mask the bit + // off here when the cap isn't advertised. Computed up + // front so the deferred-completion enqueue (inside the + // `if let` below) uses the masked options. + let caps = backend.present_capabilities(req.window, domain.crtc_id); + let masked_options = if caps.async_may_tear { + req.options + } else { + const PRESENT_OPTION_ASYNC_MAY_TEAR: u32 = 0x10; + req.options & !PRESENT_OPTION_ASYNC_MAY_TEAR + }; + // INSTRUMENTATION (2026-05-29, wait_fence hypothesis check): on a + // BLANK Firefox run, do content-sized presents even arrive, and is + // the wait_fence un-triggered when we copy? Logs src kind+SIZE, + // wait_fence + our server-side triggered bit (caveat: that bit is + // set by SYNC TriggerFence; Mesa may trigger the xshmfence + // out-of-band, so `wait_triggered` reflects only what the server + // observed, not the true GPU/xshmfence state). Grep "PRESENT-INSTR". + { + let (src_kind, sw, sh) = match &src { + Some(crate::resources::HostDrawableTarget::Pixmap { + width, height, .. + }) => ("pixmap", *width, *height), + Some(_) => ("non-pixmap", 0, 0), + None => ("unresolved", 0, 0), + }; + let wait_triggered = if req.wait_fence == 0 { + "no-fence".to_string() + } else { + match state.sync_fences.get(&req.wait_fence) { + Some(f) => format!("{}", f.triggered), + None => "unknown-fence".to_string(), + } + }; + log::debug!( + "PRESENT-INSTR client {} #{} Pixmap serial={} src={} {}x{} \ + window=0x{:x} wait_fence=0x{:x} wait_triggered={} idle_fence=0x{:x}", + client_id.0, + sequence.0, + req.serial, + src_kind, + sw, + sh, + req.window, + req.wait_fence, + wait_triggered, + req.idle_fence, + ); + } + // Diagnostic: the copy below is gated on the source resolving to + // a usable host pixmap and the window resolving to a host target. + // The pixmap/window resource-existence checks already ran above + // (BadDrawable/BadWindow), so reaching here unresolved means the + // resource exists but has no backend host xid — the classic + // failed-DRI3-dmabuf-import shape (e.g. PixmapFromBuffers rejected + // a multi-plane/modifier buffer). Without this warn the present is + // silently dropped and the window shows stale content. + if !matches!( + src, + Some(crate::resources::HostDrawableTarget::Pixmap { .. }) + ) || dst.is_none() + { + log::warn!( + "client {} #{} Present::Pixmap pixmap=0x{:x} window=0x{:x}: dropping present \ + copy — src_resolved_as_host_pixmap={} dst_resolved={} (window keeps stale \ + content; a preceding DRI3 dmabuf import likely failed)", + client_id.0, + sequence.0, + req.pixmap, + req.window, + matches!( + src, + Some(crate::resources::HostDrawableTarget::Pixmap { .. }) + ), + dst.is_some(), + ); + } + if let ( + Some(crate::resources::HostDrawableTarget::Pixmap { + host_xid, + width, + height, + depth: _src_depth, + .. + }), + Some(dst), + ) = (src, dst) + { + let paint_dst_host_xid = dst.host_xid(); + // DIAG (2026-07-08, MATE compositor slow-drag smear): log what the + // compositor actually presents into the COW so we can tell whether + // the `update` region is a full frame or thin drag slivers, and + // whether the slivers tile the swept region. Env-gated + // (YSERVER_PRESENT_TRACE=1) so it is zero-cost / no timing + // perturbation when off. Grep "PRESENT-UPDATE". See + // docs/superpowers/findings/2026-07-08-mate-compositor-drag-smear-diagnosis.md + { + use std::sync::OnceLock; + static TRACE: OnceLock = OnceLock::new(); + if *TRACE.get_or_init(|| std::env::var_os("YSERVER_PRESENT_TRACE").is_some()) { + let (nrects, bbox): (isize, Option<(i32, i32, i32, i32)>) = + if req.update == 0 { + (-1, None) // full copy: no update region + } else if let Some(region) = state.xfixes_regions.get(&req.update) { + let bbox = region.rects().iter().fold( + None, + |acc: Option<(i32, i32, i32, i32)>, r| { + let x0 = i32::from(r.x); + let y0 = i32::from(r.y); + let x1 = x0 + i32::from(r.width); + let y1 = y0 + i32::from(r.height); + Some(match acc { + None => (x0, y0, x1, y1), + Some((ax0, ay0, ax1, ay1)) => { + (ax0.min(x0), ay0.min(y0), ax1.max(x1), ay1.max(y1)) + } + }) + }, + ); + (region.rects().len() as isize, bbox) + } else { + (-2, None) // update id set but region not found → full copy + }; + log::info!( + "PRESENT-UPDATE window=0x{:x} x_off={} y_off={} pixmap={}x{} \ + update_id=0x{:x} nrects={} bbox={:?}", + req.window, + req.x_off, + req.y_off, + width, + height, + req.update, + nrects, + bbox, + ); + } + } + // Snapshot the region now: XFixes regions are mutable resources, + // while an imported producer may keep this request parked. + let update_rects = if req.update == 0 { + None + } else { + state + .xfixes_regions + .get(&req.update) + .map(crate::server::XFixesRegion::rects) + }; + let present_id = state.next_present_id(); + let window_generation = state.present_window_generation(req.window); + let effective_target_msc = effective_present_target_raw( + domain, + req.target_msc, + req.divisor, + req.remainder, + masked_options, + ); + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} client={} serial={} stage=request kind=pixmap target_msc={} div={} rem={} kernel_msc={} eff={:?}", + pace_instr_ms(), present_id, client_id.0, req.serial, req.target_msc, req.divisor, req.remainder, domain.raw_msc, effective_target_msc + ); + let pending = PendingPresentPixmap { + origin, + client_id, + request: PendingPresentRequest::Pixmap(req.clone()), + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: req.idle_fence, + }, + masked_options, + src_host_xid: host_xid.as_raw(), + paint_dst_host_xid, + completion_dst_host_xid: completion_host.unwrap_or(paint_dst_host_xid), + src_width: width, + src_height: height, + update_rects, + present_id, + window_generation, + crtc_id: domain.crtc_id, + crtc_epoch: domain.crtc_epoch, + msc_offset: domain.msc_offset, + effective_target_msc, + }; + // Arm before scrap — see + // `arm_present_pixmap_source_then_supersede` doc comment + // for why the order matters (a fallible arm after scrap + // would destroy a frame nothing replaces). + let armed = arm_present_pixmap_source_then_supersede(state, backend, &pending)?; + match armed { + crate::backend::PresentSourceWait::Ready => { + arrival_execute_or_park_present_pixmap(state, backend, present_id, pending); + } + crate::backend::PresentSourceWait::Deferred(wait_id) => { + log::debug!(target: "present_pace", "PACE-INSTR t={} pid={} stage=source_deferred wait_id={}", pace_instr_ms(), pending.present_id, wait_id); + let pin = backend.pin_present_source(pending.src_host_xid); + if state + .present_wait_to_id + .insert(wait_id, present_id) + .is_some() + { + log::warn!("backend reused live Present source wait id {wait_id}"); + } + state.present_pending_exec.insert( + present_id, + crate::server::PendingPresentEntry { + pending, + source_ready: false, + superseded_by_executed_present_id: None, + wait_id: Some(wait_id), + pin, + }, + ); + } + } + } + debug!( + "client {} #{} PRESENT::Pixmap serial={} notifies={}", + client_id.0, + sequence.0, + req.serial, + req.notifies.len() + ); + } + x11present::NOTIFY_MSC => { + if let Some(req) = x11present::parse_notify_msc(body) { + if state.resources.window(ResourceId(req.window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + // Xorg resolves the target window first. Invalid residue is + // BadValue only once BadWindow has been ruled out. + if present_remainder_invalid(req.divisor, req.remainder) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + present_remainder_error_value(req.remainder), + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + let domain = select_present_domain(state, backend, req.window, 0, true) + .expect("implicit Present CRTC selection cannot fail"); + let raw_target_msc = req.target_msc.wrapping_add(domain.msc_offset); + // Vblank-paced clock: the current MSC is the real kernel + // value from the last pageflip (mirrored into ServerState). + // If already satisfied (and we have a real flip to time + // against), complete now; otherwise PARK the request and let + // a future pageflip fire it (drain_present_completions). On + // master these were dropped when unsatisfied, which froze a + // compositor's `present` frame clock after one frame. + let current_msc = domain.raw_msc; + let clockless = + domain.crtc_id == 0 || !present_crtc_is_enabled(state, domain.crtc_id); + let satisfied = clockless + || (current_msc > 0 + && notify_msc_satisfied( + current_msc, + raw_target_msc, + req.divisor, + req.remainder, + )); + if satisfied { + fire_present_notify_msc_complete_events( + state, + byte_order, + PRESENT_MAJOR_OPCODE, + req.window, + req.serial, + current_msc.wrapping_sub(domain.msc_offset), + domain.raw_ust, + ); + } else { + state + .present_pending_msc + .push(crate::server::PendingNotifyMsc { + owner: client_id, + window: req.window, + crtc_id: domain.crtc_id, + crtc_epoch: domain.crtc_epoch, + msc_offset: domain.msc_offset, + serial: req.serial, + target_msc: raw_target_msc, + divisor: req.divisor, + remainder: req.remainder, + byte_order, + }); + } + } + debug!("client {} #{} PRESENT::NotifyMSC", client_id.0, sequence.0); + } + x11present::PIXMAP_SYNCED => { + let Some(req) = x11present::parse_pixmap_synced(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + }; + let acquire_known = req.acquire_syncobj != 0 + && backend.dri3_syncobj_owned(client_id, req.acquire_syncobj); + if !acquire_known { + // Mirror Xorg's bad-value choice: VERIFY_DRI3_SYNCOBJ + // (dri3/dri3.h:51-56) sets client->errorValue = when the + // syncobj lookup fails. This is the error ARGUMENT, not the + // error CODE — it is NOT part of the declared divergence + // (which covers the code only). + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.acquire_syncobj, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + let release_handle = if req.release_syncobj != 0 + && backend.dri3_syncobj_owned(client_id, req.release_syncobj) + { + backend.dri3_syncobj_handle(req.release_syncobj) + } else { + None + }; + let Some(release_handle) = release_handle else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.release_syncobj, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + }; + if req.acquire_value == 0 + || req.release_value == 0 + || (req.acquire_syncobj == req.release_syncobj + && req.acquire_value >= req.release_value) + { + // Point/ordering failures in Xorg (present_request.c:299-301) + // leave errorValue at zero. + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + let window_exists = state.resources.window(ResourceId(req.window)).is_some(); + let pixmap_exists = state.resources.pixmap(ResourceId(req.pixmap)).is_some(); + let src = state.resources.host_drawable_target(ResourceId(req.pixmap)); + let dst = state.resources.host_drawable_target(ResourceId(req.window)); + let completion_host = state + .resources + .present_completion_host(ResourceId(req.window)); + if !window_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + if !pixmap_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.pixmap, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + // Keep domain binding after every fallible drawable validation: + // a rejected request must not change the CRTC that a later + // NotifyMSC remembers for this window. + if let ( + Some(crate::resources::HostDrawableTarget::Pixmap { + depth: src_depth, .. + }), + Some(dst), + ) = (&src, &dst) + && *src_depth != dst.depth() + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.pixmap, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + if let Some((error_code, error_value)) = present_pixmap_common_validation_error( + state, + req.valid, + req.update, + req.target_crtc, + None, + None, + req.options, + req.divisor, + req.remainder, + ) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error_code, + error_value, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + let domain = + match select_present_domain(state, backend, req.window, req.target_crtc, false) { + Ok(domain) => domain, + Err(crtc) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + crtc, + u16::from(header.data), + PRESENT_MAJOR_OPCODE, + ); + } + }; + let caps = backend.present_capabilities(req.window, domain.crtc_id); + let masked_options = if caps.async_may_tear { + req.options + } else { + const PRESENT_OPTION_ASYNC_MAY_TEAR: u32 = 0x10; + req.options & !PRESENT_OPTION_ASYNC_MAY_TEAR + }; + // INSTRUMENTATION (2026-05-29): synced variant uses acquire_syncobj + // (explicit-sync timeline) as its wait. Log src kind+SIZE + the + // acquire/release syncobj so a blank run shows whether content-sized + // synced presents arrive and what sync points they carry. + // Grep "PRESENT-INSTR". + { + let (src_kind, sw, sh) = match &src { + Some(crate::resources::HostDrawableTarget::Pixmap { + width, height, .. + }) => ("pixmap", *width, *height), + Some(_) => ("non-pixmap", 0, 0), + None => ("unresolved", 0, 0), + }; + log::debug!( + "PRESENT-INSTR client {} #{} PixmapSynced serial={} src={} {}x{} \ + window=0x{:x} acquire_syncobj=0x{:x} acquire_value={} \ + release_syncobj=0x{:x} release_value={}", + client_id.0, + sequence.0, + req.serial, + src_kind, + sw, + sh, + req.window, + req.acquire_syncobj, + req.acquire_value, + req.release_syncobj, + req.release_value, + ); + } + // Same silent-drop diagnostic as the Present::Pixmap path: if the + // source pixmap didn't resolve to a backend host pixmap (failed + // DRI3 dmabuf import) or the window didn't resolve, the copy below + // is skipped and the window keeps stale content. + if !matches!( + src, + Some(crate::resources::HostDrawableTarget::Pixmap { .. }) + ) || dst.is_none() + { + log::warn!( + "client {} #{} Present::PixmapSynced pixmap=0x{:x} window=0x{:x}: dropping \ + present copy — src_resolved_as_host_pixmap={} dst_resolved={} (window keeps \ + stale content; a preceding DRI3 dmabuf import likely failed)", + client_id.0, + sequence.0, + req.pixmap, + req.window, + matches!( + src, + Some(crate::resources::HostDrawableTarget::Pixmap { .. }) + ), + dst.is_some(), + ); + } + let queued_copy = if let ( + Some(crate::resources::HostDrawableTarget::Pixmap { + host_xid, + width, + height, + depth: src_depth, + .. + }), + Some(dst), + ) = (src, dst) + { + let paint_dst_host_xid = dst.host_xid(); + if src_depth != dst.depth() { + false + } else { + let update_rects = if req.update == 0 { + None + } else { + state + .xfixes_regions + .get(&req.update) + .map(crate::server::XFixesRegion::rects) + }; + let present_id = state.next_present_id(); + let window_generation = state.present_window_generation(req.window); + let effective_target_msc = effective_present_target_raw( + domain, + req.target_msc, + req.divisor, + req.remainder, + masked_options, + ); + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} client={} serial={} stage=request kind=synced target_msc={} div={} rem={} kernel_msc={} eff={:?} acquire=0x{:x}@{} release=0x{:x}@{}", + pace_instr_ms(), present_id, client_id.0, req.serial, req.target_msc, req.divisor, req.remainder, domain.raw_msc, effective_target_msc, + req.acquire_syncobj, req.acquire_value, req.release_syncobj, req.release_value, + ); + let pending = PendingPresentPixmap { + origin, + client_id, + request: PendingPresentRequest::PixmapSynced(req.clone()), + wake: crate::backend::PresentWake::PixmapSynced { + release: release_handle.clone(), + release_syncobj: req.release_syncobj, + release_value: req.release_value, + }, + masked_options, + src_host_xid: host_xid.as_raw(), + paint_dst_host_xid, + completion_dst_host_xid: completion_host.unwrap_or(paint_dst_host_xid), + src_width: width, + src_height: height, + update_rects, + present_id, + window_generation, + crtc_id: domain.crtc_id, + crtc_epoch: domain.crtc_epoch, + msc_offset: domain.msc_offset, + effective_target_msc, + }; + // Arm before scrap — see + // `arm_present_pixmap_synced_source_then_supersede` + // doc comment for why the order matters (a fallible + // arm after scrap would destroy a frame nothing + // replaces). + let armed = arm_present_pixmap_synced_source_then_supersede( + state, + backend, + req.acquire_syncobj, + req.acquire_value, + &pending, + )?; + match armed { + crate::backend::PresentSourceWait::Ready => { + arrival_execute_or_park_present_pixmap( + state, backend, present_id, pending, + ); + } + crate::backend::PresentSourceWait::Deferred(wait_id) => { + log::debug!(target: "present_pace", "PACE-INSTR t={} pid={} stage=acquire_deferred wait_id={} syncobj=0x{:x} value={}", pace_instr_ms(), pending.present_id, wait_id, req.acquire_syncobj, req.acquire_value); + let pin = backend.pin_present_source(pending.src_host_xid); + if state + .present_wait_to_id + .insert(wait_id, present_id) + .is_some() + { + log::warn!("backend reused live Present syncobj wait id {wait_id}"); + } + state.present_pending_exec.insert( + present_id, + crate::server::PendingPresentEntry { + pending, + source_ready: false, + superseded_by_executed_present_id: None, + wait_id: Some(wait_id), + pin, + }, + ); + } + } + true + } + } else { + false + }; + if !queued_copy { + log::debug!( + "PRESENT::PixmapSynced copy path was not queued \ + (window=0x{:x} pixmap=0x{:x})", + req.window, + req.pixmap + ); + } + debug!( + "client {} #{} PRESENT::PixmapSynced serial={} acquire=0x{:x}@{} release=0x{:x}@{}", + client_id.0, + sequence.0, + req.serial, + req.acquire_syncobj, + req.acquire_value, + req.release_syncobj, + req.release_value + ); + } + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(minor), + header.opcode, + ); + } + } + Ok(RequestOutcome::Handled) +} + +fn notify_msc_satisfied(current_msc: u64, target_msc: u64, divisor: u64, remainder: u64) -> bool { + if crate::present_scheduler::msc_is_after(target_msc, current_msc) { + return false; + } + if divisor == 0 { + return true; + } + current_msc % divisor == remainder +} + +/// Fan out `CompleteNotify { mode: Copy }` and `IdleNotify` to every +/// `present_event_selections` entry that subscribed to the window +/// with the matching event-mask bit. Phase 4.2.3 design §3.3.2. +pub fn fire_present_completion_events( + state: &mut ServerState, + event: &crate::backend::CompletedPresentEvent, +) { + let cached = cached_present_crtc_clock(state, event.crtc_id, event.crtc_epoch); + let raw = event.completion_clock.unwrap_or({ + if cached.completion.msc > 0 { + cached.completion + } else { + crate::backend::PresentClockSample { + msc: cached.msc, + ust: cached.ust, + source: crate::backend::PresentClockSource::Immediate, + } + } + }); + let clock = present_wire_clock(raw, event.msc_offset); + fire_present_completion_events_at( + state, + event, + clock, + yserver_protocol::x11::present::COMPLETE_MODE_COPY, + true, + true, + ); +} + +pub(crate) fn fire_present_completion_events_at( + state: &mut ServerState, + event: &crate::backend::CompletedPresentEvent, + clock: crate::backend::PresentClockSample, + mode: u8, + emit_idle: bool, + emit_complete: bool, +) { + use crate::backend::PresentWake; + use yserver_protocol::x11::present as x11present; + + /// PRESENT major opcode. + const PRESENT_MAJOR_OPCODE: u8 = 145; + /// `PresentEventMaskCompleteNotify` per `presentproto`. + const COMPLETE_NOTIFY_MASK: u32 = 0x2; + /// `PresentEventMaskIdleNotify`. + const IDLE_NOTIFY_MASK: u32 = 0x4; + + let window = ResourceId(event.dst_host_xid); + // Report the provenance-aware display sample selected by the caller. + // Pixmap completion deliberately excludes standalone sequence events + // observed while scanout is active, while NotifyMSC remains driven by + // the general vblank clock. (Was: a per-window software counter + ust=0, + // which picom rejects as "Invalid PresentCompleteNotify event".) + let current_msc = clock.msc; + let pixmap_xid = event.host_xid; + let idle_fence = match &event.wake { + PresentWake::Pixmap { idle_fence_xid } => *idle_fence_xid, + PresentWake::PixmapSynced { + release_syncobj, .. + } => *release_syncobj, + }; + + // Gather the matching (eid, owning client, mask) tuples up front + // so we can iterate state.clients without holding a borrow on + // present_event_selections. + let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); + for (eid, sel) in &state.present_event_selections { + if sel.window == window { + targets.push((*eid, sel.owner, sel.event_mask)); + } + } + debug!( + "PRESENT events: window=0x{:x} serial={} pixmap=0x{:x} targets={:?}", + window.0, + event.serial, + pixmap_xid, + targets + .iter() + .map(|(e, c, m)| format!("eid=0x{e:x}/client={}/mask=0x{m:x}", c.0)) + .collect::>() + ); + + for (eid, owner, mask) in targets { + let Some(client) = state.clients.get_mut(&owner.0) else { + continue; + }; + // byte_order is sourced from the OWNER client (the one + // receiving the event), not the caller. Fixes a latent bug + // where events to owners of different endianness than the + // submitting client were mis-encoded. + let byte_order = client.byte_order; + let seq = SequenceNumber( + client + .last_sequence + .load(std::sync::atomic::Ordering::Relaxed), + ); + // Per Xorg's present_execute_copy: IdleNotify fires *first* + // (the pixmap is idle as soon as the GPU finishes reading, + // which on our synchronous CopyArea path is immediately), + // CompleteNotify fires on vblank afterwards. Mesa's + // loader_dri3 expects this order — flipping it makes + // vkAcquireNextImage hang on the second frame. + if emit_idle && mask & IDLE_NOTIFY_MASK != 0 { + let ev = x11present::encode_idle_notify( + byte_order, + seq, + PRESENT_MAJOR_OPCODE, + eid, + window.0, + event.serial, + pixmap_xid, + idle_fence, + ); + let outcome = write_to_client(client, owner, &ev); + debug!( + "PRESENT IdleNotify -> client {} eid=0x{eid:x} pixmap=0x{:x} fence=0x{idle_fence:x} ({} bytes) outcome={:?} outbound_len={}", + owner.0, + pixmap_xid, + ev.len(), + outcome, + client.outbound.len(), + ); + } + if emit_complete && mask & COMPLETE_NOTIFY_MASK != 0 { + let ev = x11present::encode_complete_notify( + byte_order, + seq, + PRESENT_MAJOR_OPCODE, + eid, + window.0, + event.serial, + x11present::COMPLETE_KIND_PIXMAP, + mode, + clock.ust, + current_msc, + ); + debug!( + "PRESENT CompleteNotify -> client {} eid=0x{eid:x} ({} bytes)", + owner.0, + ev.len() + ); + let _ = write_to_client(client, owner, &ev); + } + } +} + +/// Emit `Present::ConfigureNotify` to every client that selected +/// `EVENT_MASK_CONFIGURE_NOTIFY` on `window`. Triggered from +/// `handle_configure_window` whenever the window's geometry changes +/// (size primarily — Mesa keys buffer reallocation on +/// `pixmap_{width,height}` here). Mirrors the iteration shape of +/// `fire_present_completion_events`. +pub(crate) fn fire_present_configure_notify_for_window( + state: &mut ServerState, + window_id: ResourceId, + geometry: yserver_protocol::x11::Geometry, +) { + send_present_configure_notify( + state, + window_id, + (geometry.x, geometry.y, geometry.width, geometry.height), + 0, + ); +} + +/// Xorg `present_destroy_window` (`present/present_screen.c:96-103`): a +/// destroyed window's `ConfigureNotify(PresentWindowDestroyed)`, with its +/// `drawable` x/y (absolute, inside the border) and inside size. Call while +/// `window` is still in the tree, before its selections are purged. +pub(crate) fn fire_present_window_destroyed(state: &mut ServerState, window_id: ResourceId) { + const PRESENT_WINDOW_DESTROYED: u32 = 1 << 0; + let Some(window) = state.resources.window(window_id) else { + return; + }; + let (width, height) = (window.width, window.height); + let (x, y) = state.resources.window_absolute_position(window_id); + // Xorg's `xPresentConfigureNotify` x/y are INT16, truncated from `int`. + #[allow(clippy::cast_possible_truncation)] + let (x, y) = (x as i16, y as i16); + send_present_configure_notify( + state, + window_id, + (x, y, width, height), + PRESENT_WINDOW_DESTROYED, + ); +} + +/// `present_send_config_notify` (`present/present_event.c:105-130`). +fn send_present_configure_notify( + state: &mut ServerState, + window_id: ResourceId, + (x, y, width, height): (i16, i16, u16, u16), + pixmap_flags: u32, +) { + use yserver_protocol::x11::present as x11present; + const PRESENT_MAJOR_OPCODE: u8 = 145; + + let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); + for (eid, sel) in &state.present_event_selections { + if sel.window == window_id { + targets.push((*eid, sel.owner, sel.event_mask)); + } + } + for (eid, owner, mask) in targets { + if mask & x11present::EVENT_MASK_CONFIGURE_NOTIFY == 0 { + continue; + } + let Some(client) = state.clients.get_mut(&owner.0) else { + continue; + }; + let byte_order = client.byte_order; + let seq = SequenceNumber( + client + .last_sequence + .load(std::sync::atomic::Ordering::Relaxed), + ); + let ev = x11present::encode_configure_notify( + byte_order, + seq, + PRESENT_MAJOR_OPCODE, + eid, + window_id.0, + x, + y, + width, + height, + 0, + 0, + width, + height, + pixmap_flags, + ); + let _ = write_to_client(client, owner, &ev); + debug!( + "PRESENT ConfigureNotify -> client {} eid=0x{eid:x} window=0x{:x} \ + geom=({x},{y} {width}x{height}) flags=0x{pixmap_flags:x}", + owner.0, window_id.0, + ); + } +} + +fn fire_present_notify_msc_complete_events( + state: &mut ServerState, + byte_order: yserver_protocol::x11::ClientByteOrder, + extension_major: u8, + window: u32, + serial: u32, + current_msc: u64, + ust: u64, +) { + use yserver_protocol::x11::present as x11present; + const COMPLETE_NOTIFY_MASK: u32 = 0x2; + + let window = ResourceId(window); + let mut targets: Vec<(u32, ClientId, u32)> = Vec::new(); + for (eid, sel) in &state.present_event_selections { + if sel.window == window { + targets.push((*eid, sel.owner, sel.event_mask)); + } + } + + for (eid, owner, mask) in targets { + if mask & COMPLETE_NOTIFY_MASK == 0 { + continue; + } + let Some(client) = state.clients.get_mut(&owner.0) else { + continue; + }; + let seq = SequenceNumber( + client + .last_sequence + .load(std::sync::atomic::Ordering::Relaxed), + ); + let ev = x11present::encode_complete_notify( + byte_order, + seq, + extension_major, + eid, + window.0, + serial, + x11present::COMPLETE_KIND_NOTIFY_MSC, + x11present::COMPLETE_MODE_COPY, + ust, + current_msc, + ); + debug!( + "PRESENT NotifyMSC CompleteNotify -> client {} eid=0x{eid:x} msc={current_msc} ust={ust} ({} bytes)", + owner.0, + ev.len() + ); + let _ = write_to_client(client, owner, &ev); + } +} + +/// Fire every parked `NotifyMSC` (NOTIFY_MSC handler) whose target MSC is now +/// satisfied by the real kernel `(msc, ust)` from the latest pageflip. +/// Called from `drain_present_completions` after the backend advances the +/// vblank clock — this is what keeps a compositor's `present` frame clock +/// running at the display refresh rate. +#[cfg(test)] +pub(super) fn fire_due_present_notify_msc(state: &mut ServerState, msc: u64, ust: u64) { + let mut domains: Vec<(u32, u64)> = state + .present_pending_msc + .iter() + .map(|pending| (pending.crtc_id, pending.crtc_epoch)) + .collect(); + domains.sort_unstable(); + domains.dedup(); + for (crtc_id, crtc_epoch) in domains { + fire_due_present_notify_msc_for_domain(state, crtc_id, crtc_epoch, msc, ust, false); + } +} + +pub(crate) fn fire_due_present_notify_msc_for_domain( + state: &mut ServerState, + crtc_id: u32, + crtc_epoch: u64, + msc: u64, + ust: u64, + force: bool, +) { + if (!force && msc == 0) || state.present_pending_msc.is_empty() { + return; + } + const PRESENT_MAJOR_OPCODE: u8 = 145; + let mut still_pending = Vec::new(); + for p in std::mem::take(&mut state.present_pending_msc) { + if p.crtc_id != crtc_id || p.crtc_epoch != crtc_epoch { + still_pending.push(p); + } else if force || notify_msc_satisfied(msc, p.target_msc, p.divisor, p.remainder) { + fire_present_notify_msc_complete_events( + state, + p.byte_order, + PRESENT_MAJOR_OPCODE, + p.window, + p.serial, + msc.wrapping_sub(p.msc_offset), + ust, + ); + } else { + still_pending.push(p); + } + } + state.present_pending_msc = still_pending; +} + +/// Milliseconds since first call, for correlating per-present pipeline stages +/// under `target: "present_pace"`. +/// +/// Kept deliberately (was introduced as TEMP scaffolding): the +/// `PresentPixmapSynced` acquire-wait work reports its ready/deferred/signalled +/// stages through this target, and the numbers that validated that fix — 473 of +/// 2,221 synced requests arriving before their acquire point, 0.87 ms mean +/// wait — came from it. Emission is `log::debug!(target: "present_pace", ...)`, +/// so it is silent unless that target is explicitly enabled and costs nothing +/// at the default log level. +pub(crate) fn pace_instr_ms() -> u128 { + use std::{sync::OnceLock, time::Instant}; + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_millis() +} + +/// Signal the client's retained wake (real xshmfence/syncobj) via the +/// backend, update X11 fence bookkeeping, then emit IdleNotify+CompleteNotify +/// (idle-before-complete, per Xorg). Stamps the complete event with the +/// latest cached clock for this request's exact CRTC epoch. Used for ungated +/// completions and teardown; paced completion passes an explicit raw sample. +pub(crate) fn complete_present_now( + state: &mut ServerState, + backend: &mut dyn Backend, + event: &crate::backend::CompletedPresentEvent, +) { + let cached = cached_present_crtc_clock(state, event.crtc_id, event.crtc_epoch); + let clock = event.completion_clock.unwrap_or({ + if cached.completion.msc > 0 { + cached.completion + } else { + crate::backend::PresentClockSample { + msc: cached.msc, + ust: cached.ust, + source: crate::backend::PresentClockSource::Immediate, + } + } + }); + complete_present_with_clock( + state, + backend, + event, + clock, + event.completion_mode, + event.emit_idle, + ); +} + +/// Whether a backend completion still belongs to the live destination window +/// that accepted it. Numeric XIDs may be reused after destruction, so resource +/// existence alone is not sufficient. +pub(crate) fn present_event_window_is_current( + state: &ServerState, + event: &crate::backend::CompletedPresentEvent, +) -> bool { + // Legacy unit fixtures predate window generations and use zero. Real + // accepted Presents always allocate a nonzero generation. + #[cfg(test)] + if event.window_generation == 0 { + return true; + } + state + .resources + .window(ResourceId(event.dst_host_xid)) + .is_some() + && state + .present_window_generations + .get(&event.dst_host_xid) + .is_some_and(|&generation| generation == event.window_generation) +} + +/// Drop a backend completion for a destroyed/reused window without emitting +/// wire events. Copy completions may release once their GPU read retired; +/// direct completions must wait for the distinct retired-idle event because +/// their source can still be scanned out. +pub(crate) fn discard_stale_present_event( + state: &mut ServerState, + backend: &mut dyn Backend, + event: &crate::backend::CompletedPresentEvent, + retired_idle: bool, +) { + let release = retired_idle || event.emit_idle; + if !release { + return; + } + backend.signal_present_wake(event.present_id); + if let crate::backend::PresentWake::Pixmap { idle_fence_xid } = &event.wake + && *idle_fence_xid != 0 + { + crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); + } +} + +/// `mode`/`emit_idle` are the wire mode byte and whether to also release +/// the retained wake / emit IdleNotify (spec §Ordered completion delivery +/// item 1): a parked Skip (Task 8 supersession) already released its idle +/// fence/syncobj and set the `sync_fences` mirror at scrap time, so its +/// delivery here must not touch idle machinery a second time — no +/// `signal_present_wake`, no IdleNotify, no fence-mirror write. +/// `signal_present_wake` is gated too (not just the fence mirror / +/// IdleNotify): both `emit_idle == false` populations — scrap (Task 8 +/// §Supersession) and the copy-failure reroute (Task 8 round-4 F5) — are +/// never-executed: the failing copy precedes `enqueue_present_completion` +/// just as scrap precedes it, so neither ever retains a real backend +/// wake, and the by-XID release (fence/syncobj + mirror + IdleNotify) at +/// scrap/failure time is each entry's sole release path. Gating this +/// signal is therefore a no-op today given how the two populations are +/// built — kept explicit (rather than relying on the backend's +/// unknown-id no-op guard) so a future `emit_idle: false` population +/// that DOES retain a real wake cannot silently double-fire it. +pub(crate) fn complete_present_with_clock( + state: &mut ServerState, + backend: &mut dyn Backend, + event: &crate::backend::CompletedPresentEvent, + clock: crate::backend::PresentClockSample, + mode: u8, + emit_idle: bool, +) { + use crate::backend::PresentWake; + let clock = present_wire_clock(clock, event.msc_offset); + match &event.wake { + PresentWake::Pixmap { idle_fence_xid } => log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=signal_wake msc={} source={:?} idle_fence=0x{:x}", + pace_instr_ms(), event.present_id, clock.msc, clock.source, idle_fence_xid, + ), + PresentWake::PixmapSynced { + release_syncobj, + release_value, + .. + } => log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=signal_wake msc={} source={:?} release=0x{:x}@{}", + pace_instr_ms(), event.present_id, clock.msc, clock.source, + release_syncobj, release_value, + ), + } + if emit_idle { + backend.signal_present_wake(event.present_id); + } + if emit_idle + && let PresentWake::Pixmap { idle_fence_xid } = &event.wake + && *idle_fence_xid != 0 + { + crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); + } + fire_present_completion_events_at(state, event, clock, mode, emit_idle, true); +} + +/// Release a previously completed direct-scanout source after its replacement +/// has retired. This emits IdleNotify only; CompleteNotify was emitted when +/// the source first reached every CRTC. +pub(crate) fn retire_present_idle( + state: &mut ServerState, + backend: &mut dyn Backend, + event: &crate::backend::CompletedPresentEvent, +) { + use crate::backend::PresentWake; + + backend.signal_present_wake(event.present_id); + if let PresentWake::Pixmap { idle_fence_xid } = &event.wake + && *idle_fence_xid != 0 + { + crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); + } + let clock = refresh_present_crtc_completion_clock( + state, + backend, + event.crtc_id, + event.crtc_epoch, + event.completion_clock, + ); + let clock = present_wire_clock(clock, event.msc_offset); + fire_present_completion_events_at(state, event, clock, event.completion_mode, true, false); +} + +/// Fire parked completions whose target MSC has been reached. Called from the +/// MSC-advance drain, alongside `fire_due_present_notify_msc`. +/// +/// Delivery is per-window `present_id` order, not raw queue order (spec +/// §"Ordered completion delivery (per-window `present_id` order)"): +/// `present_id` is allocated monotonically at request time, so it IS +/// per-window `CompleteNotify` serial order, and Mesa's `loader_dri3` +/// regenerates its swap accounting from the latest event's serial — a +/// backward serial is a real client hazard. A Copy enters this queue at +/// GPU-fence-retirement time while a Skip (Task 8 supersession) enters at +/// scrap (request-arrival) time, so raw insertion order is not serial +/// order: a due entry for window `W` must be held back while any SMALLER +/// `present_id` for `W` is still unresolved in any of three places — +/// msc-parked-unexecuted (`present_pending_exec`), executed-but-undrained +/// (`present_complete_gate`, which carries `dst_window_xid`), or +/// parked-not-yet-due (this same queue). The hold-back is per-window so a +/// stalled window's GPU copy cannot head-of-line block another window's +/// completions. +#[cfg(test)] +pub(crate) fn fire_due_present_completions( + state: &mut ServerState, + backend: &mut dyn Backend, + clock: crate::backend::PresentClockSample, +) { + let mut domains: Vec<(u32, u64)> = state + .present_pending_complete + .iter() + .map(|pending| (pending.event.crtc_id, pending.event.crtc_epoch)) + .collect(); + domains.sort_unstable(); + domains.dedup(); + for (crtc_id, crtc_epoch) in domains { + advance_present_crtc_completion_clock(state, crtc_id, crtc_epoch, clock); + } + fire_present_completions_sweep(state, backend, false); +} + +pub(crate) fn fire_due_present_completions_for_domain( + state: &mut ServerState, + backend: &mut dyn Backend, + crtc_id: u32, + crtc_epoch: u64, + clock: crate::backend::PresentClockSample, +) { + advance_present_crtc_completion_clock(state, crtc_id, crtc_epoch, clock); + fire_present_completions_sweep(state, backend, false); +} + +/// Blackout flush (spec Lifecycle §"DPMS-off / VT-away blackout"; Task 7): +/// deliver every parked completion NOW, ignoring the msc-due check — +/// `present_scanout_blackout()` means no flips and no sequence samples +/// will ever arrive, so the clock is frozen and would never otherwise +/// satisfy `fire_due_present_completions`'s due test (round-4 F1c). The +/// per-window hold-back (`blocked`) still applies unmodified: an +/// outstanding GPU fence in `present_complete_gate` is not something a +/// dark display can force to retire early. +/// +/// The msc-parked half of the hold-back is only PARTIALLY cleared by +/// `drain_due_present_pending_exec`'s own blackout branch, which runs +/// first in the same due-pass: that branch force-executes `source_ready` +/// entries only (deliberately — a `source_ready == false` entry is still +/// waiting on its own producer fence, and blackout does nothing to +/// resolve that). So an uncovered `source_ready:false` entry that the +/// successor gate declines to scrap (spec §Supersession) keeps its +/// window's parked completions held back through this flush too, even +/// while blackout is on. DECISION (accepted, do not change): holding the +/// order here is correct — the entry's own producer fence can still +/// signal during blackout (GPU work is display-independent), after which +/// the *next* blackout pass force-executes it and the queue drains. The +/// truly-stuck case (the producer fence never signals) is the same +/// pre-existing exposure that entry always had regardless of blackout, +/// and the purge paths (destroy/disconnect/shutdown) clear it. +pub(super) fn fire_all_present_completions_now(state: &mut ServerState, backend: &mut dyn Backend) { + fire_present_completions_sweep(state, backend, true); +} + +fn fire_present_completions_sweep(state: &mut ServerState, backend: &mut dyn Backend, force: bool) { + if state.present_pending_complete.is_empty() { + return; + } + + // Smallest still-unresolved present_id per window in the other two + // hold-back states (BTreeMap iteration order doesn't matter here — + // every entry is visited to find the per-window min). + let mut exec_min_by_window: HashMap = HashMap::new(); + for (&pid, entry) in &state.present_pending_exec { + exec_min_by_window + .entry(entry.pending.request.window()) + .and_modify(|m| *m = (*m).min(pid)) + .or_insert(pid); + } + let mut gate_min_by_window: HashMap = HashMap::new(); + for (&pid, gate) in &state.present_complete_gate { + gate_min_by_window + .entry(gate.dst_window_xid) + .and_modify(|m| *m = (*m).min(pid)) + .or_insert(pid); + } + + // BTreeMap (not HashMap): the rebuild below walks this in window-XID + // order, which makes the surviving `still_pending` queue's + // cross-window order deterministic run-to-run. Nothing currently + // depends on that order, but a HashMap here would be a standing + // test-flakiness trap for whatever eventually does. + let mut by_window: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + for p in std::mem::take(&mut state.present_pending_complete) { + by_window.entry(p.event.dst_host_xid).or_default().push(p); + } + + let mut still_pending = Vec::new(); + for (window, mut entries) in by_window { + // Ascending present_id: the third hold-back state (parked-not-yet- + // due, i.e. an earlier entry in this very group) falls out of + // walking in this order and stopping at the first entry that is + // not both due and externally unblocked — everything after it is + // held back too, by construction. + entries.sort_by_key(|p| p.event.present_id); + let ext_min = match ( + exec_min_by_window.get(&window), + gate_min_by_window.get(&window), + ) { + (Some(&a), Some(&b)) => Some(a.min(b)), + (Some(&a), None) | (None, Some(&a)) => Some(a), + (None, None) => None, + }; + let mut iter = entries.into_iter(); + for p in iter.by_ref() { + let blocked = ext_min.is_some_and(|m| m < p.event.present_id); + let due_clock = present_completion_due_clock(state, &p.event); + // The domain cache decides when a paced event is due. An exact + // grouped-direct reference sample only stamps that event; using an + // older exact retirement as the due clock would park it forever + // after the domain itself advanced past the target. + let stamp_clock = p.event.completion_clock.unwrap_or(due_clock); + let epoch_current = + backend.present_crtc_clock_epoch(p.event.crtc_id) == p.event.crtc_epoch; + // Due when msc has reached/passed the target (wrap-safe): NOT + // (target after msc) — or unconditionally due when `force` + // (blackout flush) bypasses the clock test entirely. An epoch + // mismatch also fails open: its raw target belongs to a counter + // that no longer backs this RANDR XID and must never be compared + // against the replacement epoch. + let due = force + || !epoch_current + || (due_clock.msc > 0 + && !crate::present_scheduler::msc_is_after( + p.effective_target_msc, + due_clock.msc, + )); + if blocked || !due { + still_pending.push(p); + break; + } + log::debug!( + target: "present_pace", + "PACE-INSTR t={} pid={} stage=fired msc={} eff={} source={:?}", + pace_instr_ms(), p.event.present_id, stamp_clock.msc, p.effective_target_msc, + stamp_clock.source + ); + complete_present_with_clock(state, backend, &p.event, stamp_clock, p.mode, p.emit_idle); + } + still_pending.extend(iter); + } + state.present_pending_complete = still_pending; +} diff --git a/crates/yserver-core/src/core_loop/process_request/props.rs b/crates/yserver-core/src/core_loop/process_request/props.rs new file mode 100644 index 000000000..d6e5e5782 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/props.rs @@ -0,0 +1,1585 @@ +use crate::{ + access::{AccessMode, Decision, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext}, + core_loop::{ + fanout::{emit_window_event_to_state, fanout_event_to_clients}, + process_request::{ + RequestOutcome, XI2_FIRST_ERROR, XI2_MAJOR_OPCODE, emit_x11_error, + emit_x11_error_with_minor, write_to_client, + }, + }, + properties, + server::{ServerState, XI_FIRST_EVENT}, + xinput::{XI_DEVICE_PROPERTY_NOTIFY_OFFSET, XI2_PROPERTY_EVENT_MASK}, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{AtomId, ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +pub(super) fn window_host_xid(state: &ServerState, window: ResourceId) -> u32 { + state + .resources + .window(window) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()) + .unwrap_or(window.0) +} + +/// Why the shared property-change dispatch helper rejected a request. +/// +/// Each variant maps 1:1 to a wire X error: the caller turns it into an +/// `emit_x11_error_with_minor` call with the variant-specific code and +/// error_value. Kept inside `process_request.rs` so the field types +/// don't leak ServerState into `xinput::libinput_props`. Variants +/// share the `Bad` prefix on purpose — they mirror the X11 error code +/// constants (BadAtom = 5, BadAccess = 10, BadValue = 2, BadMatch = 8). +#[derive(Debug)] +#[allow(clippy::enum_variant_names)] +pub(in crate::core_loop) enum PropertyDispatchError { + /// Atom is not interned → X error code 5 (BadAtom). Echoes the atom. + BadAtom { atom: u32 }, + /// Write targets a ReadOnly descriptor → X error code 10 (BadAccess). + /// Echoes the atom. + BadAccess { atom: u32 }, + /// Value failed `validate_value` / `decode_change` / backend + /// rejected it as `Invalid` → X error code 2 (BadValue). Echoes the + /// wire `format` for spec parity with the other BadValue sites in + /// the property arms. + BadValue { error_value: u32 }, + /// Backend rejected the setting as `Unsupported` → X error code 8 + /// (BadMatch). error_value is always 0 here (matches xserver). + BadMatch, + /// The requested XI id disappeared or now names a different source. + BadDevice { deviceid: u16 }, +} + +/// A validated physical driver write, ready for Task 8's source-targeted +/// backend submission and subsequent commit. +#[derive(Debug, Clone)] +pub(in crate::core_loop) struct ValidatedXiChange { + pub request: crate::core_loop::message::XiConfigRequest, + pub source_id: crate::xinput::InputSourceId, + /// The live XI id for this physical facet. + pub facet_id: u16, + pub facet_kind: crate::xinput::XiFacetKind, + /// Fully merged, normalized value. Flags are retained for an existing + /// entry and default to the XICreateDeviceProperty flags for recreation. + pub merged_property: crate::xinput::XiProperty, + pub change: crate::xinput::libinput_props::DeviceConfigChange, +} + +/// XI request headers are normalized by the reader, while the typed value +/// tail remains opaque. Store 16/32-bit property items in the same LE form as +/// the rest of the XI property registry and the libinput decoders. +pub(super) fn canonicalize_xi_property_data( + byte_order: x11::ClientByteOrder, + format: u8, + data: &[u8], +) -> Vec { + let mut canonical = data.to_vec(); + if byte_order == x11::ClientByteOrder::BigEndian { + match format { + 16 => canonical + .chunks_exact_mut(2) + .for_each(|value| value.reverse()), + 32 => canonical + .chunks_exact_mut(4) + .for_each(|value| value.reverse()), + _ => {} + } + } + canonical +} + +/// Validate and merge one recognized physical libinput property write. +/// +/// Support comes from the live source/facet snapshot and descriptor table, +/// never from whether the property happens to be present in the XI map. +/// This lets deleted supported properties be recreated and prevents an +/// ordinary client property from manufacturing driver support. +pub(in crate::core_loop) fn validate_xi_change( + state: &ServerState, + request: &crate::core_loop::message::XiConfigRequest, +) -> Result { + if !state.atoms.exists(request.property) { + return Err(PropertyDispatchError::BadAtom { + atom: request.property.0, + }); + } + if is_xtest_marker_property(state, request.deviceid, request.property) { + return Err(PropertyDispatchError::BadAccess { + atom: request.property.0, + }); + } + + let device = + state + .xi_devices + .device(request.deviceid) + .ok_or(PropertyDispatchError::BadDevice { + deviceid: request.deviceid, + })?; + if device.source_id != Some(request.expected_source) { + return Err(PropertyDispatchError::BadDevice { + deviceid: request.deviceid, + }); + } + let source = state.xi_devices.source(request.expected_source).ok_or( + PropertyDispatchError::BadDevice { + deviceid: request.deviceid, + }, + )?; + + let property_name = + state + .atoms + .name(request.property) + .ok_or(PropertyDispatchError::BadAtom { + atom: request.property.0, + })?; + let descriptor = crate::xinput::libinput_props::descriptor_by_name(property_name) + .ok_or(PropertyDispatchError::BadMatch)?; + + // Every recognized libinput descriptor belongs to the pointer facet. + // A mixed physical source's keyboard facet cannot borrow its sibling's + // pointer support. + if device.facet != Some(crate::xinput::XiFacetKind::PointerTouch) + || !source.capabilities.pointer + { + return Err(PropertyDispatchError::BadMatch); + } + + if descriptor.access == crate::xinput::libinput_props::Access::ReadOnly { + return Err(PropertyDispatchError::BadAccess { + atom: request.property.0, + }); + } + + let expected_type = crate::xinput::type_atom_for(descriptor.val, state.float_atom); + if request.format != descriptor.format || request.type_atom != expected_type { + return Err(PropertyDispatchError::BadMatch); + } + + let existing = device.properties.get(&request.property); + let merged_data = match (request.mode, existing) { + (mode, Some(existing)) if mode == crate::xinput::XI_PROP_MODE_APPEND => { + if existing.format != request.format || existing.type_atom != request.type_atom { + return Err(PropertyDispatchError::BadMatch); + } + let mut data = existing.data.clone(); + data.extend_from_slice(&request.data); + data + } + (mode, Some(existing)) if mode == crate::xinput::XI_PROP_MODE_PREPEND => { + if existing.format != request.format || existing.type_atom != request.type_atom { + return Err(PropertyDispatchError::BadMatch); + } + let mut data = request.data.clone(); + data.extend_from_slice(&existing.data); + data + } + (mode, None) + if mode == crate::xinput::XI_PROP_MODE_APPEND + || mode == crate::xinput::XI_PROP_MODE_PREPEND => + { + request.data.clone() + } + _ => request.data.clone(), + }; + + // Match xf86-input-libinput's setter shape checks before disabled-device + // and availability checks. Format/type mismatches were rejected above. + // Accel Profile Enabled reports an oversized merged value as BadValue; + // the other exact-width descriptors retain their Xorg BadMatch result. + let shape_matches = match descriptor.kind { + crate::xinput::libinput_props::ValueKind::Scalar => { + merged_data.len() == usize::from(descriptor.format / 8) + } + crate::xinput::libinput_props::ValueKind::OneHot { n } + | crate::xinput::libinput_props::ValueKind::BitFlags { n } => { + merged_data.len() == usize::from(n) + } + crate::xinput::libinput_props::ValueKind::OneHotOrNone { n, min } => { + merged_data.len() >= usize::from(min) && merged_data.len() <= usize::from(n) + } + }; + if !shape_matches { + return if descriptor.binding == Some(crate::xinput::libinput_props::Binding::AccelProfile) { + Err(PropertyDispatchError::BadValue { + error_value: u32::from(request.format), + }) + } else { + Err(PropertyDispatchError::BadMatch) + }; + } + + if crate::xinput::libinput_props::validate_value(descriptor.kind, request.format, &merged_data) + .is_err() + { + return Err(PropertyDispatchError::BadValue { + error_value: u32::from(request.format), + }); + } + + // Scalar bool domains and accel-speed limits are checked by the Xorg + // setter before it tests whether the physical handle is enabled. + if matches!( + descriptor.binding, + Some( + crate::xinput::libinput_props::Binding::Tap + | crate::xinput::libinput_props::Binding::TapDrag + | crate::xinput::libinput_props::Binding::TapDragLock + | crate::xinput::libinput_props::Binding::NaturalScroll + | crate::xinput::libinput_props::Binding::Dwt + | crate::xinput::libinput_props::Binding::MiddleEmulation + | crate::xinput::libinput_props::Binding::ScrollButtonLock + ) + ) && merged_data[0] > 1 + { + return Err(PropertyDispatchError::BadValue { + error_value: u32::from(request.format), + }); + } + if descriptor.binding == Some(crate::xinput::libinput_props::Binding::AccelSpeed) { + let speed = f32::from_le_bytes(merged_data[..4].try_into().expect("scalar Float shape")); + if !(-1.0..=1.0).contains(&speed) && !speed.is_nan() { + return Err(PropertyDispatchError::BadValue { + error_value: u32::from(request.format), + }); + } + } + + // libinput's property setter sees the source's shared handle, not the + // target XI facet. The handle stays open while any source facet remains + // enabled (xf86libinput.c:416-432, 4392-4410). + if !state + .xi_devices + .source_has_enabled_facet(request.expected_source) + { + return Err(PropertyDispatchError::BadMatch); + } + if !crate::xinput::descriptor_available(descriptor, &source.config) { + return Err(PropertyDispatchError::BadMatch); + } + + let binding = descriptor + .binding + .expect("writable descriptor must have a config binding"); + let normalized = + crate::xinput::libinput_props::normalize_value(descriptor.kind, &merged_data).into_owned(); + let change = + crate::xinput::libinput_props::decode_change(binding, &normalized).map_err(|_| { + PropertyDispatchError::BadValue { + error_value: u32::from(request.format), + } + })?; + + // A syntactically valid requested profile/mode can still be unavailable + // on this source. Xorg checks this after its disabled-device gate. + let requested_value_available = match change { + crate::xinput::libinput_props::DeviceConfigChange::AccelProfile(Some(profile)) => { + source.config.accel_profile_available_mask & (1 << profile) != 0 + } + crate::xinput::libinput_props::DeviceConfigChange::ScrollMethod(Some(method)) => { + source.config.scroll_method.available_mask & (1 << method) != 0 + } + crate::xinput::libinput_props::DeviceConfigChange::SendEvents(mask) => { + mask & !source.config.send_events.available_mask == 0 + } + _ => true, + }; + if !requested_value_available { + return Err(PropertyDispatchError::BadValue { + error_value: u32::from(request.format), + }); + } + + let (read_only, deletable) = existing.map_or((false, true), |property| { + (property.read_only, property.deletable) + }); + Ok(ValidatedXiChange { + request: request.clone(), + source_id: request.expected_source, + facet_id: request.deviceid, + facet_kind: device.facet.expect("physical source has a facet"), + merged_property: crate::xinput::XiProperty { + type_atom: request.type_atom, + format: request.format, + data: normalized, + read_only, + deletable, + }, + change, + }) +} + +/// Commit one previously validated property only after its source-targeted +/// backend operation succeeds. A missing property is recreated with +/// XICreateDeviceProperty's writable/deletable defaults. +fn commit_validated_xi_change( + state: &mut ServerState, + change: &ValidatedXiChange, +) -> Result { + if state.xi_devices.source(change.source_id).is_none() { + return Err(PropertyDispatchError::BadDevice { + deviceid: change.facet_id, + }); + } + let device = state + .xi_devices + .device_mut(change.facet_id) + .filter(|device| { + device.source_id == Some(change.source_id) && device.facet == Some(change.facet_kind) + }) + .ok_or(PropertyDispatchError::BadDevice { + deviceid: change.facet_id, + })?; + + let (what, read_only, deletable) = match device.properties.get(&change.request.property) { + Some(property) => ( + crate::xinput::PropWhat::Modified, + property.read_only, + property.deletable, + ), + None => (crate::xinput::PropWhat::Created, false, true), + }; + let mut property = change.merged_property.clone(); + property.read_only = read_only; + property.deletable = deletable; + device.properties.insert(change.request.property, property); + Ok(what) +} + +/// Commit a confirmed source change against the current XI registry. When a +/// protocol continuation survived in the current generation, preserve its +/// already validated/merged bytes. After disconnect or reset, derive the +/// current atom and property bytes from the submitted setting instead of +/// using retired request metadata. +pub(in crate::core_loop) fn commit_confirmed_xi_change( + state: &mut ServerState, + source_id: crate::xinput::InputSourceId, + change: crate::xinput::libinput_props::DeviceConfigChange, + validated: Option<&ValidatedXiChange>, +) -> Result<(u16, AtomId, crate::xinput::PropWhat), PropertyDispatchError> { + if let Some(validated) = validated { + let what = commit_validated_xi_change(state, validated)?; + return Ok((validated.facet_id, validated.request.property, what)); + } + + if state.xi_devices.source(source_id).is_none() { + return Err(PropertyDispatchError::BadDevice { deviceid: 0 }); + } + let facet_id = state + .xi_devices + .facet(source_id, crate::xinput::XiFacetKind::PointerTouch) + .ok_or(PropertyDispatchError::BadDevice { deviceid: 0 })?; + let descriptor = crate::xinput::libinput_props::descriptor_for_change(change); + let property = state.atoms.intern(descriptor.name, false); + let type_atom = crate::xinput::type_atom_for(descriptor.val, state.float_atom); + let device = state + .xi_devices + .device_mut(facet_id) + .filter(|device| { + device.source_id == Some(source_id) + && device.facet == Some(crate::xinput::XiFacetKind::PointerTouch) + }) + .ok_or(PropertyDispatchError::BadDevice { deviceid: facet_id })?; + let (what, read_only, deletable) = match device.properties.get(&property) { + Some(existing) => ( + crate::xinput::PropWhat::Modified, + existing.read_only, + existing.deletable, + ), + None => (crate::xinput::PropWhat::Created, false, true), + }; + device.properties.insert( + property, + crate::xinput::XiProperty { + type_atom, + format: descriptor.format, + data: crate::xinput::libinput_props::encode_change_value(change), + read_only, + deletable, + }, + ); + Ok((facet_id, property, what)) +} + +/// Apply a parsed XI property request. Recognized writes on physical sources +/// use the facet-aware validator; unknown properties and virtual/master +/// properties retain ordinary XI storage behavior. +pub(super) fn is_xtest_marker_property( + state: &ServerState, + deviceid: u16, + property: AtomId, +) -> bool { + matches!( + deviceid, + crate::xinput::DEVICEID_XTEST_POINTER | crate::xinput::DEVICEID_XTEST_KEYBOARD + ) && property == state.xtest_device_atom +} + +pub(super) enum PropertyChangeOutcome { + Changed(crate::xinput::PropWhat), + Pending(crate::core_loop::message::XiConfigRequest), +} + +pub(super) fn dispatch_change_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client: ClientId, + sequence: SequenceNumber, + minor_opcode: u16, + deviceid: u16, + mode: u8, + format: u8, + property: AtomId, + type_atom: AtomId, + data: &[u8], +) -> Result { + // 1. BadAtom. + if !state.atoms.exists(property) { + return Err(PropertyDispatchError::BadAtom { atom: property.0 }); + } + if is_xtest_marker_property(state, deviceid, property) { + return Err(PropertyDispatchError::BadAccess { atom: property.0 }); + } + // 2. Resolve source/facet identity before descriptor lookup. Names and + // node paths are metadata only; virtual devices with client-created + // libinput-named properties keep ordinary Xorg property behavior. + let device = crate::xinput::find_device(&state.xi_devices, deviceid) + .expect("caller verified device exists"); + let prop_name = state.atoms.name(property).map(str::to_owned); + let source_id = device.source_id; + let source_info = source_id.and_then(|source| state.xi_devices.source(source)); + if let Some(source_info) = source_info + && let Some(name) = prop_name.as_deref() + && crate::xinput::libinput_props::descriptor_by_name(name).is_some() + { + let request = crate::core_loop::message::XiConfigRequest { + client, + sequence, + minor_opcode, + deviceid, + expected_source: source_info.source_id, + property, + type_atom, + format, + mode, + data: data.to_vec(), + }; + return Ok(PropertyChangeOutcome::Pending(request)); + } + + if source_info.is_some() + && matches!( + prop_name.as_deref(), + Some("Device Node" | "Device Product ID") + ) + { + return Err(PropertyDispatchError::BadAccess { atom: property.0 }); + } + if crate::xinput::find_device(&state.xi_devices, deviceid) + .and_then(|device| device.properties.get(&property)) + .is_some_and(|property| property.read_only) + { + return Err(PropertyDispatchError::BadAccess { atom: property.0 }); + } + + if property == state.xi_device_enabled_atom { + return dispatch_device_enabled_property_write( + state, backend, deviceid, mode, format, property, type_atom, data, + ); + } + + let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) + .expect("caller verified device exists"); + match crate::xinput::apply_change_property(device, mode, format, property, type_atom, data) { + Ok(what) => Ok(PropertyChangeOutcome::Changed(what)), + Err(crate::xinput::XiPropError::BadValue) => Err(PropertyDispatchError::BadValue { + error_value: u32::from(format), + }), + Err(crate::xinput::XiPropError::BadMatch) => Err(PropertyDispatchError::BadMatch), + // `apply_change_property` only returns BadValue / BadMatch; + // BadDevice is handled by the caller's lookup, so no BadDevice + // arm is reachable here. + Err(crate::xinput::XiPropError::BadDevice) => { + unreachable!("apply_change_property never returns BadDevice; lookup handled above") + } + } +} + +/// Apply one Device Enabled property write. The wire handlers have already +/// validated the device, mode, format range, and request length. Physical +/// facet transitions share the lifecycle emitters with VT changes, while +/// the backend drains that facet's held input before a disable is committed. +fn dispatch_device_enabled_property_write( + state: &mut ServerState, + backend: &mut dyn Backend, + deviceid: u16, + mode: u8, + format: u8, + property: AtomId, + type_atom: AtomId, + data: &[u8], +) -> Result { + if !state.atoms.exists(type_atom) { + return Err(PropertyDispatchError::BadAtom { atom: type_atom.0 }); + } + + let existing = crate::xinput::find_device(&state.xi_devices, deviceid) + .and_then(|device| device.properties.get(&property)) + .cloned(); + // Xorg treats a missing property's first write as Replace, regardless of + // the requested append/prepend mode (xiproperty.c:699-706). GetProperty + // with delete may have removed this normally non-deletable property. + let effective_mode = if existing.is_none() { + crate::xinput::XI_PROP_MODE_REPLACE + } else { + mode + }; + + // XIChangeDeviceProperty checks append/prepend type and format before it + // calls DeviceSetProperty (xiproperty.c:714-717). + if let Some(existing) = &existing + && effective_mode != crate::xinput::XI_PROP_MODE_REPLACE + && (existing.format != format || existing.type_atom != type_atom) + { + return Err(PropertyDispatchError::BadMatch); + } + let resulting_bytes = if effective_mode == crate::xinput::XI_PROP_MODE_REPLACE { + data.len() + } else { + existing.as_ref().map_or(data.len(), |existing| { + existing.data.len().saturating_add(data.len()) + }) + }; + if format != 8 || type_atom != crate::xinput::XA_INTEGER || resulting_bytes != 1 { + return Err(PropertyDispatchError::BadValue { + error_value: property.0, + }); + } + + // XIChangeDeviceProperty does not call DeviceSetProperty for an empty + // append/prepend; it leaves the value alone and still sends the normal + // Modified notification (xiproperty.c:789-800). + if effective_mode != crate::xinput::XI_PROP_MODE_REPLACE && data.is_empty() { + return apply_enabled_property_value( + state, + deviceid, + effective_mode, + format, + property, + type_atom, + data, + ); + } + + // The base masters and XTEST slaves may be asserted enabled, but clients + // cannot disable them (dix/devices.c:153-158). + let value = if effective_mode == crate::xinput::XI_PROP_MODE_REPLACE { + data[0] + } else { + existing + .as_ref() + .expect("append/prepend has an existing property") + .data[0] + }; + if matches!( + deviceid, + crate::xinput::DEVICEID_MASTER_POINTER + | crate::xinput::DEVICEID_MASTER_KEYBOARD + | crate::xinput::DEVICEID_XTEST_POINTER + | crate::xinput::DEVICEID_XTEST_KEYBOARD + ) { + if value == 0 { + return Err(PropertyDispatchError::BadAccess { atom: property.0 }); + } + return apply_enabled_property_value( + state, + deviceid, + effective_mode, + format, + property, + type_atom, + data, + ); + } + + let Some(device) = crate::xinput::find_device(&state.xi_devices, deviceid) else { + unreachable!("caller resolved the XI device before property dispatch"); + }; + if device.source_id.is_none() || device.facet.is_none() { + return apply_enabled_property_value( + state, + deviceid, + effective_mode, + format, + property, + type_atom, + data, + ); + } + + let was_enabled = device.enabled; + if value == 0 { + if was_enabled { + backend.disable_xi_facet(state, deviceid); + // Xorg's DeviceSetProperty only calls DisableDevice for an + // enabled device (devices.c:160-165). A zero written while the + // session already has the facet off records no client preference. + state.xi_set_facet_client_disabled(deviceid, true); + crate::xinput::hotplug::publish_facet_disabled(state, deviceid); + } + } else { + state.xi_set_facet_client_disabled(deviceid, false); + let is_enabled = crate::xinput::find_device(&state.xi_devices, deviceid) + .is_some_and(|device| device.enabled); + if !was_enabled && is_enabled { + backend.enable_xi_facet(state, deviceid); + crate::xinput::hotplug::publish_facet_enabled(state, deviceid); + } + } + + // XIChangeDeviceProperty stores the caller's complete value and sends its + // own notification after the handler returns (xiproperty.c:785-801). + // For a transition this follows the lifecycle sequence above and keeps + // nonzero values such as 5 intact. + apply_enabled_property_value( + state, + deviceid, + effective_mode, + format, + property, + type_atom, + data, + ) +} + +fn apply_enabled_property_value( + state: &mut ServerState, + deviceid: u16, + mode: u8, + format: u8, + property: AtomId, + type_atom: AtomId, + data: &[u8], +) -> Result { + let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) + .expect("caller resolved the XI device before property dispatch"); + match crate::xinput::apply_change_property(device, mode, format, property, type_atom, data) { + Ok(what) => Ok(PropertyChangeOutcome::Changed(what)), + Err(crate::xinput::XiPropError::BadValue) => Err(PropertyDispatchError::BadValue { + error_value: u32::from(format), + }), + Err(crate::xinput::XiPropError::BadMatch) => Err(PropertyDispatchError::BadMatch), + Err(crate::xinput::XiPropError::BadDevice) => { + unreachable!("apply_change_property never returns BadDevice") + } + } +} + +/// Map a [`PropertyDispatchError`] onto the XI minor-opcode error-emit +/// path. Pure plumbing — the variant carries the error code + value. +pub(in crate::core_loop) fn emit_property_dispatch_error( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + err: PropertyDispatchError, + minor_opcode: u16, +) -> io::Result { + let (code, bad_value) = match err { + PropertyDispatchError::BadAtom { atom } => (5u8, atom), + PropertyDispatchError::BadAccess { atom } => (10u8, atom), + PropertyDispatchError::BadValue { error_value } => (2u8, error_value), + PropertyDispatchError::BadMatch => (8u8, 0u32), + PropertyDispatchError::BadDevice { deviceid } => (XI2_FIRST_ERROR, u32::from(deviceid)), + }; + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + minor_opcode, + XI2_MAJOR_OPCODE, + ) +} + +/// Emit the property-change notification(s) to every client that +/// selected for them on this device. Single fan-out for both XI2 +/// (`XI_PropertyEvent`, evtype 12) and XI1 (`DevicePropertyNotify`, +/// XI1 event code 16 within the XInput event block, delivered as wire +/// type `XI_FIRST_EVENT + 16 = 82`), keyed by the same +/// `(deviceid, property, what)` tuple so the two notifications can +/// never diverge. +/// +/// Delivery follows xserver's `send_property_event` +/// (`Xi/xiproperty.c:189-208`) via `SendEventToAllWindows`: every +/// client that has selected `XI_PropertyEventMask` (XI2) or a matching +/// `XEventClass` via `SelectExtensionEvent` (XI1) for the affected +/// device on **any** window receives one copy of the event. Because +/// neither `xXIPropertyEvent` nor `devicePropertyNotify` carries an +/// event-window field, per-window distinctions only affect *which +/// clients* receive — the wire bytes are identical for every +/// recipient. Deduplication by client id is handled inside +/// `fanout_event_to_clients`. +/// +/// `deviceid` is the literal device id the change applied to (the +/// reserved XTEST ID for a virtual-device change, or a registry-assigned +/// facet ID for a physical source). The XISelectEvents storage keys masks by +/// the deviceid the client *requested*, which may be `XIAllDevices(0)` +/// (a client that wants events from every device) or +/// `XIAllMasterDevices(1)` (every master). xserver's delivery walks +/// `dix/events.c::EventMaskForClient` and OR's the masks stored under +/// the specific id AND the wildcard ids — we must mirror that here, or +/// a client that called `xinput watch-props` (which selects with +/// `deviceid=0`) silently receives nothing. The XI2 and XI1 emits are +/// independent: a client may have selected via either (or both) paths +/// and receives one copy per path. +pub(crate) fn emit_property_change( + state: &mut ServerState, + deviceid: u16, + property: AtomId, + what: crate::xinput::PropWhat, +) -> Vec { + // XI2 emit: clients select XI_PropertyEvent via + // `xi2_masks[(window, deviceid)]` keyed by the deviceid they asked + // for. A client targeting `XIAllDevices(0)` or — when the event + // device is a master — `XIAllMasterDevices(1)` selects with that + // wildcard id, so a property event on a master reaches its exact + // selector AND `dev == 1` selectors. A slave property event reaches + // its exact selector AND `dev == 0` selectors. xinput's + // `watch-props` uses `dev == 0`; without the wildcard match it + // sees nothing. + // XI device-id wildcards from `XI2.h`: XIAllDevices=0 selects any + // device; XIAllMasterDevices=1 selects any master. Physical touchpad + // facets use registry-assigned IDs; the reserved XTEST ID is only + // used for virtual-device properties. Slaves never match the + // master-only wildcard. + const XI_ALL_DEVICES: u16 = 0; + let xi2_targets: Vec = state + .clients + .iter() + .filter_map(|(id, client)| { + let selected = client.xi2_masks.iter().any(|(&(_, dev), &mask)| { + let device_matches = dev == deviceid || dev == XI_ALL_DEVICES; + device_matches && (mask & u64::from(XI2_PROPERTY_EVENT_MASK)) != 0 + }); + selected.then_some(ClientId(*id)) + }) + .collect(); + let time = state.timestamp_now(); + let mut dropped = Vec::new(); + if !xi2_targets.is_empty() { + dropped.extend(fanout_event_to_clients( + state, + &xi2_targets, + |buf, seq, order| { + let event = crate::xinput::encode_xi2_property_event( + order, + seq, + XI2_MAJOR_OPCODE, + deviceid, + time, + property, + what, + ); + buf.extend_from_slice(&event); + }, + )); + } + // XI1 `DevicePropertyNotify` fan-out, keyed off + // `ClientState::xi1_event_classes`. A client selects via + // `SelectExtensionEvent` (minor 6) and the recorded class is + // `(deviceid << 8) | (XI_FIRST_EVENT + 16)` — a property delivery + // matches only when the client has that exact class. The XI2 and + // XI1 emits are independent: a client may have selected via either + // (or both) paths and receives one copy per path. + // + // XI1 deviceids are CARD8 on the wire, so the high byte of + // `xi1_class` is always zero — `as u8` truncations in the + // SelectExtensionEvent handler (minor 6) rely on this invariant. + debug_assert!(deviceid <= 0xFF, "XI1 deviceid must fit in CARD8"); + let xi1_class = + (u32::from(deviceid) << 8) | u32::from(XI_FIRST_EVENT + XI_DEVICE_PROPERTY_NOTIFY_OFFSET); + let xi1_targets: Vec = state + .clients + .iter() + .filter_map(|(id, client)| { + client + .xi1_event_classes + .contains(&xi1_class) + .then_some(ClientId(*id)) + }) + .collect(); + if !xi1_targets.is_empty() { + let deleted = matches!(what, crate::xinput::PropWhat::Deleted); + dropped.extend(fanout_event_to_clients( + state, + &xi1_targets, + |buf, seq, order| { + let event = crate::xinput::encode_xi1_device_property_notify( + order, + seq, + XI_FIRST_EVENT, + deviceid, + time, + property, + deleted, + ); + buf.extend_from_slice(&event); + }, + )); + } + dropped +} + +pub(super) fn handle_intern_atom( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let name = x11::intern_atom_name(body); + let atom = state.atoms.intern(&name, header.data != 0); + debug!( + "client {} #{} InternAtom {:?} -> {}", + client_id.0, sequence.0, name, atom.0 + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_intern_atom_reply(&mut buf, byte_order, sequence, atom)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_list_properties( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + debug!("client {} #{} ListProperties", client_id.0, sequence.0); + let access_request = RequestOpcodes::for_request(header); + let mut atoms = Vec::new(); + if let Some(bytes) = body.get(..4) { + let window = ResourceId(u32::from_le_bytes( + bytes.try_into().expect("four-byte window id"), + )); + if state.resources.window(window).is_some() { + if let Err((code, value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::LIST_PROP, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, value, 21); + } + atoms = state + .resources + .window(window) + .map(|w| w.properties.keys().copied().collect()) + .unwrap_or_default(); + atoms.retain(|&property| { + matches!( + state.check_property( + client_id, + window, + property, + AccessMode::GET_ATTR, + Some(access_request), + ), + Decision::Allow + ) + }); + } + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32 + atoms.len() * 4); + x11::write_list_properties_reply(&mut buf, byte_order, sequence, &atoms)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_get_atom_name( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + let atom = x11::request_atom(body); + debug!( + "client {} #{} GetAtomName {}", + client_id.0, sequence.0, atom.0 + ); + let local = state.atoms.name(atom).map(str::to_owned); + let name = match local { + Some(n) => Some(n), + None => backend.get_atom_name(origin, atom.0).ok().flatten(), + }; + match name { + Some(name) => { + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32 + name.len()); + x11::write_get_atom_name_reply(&mut buf, byte_order, sequence, &name)?; + Ok(write_to_client(client, client_id, &buf)) + } + None => emit_x11_error(state, client_id, sequence, x11::error::BAD_ATOM, atom.0, 17), + } +} + +pub(super) fn handle_change_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let Some(req) = x11::change_property_request(header.data, body) else { + // Diagnostic: dump the request header + body shape that we + // rejected as malformed, so we can see what the client sent. + let preview_len = body.len().min(64); + let body_preview = &body[..preview_len]; + debug!( + "ChangeProperty BadLength (parse-fail): client={} seq={} \ + header.data={:#x} body.len={} length_units={} preview={:02x?}", + client_id.0, + sequence.0, + header.data, + body.len(), + header.length_units, + body_preview, + ); + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 18); + }; + let Some(mode) = properties::ChangeMode::from_protocol(req.mode) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.mode), + 18, + ); + }; + let Some(format) = properties::PropertyFormat::from_protocol(req.format) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.format), + 18, + ); + }; + let expected_bytes = (req.length as usize).checked_mul(format.bytes()); + if expected_bytes != Some(req.data.len()) { + debug!( + "ChangeProperty BadLength (length mismatch): client={} seq={} \ + req.length={} format={} expected={:?} got={}", + client_id.0, + sequence.0, + req.length, + req.format, + expected_bytes, + req.data.len(), + ); + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 18); + } + if state.resources.window(req.window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window.0, + 18, + ); + } + let access_request = RequestOpcodes::for_request(header); + if let Err((code, value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: req.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_PROP, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, value, 18); + } + if !state.atoms.exists(req.property) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.property.0, + 18, + ); + } + if !state.atoms.exists(req.r#type) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.r#type.0, + 18, + ); + } + let existing = state + .resources + .window_property(req.window, req.property) + .cloned(); + let property_mode = match (mode, existing.is_some()) { + (_, false) => AccessMode::CREATE | AccessMode::WRITE, + (properties::ChangeMode::Replace, true) => AccessMode::WRITE, + (properties::ChangeMode::Append | properties::ChangeMode::Prepend, true) => { + AccessMode::BLEND + } + }; + if let Decision::Deny(error) = state.check_property( + client_id, + req.window, + req.property, + property_mode, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 18); + } + // Diagnostic: log WM_CLASS (and _NET_WM_PID) so we can map + // yserver client_id → user-space process when debugging + // missing-click / dead-applet issues. WM_CLASS is two + // null-terminated strings (instance, class); _NET_WM_PID is a + // CARD32. Both are set once near client init, so noise is + // bounded. + if let Some(prop_name) = state.atoms.name(req.property) { + if prop_name == "WM_CLASS" && req.format == 8 { + let s = String::from_utf8_lossy(&req.data).replace('\0', " | "); + let trimmed = s.trim_end_matches(" | ").to_string(); + log::debug!( + "client {} WM_CLASS on 0x{:x}: {}", + client_id.0, + req.window.0, + trimmed, + ); + // Mirror into the side-table so the MIT-SHM PutImage perf + // log (and any future client-attributed diagnostics) can + // resolve drawable owner → recognisable process name + // without re-grepping the log. + state.client_wm_class.entry(client_id.0).or_insert(trimmed); + } else if prop_name == "_NET_WM_PID" && req.format == 32 && req.data.len() >= 4 { + let pid = u32::from_le_bytes([req.data[0], req.data[1], req.data[2], req.data[3]]); + log::debug!( + "client {} _NET_WM_PID on 0x{:x}: {}", + client_id.0, + req.window.0, + pid, + ); + } else if prop_name == "_NET_FRAME_EXTENTS" && req.format == 32 && req.data.len() >= 16 { + // 4× CARDINAL: left, right, top, bottom (frame inset + // around the client window). GTK reads this to position + // popups; if it's corrupted we'd see the popup-placement + // bug for reparented application windows. + let l = u32::from_le_bytes([req.data[0], req.data[1], req.data[2], req.data[3]]); + let r = u32::from_le_bytes([req.data[4], req.data[5], req.data[6], req.data[7]]); + let t = u32::from_le_bytes([req.data[8], req.data[9], req.data[10], req.data[11]]); + let b = u32::from_le_bytes([req.data[12], req.data[13], req.data[14], req.data[15]]); + log::info!( + "client {} _NET_FRAME_EXTENTS on 0x{:x}: left={} right={} top={} bottom={}", + client_id.0, + req.window.0, + l, + r, + t, + b, + ); + } else if prop_name == "_NET_WORKAREA" && req.format == 32 && req.data.len() >= 16 { + // 4× CARDINAL per desktop: x, y, width, height. Log + // the first desktop's quad; subsequent desktops are + // rare and the first is the one popup placement uses. + let x = u32::from_le_bytes([req.data[0], req.data[1], req.data[2], req.data[3]]); + let y = u32::from_le_bytes([req.data[4], req.data[5], req.data[6], req.data[7]]); + let w = u32::from_le_bytes([req.data[8], req.data[9], req.data[10], req.data[11]]); + let h = u32::from_le_bytes([req.data[12], req.data[13], req.data[14], req.data[15]]); + log::info!( + "client {} _NET_WORKAREA on 0x{:x}: x={} y={} w={} h={} (desktop 0)", + client_id.0, + req.window.0, + x, + y, + w, + h, + ); + } + } + let new_value = + match properties::apply_change(existing.as_ref(), mode, req.r#type, format, &req.data) { + Ok(v) => v, + Err(properties::ChangePropertyError::BadMatch) => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.window.0, + 18, + ); + } + Err(properties::ChangePropertyError::BadAlloc) => { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 18); + } + Err(properties::ChangePropertyError::BadValue) => { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 18); + } + }; + store_window_property(state, backend, req.window, req.property, new_value); + debug!("client {} #{} ChangeProperty", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// ChangeProperty after validation: store, the backend hook, then +/// PropertyNotify. +fn store_window_property( + state: &mut ServerState, + backend: &mut dyn Backend, + window: ResourceId, + property: AtomId, + value: properties::PropertyValue, +) { + state.resources.set_window_property(window, property, value); + backend.on_window_property_changed(state, window_host_xid(state, window), property); + crate::rootless::note_property_changed(state, window, property); + if window == crate::resources::ROOT_WINDOW + && state.atoms.name(property) == Some("_XKB_RULES_NAMES") + && let Some(value) = state + .resources + .window_property(window, property) + .map(|p| p.data.clone()) + { + crate::core_loop::xkb_layout::apply_rules_names_change(state, backend, &value); + } + emit_property_notify(state, window, property, false); +} + +/// PropertyNotify of `property` on `window`, `deleted` or a new value, to +/// the clients that select PropertyChange there, and to a rootless host's +/// selection bridge when the window is one it watches. +fn emit_property_notify( + state: &mut ServerState, + window: ResourceId, + property: AtomId, + deleted: bool, +) { + let timestamp = state.timestamp_now(); + let _dropped = emit_window_event_to_state( + state, + window, + 0x0040_0000, // PropertyChangeMask + |buf, seq, order| { + x11::encode_property_notify_event( + buf, seq, order, window, property, timestamp, deleted, + ); + }, + ); + crate::rootless::selection::note_property_notify(state, window, property, timestamp, deleted); +} + +/// ChangeProperty (Replace) as the server; `data` is in server (LE) order. +pub(crate) fn change_property_as_server( + state: &mut ServerState, + backend: &mut dyn Backend, + window: ResourceId, + property: AtomId, + r#type: AtomId, + format: properties::PropertyFormat, + data: Vec, +) { + store_window_property( + state, + backend, + window, + property, + properties::PropertyValue { + r#type, + format, + data, + }, + ); +} + +pub(super) fn handle_get_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::ClientByteOrder; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let Some(req) = x11::get_property_request(header.data, body) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 20); + }; + if state.resources.window(req.window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window.0, + 20, + ); + } + let access_request = RequestOpcodes::for_request(header); + let window_mode = if req.delete { + AccessMode::GET_PROP | AccessMode::SET_PROP + } else { + AccessMode::GET_PROP + }; + if let Err((code, value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: req.window, + kind: ResourceKind::Window, + creation: None, + }, + window_mode, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, value, 20); + } + if !state.atoms.exists(req.property) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.property.0, + 20, + ); + } + if req.r#type.0 != 0 && !state.atoms.exists(req.r#type) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.r#type.0, + 20, + ); + } + let existing = state + .resources + .window_property(req.window, req.property) + .cloned(); + if existing.is_some() { + let property_mode = if req.delete { + AccessMode::READ | AccessMode::DESTROY + } else { + AccessMode::READ + }; + if let Decision::Deny(error) = state.check_property( + client_id, + req.window, + req.property, + property_mode, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 20); + } + } + // Build the reply against an immutable borrow of state.resources, + // copy the bytes into an owned buffer, then drop the borrow before + // we touch state again for the optional delete + fanout. + let (reply_bytes, type_matched, slice_bytes_after, existing_some) = { + let slice = match properties::slice_for_get( + existing.as_ref(), + req.r#type, + req.long_offset, + req.long_length, + ) { + Ok(s) => s, + Err(properties::ChangePropertyError::BadValue) => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.long_offset, + 20, + ); + } + Err(_) => unreachable!("slice_for_get only returns BadValue on error"), + }; + let value_len_units = if slice.format == 0 { + 0 + } else { + slice.value.len() as u32 / u32::from(slice.format / 8) + }; + let mut buf: Vec = Vec::with_capacity(32 + slice.value.len()); + x11::write_get_property_reply( + &mut buf, + byte_order, + sequence, + x11::GetPropertyReply { + format: slice.format, + r#type: slice.r#type, + bytes_after: slice.bytes_after, + value_len: value_len_units, + value: slice.value, + }, + )?; + let type_matched = existing + .as_ref() + .is_some_and(|p| req.r#type.0 == 0 || req.r#type == p.r#type); + (buf, type_matched, slice.bytes_after, existing.is_some()) + }; + // Send reply bytes through client_io::write_or_buffer. + let outcome = match state.clients.get_mut(&client_id.0) { + Some(client) => write_to_client(client, client_id, &reply_bytes), + None => RequestOutcome::Handled, + }; + if matches!(outcome, RequestOutcome::Disconnect(_)) { + return Ok(outcome); + } + // Optional delete + PropertyNotify fanout (state=true) when + // delete=1 fires per spec. + if req.delete && type_matched && slice_bytes_after == 0 && existing_some { + let _ = state + .resources + .delete_window_property(req.window, req.property); + backend.on_window_property_changed(state, window_host_xid(state, req.window), req.property); + crate::rootless::note_property_changed(state, req.window, req.property); + emit_property_notify(state, req.window, req.property, true); + } + debug!("client {} #{} GetProperty", client_id.0, sequence.0); + Ok(outcome) +} + +pub(super) fn handle_delete_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let Some(req) = x11::delete_property_request(body) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, 19); + }; + if state.resources.window(req.window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window.0, + 19, + ); + } + let access_request = RequestOpcodes::for_request(header); + if let Err((code, value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: req.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_PROP, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, value, 19); + } + if state + .resources + .window_property(req.window, req.property) + .is_some() + && let Decision::Deny(error) = state.check_property( + client_id, + req.window, + req.property, + AccessMode::DESTROY, + Some(access_request), + ) + { + return emit_x11_error(state, client_id, sequence, error.code, error.value, 19); + } + delete_window_property(state, backend, req.window, req.property); + debug!("client {} #{} DeleteProperty", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// DeleteProperty after validation, the request's or the server's own: a +/// property that was there is removed, and PropertyNotify says so. +pub(crate) fn delete_window_property( + state: &mut ServerState, + backend: &mut dyn Backend, + window: ResourceId, + property: AtomId, +) { + if state + .resources + .delete_window_property(window, property) + .is_none() + { + return; + } + backend.on_window_property_changed(state, window_host_xid(state, window), property); + crate::rootless::note_property_changed(state, window, property); + emit_property_notify(state, window, property, true); +} + +/// `RotateProperties`, as Xorg's `ProcRotateProperties` +/// (`dix/property.c:133-200`): property `(i + delta) mod n` takes property +/// i's type, format and data, then one `PropertyNotify` NewValue per listed +/// property in list order. A rotation by a multiple of n changes nothing and +/// sends no events. Errors are checked atom by atom in list order: BadAtom +/// for an invalid atom, BadMatch for a later duplicate, BadMatch for a +/// property the window does not have. +pub(super) fn handle_rotate_properties( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + const OPCODE: u8 = 114; + let Some(req) = x11::rotate_properties_request(body) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + OPCODE, + ); + }; + if state.resources.window(req.window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window.0, + OPCODE, + ); + } + let access_request = RequestOpcodes::for_request(header); + if let Err((code, value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: req.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_PROP, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, value, OPCODE); + } + let atoms = &req.properties; + let mut saved = Vec::with_capacity(atoms.len()); + for (i, &atom) in atoms.iter().enumerate() { + if !state.atoms.exists(atom) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + atom.0, + OPCODE, + ); + } + if atoms[i + 1..].contains(&atom) { + // Xorg reports whatever errorValue the previous lookup left: + // the window for the first atom, else the previous atom. + let value = if i == 0 { req.window.0 } else { atoms[i - 1].0 }; + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + value, + OPCODE, + ); + } + let Some(value) = state.resources.window_property(req.window, atom) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + atom.0, + OPCODE, + ); + }; + if let Decision::Deny(error) = state.check_property( + client_id, + req.window, + atom, + AccessMode::READ | AccessMode::WRITE, + Some(access_request), + ) { + return emit_x11_error(state, client_id, sequence, error.code, error.value, OPCODE); + } + saved.push(value.clone()); + } + let n = atoms.len(); + let delta = if n == 0 { + 0 + } else { + usize::try_from(i32::from(req.delta).rem_euclid(i32::try_from(n).unwrap_or(i32::MAX))) + .unwrap_or(0) + }; + if delta != 0 { + for (i, value) in saved.into_iter().enumerate() { + state + .resources + .set_window_property(req.window, atoms[(i + delta) % n], value); + } + let host = window_host_xid(state, req.window); + let window = req.window; + for &property in atoms { + backend.on_window_property_changed(state, host, property); + crate::rootless::note_property_changed(state, window, property); + emit_property_notify(state, window, property, false); + } + } + debug!( + "client {} #{} RotateProperties n={n} delta={}", + client_id.0, sequence.0, req.delta + ); + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext.rs new file mode 100644 index 000000000..7d24a1f55 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext.rs @@ -0,0 +1,417 @@ +//! RANDR and Xinerama requests: `handle_randr_request` hands each RANDR +//! minor to its own `handle_randr_*` fn. This file holds the CRTC-config +//! continuation types, the helpers several groups share and the +//! CreateMode/CreateLease and FreeLease stubs; the rest lives in: +//! +//! - `screen`: version, SelectInput, screen info, size and resources (0, +//! 4–8, 25), RANDR 1.0 SetScreenConfig (2). +//! - `output`: output info and primary (9, 30, 31), output properties +//! (10–15). +//! - `crtc`: CRTC info and config (20, 21), gamma (22–24), transforms +//! (26, 27), panning (28, 29), the asynchronous CRTC-config +//! start/complete/reply. +//! - `provider`: providers (32–35), provider properties (36–41). +//! - `monitor`: monitors (42–44). +//! - `xinerama`: the Xinerama extension. + +mod crtc; +mod monitor; +mod output; +mod provider; +mod screen; +mod xinerama; + +use crate::{ + backend::{Backend, CrtcConfigToken}, + core_loop::process_request::{ + RANDR_REQUEST_COUNT, RequestOutcome, emit_x11_error_with_minor, + randr_ext::{ + monitor::{ + handle_randr_delete_monitor, handle_randr_get_monitors, handle_randr_set_monitor, + }, + output::{ + handle_randr_change_output_property, handle_randr_configure_output_property, + handle_randr_delete_output_property, handle_randr_get_output_info, + handle_randr_get_output_primary, handle_randr_get_output_property, + handle_randr_list_output_properties, handle_randr_query_output_property, + handle_randr_set_output_primary, + }, + provider::{ + handle_randr_get_provider_info, handle_randr_get_providers, + handle_randr_provider_property, handle_randr_set_provider_offload_sink, + handle_randr_set_provider_output_source, + }, + screen::{ + handle_randr_get_screen_info, handle_randr_get_screen_resources, + handle_randr_get_screen_resources_current, handle_randr_get_screen_size_range, + handle_randr_query_version, handle_randr_select_input, + handle_randr_set_screen_size, set_screen_config, + }, + }, + }, + server::ServerState, +}; +pub(crate) use crtc::*; +use log::debug; +use std::io; +pub(super) use xinerama::*; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber, randr as x11randr}, +}; + +/// Continuation data needed to finish an asynchronous `RRSetCrtcConfig` +/// without redispatching the original request. +#[derive(Debug, Clone)] +pub struct PendingCrtcConfig { + pub token: CrtcConfigToken, + pub completion: CrtcConfigCompletion, +} + +/// Protocol continuation shared by synchronous and asynchronous CRTC apply +/// paths. It contains no backend token, so immediate completion never needs a +/// sentinel token value. +#[derive(Debug, Clone)] +pub struct CrtcConfigCompletion { + pub output_id: u32, + pub set_time: u32, + pub output_bbox_before: Option<(u16, u16)>, + pub byte_order: yserver_protocol::x11::ClientByteOrder, + /// The pending transform this enable applies, snapshotted at request + /// time, when it differs from the current one (`RRCrtcPendingTransform`, + /// rrcrtc.c:765). + pub apply_transform: Option>, + /// The rotation this enable sets, when it differs from the CRTC's + /// (`RRCrtcSet`'s `rotation != crtc->rotation`, rrcrtc.c:749). A + /// disable keeps the rotation, as `xf86RandR12CrtcSet` does. + pub apply_rotation: Option, + /// Which request is waiting for the reply. + pub reply: CrtcConfigReply, +} + +/// The request a CRTC configuration answers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CrtcConfigReply { + /// `RRSetCrtcConfig`. + CrtcConfig, + /// RANDR 1.0 `RRSetScreenConfig`: its own reply, and `lastSetTime` + /// moves on every success (rrscreen.c:1099-1101). + ScreenConfig, +} + +/// The protocol-visible monitor list (`RRMonitorMakeList`), shared by RANDR +/// `GetMonitors` and XINERAMA so their counts/order cannot diverge. +pub(super) fn active_monitors(state: &ServerState, get_active: bool) -> Vec { + state + .randr + .monitors(&state.randr_client_monitors, get_active) +} + +/// `RRSendConfigNotify` (rrscreen.c): a core ConfigureNotify on the root +/// carrying its current geometry — all `SetMonitor`/`DeleteMonitor` send. +/// No RANDR event: the monitor list has none of its own. +fn send_root_config_notify(state: &mut ServerState) { + let Some(root) = state.resources.window(crate::resources::ROOT_WINDOW) else { + return; + }; + let geometry = x11::Geometry { + root: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: root.width, + height: root.height, + border_width: root.border_width, + depth: root.depth, + }; + let override_redirect = root.override_redirect; + let _dropped = crate::core_loop::fanout::emit_window_event_to_state( + state, + crate::resources::ROOT_WINDOW, + 0x0002_0000, // StructureNotifyMask + |buf, seq, order| { + x11::encode_configure_notify_event( + buf, + seq, + order, + crate::resources::ROOT_WINDOW, + crate::resources::ROOT_WINDOW, + None, + geometry, + override_redirect, + ); + }, + ); +} + +/// Record an unsupported RANDR minor and report whether this is the first +/// occurrence for this server instance. +pub(super) fn mark_randr_unsupported_warned(state: &mut ServerState, minor: u8) -> bool { + let Some(bit) = 1u64.checked_shl(u32::from(minor)) else { + return true; + }; + let first = state.randr_unsupported_warned_mask & bit == 0; + state.randr_unsupported_warned_mask |= bit; + first +} + +fn warn_randr_unsupported_once( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + minor: u8, + request_name: &str, + action: &str, +) { + if mark_randr_unsupported_warned(state, minor) { + log::warn!( + "client {} #{} RANDR::{} is unsupported; {}", + client_id.0, + sequence.0, + request_name, + action, + ); + } else { + debug!( + "client {} #{} RANDR::{} remains unsupported; {}", + client_id.0, sequence.0, request_name, action, + ); + } +} + +const RANDR_MAJOR_OPCODE: u8 = 128; + +fn request_xid(body: &[u8]) -> u32 { + body.get(0..4) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) + .unwrap_or(0) +} + +pub(super) fn handle_randr_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + match minor { + x11randr::RR_QUERY_VERSION => { + handle_randr_query_version(state, client_id, sequence, body, byte_order) + } + x11randr::RR_GET_SCREEN_SIZE_RANGE => { + handle_randr_get_screen_size_range(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_GET_SCREEN_RESOURCES => handle_randr_get_screen_resources( + state, backend, client_id, sequence, header, body, byte_order, minor, + ), + x11randr::RR_GET_SCREEN_RESOURCES_CURRENT => handle_randr_get_screen_resources_current( + state, client_id, sequence, body, byte_order, minor, + ), + x11randr::RR_GET_OUTPUT_INFO => { + handle_randr_get_output_info(state, client_id, sequence, header, body, byte_order) + } + x11randr::RR_GET_CRTC_INFO => { + handle_randr_get_crtc_info(state, client_id, sequence, header, body, byte_order) + } + x11randr::RR_SET_CRTC_TRANSFORM => { + handle_randr_set_crtc_transform(state, client_id, sequence, body, minor) + } + x11randr::RR_GET_CRTC_TRANSFORM => { + handle_randr_get_crtc_transform(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_LIST_OUTPUT_PROPERTIES => handle_randr_list_output_properties( + state, backend, client_id, sequence, body, byte_order, minor, + ), + x11randr::RR_QUERY_OUTPUT_PROPERTY => handle_randr_query_output_property( + state, backend, client_id, sequence, body, byte_order, minor, + ), + x11randr::RR_CONFIGURE_OUTPUT_PROPERTY => { + handle_randr_configure_output_property(state, client_id, sequence, body, minor) + } + x11randr::RR_CHANGE_OUTPUT_PROPERTY => { + handle_randr_change_output_property(state, client_id, sequence, body, minor) + } + x11randr::RR_DELETE_OUTPUT_PROPERTY => { + handle_randr_delete_output_property(state, client_id, sequence, body, minor) + } + x11randr::RR_GET_PANNING => { + handle_randr_get_panning(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_SET_PANNING => { + handle_randr_set_panning(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_SET_OUTPUT_PRIMARY => { + handle_randr_set_output_primary(state, client_id, sequence, body, minor) + } + x11randr::RR_GET_OUTPUT_PRIMARY => { + handle_randr_get_output_primary(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_GET_PROVIDERS => { + handle_randr_get_providers(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_GET_PROVIDER_INFO => { + handle_randr_get_provider_info(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK => { + handle_randr_set_provider_offload_sink(state, client_id, sequence, body, minor) + } + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE => handle_randr_set_provider_output_source( + state, backend, client_id, sequence, body, minor, + ), + x11randr::RR_GET_MONITORS => { + handle_randr_get_monitors(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_SET_MONITOR => { + handle_randr_set_monitor(state, client_id, sequence, body, minor) + } + x11randr::RR_DELETE_MONITOR => { + handle_randr_delete_monitor(state, client_id, sequence, body, minor) + } + x11randr::RR_GET_CRTC_GAMMA_SIZE => handle_randr_get_crtc_gamma_size( + state, backend, client_id, sequence, header, body, byte_order, + ), + x11randr::RR_GET_CRTC_GAMMA => handle_randr_get_crtc_gamma( + state, backend, client_id, sequence, header, body, byte_order, + ), + x11randr::RR_SET_CRTC_GAMMA => { + handle_randr_set_crtc_gamma(state, backend, client_id, sequence, header, body) + } + x11randr::RR_GET_OUTPUT_PROPERTY => handle_randr_get_output_property( + state, backend, client_id, sequence, body, byte_order, minor, + ), + x11randr::RR_SELECT_INPUT => { + handle_randr_select_input(state, client_id, sequence, body, minor) + } + x11randr::RR_GET_SCREEN_INFO => { + handle_randr_get_screen_info(state, client_id, sequence, body, byte_order, minor) + } + x11randr::RR_SET_SCREEN_SIZE => { + handle_randr_set_screen_size(state, backend, client_id, sequence, header, body, minor) + } + x11randr::RR_SET_SCREEN_CONFIG => { + set_screen_config(state, backend, client_id, sequence, byte_order, body) + } + x11randr::RR_SET_CRTC_CONFIG => handle_randr_set_crtc_config( + state, backend, client_id, sequence, header, body, byte_order, + ), + 16 | 45 => handle_randr_create_mode_or_lease(state, client_id, sequence, minor), + x11randr::RR_LIST_PROVIDER_PROPERTIES + | x11randr::RR_QUERY_PROVIDER_PROPERTY + | x11randr::RR_CONFIGURE_PROVIDER_PROPERTY + | x11randr::RR_CHANGE_PROVIDER_PROPERTY + | x11randr::RR_DELETE_PROVIDER_PROPERTY + | x11randr::RR_GET_PROVIDER_PROPERTY => { + handle_randr_provider_property(state, client_id, sequence, body, minor) + } + 46 => handle_randr_free_lease(state, client_id, sequence, body, minor), + // 1 RROldGetScreenInfo and 3 RROldScreenChangeSelectInput are literal + // NULL entries in Xorg's ProcRandrVector (randr/rrdispatch.c), and + // ProcRRDispatch rejects a NULL slot exactly like an out-of-range + // minor: `if (stuff->data >= RRNumberRequests || + // !ProcRandrVector[stuff->data]) return BadRequest;` (randr/randr.c). + // They are request numbers that were never assigned, not requests we + // have yet to write. + 1 | 3 => emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(minor), + header.opcode, + ), + other if other >= RANDR_REQUEST_COUNT => emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ), + other => { + let request_name = match other { + 17 => "DestroyMode", + 18 => "AddOutputMode", + 19 => "DeleteOutputMode", + _ => "known request", + }; + warn_randr_unsupported_once( + state, + client_id, + sequence, + other, + request_name, + "accepting void request as a compatibility no-op", + ); + Ok(RequestOutcome::Handled) + } + } +} + +#[allow(clippy::needless_return)] +fn handle_randr_create_mode_or_lease( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + minor: u8, +) -> io::Result { + // TODO(unimplemented): RRCreateMode (16) / RRCreateLease (45) + // are NOT actually implemented. This + // BadImplementation is a STOPGAP to stop the client hanging on a + // reply that never comes — it is NOT protocol-correct: Xorg + // implements both and returns real data. Replace with real + // implementations (custom modes / DRM lease). + // + // Void unimplemented RANDR requests remain wire-success no-ops + // via `other` below — Xorg implements those as success, so + // erroring them would be a new Xorg-divergence. Their first use + // is nevertheless warned so the unsupported behavior is visible. + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_IMPLEMENTATION, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); +} + +#[allow(clippy::needless_return)] +fn handle_randr_free_lease( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // CreateLease is not implemented and cannot create a live lease, + // so FreeLease always follows Xorg's failed lease lookup. + // + // That lookup yields plain `BadValue`, NOT `BadRRLease`. Xorg + // registers RRLeaseType with `CreateNewResourceType` (rrlease.c) + // and never calls `SetResourceTypeErrorValue` for it, so the type + // keeps dix's default `errorValue = BadValue` (dix/resource.c); + // `BadRRLease` is defined in randr.h but referenced nowhere in the + // Xorg tree. Measured on real Xorg with `tools/randr-probe`: + // RRFreeLease(bogus) -> code=2 (BadValue), not 151. + let lease = body + .get(0..4) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) + .unwrap_or(0); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + lease, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext/crtc.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext/crtc.rs new file mode 100644 index 000000000..6dcb8c175 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext/crtc.rs @@ -0,0 +1,833 @@ +use crate::{ + backend::{Backend, CrtcConfigApply, ModeSpec}, + core_loop::process_request::{ + RANDR_BAD_CRTC, RequestOutcome, emit_x11_error_with_minor, + randr_ext::{ + CrtcConfigCompletion, CrtcConfigReply, PendingCrtcConfig, RANDR_MAJOR_OPCODE, + request_xid, screen::x11randr_encode_set_screen_config, warn_randr_unsupported_once, + }, + write_to_client, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber, randr as x11randr}, +}; + +fn crtc_is_leased(_state: &ServerState, _crtc: u32) -> bool { + false +} + +fn crtc_exists(state: &ServerState, crtc: u32) -> bool { + state + .randr + .outputs + .iter() + .any(|output| output.crtc_id == crtc) +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_crtc_info( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let Some(req) = x11randr::parse_crtc_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(crtc_data) = state.randr.crtc_info(req.crtc, req.config_timestamp) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + req.crtc, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + let buf = x11randr::encode_get_crtc_info_reply( + byte_order, + sequence, + &x11randr::CrtcInfoReply { + timestamp: crtc_data.timestamp, + x: crtc_data.x, + y: crtc_data.y, + width: crtc_data.width, + height: crtc_data.height, + mode: crtc_data.mode_id, + rotation: state.randr.crtc_rotation(req.crtc), + rotations: state.randr.limits.rotations, + outputs: &crtc_data.outputs, + possible: &crtc_data.possible_outputs, + }, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_crtc_transform( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // ProcRRSetCrtcTransform (rrcrtc.c:1755-1785) + RRCrtcTransformSet + // (rrcrtc.c:1091-1128), then the spec's D2 contract. + let error = |state: &mut ServerState, code: u8, value: u32| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ) + }; + let Some(req) = x11randr::parse_set_crtc_transform_request(body) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if !crtc_exists(state, req.crtc) { + return error(state, RANDR_BAD_CRTC, req.crtc); + } + if crtc_is_leased(state, req.crtc) { + return error(state, x11::error::BAD_ACCESS, 0); + } + if !crate::randr::CrtcTransform::invertible(&req.transform) { + return error(state, x11::error::BAD_MATCH, 0); + } + let Some(spec) = req.filter else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + // `!crtc->transforms` (rrcrtc.c:1088). + if !state.randr.limits.transforms { + return error(state, x11::error::BAD_VALUE, 0); + } + let filter = if spec.name.is_empty() { + if !spec.params.is_empty() { + return error(state, x11::error::BAD_MATCH, 0); + } + None + } else { + let Some(filter) = crate::randr::Filter::from_name(&spec.name) else { + return error(state, x11::error::BAD_NAME, 0); + }; + if !filter.params_valid(&spec.params) { + return error(state, x11::error::BAD_MATCH, 0); + } + Some(filter) + }; + let Some(transform) = crate::randr::CrtcTransform::new(req.transform, filter, spec.params) + else { + return error(state, x11::error::BAD_MATCH, 0); + }; + // D2: pure scale, nearest/bilinear only; the rest is refused on + // purpose rather than rendered approximately. + if !(transform.is_identity() || transform.is_pure_scale()) + || filter == Some(crate::randr::Filter::Convolution) + { + return error(state, x11::error::BAD_MATCH, 0); + } + if let Some(output) = state + .randr + .outputs + .iter_mut() + .find(|o| o.crtc_id == req.crtc) + { + output.pending_transform = transform; + } + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_crtc_transform( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + // REQUEST_SIZE_MATCH(xRRGetCrtcTransformReq) before the lookup. + if body.len() != 4 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let crtc = request_xid(body); + if !crtc_exists(state, crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + crtc, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let Some(output) = state.randr.outputs.iter().find(|o| o.crtc_id == crtc) else { + return Ok(RequestOutcome::Handled); + }; + // `transform_filter_encode`: no filter, no name and no params. + fn part(t: &crate::randr::CrtcTransform) -> x11randr::CrtcTransformReplyPart<'_> { + x11randr::CrtcTransformReplyPart { + matrix: t.matrix, + filter_name: t.filter.map_or(&[][..], |f| f.canonical_name().as_bytes()), + params: if t.filter.is_some() { &t.params } else { &[] }, + } + } + let buf = x11randr::encode_get_crtc_transform_reply( + byte_order, + sequence, + state.randr.limits.transforms, + part(&output.pending_transform), + part(&output.current_transform), + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_panning( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let crtc = request_xid(body); + if !crtc_exists(state, crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + crtc, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let timestamp = state.randr.timestamp; + let buf = x11randr::encode_get_panning_reply(byte_order, sequence, timestamp); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_panning( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let Some(req) = x11randr::parse_set_panning_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + if !crtc_exists(state, req.crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + req.crtc, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let status = if req.is_disabled() { + x11randr::SET_CONFIG_SUCCESS + } else { + // A live panning viewport needs transformed/composited + // scanout. Report a RANDR configuration failure rather than + // claiming the requested geometry was installed. + warn_randr_unsupported_once( + state, + client_id, + sequence, + minor, + "SetPanning", + "returning SetConfigFailed for active panning", + ); + x11randr::SET_CONFIG_FAILED + }; + let buf = + x11randr::encode_set_panning_reply(byte_order, sequence, status, state.randr.timestamp); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_crtc_gamma_size( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let Some(req) = x11randr::parse_crtc_id_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + if !crtc_exists(state, req.crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + req.crtc, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + let buf = x11randr::encode_get_crtc_gamma_size_reply( + byte_order, + sequence, + backend.crtc_gamma_size(req.crtc), + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_crtc_gamma( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let Some(req) = x11randr::parse_crtc_id_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + if !crtc_exists(state, req.crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + req.crtc, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + let (red, green, blue) = backend.get_crtc_gamma(req.crtc); + let buf = x11randr::encode_get_crtc_gamma_reply(byte_order, sequence, &red, &green, &blue); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_crtc_gamma( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let Some(crtc_bytes) = body.get(0..4) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + let crtc = u32::from_le_bytes(crtc_bytes.try_into().unwrap()); + if !crtc_exists(state, crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_CRTC, + crtc, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + if crtc_is_leased(state, crtc) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + crtc, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + let Some(size_bytes) = body.get(4..6) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + let size = u16::from_le_bytes(size_bytes.try_into().unwrap()); + let expected_units = (3 * u32::from(size) + 1) >> 1; + let expected_bytes = 8usize.saturating_add(usize::from(size).saturating_mul(6)); + if header.length_units.saturating_sub(3) < expected_units || body.len() < expected_bytes { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + let gamma_size = backend.crtc_gamma_size(crtc); + if size != gamma_size { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + + let channel_bytes = usize::from(size) * 2; + let red: Vec = body[8..8 + channel_bytes] + .chunks_exact(2) + .map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap())) + .collect(); + let green_start = 8 + channel_bytes; + let green_end = green_start + channel_bytes; + let green: Vec = body[green_start..green_end] + .chunks_exact(2) + .map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap())) + .collect(); + let blue: Vec = body[green_end..green_end + channel_bytes] + .chunks_exact(2) + .map(|chunk| u16::from_le_bytes(chunk.try_into().unwrap())) + .collect(); + + if let Err(e) = backend.set_crtc_gamma(crtc, &red, &green, &blue) { + log::warn!("RRSetCrtcGamma apply failed for CRTC 0x{crtc:x}: {e}"); + } + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_crtc_config( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + // Body layout (post-header): + // crtc(4) timestamp(4) config_timestamp(4) x(2) y(2) + // mode(4) rotation(2) pad(2) outputs(4*N) + // config_timestamp is parsed but NOT validated — rrcrtc.c + // does not gate SetCrtcConfig on it (only the 1.0 + // SetScreenConfig uses InvalidConfigTime/InvalidTime). + let Some(crtc_bytes) = body.get(0..4) else { + return Ok(RequestOutcome::Handled); + }; + let crtc = u32::from_le_bytes(crtc_bytes.try_into().unwrap()); + let req_timestamp = body + .get(4..8) + .map(|b| u32::from_le_bytes(b.try_into().unwrap())) + .unwrap_or(0); + let x = body + .get(12..14) + .map(|b| i16::from_le_bytes(b.try_into().unwrap())) + .unwrap_or(0); + let y = body + .get(14..16) + .map(|b| i16::from_le_bytes(b.try_into().unwrap())) + .unwrap_or(0); + let mode = body + .get(16..20) + .map(|b| u32::from_le_bytes(b.try_into().unwrap())) + .unwrap_or(0); + let rotation = body + .get(20..22) + .map(|b| u16::from_le_bytes(b.try_into().unwrap())) + .unwrap_or(1); + let outputs: Vec = body + .get(24..) + .map(|tail| { + tail.chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap())) + .collect() + }) + .unwrap_or_default(); + + // (1) arity + output + mode resolution FIRST (Xorg rrcrtc.c order). + let resolved = match state.randr.validate_set_crtc_config(crtc, mode, &outputs) { + Err((code, error_value)) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + error_value, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + Ok(r) => r, + }; + // (2) rotation only when enabling. + if resolved.is_some() { + if !matches!(rotation & 0xf, 1 | 2 | 4 | 8) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(rotation), + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + if !state.randr.limits.rotations & rotation != 0 { + // `(~crtc->rotations) & rotation` (rrcrtc.c:1403). + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + u32::from(rotation), + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + // The screen bounds bind only a CRTC without transform support + // (rrcrtc.c:1420-1457); with it, a screen may crop a CRTC. + if let Some(m) = resolved + && !state.randr.limits.transforms + { + let (width, height) = if crate::randr::rotation_swaps_axes(rotation) { + (m.height, m.width) + } else { + (m.width, m.height) + }; + for (origin, size, screen) in [ + (x, width, state.randr.screen_width), + (y, height, state.randr.screen_height), + ] { + if i32::from(origin) + i32::from(size) > i32::from(screen) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + i32::from(origin).cast_unsigned(), + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + } + } + } + + // Resolve connector name from crtc_id (validated above → + // guaranteed to exist). + let output_row = state.randr.outputs.iter().find(|o| o.crtc_id == crtc); + let Some(output_row) = output_row else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + crtc, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + let output_id = output_row.output_id; + let connector = output_row.name.clone(); + // A disable keeps the current transform (xf86RandR12CrtcSet + // only installs one with a mode). + let apply_transform = (resolved.is_some() + && !output_row + .pending_transform + .equivalent(&output_row.current_transform)) + .then(|| Box::new(output_row.pending_transform.applied())); + let apply_rotation = + (resolved.is_some() && rotation != output_row.rotation).then_some(rotation); + // The combined matrix drives the footprint and the scale pass; a + // pixman overflow (Xorg's rescaled projective fallback) is not + // rendered. + if let Some(m) = resolved + && crate::randr::crtc_matrix( + rotation, + m.width, + m.height, + &output_row.pending_transform.applied(), + ) + .is_none() + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + u32::from(rotation), + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + let mode_spec = resolved.map(|m| ModeSpec { + width: m.width, + height: m.height, + vrefresh: m.vrefresh, + }); + // lastSetTime = client timestamp (0/CurrentTime ⇒ server now). + let set_time = if req_timestamp == 0 { + state.timestamp_now() + } else { + req_timestamp + }; + let output_bbox_before = crate::core_loop::run::enabled_output_bbox(state); + let completion = CrtcConfigCompletion { + output_id, + set_time, + output_bbox_before, + byte_order, + apply_transform, + apply_rotation, + reply: CrtcConfigReply::CrtcConfig, + }; + return start_crtc_config( + state, + backend, + client_id, + sequence, + &connector, + mode_spec, + (i32::from(x), i32::from(y)), + completion, + ); +} + +/// Hand one CRTC configuration to the backend and complete it now, or park +/// it until an asynchronous qualification finishes. +#[allow(clippy::too_many_arguments)] +pub(super) fn start_crtc_config( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + connector: &str, + mode_spec: Option, + (x, y): (i32, i32), + completion: CrtcConfigCompletion, +) -> io::Result { + match backend.begin_crtc_config(completion.output_id, connector, mode_spec, x, y) { + Ok(CrtcConfigApply::Applied(changed)) => { + complete_crtc_config(state, backend, client_id, sequence, completion, Ok(changed)) + } + Ok(CrtcConfigApply::Pending(token)) => { + Ok(RequestOutcome::PendingCrtcConfig(PendingCrtcConfig { + token, + completion, + })) + } + Err(e) => complete_crtc_config(state, backend, client_id, sequence, completion, Err(e)), + } +} + +/// Complete the protocol-visible half of `RRSetCrtcConfig` after either a +/// synchronous apply or an asynchronous backend result. Keeping this as one +/// continuation prevents the async path from redispatching validation or +/// accidentally diverging in notification/timestamp behavior. +pub(crate) fn complete_crtc_config( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + completion: CrtcConfigCompletion, + result: io::Result, +) -> io::Result { + let status = match result { + // A new transform is a change even with identical mode/x/y. + Ok(changed) + if changed + || completion.apply_transform.is_some() + || completion.apply_rotation.is_some() => + { + // Something actually changed. Single rebuild path: a CRTC set + // bumps lastSetTime (to the client timestamp) but NOT + // lastConfigTime. + backend.refresh_randr_state_set_time(state, completion.set_time); + if let Some(transform) = completion.apply_transform + && let Some(output) = state + .randr + .outputs + .iter_mut() + .find(|o| o.output_id == completion.output_id) + { + // RRCrtcNotify: RRTransformCopy of pending into current. + output.current_transform = *transform; + } + if let Some(rotation) = completion.apply_rotation + && let Some(output) = state + .randr + .outputs + .iter_mut() + .find(|o| o.output_id == completion.output_id) + { + output.rotation = rotation; + } + backend.randr_layout_changed(state); + let changed: Vec<(u32, u32, u32)> = state + .randr + .outputs + .iter() + .find(|o| o.output_id == completion.output_id) + .map(|o| (o.output_id, o.crtc_id, o.mode_id)) + .into_iter() + .collect(); + crate::core_loop::run::emit_randr_change_notifications(state, &changed); + crate::core_loop::run::emit_screen_resize_window_notifications_if_outputs_caught_up( + state, + completion.output_bbox_before, + ); + 0 + } + Ok(_) => { + // A no-op succeeds without a rebuild or change notification. + 0 + } + Err(e) => { + log::warn!("RRSetCrtcConfig apply failed: {e}"); + // RRSetConfigFailed=3 (a status reply, not a protocol error). + 3 + } + }; + if completion.reply == CrtcConfigReply::ScreenConfig { + if status == 0 { + state.randr.timestamp = completion.set_time; + } + let reply = + x11randr_encode_set_screen_config(state, completion.byte_order, sequence, status); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + let timestamp = state.randr.timestamp; + reply_set_crtc_config( + state, + client_id, + sequence, + completion.byte_order, + status, + timestamp, + ) +} + +/// Build and send the 32-byte `SetCrtcConfig` reply. +/// +/// Wire format: `status` (data byte) + length=0 + `new_timestamp`(4) + +/// pad(20). On success `new_timestamp` is the post-set `state.randr.timestamp`; +/// on failure it is the unmodified existing value (caller resolves which). +fn reply_set_crtc_config( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + byte_order: yserver_protocol::x11::ClientByteOrder, + status: u8, + new_timestamp: u32, +) -> io::Result { + let mut reply = x11::fixed_reply(byte_order, sequence, status, 0); + x11::write_u32(byte_order, &mut reply, new_timestamp); + reply.extend_from_slice(&[0u8; 20]); + debug_assert_eq!(reply.len(), 32); + debug!( + "client {} #{} RANDR::SetCrtcConfig -> status={} new_timestamp={}", + client_id.0, sequence.0, status, new_timestamp, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &reply)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext/monitor.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext/monitor.rs new file mode 100644 index 000000000..096a06dea --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext/monitor.rs @@ -0,0 +1,203 @@ +use crate::{ + core_loop::process_request::{ + RequestOutcome, emit_x11_error_with_minor, + randr_ext::{RANDR_MAJOR_OPCODE, active_monitors, request_xid, send_root_config_notify}, + write_to_client, + }, + server::ServerState, +}; +use std::io; +use yserver_protocol::{ + x11, + x11::{AtomId, ClientByteOrder, ClientId, ResourceId, SequenceNumber, randr as x11randr}, +}; + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_monitors( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // RRMonitorTimestamp: lastConfigTime, which Set/DeleteMonitor + // leave alone ("XXX should take client monitor changes into + // account", rrmonitor.c). + let t = state.randr.timestamp; + let get_active = body.get(4).is_some_and(|&b| b != 0); + struct MonitorRow { + name_atom: u32, + primary: bool, + automatic: bool, + x: i16, + y: i16, + width: u16, + height: u16, + width_mm: u32, + height_mm: u32, + outputs: Vec, + } + let monitors_list = active_monitors(state, get_active); + let rows: Vec = monitors_list + .into_iter() + .map(|monitor| MonitorRow { + name_atom: match monitor.name { + crate::randr::MonitorName::Atom(atom) => atom, + crate::randr::MonitorName::Output(name) => state.atoms.intern(&name, false).0, + }, + primary: monitor.primary, + automatic: monitor.automatic, + x: monitor.x, + y: monitor.y, + width: monitor.width, + height: monitor.height, + width_mm: monitor.width_mm, + height_mm: monitor.height_mm, + outputs: monitor.outputs, + }) + .collect(); + let monitors: Vec> = rows + .iter() + .map(|r| x11randr::MonitorInfo { + name: r.name_atom, + primary: r.primary, + automatic: r.automatic, + x: r.x, + y: r.y, + width: r.width, + height: r.height, + width_mm: r.width_mm, + height_mm: r.height_mm, + outputs: &r.outputs, + }) + .collect(); + let buf = x11randr::encode_get_monitors_reply(byte_order, sequence, t, &monitors); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_monitor( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // ProcRRSetMonitor + RRMonitorAdd as shipped in Xorg 21.1 + // (rrmonitor.c), measured by tools/vng-scenarios/xrandr-monitors.sh. + let error = |state: &mut ServerState, code: u8, value: u32| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ) + }; + let Some(req) = x11randr::parse_set_monitor_request(body) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if usize::from(req.noutput) != req.outputs.len() { + return error(state, x11::error::BAD_LENGTH, 0); + } + if state.resources.window(ResourceId(req.window)).is_none() { + return error(state, x11::error::BAD_WINDOW, req.window); + } + // !ValidAtom: Xorg sets no errorValue here, so the wire carries + // the window id the successful lookup just left in it. + if req.name == 0 || state.atoms.name(AtomId(req.name)).is_none() { + return error(state, x11::error::BAD_ATOM, req.window); + } + let name = state.atoms.name(AtomId(req.name)).unwrap_or_default(); + // 'name' must match neither an Output nor an existing Monitor. + // (xserver main replaces a same-named monitor instead, 146bb9b2c; + // 21.1 refuses it.) + if state.randr.outputs.iter().any(|output| output.name == name) + || state + .randr_client_monitors + .iter() + .any(|monitor| monitor.name == req.name) + { + return error(state, x11::error::BAD_VALUE, req.name); + } + if req.primary { + for monitor in &mut state.randr_client_monitors { + monitor.primary = false; + } + } + state + .randr_client_monitors + .push(crate::randr::ClientMonitor { + name: req.name, + primary: req.primary, + outputs: req.outputs, + x: req.x, + y: req.y, + width: req.width, + height: req.height, + width_mm: req.width_mm, + height_mm: req.height_mm, + }); + send_root_config_notify(state); + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_delete_monitor( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // ProcRRDeleteMonitor + RRMonitorDelete (rrmonitor.c). + let error = |state: &mut ServerState, code: u8, value: u32| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ) + }; + let Some((window, name)) = x11randr::parse_delete_monitor_request(body) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if state.resources.window(ResourceId(window)).is_none() { + return error(state, x11::error::BAD_WINDOW, window); + } + if name == 0 || state.atoms.name(AtomId(name)).is_none() { + return error(state, x11::error::BAD_ATOM, name); + } + let Some(index) = state + .randr_client_monitors + .iter() + .position(|monitor| monitor.name == name) + else { + return error(state, x11::error::BAD_VALUE, name); + }; + state.randr_client_monitors.remove(index); + send_root_config_notify(state); + return Ok(RequestOutcome::Handled); +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext/output.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext/output.rs new file mode 100644 index 000000000..7d08e365d --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext/output.rs @@ -0,0 +1,832 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{ + RANDR_BAD_OUTPUT, RequestOutcome, emit_x11_error_with_minor, + randr_ext::{RANDR_MAJOR_OPCODE, request_xid}, + write_to_client, + }, + properties, + server::ServerState, +}; +use std::io; +use yserver_protocol::{ + x11, + x11::{ + AtomId, ClientByteOrder, ClientId, RequestHeader, ResourceId, SequenceNumber, + randr as x11randr, + }, +}; + +fn output_exists(state: &ServerState, output: u32) -> bool { + state + .randr + .outputs + .iter() + .any(|candidate| candidate.output_id == output) +} + +/// Backend-synthesized read-only identity properties (`EDID` / +/// `EDID_DATA` / `ConnectorType`), resolved live from +/// `Backend::output_identity` rather than stored. Consulted only when +/// `output_id` has no matching entry in `state.randr_output_properties` +/// — a real store entry always shadows the synthesized value, matching +/// Xorg's generic property store (a client `ChangeOutputProperty` on +/// e.g. `EDID` overwrites whatever the driver put there). +fn synthetic_output_property( + state: &mut ServerState, + backend: &mut dyn Backend, + output_id: u32, + property: AtomId, +) -> Option<(u32, u8, Vec)> { + const XA_ATOM: u32 = 4; + const XA_INTEGER: u32 = 19; + let prop_name = state.atoms.name(property).map(str::to_owned); + let identity = backend.output_identity(output_id); + match (prop_name.as_deref(), identity) { + (Some("EDID" | "EDID_DATA"), Some((edid, _))) if !edid.is_empty() => { + Some((XA_INTEGER, 8, edid)) + } + (Some("ConnectorType"), Some((_, ctype))) if !ctype.is_empty() => { + let atom = state.atoms.intern(&ctype, false).0; + Some((XA_ATOM, 32, atom.to_le_bytes().to_vec())) + } + _ => None, + } +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_output_info( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let Some(req) = x11randr::parse_output_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(info_data) = state.randr.output_info(req.output, req.config_timestamp) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + req.output, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + // The `crtcs` array is the output's *possible* CRTCs, not the + // currently-assigned one (which is 0 for a connected-but-off + // output and would advertise an invalid crtcs=[0]). + let crtc_ids = info_data.possible_crtcs.as_slice(); + let mode_ids = info_data.mode_ids.as_slice(); + let name_bytes = info_data.name.as_bytes(); + let buf = x11randr::encode_get_output_info_reply( + byte_order, + sequence, + &x11randr::OutputInfoReply { + timestamp: info_data.timestamp, + crtc: info_data.crtc, + width_mm: info_data.width_mm, + height_mm: info_data.height_mm, + connection: info_data.connection, + subpixel_order: 0, + crtcs: crtc_ids, + modes: mode_ids, + num_preferred: info_data.num_preferred, + clones: &[], + name: name_bytes, + }, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_list_output_properties( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let output_id = request_xid(body); + if !output_exists(state, output_id) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + output_id, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // Real client-set properties first, then the backend-synthesized + // identity properties (EDID + EDID_DATA + ConnectorType) iff the + // backend has EDID for this output and no real entry already + // shadows that atom name. + let mut atoms: Vec = state + .randr_output_properties + .get(&output_id) + .map(|entries| entries.iter().map(|(atom, _)| atom.0).collect()) + .unwrap_or_default(); + if let Some((edid, _)) = backend.output_identity(output_id) + && !edid.is_empty() + { + for name in ["EDID", "EDID_DATA", "ConnectorType"] { + let atom = state.atoms.intern(name, false).0; + if !atoms.contains(&atom) { + atoms.push(atom); + } + } + } + let buf = x11randr::encode_list_output_properties_reply(byte_order, sequence, &atoms); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_query_output_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + // Error packets carry the EXTENSION major opcode (128) with + // the request's minor in the minor field — passing the minor + // as `major_opcode` (pre-fix) made xtrace print "major=11, + // minor=0" for this BadName. + let Some(req) = x11randr::parse_output_property_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(x11randr::RR_QUERY_OUTPUT_PROPERTY), + RANDR_MAJOR_OPCODE, + ); + }; + if !output_exists(state, req.output) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let property = AtomId(req.property); + let real = state + .randr_output_properties + .get(&req.output) + .and_then(|entries| entries.iter().find(|(atom, _)| *atom == property)); + let buf = if let Some((_, prop)) = real { + x11randr::encode_query_output_property_reply( + byte_order, + sequence, + prop.is_pending, + prop.range, + prop.immutable, + &prop.valid_values, + ) + } else if synthetic_output_property(state, backend, req.output, property).is_some() { + x11randr::encode_query_output_property_reply(byte_order, sequence, false, false, true, &[]) + } else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_NAME, + req.property, + u16::from(x11randr::RR_QUERY_OUTPUT_PROPERTY), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_configure_output_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // No lease check (real output leases can't exist — CreateLease + // always fails) and no immutable check: Xorg's wire handler + // hardcodes `immutable = FALSE` for a client-issued Configure, so + // `prop->immutable && !immutable` can only fire for a + // driver-marked property, which yserver never creates. + let Some(req) = x11randr::parse_configure_output_property_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + if !output_exists(state, req.output) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // Ranges must have an even number of values (min,max pairs). + if req.range && req.valid_values.len() % 2 != 0 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let property = AtomId(req.property); + let entries = state.randr_output_properties.entry(req.output).or_default(); + let prop = match entries.iter_mut().find(|(atom, _)| *atom == property) { + Some((_, prop)) => prop, + None => { + // Prepend, matching Xorg's RRCreateOutputProperty list + // insertion (see the ChangeOutputProperty handler above). + entries.insert(0, (property, crate::randr::RandrOutputProperty::default())); + &mut entries[0].1 + } + }; + // "Property moving from pending to non-pending loses any pending + // values" (Xorg RRConfigureOutputProperty). + if prop.is_pending && !req.pending { + prop.pending = None; + } + prop.is_pending = req.pending; + prop.range = req.range; + prop.valid_values = req.valid_values; + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_change_output_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // Order mirrors Xorg's ProcRRChangeOutputProperty: mode, then + // format, then length consistency, then output, then the + // property/type atoms — a request that violates several of + // these at once must fail with the same error Xorg reports. + let Some(req) = x11randr::parse_change_output_property_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(mode) = properties::ChangeMode::from_protocol(req.mode) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.mode), + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(format) = properties::PropertyFormat::from_protocol(req.format) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.format), + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let expected_bytes = (req.n_units as usize).checked_mul(format.bytes()); + if expected_bytes != Some(req.data.len()) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + if !output_exists(state, req.output) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let property = AtomId(req.property); + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.property, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let prop_type = AtomId(req.prop_type); + if !state.atoms.exists(prop_type) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.prop_type, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let entries = state.randr_output_properties.entry(req.output).or_default(); + let slot = entries.iter().position(|(atom, _)| *atom == property); + // Only a property previously marked pending-capable via + // ConfigureOutputProperty writes into `.pending` (and skips the + // notify) — the wire request itself has no pending flag; Xorg's + // ProcRRChangeOutputProperty always passes `pending=TRUE` + // internally, and RRChangeOutputProperty reduces that to + // `prop->is_pending`. + let is_pending_configured = slot.is_some_and(|i| entries[i].1.is_pending); + let existing_value = slot.and_then(|i| { + if is_pending_configured { + entries[i].1.pending.clone() + } else { + entries[i].1.current.clone() + } + }); + let new_value = + match properties::apply_change(existing_value.as_ref(), mode, prop_type, format, &req.data) + { + Ok(v) => v, + Err(properties::ChangePropertyError::BadMatch) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + Err(properties::ChangePropertyError::BadAlloc) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + Err(properties::ChangePropertyError::BadValue) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + }; + match slot { + Some(i) => { + if is_pending_configured { + entries[i].1.pending = Some(new_value); + } else { + entries[i].1.current = Some(new_value); + } + } + // Xorg's RRCreateOutputProperty prepends a newly created + // property onto the output's property list, so + // ListOutputProperties enumerates newest-first. + None => entries.insert( + 0, + ( + property, + crate::randr::RandrOutputProperty { + current: Some(new_value), + ..Default::default() + }, + ), + ), + } + // Xorg's `sendevent` is unconditional in `RRChangeOutputProperty` + // (`ProcRRChangeOutputProperty` always passes `sendevent=TRUE`) + // — only the unrelated `RRNoticePropertyChange` driver hook is + // gated on `is_pending`. The wire notify fires regardless of + // whether this write landed in `.current` or `.pending`. + crate::core_loop::run::notify_randr_output_property_changed( + state, + req.output, + property, + x11randr::PROPERTY_NEW_VALUE, + ); + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_delete_output_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // No lease check: real output leases can't exist. + let Some(req) = x11randr::parse_output_property_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + if !output_exists(state, req.output) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let property = AtomId(req.property); + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.property, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let entries = state.randr_output_properties.entry(req.output).or_default(); + let Some(index) = entries.iter().position(|(atom, _)| *atom == property) else { + // Known caveat: a synthetic-only identity atom (EDID / + // EDID_DATA / ConnectorType) with no real store entry + // returns BadName here rather than Xorg's BadAccess for an + // immutable driver property — no real caller deletes + // output identity metadata. + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_NAME, + req.property, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + if entries[index].1.immutable { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + req.property, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + entries.remove(index); + crate::core_loop::run::notify_randr_output_property_changed( + state, + req.output, + property, + x11randr::PROPERTY_DELETE, + ); + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_output_primary( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let output = body + .get(4..8) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) + .unwrap_or(0); + if output != 0 && !output_exists(state, output) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // None (0) clears the primary output. A nonzero id is already + // validated above; yserver has one screen and no leased outputs, + // so Xorg's remaining cross-screen/lease checks are vacuous. + let previous = state.randr.primary_output; + // Even an idempotent request turns the topology-derived default + // into an explicit client choice that must survive rebuilds. + state.randr_primary_output_explicit = true; + if previous == output { + // Xorg's RRSetPrimaryOutput returns early when nothing moves, + // so no notify storm from an idempotent set. + return Ok(RequestOutcome::Handled); + } + state.randr.primary_output = output; + // A primary change is a LAYOUT change in Xorg: RROutputChanged on + // the affected outputs + layoutChanged, then RRTellChanged + // (randr/rroutput.c). Both the old and new primary changed, so both + // are announced; clients learn about this by notify, not polling. + let changed: Vec = [previous, output].into_iter().filter(|o| *o != 0).collect(); + crate::core_loop::run::notify_randr_layout_changed(state, &changed); + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_output_primary( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let primary = state.randr.primary_output; + let buf = x11randr::encode_get_output_primary_reply(byte_order, sequence, primary); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_output_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let Some(req) = x11randr::parse_get_output_property_request(body) else { + let buf = x11randr::encode_get_output_property_reply(byte_order, sequence, 0, 0, 0, &[]); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &buf)); + }; + if !output_exists(state, req.output) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_OUTPUT, + req.output, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let property = AtomId(req.property); + // Xorg validates the property atom, then the delete BOOL, then + // the requested type atom, all before ever looking up the + // property (`ProcRRGetOutputProperty`, randr/rrproperty.c). + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.property, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + if req.delete_raw != 0 && req.delete_raw != 1 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.delete_raw), + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + if req.prop_type != 0 && !state.atoms.exists(AtomId(req.prop_type)) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + req.prop_type, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // A real store entry always shadows the backend-synthesized + // identity properties (EDID / EDID_DATA / ConnectorType). + let real = state + .randr_output_properties + .get(&req.output) + .and_then(|entries| entries.iter().find(|(atom, _)| *atom == property)) + .map(|(_, prop)| prop.clone()); + let (served, immutable): (Option<(u32, u8, Vec)>, bool) = if let Some(prop) = real.as_ref() + { + let value = if req.pending && prop.is_pending { + prop.pending.as_ref() + } else { + prop.current.as_ref() + }; + ( + value.map(|v| (v.r#type.0, v.format.protocol_value(), v.data.clone())), + prop.immutable, + ) + } else if let Some(syn) = synthetic_output_property(state, backend, req.output, property) { + (Some(syn), true) + } else { + (None, false) + }; + if req.delete && immutable { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + req.property, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let (buf, bytes_after): (Vec, u32) = match served { + // Type-mismatch (client asked for a specific, different type): + // reply with the real type + empty value + full bytes_after. + // `bytes_after` is an ELEMENT count here (Xorg: + // `reply.bytesAfter = prop_value->size`, and `size` is + // stored in format-units — see `RRChangeOutputProperty`'s + // `new_value.size = total_len` where `total_len` counts + // `nUnits`, not bytes), not `full.len()`. + Some((ptype, format, full)) if req.prop_type != 0 && req.prop_type != ptype => { + let unit = (format as usize / 8).max(1); + let bytes_after = u32::try_from(full.len() / unit).unwrap_or(u32::MAX); + ( + x11randr::encode_get_output_property_reply( + byte_order, + sequence, + ptype, + format, + bytes_after, + &[], + ), + bytes_after, + ) + } + Some((ptype, format, full)) => { + // Windowing: long-offset / long-length are in 32-bit units. + let total = full.len(); + let start = (req.long_offset as usize).saturating_mul(4); + if start > total { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.long_offset, + u16::from(x11randr::RR_GET_OUTPUT_PROPERTY), + RANDR_MAJOR_OPCODE, + ); + } + let avail = total - start; + let take = avail.min((req.long_length as usize).saturating_mul(4)); + let bytes_after = u32::try_from(avail - take).unwrap_or(u32::MAX); + ( + x11randr::encode_get_output_property_reply( + byte_order, + sequence, + ptype, + format, + bytes_after, + &full[start..start + take], + ), + bytes_after, + ) + } + None => ( + x11randr::encode_get_output_property_reply(byte_order, sequence, 0, 0, 0, &[]), + 0, + ), + }; + // Xorg fires the delete notify before writing the reply, then + // physically removes the property once bytesAfter==0 — reachable + // only for a real (non-immutable) store entry, since the + // immutable check above already rejected a synthetic property. + if req.delete && bytes_after == 0 && real.is_some() { + crate::core_loop::run::notify_randr_output_property_changed( + state, + req.output, + property, + x11randr::PROPERTY_DELETE, + ); + if let Some(entries) = state.randr_output_properties.get_mut(&req.output) { + entries.retain(|(atom, _)| *atom != property); + } + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext/provider.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext/provider.rs new file mode 100644 index 000000000..03e961620 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext/provider.rs @@ -0,0 +1,398 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{ + RANDR_BAD_PROVIDER, RequestOutcome, emit_x11_error_with_minor, + randr_ext::{RANDR_MAJOR_OPCODE, request_xid, warn_randr_unsupported_once}, + write_to_client, + }, + properties, + server::ServerState, +}; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, ResourceId, SequenceNumber, randr as x11randr}, +}; + +fn provider_relationship_protocol_error( + error: crate::randr::ProviderRelationshipError, +) -> (u8, u32) { + match error { + crate::randr::ProviderRelationshipError::UnknownProvider(provider) => { + (RANDR_BAD_PROVIDER, provider) + } + // Xorg returns BadValue for a missing provider capability or an + // initiating provider that is not a GPU screen without assigning + // client->errorValue, so the wire value remains zero. + crate::randr::ProviderRelationshipError::MissingCapability(_) + | crate::randr::ProviderRelationshipError::NotGpuProvider(_) => (x11::error::BAD_VALUE, 0), + } +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_providers( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + // Xorg uses REQUEST_SIZE_MATCH for this fixed-size request. + if body.len() != 4 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let timestamp = state.randr.timestamp; + let providers: Vec = state + .randr + .providers + .iter() + .map(|provider| provider.provider_id) + .collect(); + let buf = x11randr::encode_get_providers_reply(byte_order, sequence, timestamp, &providers); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_provider_info( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let Some(req) = x11randr::parse_provider_info_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(provider) = state.randr.provider(req.provider) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_PROVIDER, + req.provider, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + // Xorg accepts config_timestamp but does not use it for this + // request; a live provider always reports RRSetConfigSuccess. + let _ = req.config_timestamp; + let associated_providers: Vec = provider + .associations + .iter() + .map(|association| association.provider_id) + .collect(); + let associated_capabilities: Vec = provider + .associations + .iter() + .map(|association| association.capability) + .collect(); + let buf = x11randr::encode_get_provider_info_reply( + byte_order, + sequence, + &x11randr::ProviderInfoReply { + status: x11randr::SET_CONFIG_SUCCESS, + timestamp: state.randr.timestamp, + capabilities: provider.capabilities, + crtcs: &provider.crtcs, + outputs: &provider.outputs, + associated_providers: &associated_providers, + associated_capabilities: &associated_capabilities, + name: provider.name.as_bytes(), + }, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_provider_offload_sink( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + let Some(req) = x11randr::parse_set_provider_offload_sink_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + if let Err(error) = state + .randr + .validate_provider_offload_sink(req.provider, req.sink_provider) + { + let (error_code, error_value) = provider_relationship_protocol_error(error); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error_code, + error_value, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let _ = req.config_timestamp; + warn_randr_unsupported_once( + state, + client_id, + sequence, + minor, + "SetProviderOffloadSink", + "rejecting a validated relationship because offload transport is unavailable", + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_IMPLEMENTATION, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_provider_output_source( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + let Some(req) = x11randr::parse_set_provider_output_source_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + if let Err(error) = state + .randr + .validate_provider_output_source(req.provider, req.source_provider) + { + let (error_code, error_value) = provider_relationship_protocol_error(error); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error_code, + error_value, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let _ = req.config_timestamp; + let changed = match backend.set_provider_output_source( + state, + req.provider, + (req.source_provider != 0).then_some(req.source_provider), + ) { + Ok(changed) => changed, + Err(err) => { + log::warn!( + "client {} #{} RANDR::SetProviderOutputSource provider={} source={} failed: {err}", + client_id.0, + sequence.0, + req.provider, + req.source_provider, + ); + let (error_code, error_value) = if err.kind() == io::ErrorKind::InvalidInput { + (x11::error::BAD_MATCH, req.provider) + } else { + (x11::error::BAD_IMPLEMENTATION, 0) + }; + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error_code, + error_value, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + }; + if changed { + crate::core_loop::run::notify_randr_provider_changed(state, req.provider); + } + return Ok(RequestOutcome::Handled); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_provider_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + // These requests remain deliberately unsupported, but now that + // providers are live we must preserve Xorg's validation order: + // request shape first, then provider lookup, then the unsupported + // result. ChangeProviderProperty additionally validates mode and + // format before its computed-length check and provider lookup. + let provider = match minor { + x11randr::RR_LIST_PROVIDER_PROPERTIES if body.len() == 4 => request_xid(body), + x11randr::RR_QUERY_PROVIDER_PROPERTY | x11randr::RR_DELETE_PROVIDER_PROPERTY + if body.len() == 8 => + { + request_xid(body) + } + x11randr::RR_CONFIGURE_PROVIDER_PROPERTY + if body.len() >= 12 && body.len().is_multiple_of(4) => + { + request_xid(body) + } + x11randr::RR_GET_PROVIDER_PROPERTY if body.len() == 24 => request_xid(body), + x11randr::RR_CHANGE_PROVIDER_PROPERTY => { + let Some(req) = x11randr::parse_change_provider_property_header(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(_mode) = properties::ChangeMode::from_protocol(req.mode) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.mode), + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let Some(format) = properties::PropertyFormat::from_protocol(req.format) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.format), + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + }; + let expected_len = usize::try_from(req.n_units) + .ok() + .and_then(|units| units.checked_mul(format.bytes())) + .and_then(|bytes| bytes.checked_add(3)) + .map(|bytes| bytes & !3) + .and_then(|bytes| 20usize.checked_add(bytes)); + if expected_len != Some(body.len()) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + req.provider + } + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + }; + if state.randr.provider(provider).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + RANDR_BAD_PROVIDER, + provider, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let request_name = match minor { + x11randr::RR_LIST_PROVIDER_PROPERTIES => "ListProviderProperties", + x11randr::RR_QUERY_PROVIDER_PROPERTY => "QueryProviderProperty", + x11randr::RR_CONFIGURE_PROVIDER_PROPERTY => "ConfigureProviderProperty", + x11randr::RR_CHANGE_PROVIDER_PROPERTY => "ChangeProviderProperty", + x11randr::RR_DELETE_PROVIDER_PROPERTY => "DeleteProviderProperty", + x11randr::RR_GET_PROVIDER_PROPERTY => "GetProviderProperty", + _ => unreachable!(), + }; + warn_randr_unsupported_once( + state, + client_id, + sequence, + minor, + request_name, + "rejecting request because provider properties are unavailable", + ); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_IMPLEMENTATION, + 0, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext/screen.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext/screen.rs new file mode 100644 index 000000000..304ce1b05 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext/screen.rs @@ -0,0 +1,630 @@ +use crate::{ + backend::{Backend, CrtcConfigApply, ModeSpec}, + core_loop::process_request::{ + RequestOutcome, emit_x11_error_with_minor, + randr_ext::{ + CrtcConfigCompletion, CrtcConfigReply, RANDR_MAJOR_OPCODE, crtc::start_crtc_config, + request_xid, + }, + write_to_client, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use std::io; +use yserver_protocol::{ + x11, + x11::{ + ClientByteOrder, ClientId, RequestHeader, ResourceId, SequenceNumber, randr as x11randr, + }, +}; + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_query_version( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + if let Some(r) = x11randr::parse_query_version(body) { + state + .randr_client_versions + .insert(client_id, (r.major, r.minor)); + } + let (reply_major, reply_minor) = x11randr::parse_query_version(body) + .map(|r| { + let reply_major = x11randr::MAJOR_VERSION; + let reply_minor = if r.major < x11randr::MAJOR_VERSION { + r.minor + } else { + x11randr::MINOR_VERSION + }; + (reply_major, reply_minor) + }) + .unwrap_or((x11randr::MAJOR_VERSION, x11randr::MINOR_VERSION)); + let buf = x11randr::encode_query_version_reply(byte_order, sequence, reply_major, reply_minor); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_screen_size_range( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let (min_w, min_h, max_w, max_h) = state.randr.screen_size_range(); + let buf = x11randr::encode_get_screen_size_range_reply( + byte_order, sequence, min_w, min_h, max_w, max_h, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_screen_resources( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // Force a connector re-probe before replying (Xorg + // RRGetInfo force_query=TRUE). A probe failure surfaces as + // BadAlloc, matching Xorg. GetScreenResourcesCurrent below + // skips this and serves the cached view. + if let Err(e) = backend.reprobe_connectors(state) { + log::warn!("RRGetScreenResources reprobe failed: {e}"); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + let resources = state.randr.screen_resources_current(); + let buf = x11randr::encode_get_screen_resources_current_reply(byte_order, sequence, &resources); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_screen_resources_current( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + let resources = state.randr.screen_resources_current(); + let buf = x11randr::encode_get_screen_resources_current_reply(byte_order, sequence, &resources); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +pub(super) fn handle_randr_select_input( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if let Some(req) = x11randr::parse_select_input(body) { + if state.resources.window(ResourceId(req.window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + if req.enable == 0 { + state + .randr_select_masks + .remove(&(client_id.0, ResourceId(req.window))); + } else { + state + .randr_select_masks + .insert((client_id.0, ResourceId(req.window)), req.enable); + } + } + } + Ok(RequestOutcome::Handled) +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_get_screen_info( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let window = request_xid(body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // ProcRRGetScreenInfo (rrscreen.c:760-898) over RR10GetData. + let has_rate = randr_client_knows_rates(state, client_id); + let data = state.randr.rr10_data(); + let rates: Vec> = data.as_ref().map_or_else(Vec::new, |d| { + d.sizes + .iter() + .map(|s| s.rates.iter().map(|(r, _)| *r).collect()) + .collect() + }); + let sizes: Vec> = data + .as_ref() + .map(|d| { + d.sizes + .iter() + .zip(&rates) + .map(|(s, rates)| x11randr::ScreenInfoSize { + width: s.width, + height: s.height, + mm_width: s.mm_width, + mm_height: s.mm_height, + rates, + }) + .collect() + }) + .unwrap_or_default(); + let now = state.timestamp_now(); + #[allow(clippy::cast_possible_truncation)] + let info = match &data { + Some(d) => x11randr::ScreenInfoReply { + root: ROOT_WINDOW.0, + timestamp: state.randr.timestamp, + config_timestamp: state.randr.config_timestamp, + // setOfRotations is a CARD8. + rotations: state.randr.limits.rotations as u8, + rotation: state.randr.first_output_rotation(), + size_id: d.size_id, + rate: d.rate, + sizes: &sizes, + has_rate, + }, + // No output with a CRTC: Rotate_0, no sizes, current time. + None => x11randr::ScreenInfoReply { + root: ROOT_WINDOW.0, + timestamp: now, + config_timestamp: now, + rotations: crate::randr::RR_ROTATE_0 as u8, + rotation: crate::randr::RR_ROTATE_0, + size_id: 0, + rate: 0, + sizes: &[], + has_rate, + }, + }; + let buf = x11randr::encode_get_screen_info_reply(byte_order, sequence, &info); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_randr_set_screen_size( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + minor: u8, +) -> io::Result { + let Some(req) = x11randr::parse_set_screen_size_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + }; + if state.resources.window(ResourceId(req.window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + u16::from(minor), + RANDR_MAJOR_OPCODE, + ); + } + // Validation order matches rrscreen.c: width range → + // height range → crop → zero-mm. errorValue is the + // offending dimension (width vs height reported + // separately), not always width. + let (min_w, min_h, max_w, max_h) = state.randr.screen_size_range(); + if req.width < min_w || req.width > max_w { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.width), + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + if req.height < min_h || req.height > max_h { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.height), + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + if state.randr.screen_size_would_crop(req.width, req.height) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + if req.mm_width == 0 || req.mm_height == 0 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + if let Err(e) = backend.set_logical_screen_size(req.width, req.height) { + log::warn!("RRSetScreenSize: backend resize failed: {e}"); + // Xorg ProcRRSetScreenSize returns BadMatch when + // RRScreenSizeSet fails (rrscreen.c). Silently + // succeeding would make the client believe the + // resize took. Leave prior state intact + report. + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(header.data), + RANDR_MAJOR_OPCODE, + ); + } + // RRScreenSizeNotify (rrscreen.c) returns before any event when + // pixel size and mm both equal the last notified ones. + let unchanged = ( + state.randr.screen_width, + state.randr.screen_height, + state.randr.width_mm, + state.randr.height_mm, + ) == (req.width, req.height, req.mm_width, req.mm_height); + state + .randr + .set_logical_size(req.width, req.height, req.mm_width, req.mm_height); + // Pure screen-size change: fire root ConfigureNotify + + // ScreenChangeNotify ONLY — no per-CRTC/Output change + // (CRTC positions are unchanged). Pass an empty changed + // list so only ScreenChangeNotify + root ConfigureNotify fire. + if !unchanged { + crate::core_loop::run::apply_screen_size_side_effects( + state, + backend, + req.width, + req.height, + &[], + ); + } + backend.randr_layout_changed(state); + // RRSetScreenSize has NO reply (it is a void request). + return Ok(RequestOutcome::Handled); +} + +/// `ProcRRSetScreenConfig` (rrscreen.c:903-1130): the RANDR 1.0 size, +/// rotation and rate, applied to `RRFirstOutput`'s CRTC at 0,0 through the +/// SetCrtcConfig path. +pub(super) fn set_screen_config( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + byte_order: yserver_protocol::x11::ClientByteOrder, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::randr as x11randr; + const STATUS_INVALID_CONFIG_TIME: u8 = 1; + const STATUS_INVALID_TIME: u8 = 2; + const STATUS_FAILED: u8 = 3; + let error = |state: &mut ServerState, code: u8, value: u32| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(x11randr::RR_SET_SCREEN_CONFIG), + 128, + ) + }; + let status_reply = |state: &mut ServerState, status: u8| { + let reply = x11randr_encode_set_screen_config(state, byte_order, sequence, status); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &reply)) + }; + // REQUEST_SIZE_MATCH: the rate field exists only for a 1.1+ client. + let has_rate = randr_client_knows_rates(state, client_id); + if body.len() != if has_rate { 20 } else { 16 } { + return error(state, x11::error::BAD_LENGTH, 0); + } + // A DRAWABLE, not a window (`dixLookupDrawable`): a pixmap resolves to + // its screen, and an unknown xid is BadDrawable (measured with + // `tools/randr-probe`). + let drawable = u32::from_le_bytes(body[0..4].try_into().unwrap()); + let id = ResourceId(drawable); + if state.resources.window(id).is_none() && state.resources.pixmap(id).is_none() { + return error(state, x11::error::BAD_DRAWABLE, drawable); + } + let u16_at = |o: usize| u16::from_le_bytes([body[o], body[o + 1]]); + let u32_at = |o: usize| u32::from_le_bytes(body[o..o + 4].try_into().unwrap()); + let (timestamp, config_timestamp) = (u32_at(4), u32_at(8)); + let (size_id, rotation) = (u16_at(12), u16_at(14)); + let rate = if has_rate { u16_at(16) } else { 0 }; + // ClientTimeToServerTime: CurrentTime is now. + let time = if timestamp == 0 { + state.timestamp_now() + } else { + timestamp + }; + let Some(data) = state.randr.rr10_data() else { + return status_reply(state, STATUS_FAILED); + }; + if config_timestamp != state.randr.config_timestamp { + return status_reply(state, STATUS_INVALID_CONFIG_TIME); + } + let Some(size) = data.sizes.get(usize::from(size_id)) else { + return error(state, x11::error::BAD_VALUE, u32::from(size_id)); + }; + if !matches!(rotation & 0xf, 1 | 2 | 4 | 8) { + return error(state, x11::error::BAD_VALUE, u32::from(rotation)); + } + if !state.randr.limits.rotations & rotation != 0 { + return error(state, x11::error::BAD_MATCH, u32::from(rotation)); + } + let mode_id = if rate == 0 { + size.rates.first().map(|&(_, mode)| mode) + } else { + let Some(&(_, mode)) = size.rates.iter().find(|&&(r, _)| r == rate) else { + return error(state, x11::error::BAD_VALUE, u32::from(rate)); + }; + Some(mode) + }; + let Some(mode) = mode_id.and_then(|id| { + state + .randr + .mode_table + .iter() + .find(|m| m.mode_id == id) + .copied() + }) else { + return status_reply(state, STATUS_FAILED); + }; + if time < state.randr.timestamp { + return status_reply(state, STATUS_INVALID_TIME); + } + let (min_w, min_h, max_w, max_h) = state.randr.screen_size_range(); + if !(min_w..=max_w).contains(&mode.width) { + return error(state, x11::error::BAD_VALUE, u32::from(mode.width)); + } + if !(min_h..=max_h).contains(&mode.height) { + return error(state, x11::error::BAD_VALUE, u32::from(mode.height)); + } + let (width, height) = if crate::randr::rotation_swaps_axes(rotation) { + (mode.height, mode.width) + } else { + (mode.width, mode.height) + }; + let Some(target) = state + .randr + .outputs + .iter() + .find(|o| o.output_id == data.output_id) + .cloned() + else { + return status_reply(state, STATUS_FAILED); + }; + if (width, height) != (state.randr.screen_width, state.randr.screen_height) { + // Every other CRTC goes off and the screen takes the new size, mm + // unchanged. The first output's own CRTC is reconfigured in place + // below rather than lit off and on. + let others: Vec<(u32, String)> = state + .randr + .enabled_outputs() + .filter(|o| o.output_id != target.output_id) + .map(|o| (o.output_id, o.name.clone())) + .collect(); + let mut disabled = Vec::new(); + for (output_id, name) in others { + match backend.begin_crtc_config(output_id, &name, None, 0, 0) { + Ok(CrtcConfigApply::Applied(_)) => disabled.push(output_id), + Ok(CrtcConfigApply::Pending(_)) | Err(_) => { + return status_reply(state, STATUS_FAILED); + } + } + } + if !disabled.is_empty() { + let changed: Vec<(u32, u32, u32)> = state + .randr + .outputs + .iter() + .filter(|o| disabled.contains(&o.output_id)) + .map(|o| (o.output_id, o.crtc_id, 0)) + .collect(); + backend.refresh_randr_state_set_time(state, time); + backend.randr_layout_changed(state); + crate::core_loop::run::emit_randr_change_notifications(state, &changed); + } + if let Err(e) = backend.set_logical_screen_size(width, height) { + log::warn!("RRSetScreenConfig: backend resize failed: {e}"); + return status_reply(state, STATUS_FAILED); + } + let (mm_w, mm_h) = (state.randr.width_mm, state.randr.height_mm); + state.randr.set_logical_size(width, height, mm_w, mm_h); + crate::core_loop::run::apply_screen_size_side_effects(state, backend, width, height, &[]); + backend.randr_layout_changed(state); + } + // RRCrtcSet(crtc, mode, 0, 0, rotation, 1, &output) with the pending + // client transform, as SetCrtcConfig. + let Some(target) = state + .randr + .outputs + .iter() + .find(|o| o.output_id == data.output_id) + .cloned() + else { + return status_reply(state, STATUS_FAILED); + }; + let pending = target.pending_transform.applied(); + if crate::randr::crtc_matrix(rotation, mode.width, mode.height, &pending).is_none() { + return status_reply(state, STATUS_FAILED); + } + let completion = CrtcConfigCompletion { + output_id: target.output_id, + set_time: time, + output_bbox_before: crate::core_loop::run::enabled_output_bbox(state), + byte_order, + apply_transform: (!target + .pending_transform + .equivalent(&target.current_transform)) + .then(|| Box::new(pending)), + apply_rotation: (rotation != target.rotation).then_some(rotation), + reply: CrtcConfigReply::ScreenConfig, + }; + let mode_spec = ModeSpec { + width: mode.width, + height: mode.height, + vrefresh: mode.vrefresh, + }; + let connector = target.name.clone(); + start_crtc_config( + state, + backend, + client_id, + sequence, + &connector, + Some(mode_spec), + (0, 0), + completion, + ) +} + +/// `RRClientKnowsRates` (rrdispatch.c:27): the client's QueryVersion was +/// 1.1 or newer. +fn randr_client_knows_rates(state: &ServerState, client_id: ClientId) -> bool { + state + .randr_client_versions + .get(&client_id) + .is_some_and(|&version| version >= (1, 1)) +} + +/// The `SetScreenConfig` reply for `status`: `lastSetTime`, +/// `lastConfigTime` and the root, as they stand. +pub(super) fn x11randr_encode_set_screen_config( + state: &ServerState, + byte_order: yserver_protocol::x11::ClientByteOrder, + sequence: SequenceNumber, + status: u8, +) -> Vec { + yserver_protocol::x11::randr::encode_set_screen_config_reply( + byte_order, + sequence, + status, + state.randr.timestamp, + state.randr.config_timestamp, + ROOT_WINDOW.0, + ) +} diff --git a/crates/yserver-core/src/core_loop/process_request/randr_ext/xinerama.rs b/crates/yserver-core/src/core_loop/process_request/randr_ext/xinerama.rs new file mode 100644 index 000000000..31cce53e9 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/randr_ext/xinerama.rs @@ -0,0 +1,145 @@ +use crate::{ + core_loop::process_request::{ + RequestOutcome, emit_x11_error_with_minor, randr_ext::active_monitors, write_to_client, + }, + server::ServerState, +}; +use std::io; +use yserver_protocol::x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}; + +pub(in crate::core_loop::process_request) fn handle_xinerama_request( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, error, read_u32, xinerama as xin}; + + const XINERAMA_MAJOR_OPCODE: u8 = 151; + + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + + // RRXineramaScreenCount counts every monitor (`RRMonitorCountList`, + // get_active FALSE); QueryScreens lists only the non-empty ones + // (rrxinerama.c) — a 0x0 client monitor is counted but not listed. + let screen_count = active_monitors(state, false).len(); + let screens: Vec = active_monitors(state, true) + .into_iter() + .map(|monitor| xin::ScreenInfo { + x_org: monitor.x, + y_org: monitor.y, + width: monitor.width, + height: monitor.height, + }) + .collect(); + + macro_rules! require_len { + ($n:expr) => { + if body.len() != $n { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error::BAD_LENGTH, + 0, + u16::from(minor), + XINERAMA_MAJOR_OPCODE, + ); + } + }; + } + + let buf = match minor { + xin::QUERY_VERSION => { + require_len!(4); + xin::encode_query_version_reply(byte_order, sequence) + } + xin::IS_ACTIVE => { + require_len!(0); + xin::encode_is_active_reply(byte_order, sequence, screen_count > 0) + } + xin::QUERY_SCREENS => { + require_len!(0); + xin::encode_query_screens_reply(byte_order, sequence, &screens) + } + xin::GET_STATE => { + require_len!(4); + let window = read_u32(byte_order, body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error::BAD_WINDOW, + window, + u16::from(minor), + XINERAMA_MAJOR_OPCODE, + ); + } + xin::encode_get_state_reply(byte_order, sequence, true, window) + } + xin::GET_SCREEN_COUNT => { + require_len!(4); + let window = read_u32(byte_order, body); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error::BAD_WINDOW, + window, + u16::from(minor), + XINERAMA_MAJOR_OPCODE, + ); + } + #[allow(clippy::cast_possible_truncation)] + let count = screen_count as u8; + xin::encode_get_screen_count_reply(byte_order, sequence, count, window) + } + xin::GET_SCREEN_SIZE => { + require_len!(8); + let window = read_u32(byte_order, body); + let screen = read_u32(byte_order, &body[4..]); + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error::BAD_WINDOW, + window, + u16::from(minor), + XINERAMA_MAJOR_OPCODE, + ); + } + xin::encode_get_screen_size_reply( + byte_order, + sequence, + u32::from(state.randr.screen_width), + u32::from(state.randr.screen_height), + window, + screen, + ) + } + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + error::BAD_REQUEST, + 0, + u16::from(minor), + XINERAMA_MAJOR_OPCODE, + ); + } + }; + + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/redirect.rs b/crates/yserver-core/src/core_loop/process_request/redirect.rs new file mode 100644 index 000000000..880137cf5 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/redirect.rs @@ -0,0 +1,1043 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::damage_fanout::{ + accumulate_damage_border_to_state, accumulate_damage_full_to_state, + }, + resources::{COMPOSITE_OVERLAY_WINDOW, MapState, ROOT_WINDOW, ViewabilityDelta}, + server::ServerState, +}; +use yserver_protocol::{x11, x11::ResourceId}; + +/// Who reports DAMAGE for a freshly allocated redirect backing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BackingDamage { + /// The allocation: the window was already viewable, so nothing else + /// tells the compositor that the new backing holds its pixels. + Allocation, + /// The window's map exposures, after its MapNotify: Xorg allocates on + /// realize (`compRealizeWindow`) without damage, and `MapWindow` + /// delivers MapNotify before `RealizeTree` (`dix/window.c:2677-2683`). + MapExposures, +} + +/// Allocate the redirect's reason-1 backing for `window` and set +/// `Window.redirected_backing`. Shared between B.6a (single-window +/// REDIRECT_WINDOW), B.6b (REDIRECT_SUBWINDOWS walking children), +/// and the CreateWindow child-of-redirected hook. +/// +/// Silently no-ops if the window doesn't exist, has no host XID +/// yet, or the backend rejects the allocation. The caller doesn't +/// emit a protocol error in any of those cases — the redirect +/// record is already in place, and a later paint names the window, +/// which the backend paints in its own storage until a backing exists. +/// +/// Stage 4b: wired into the COMPOSITE `RedirectWindow` / +/// `RedirectSubwindows` dispatch, gated on +/// `Backend::supports_redirect_activation()`. v1 (`KmsBackend`) +/// returns `false`, preserving the post-`3751c11` revert that +/// fixed MATE; v2 (`KmsBackend`) overrides to `true` and the +/// full allocate + participation-flip path runs. +/// +/// `mode` drives the scene-participation flip after a successful +/// allocate: Manual → window participating=false (the external +/// compositor drives presentation), Automatic → window +/// participating=true AND backing participating=true (paint +/// resolves through the backing and the scene walk picks it up +/// via W's `redirected_target` indirection in 4c). +pub(super) fn activate_redirect_backing_for( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + mode: crate::server::CompositeRedirectMode, + damage: BackingDamage, +) { + // Xorg compCheckRedirect (composite/compwindow.c:156-170): the + // overlay window is NEVER actually redirected — should=FALSE for + // pWin == cs->pOverlayWin — regardless of trigger + // (RedirectSubwindows(root), explicit RedirectWindow, or + // auto-redirect-on-map). The COW is a real child of root (Phase 2), + // so RedirectSubwindows(root, Manual) would otherwise hand it a + // Manual backing + scene_participating=false, and the Phase 3 + // Manual-skip would drop the whole composited desktop from scanout. + // The COW reaches scanout via the normal paint path. + if window == COMPOSITE_OVERLAY_WINDOW { + return; + } + // compCheckRedirect allocates only for a realized window (compwindow.c:162); realize does it later. + if state + .resources + .window(window) + .is_none_or(|w| w.map_state != MapState::Viewable) + { + return; + } + // Mode-flip on an existing redirect is routed through + // `flip_redirect_target_mode` upstream — don't reallocate + // here (Xorg preserves the backing per + // `xserver/composite/compwindow.c:172` + + // `compositeproto.txt:80`). If the caller reaches us with a + // populated `redirected_backing` it's a same-mode idempotent + // call (or a stale handoff — log + skip rather than crash). + if state + .resources + .window(window) + .is_some_and(|w| w.redirected_backing.is_some()) + { + log::debug!( + "activate_redirect_backing_for(0x{:x}): backing already present (same-mode \ + idempotent); skipping reallocation", + window.0 + ); + return; + } + let snapshot = state + .resources + .window(window) + .map(|w| (w.host_xid, w.width, w.height, w.border_width, w.depth)); + let Some((Some(host_window), w_width, w_height, w_border, w_depth)) = snapshot else { + return; + }; + // #133 step 3 (3.3) — a redirect backing is allocated at the + // BORDERED extent, `(w + 2bw) x (h + 2bw)`, and holds the window at + // its OUTER origin with the content `bw` inside: Xorg + // `compAllocPixmap` computes exactly `w = width + (bw << 1)` / + // `h = height + (bw << 1)` and hands that to `compNewPixmap` + // (`composite/compalloc.c:608-618`). The render backend's seed / + // inferior-reconstruct paths place content at `(bw, bw)` in this + // pixmap, and `NameWindowPixmap` hands the whole bordered image to + // the compositor, so the border is part of it by design. + // `bordered_backing_extent` is the identity at `bw == 0`. + let (w_width, w_height) = bordered_backing_extent(w_width, w_height, w_border); + match backend.allocate_redirected_backing(origin, host_window, w_width, w_height, w_depth) { + Ok(host_pixmap) => { + if let Some(w) = state.resources.window_mut(window) { + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap, + width: w_width, + height: w_height, + depth: w_depth, + }); + } + // compAllocPixmap → compSetPixmap (`composite/compalloc.c:620`). + crate::core_loop::damage_fanout::move_window_damage_to_list_head(state, window); + // YSERVER_TRAY_DEBUG: capture-side timeline for the systray + // sliver/blank race — when each (socket) window's redirect + // backing is allocated, its size, and the mode. Correlate + // against the `TRAY fill/damage` lines (which carry the plug + // child geometry at Clear time). REMOVE with the rest of the + // tray diag once the redirect-backing race is fixed. + if std::env::var_os("YSERVER_TRAY_DEBUG").is_some() { + log::info!( + target: "yserver_core::core_loop::tray", + "TRAY redirect-alloc win=0x{:x} backing={w_width}x{w_height}d{w_depth} mode={mode:?}", + window.0, + ); + } + // Scene-participation flip. Spec §285+360 names + // redirect-state change as a scene-structure damage + // source; the v2 impl of these setters fires that + // damage internally so the protocol handler just + // makes the calls. + // + // W: Automatic → true (scene walks W, samples B via + // 4c.3 indirection). Manual → false (the external + // compositor owns presentation and reintroduces the + // window via its own output/COW surface, while the + // post-6ffd370 scene still emits W's own backing as + // its source — both controlled by the B flag below). + // + // B: always true. Post-6ffd370 the scene samples B + // through W's `redirected_target` in both modes + // (Automatic via W's own entry, Manual via the parent + // backing emit), so `store.damage(B_id, ..)` from + // every paint into the backing must accumulate. + // Leaving B non-participating in Manual mode silently + // drops all those damages and buffer-age compose + // retains stale BO pixels except where cursor damage + // happens to overlap. + let window_participating = + matches!(mode, crate::server::CompositeRedirectMode::Automatic); + if let Err(err) = + backend.set_window_scene_participation(origin, host_window, window_participating) + { + log::warn!( + "set_window_scene_participation(0x{:x}, {window_participating}) failed: {err}", + window.0 + ); + } + if let Err(err) = backend.set_backing_scene_participation(origin, host_pixmap, true) { + log::warn!( + "set_backing_scene_participation(0x{:x}, true) failed: {err}", + host_pixmap.as_raw() + ); + } + // Redirecting an already-viewable window hands the compositor a + // valid NameWindowPixmap source immediately, but the backing seed + // above happened before any later client paint. If we don't emit an + // initial full-window damage wakeup here, compositors such as picom + // can leave the freshly-redirected window absent from the COW until + // some unrelated later event (click, move, resize) dirties it. + // A window being mapped must not: its compositor tracks it from + // MapNotify, and the map exposures report the paints after that. + if damage == BackingDamage::Allocation + && state + .resources + .window(window) + .is_some_and(|w| w.map_state == MapState::Viewable) + { + let _dropped = accumulate_damage_full_to_state(state, window); + // #143 — and the RING, which `accumulate_damage_full_to_state` + // cannot express: its rect is `(0, 0, width, height)`, i.e. + // `winSize`, which excludes the border by construction. The + // backing we just allocated is the BORDERED extent and + // `allocate_redirected_backing` paints the ring into it, so + // the compositor has to be told about those pixels too. + // Xorg gets this for free — `compSetPixmapVisitWindow` queues + // `compRepaintBorder` whenever `bw != 0` + // (`composite/compwindow.c:137-139`), and that repaint is an + // ordinary GC op the DAMAGE wrapper sees. Identity at + // `bw == 0`. + let _dropped = accumulate_damage_border_to_state(state, window); + } + } + Err(err) => { + log::warn!( + "activate_redirect_backing_for(0x{:x}): allocate failed: {err}", + window.0 + ); + } + } +} + +/// Stage 4b.8: same-owner mode-flip handler. When a client +/// re-issues `Redirect{Window,Subwindows}(W, new_mode)` while it +/// already owns a record at the same key with a different mode, +/// Xorg's `compCheckRedirect` +/// (`xserver/composite/compwindow.c:172`) preserves the backing +/// pixmap and every `NameWindowPixmap` alias; only `redirectDraw` +/// flips. Composite spec line 80: "old named pixmaps remain +/// allocated until FreePixmap." +/// +/// In v2 the equivalent is: keep `Window.redirected_backing` + +/// `KmsCore.alias_registry` + `KmsCore.host_window_to_backing` + +/// `Drawable.redirected_target` untouched; only fire the +/// participation-flip pair for the new mode. +/// +/// **No re-seed** per the plan's codex-round-6 decision: the +/// backing's current content is whatever the compositor has been +/// reading from (Automatic) or the still-frozen pre-redirect snapshot +/// (Manual just-flipped-from-Automatic). Running `copy_area(W, B)` +/// would replace that with W's storage which under Manual is empty — +/// strictly worse than the existing backing contents. +fn flip_redirect_target_mode( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + target: ResourceId, + new_mode: crate::server::CompositeRedirectMode, +) { + let snapshot = state.resources.window(target).map(|w| { + ( + w.host_xid, + w.redirected_backing.as_ref().map(|b| b.host_pixmap), + ) + }); + let Some((Some(host_window), Some(backing))) = snapshot else { + // No existing backing → fall back to a fresh activation. + // This shouldn't normally fire (the caller gates on + // `prev.mode != new_mode` which implies a prior record + // existed, and any prior record under + // `supports_redirect_activation()` allocated a backing), + // but stay defensive. + log::debug!( + "flip_redirect_target_mode(0x{:x}): no existing backing; falling back to allocate", + target.0 + ); + activate_redirect_backing_for( + state, + backend, + origin, + target, + new_mode, + BackingDamage::Allocation, + ); + return; + }; + // See activate_redirect_backing_for for the rationale: B is + // always scene-participating because the post-6ffd370 scene + // samples B via `redirected_target` in both modes; only W's + // own scene presence toggles with mode. + let window_participating = matches!(new_mode, crate::server::CompositeRedirectMode::Automatic); + if let Err(err) = + backend.set_window_scene_participation(origin, host_window, window_participating) + { + log::warn!( + "flip_redirect_target_mode(0x{:x}, {window_participating}): \ + set_window_scene_participation failed: {err}", + target.0 + ); + } + if let Err(err) = backend.set_backing_scene_participation(origin, backing, true) { + log::warn!( + "flip_redirect_target_mode(0x{:x}, true): \ + set_backing_scene_participation failed: {err}", + target.0 + ); + } +} + +/// The children a `RedirectSubwindows(parent)` applies to: all of them but +/// the COW, which gets no record (compRedirectWindow returns Success for it). +/// Bottom-most first, as Xorg walks `lastChild` → `prevSib` +/// (`composite/compalloc.c:383`). +pub(crate) fn subwindows_redirect_targets( + state: &ServerState, + parent: ResourceId, +) -> Vec { + state + .resources + .children(parent) + .iter() + .copied() + .filter(|child| *child != COMPOSITE_OVERLAY_WINDOW) + .collect() +} + +/// Xorg `compCheckRedirect` after `window`'s redirect records changed from +/// effective mode `before`: allocate, flip or drop its backing to match. +/// Allocation and the flip need `supports_redirect_activation()`; a +/// teardown is a no-op for a window that never got a backing. `damage` +/// applies to an allocation only. +pub(crate) fn sync_redirect_backing( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + before: Option, + damage: BackingDamage, +) { + let after = state.composite_redirects.window_mode(window); + if before == after { + return; + } + match (before, after) { + (_, None) => crate::core_loop::process_disconnect::teardown_redirect_for_window( + state, backend, origin, window, + ), + _ if !backend.supports_redirect_activation() => {} + (None, Some(mode)) => { + activate_redirect_backing_for(state, backend, origin, window, mode, damage); + } + (Some(_), Some(mode)) => flip_redirect_target_mode(state, backend, origin, window, mode), + } +} + +/// Xorg's `compRestoreWindow` (`composite/compalloc.c:232-256`): the old +/// backing is copied back into the unredirected `window` with +/// IncludeInferiors, so DAMAGE reports its content where it shows. The +/// `still_redirected` windows are released after it and do not clip yet. +pub(super) fn damage_restored_window( + state: &mut ServerState, + window: ResourceId, + still_redirected: &[ResourceId], +) { + let region = + crate::core_loop::clip_list::not_clipped_by_children_while(state, window, still_redirected); + let _dropped = + crate::core_loop::damage_fanout::accumulate_damage_region_to_state(state, window, ®ion); +} + +/// Point GLX pixmap `glx_xid` at `new_host`, moving its export-lifetime ref along (acquire NEW, release OLD). +pub(super) fn retarget_glx_pixmap_export( + state: &mut ServerState, + backend: &mut dyn Backend, + glx_xid: u32, + new_host: u32, +) { + let Some(drawable) = state.glx_drawables.get_mut(&glx_xid) else { + return; + }; + let old_host = drawable.glx_export_host_xid.replace(new_host); + if old_host == Some(new_host) { + return; + } + backend.acquire_glx_pixmap_export(new_host); + if let Some(old_host) = old_host { + backend.release_glx_pixmap_export(old_host); + } +} + +/// A window that just became viewable under an existing redirect (its own +/// `RedirectWindow`, or its parent's `RedirectSubwindows`) gets a fresh +/// backing, as Xorg's `compRealizeWindow` → `compCheckRedirect` → +/// `compAllocPixmap` does (`composite/compwindow.c:274`, `:173-174`). +/// +/// Must be called AFTER `backend.map_subwindow`: `map_subwindow` blindly +/// sets `scene_participating = true`, and the Manual participation flip +/// inside `activate_redirect_backing_for` must land last. Callers walk the +/// delta's `became_viewable` parent first, so the seed finds the parent's +/// storage (or backing) already in place. +fn realize_redirect_backing( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, +) { + if !backend.supports_redirect_activation() { + return; + } + if state + .resources + .window(window) + .is_none_or(|w| w.redirected_backing.is_some()) + { + return; + } + let Some(mode) = effective_redirect_mode_for_window(state, window) else { + return; + }; + activate_redirect_backing_for( + state, + backend, + origin, + window, + mode, + BackingDamage::MapExposures, + ); +} + +/// Apply a viewability delta to COMPOSITE backings: the windows that became +/// unviewable (child first) drop theirs, those that became viewable (parent +/// first) get a fresh one. The redirect records are untouched. +pub(super) fn apply_viewability_delta_to_redirects( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + delta: &ViewabilityDelta, +) { + for window in &delta.became_unviewable { + let _ = crate::core_loop::process_disconnect::unrealize_redirect_backing( + state, backend, origin, *window, + ); + } + for window in &delta.became_viewable { + realize_redirect_backing(state, backend, origin, *window); + } + for window in &delta.became_viewable { + if !state.background_paint_after_backing.remove(window) { + continue; + } + let Some(xid) = state + .resources + .window(*window) + .and_then(|w| Some(w.host_xid?.as_raw())) + else { + continue; + }; + for r in clipped_by_children(state, *window) { + if let Err(err) = + backend.paint_window_background_rect(origin, xid, r.x, r.y, r.width, r.height) + { + log::warn!("paint_window_background_rect(0x{xid:x}) failed: {err}"); + break; + } + } + } +} + +/// `window`'s content less its viewable children's border boxes +/// (ClipByChildren), in its content space: where the map exposures paint its +/// background (`miPaintWindow` over the exposed region, which excludes the +/// inferiors). Painted over the whole content instead, a parent sharing a +/// backing with its children covered them, borders included, which nothing +/// paints again: a child's deferred paint is its background only. A +/// redirected window paints its own backing, so what covers it on the +/// screen does not clip it. +fn clipped_by_children(state: &ServerState, window: ResourceId) -> Vec { + use crate::core_loop::clip_list::{border_size_in_parent, subtract}; + let Some(w) = state.resources.window(window) else { + return Vec::new(); + }; + let mut region = vec![x11::xfixes::RegionRect { + x: 0, + y: 0, + width: w.width, + height: w.height, + }]; + for child in state.resources.children(window) { + // As `clip_list`'s: a viewable InputOutput child clips its parent; an + // InputOnly one draws nothing and leaves the parent's background + // whole. + let viewable = state.resources.window(*child).is_some_and(|c| { + c.map_state == MapState::Viewable + && c.class == crate::resources::WindowClass::InputOutput + }); + // A Manually redirected child paints its own backing and does not + // clip its parent, as in `clip_list`. + let transparent = state.composite_redirects.window_mode(*child) + == Some(crate::server::CompositeRedirectMode::Manual); + if viewable && !transparent { + region = subtract(®ion, &border_size_in_parent(state, *child)); + } + } + region +} + +/// Host xid of a window whose storage follows its viewability; the root and the COW own theirs. +pub(super) fn storage_lifecycle_host_xid(state: &ServerState, window: ResourceId) -> Option { + if window == ROOT_WINDOW || window == COMPOSITE_OVERLAY_WINDOW { + return None; + } + state + .resources + .window(window) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()) +} + +/// Windows that became viewable get storage, parent first; call before their redirect backings. +/// One that paints into a backing this delta allocates (its own or an ancestor's) is painted +/// once that exists: Xorg allocates the pixmap on realize (`compRealizeWindow`, +/// `composite/compwindow.c:274`), before the exposures paint. +pub(super) fn realize_storage_for_delta( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + delta: &ViewabilityDelta, +) { + use crate::backend::RealizeBackground; + let gets_backing: Vec = if backend.supports_redirect_activation() { + delta + .became_viewable + .iter() + .copied() + .filter(|w| effective_redirect_mode_for_window(state, *w).is_some()) + .collect() + } else { + Vec::new() + }; + for window in &delta.became_viewable { + let Some(xid) = storage_lifecycle_host_xid(state, *window) else { + continue; + }; + let background = if super::background_paint_inhibited(state, *window) { + RealizeBackground::Inhibited + } else if state + .resources + .window_resolved_background(*window) + .is_some() + && ancestor_or_self_in(state, *window, &gets_backing) + { + state.background_paint_after_backing.insert(*window); + RealizeBackground::Deferred + } else { + RealizeBackground::Paint + }; + if let Err(err) = backend.realize_window_storage(origin, xid, background) { + log::warn!("realize_window_storage(0x{xid:x}) failed: {err}"); + } + } +} + +fn ancestor_or_self_in(state: &ServerState, window: ResourceId, set: &[ResourceId]) -> bool { + let mut current = window; + while let Some(w) = state.resources.window(current) { + if set.contains(¤t) { + return true; + } + if w.parent == current { + break; + } + current = w.parent; + } + false +} + +/// Windows that became unviewable drop storage, child first; call after their redirect backings. +pub(super) fn release_storage_for_delta( + state: &ServerState, + backend: &mut dyn Backend, + origin: Option, + delta: &ViewabilityDelta, +) { + for window in &delta.became_unviewable { + if let Some(xid) = storage_lifecycle_host_xid(state, *window) + && let Err(err) = backend.release_window_storage(origin, xid) + { + log::warn!("release_window_storage(0x{xid:x}) failed: {err}"); + } + } +} + +/// Re-apply a window's effective COMPOSITE redirect mode after a +/// map operation. `map_subwindow` flips storage visible by default; +/// Manual-redirected windows must be forced back to +/// `scene_participating=false`, while Automatic windows stay on-scene. +pub(super) fn reapply_redirect_mode_after_map( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, +) { + let Some(mode) = effective_redirect_mode_for_window(state, window) else { + return; + }; + let Some(host_xid) = state.resources.window(window).and_then(|w| w.host_xid) else { + return; + }; + let participating = matches!(mode, crate::server::CompositeRedirectMode::Automatic); + if let Err(err) = backend.set_window_scene_participation(origin, host_xid, participating) { + log::warn!( + "reapply_redirect_mode_after_map(0x{:x}): \ + set_window_scene_participation({participating}) failed: {err}", + window.0 + ); + } +} + +/// Resize-time bookkeeping for COMPOSITE-redirected windows. yserver +/// rotates the redirected backing to fresh storage sized to the new +/// geometry. Existing `NameWindowPixmap` aliases are also retargeted +/// onto the new backing as a compatibility measure for picom/openbox: +/// in hardware repros picom kept sampling the pre-resize backing for +/// many seconds after ConfigureNotify, leaving white right/bottom +/// strips and frozen content. Following Xorg compatibility here is +/// more important than the earlier frozen-alias theory. +/// +/// On pure moves, `force_reallocate=true` routes through the same +/// rotate path even when the size is unchanged. That hands the +/// compositor a fresh backing object at the window's new position +/// instead of reusing the original named pixmap indefinitely. +/// +/// When the bordered extent changes this is `compReallocPixmap` +/// (composite/compalloc.c:670-712): the backend reallocates W's backing +/// seeded from the parent (no leaf round trip), the content is copied NW +/// from OLD, and OLD is returned still retained so the caller can carry +/// gravity-moved children out of it before +/// [`finish_redirected_backing_rotate`] drops it. `None` when nothing was +/// reallocated, including on failure, where W stays on OLD. +/// +/// `composite_named_pixmaps` is updated to point at the new backing +/// and new geometry. Each alias drops one hold on OLD and takes one +/// hold on NEW in the backend alias registry so the lifetime model +/// stays balanced. +/// +/// When the window is **not** redirected (no backing), this is a +/// no-op — `composite_named_pixmaps` should be empty by +/// construction (the protocol layer only creates aliases on +/// redirected windows). +/// #133 step 3 (3.3) — a COMPOSITE redirect backing's extent: +/// `(w + 2bw) x (h + 2bw)`, mirroring Xorg `compAllocPixmap` +/// (`composite/compalloc.c:608-618`, `w = width + (bw << 1)`). The +/// window sits at its OUTER origin inside it with the client content +/// `bw` in, so the border is part of the named pixmap by design. +/// Identity at `bw == 0`. +fn bordered_backing_extent(width: u16, height: u16, border_width: u16) -> (u16, u16) { + let bw2 = border_width.saturating_mul(2); + (width.saturating_add(bw2), height.saturating_add(bw2)) +} + +pub(super) fn rotate_redirected_backing_on_resize( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + new_width: u16, + new_height: u16, + force_reallocate: bool, + old_border_width: u16, +) -> Option { + let snapshot = state.resources.window(window).and_then(|w| { + w.redirected_backing.as_ref().map(|b| { + ( + b.host_pixmap, + b.width, + b.height, + w.host_xid, + w.depth, + w.border_width, + ) + }) + }); + let (old_backing, old_width, old_height, host_window, depth, border_width) = snapshot?; + let host_window = host_window?; + // #133 step 3 (3.3): the caller's `new_width`/`new_height` are the + // window's CONTENT size; the backing is the bordered extent (see + // `activate_redirect_backing_for`). Identity at `bw == 0`. + let (new_width, new_height) = bordered_backing_extent(new_width, new_height, border_width); + + if !force_reallocate + && old_border_width == border_width + && backend.redirected_backing_can_fit(old_backing, new_width, new_height, depth) + { + if let Some(w) = state.resources.window_mut(window) + && let Some(backing) = &mut w.redirected_backing + { + backing.width = new_width; + backing.height = new_height; + backing.depth = depth; + } + let _ = backend.update_redirected_backing_geometry( + origin, + old_backing, + new_width, + new_height, + depth, + ); + let aliases_to_retarget = state + .resources + .window(window) + .map(|w| w.composite_named_pixmaps.clone()) + .unwrap_or_default(); + for alias in &aliases_to_retarget { + let _ = state.resources.update_pixmap_geometry( + alias.client_pixmap, + new_width, + new_height, + depth, + ); + } + if let Some(w) = state.resources.window_mut(window) { + for alias in &mut w.composite_named_pixmaps { + alias.width = new_width; + alias.height = new_height; + } + } + return None; + } + + // `compReallocPixmap` (composite/compalloc.c:670-712): a new pixmap + // seeded from the parent, with OLD kept (`cw->pOldPixmap`) until + // `compCopyWindow` has carried the content and the gravity children + // out of it. The rotate retain holds OLD's storage until the caller's + // [`finish_redirected_backing_rotate`]. A failure leaves W on OLD. + if let Err(err) = backend.retain_backing_storage(origin, old_backing) { + log::warn!( + "rotate_redirected_backing_on_resize: retain_backing_storage(0x{:x}) failed: {err}", + old_backing.as_raw() + ); + return None; + } + let new_backing = match backend.reallocate_redirected_backing( + origin, + host_window, + old_backing, + new_width, + new_height, + depth, + ) { + Ok(h) => h, + Err(err) => { + log::warn!( + "rotate_redirected_backing_on_resize(0x{:x}, {new_width}x{new_height}): \ + reallocate failed, keeping the old backing: {err}", + window.0 + ); + finish_redirected_backing_rotate(backend, origin, Some(old_backing)); + return None; + } + }; + if let Some(w) = state.resources.window_mut(window) { + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: new_backing, + width: new_width, + height: new_height, + depth, + }); + } + // Compatibility retarget: existing NameWindowPixmap aliases on this + // window must follow the new backing + geometry, or compositors can + // keep sampling the pre-resize backing for seconds after the frame + // has already resized (observed with picom under openbox: white + // right/bottom strip and frozen btop content). Keep the backend + // alias-registry balanced by moving one hold per alias from OLD to + // NEW. + let aliases_to_retarget = state + .resources + .window(window) + .map(|w| w.composite_named_pixmaps.clone()) + .unwrap_or_default(); + for alias in &aliases_to_retarget { + if let Err(err) = backend.retain_backing_storage(origin, new_backing) { + log::warn!( + "rotate_redirected_backing_on_resize(0x{:x}): retain NEW alias backing 0x{:x} failed: {err}", + window.0, + new_backing.as_raw(), + ); + } + if let Err(err) = backend.drop_backing_storage(origin, alias.host_pixmap) { + log::warn!( + "rotate_redirected_backing_on_resize(0x{:x}): drop OLD alias backing 0x{:x} failed: {err}", + window.0, + alias.host_pixmap.as_raw(), + ); + } + let _ = state + .resources + .set_pixmap_host_xid(alias.client_pixmap, new_backing); + let _ = state.resources.update_pixmap_geometry( + alias.client_pixmap, + new_width, + new_height, + depth, + ); + let glx_pixmaps: Vec = state + .glx_drawables + .iter() + .filter(|(_, d)| d.x_drawable == alias.client_pixmap.0) + .map(|(xid, _)| *xid) + .collect(); + for glx_xid in glx_pixmaps { + retarget_glx_pixmap_export(state, backend, glx_xid, new_backing.as_raw()); + } + } + if let Some(w) = state.resources.window_mut(window) { + for alias in &mut w.composite_named_pixmaps { + alias.host_pixmap = new_backing; + alias.width = new_width; + alias.height = new_height; + } + } + + // compCopyWindow analog: carry pre-resize bits from OLD into NEW + // for the overlap rect. Xorg does this via `compCopyWindow` + // (composite/compwindow.c:376-388) after `compReallocPixmap` + // (compalloc.c:680-712). Without it, any compositor that re-Names + // the post-resize backing (marco on mate-panel-top during the + // 25→28-px grow) reads an empty buffer and the tray icons that + // were painted into the pre-resize backing vanish. + // + // Storage-alive contract: OLD's backend storage must remain + // readable across this call. `release_redirected_backing` above + // only frees when `alias_registry.decref` returns true (refcount + // hits 0). NameWindowPixmap aliases keep it alive through this + // path; the v2 backend's lifecycle for the no-alias case is + // tightened separately. + // + // #143: the copy carries CONTENT only. Since #133 the ring lives + // INSIDE the storage at `(0,0)..(bw,bw)` and the allocate above has + // already painted NEW's ring at the NEW extent; copying the full + // `min(old, new)` box from OLD's origin would paint over it — and on + // a SHRINK that box is the whole new backing, so NEW's right/bottom + // ring columns would get OLD's *interior* pixels. Xorg reaches the + // same end state from the other side: `compCopyWindow` copies first + // and `compSetPixmap` queues `compRepaintBorder` afterwards + // (../xserver/composite/compwindow.c:137-139), so the ring is always + // the freshly painted one. Each backing uses its allocation-time + // border inset; a border-width change moves the content between them. + let old_inset = old_border_width.saturating_mul(2); + let new_inset = border_width.saturating_mul(2); + let copy_w = old_width + .saturating_sub(old_inset) + .min(new_width.saturating_sub(new_inset)); + let copy_h = old_height + .saturating_sub(old_inset) + .min(new_height.saturating_sub(new_inset)); + let old_content_origin = i16::try_from(old_border_width).unwrap_or(i16::MAX); + let content_origin = i16::try_from(border_width).unwrap_or(i16::MAX); + // Storage preservation has no client GC, just like Present's copy. + let copy_gc = crate::backend::DrawState::default(); + if copy_w > 0 + && copy_h > 0 + && let Err(err) = backend + .apply_clip_state(origin, ©_gc.clip) + .and_then(|()| backend.apply_draw_state(origin, ©_gc)) + .and_then(|()| { + backend.copy_area( + origin, + old_backing.as_raw(), + new_backing.as_raw(), + old_content_origin, + old_content_origin, + content_origin, + content_origin, + copy_w, + copy_h, + ) + }) + { + log::warn!( + "rotate_redirected_backing_on_resize(0x{:x}): \ + copy_area(OLD=0x{:x} → NEW=0x{:x}, {copy_w}x{copy_h}) failed: {err}", + window.0, + old_backing.as_raw(), + new_backing.as_raw(), + ); + } + + if let Some(mode) = effective_redirect_mode_for_window(state, window) { + // See activate_redirect_backing_for: B always scene- + // participating so the post-6ffd370 scene's damage + // harvest sees paints through `redirected_target`. + let window_participating = matches!(mode, crate::server::CompositeRedirectMode::Automatic); + if let Err(err) = + backend.set_window_scene_participation(origin, host_window, window_participating) + { + log::warn!( + "rotate_redirected_backing_on_resize(0x{:x}): \ + set_window_scene_participation({window_participating}) failed: {err}", + window.0 + ); + } + if let Err(err) = backend.set_backing_scene_participation(origin, new_backing, true) { + log::warn!( + "rotate_redirected_backing_on_resize(0x{:x}): \ + set_backing_scene_participation(true) failed: {err}", + window.0 + ); + } + } + + // #143 — report protocol DAMAGE over the ring the reallocate above + // just repainted, at the NEW geometry. + // + // This is the realloc path only, and that is exactly Xorg's gate: + // `compReallocPixmap` allocates a new pixmap only when the BORDERED + // extent differs (`pix_w != pOld->drawable.width || pix_h != + // pOld->drawable.height`, `../xserver/composite/compalloc.c:698`, + // with `pix_w = w + (bw << 1)`), and only that branch calls + // `compSetPixmap(pWin, pNew, bw)` (`:700`). `compSetPixmapVisitWindow` + // then queues `compRepaintBorder` whenever `bw != 0` + // (`../xserver/composite/compwindow.c:137-139`), which subtracts + // `winSize` from `borderClip` and `PaintWindow(..., PW_BORDER)`s the + // difference (`:113-117`). That paint is an ordinary `PolyFillRect` + // on the window's pixmap (`../xserver/mi/miexpose.c:558`), so + // `damagePolyFillRect` (`../xserver/miext/damage/damage.c:1194`) + // reports it. The same-extent branch (`compalloc.c:702-705`) keeps + // `pOld`, never calls `compSetPixmap` and therefore reports nothing — + // which is our `redirected_backing_can_fit` early-return above, + // deliberately an EXACT extent match (`kms/render/backend.rs:20563`). + // + // Ordering matches Xorg's too: `compCopyWindow` carries the bits + // across first and the border repaint is a WorkProc that runs after, + // so the ring is always the freshly painted one. + // + // We only damage the NEW ring. The region the OLD ring vacated on a + // shrink lies outside the window's new outer extent, i.e. in the + // PARENT's area, and Xorg reports it against the parent, never + // against the shrinking window: `miComputeClips` puts the vacated + // area into `pParent->valdata->after.exposed` + // (`../xserver/mi/mivaltree.c:453-460`) and + // `miHandleValidateExposures` hands it to `miWindowExposures` + // (`../xserver/mi/miwindow.c:226`), which paints the PARENT's + // background over it (`../xserver/mi/miexpose.c:387`) — a GC op on + // the parent's drawable, so the damage lands on the parent. + // + // No-op for an unbordered window, for the root and for a + // non-viewable one (the gate lives in `accumulate_damage_to_state`). + let _dropped = accumulate_damage_border_to_state(state, window); + Some(old_backing) +} + +/// Drop the rotate retain on the OLD backing once the content copy and the +/// gravity carries have read it (`compFreeOldPixmap`, compalloc.c). +pub(super) fn finish_redirected_backing_rotate( + backend: &mut dyn Backend, + origin: Option, + old_backing: Option, +) { + let Some(old_backing) = old_backing else { + return; + }; + if let Err(err) = backend.drop_backing_storage(origin, old_backing) { + log::warn!( + "finish_redirected_backing_rotate: drop_backing_storage(0x{:x}) failed: {err}", + old_backing.as_raw() + ); + } +} + +/// A window's outer (border-inclusive) rect in its parent's content +/// space. +fn outer_rect( + x: i16, + y: i16, + width: u16, + height: u16, + border_width: u16, +) -> x11::xfixes::RegionRect { + let bw2 = border_width.saturating_mul(2); + x11::xfixes::RegionRect { + x, + y, + width: width.saturating_add(bw2), + height: height.saturating_add(bw2), + } +} + +/// `window`'s bounding region in its parent's content space for the +/// geometry given: its outer rect, cut to its bounding shape when it has +/// one (the shape is relative to its content origin). Xorg's +/// `borderSize` (`SetBorderSize`, `dix/window.c:1747-1770`). +fn bounding_in_parent( + state: &ServerState, + window: ResourceId, + (x, y, width, height, border_width): (i16, i16, u16, u16, u16), +) -> Vec { + let outer = outer_rect(x, y, width, height, border_width); + let Some(shape) = state + .shape_windows + .get(&window) + .and_then(|s| s.bounding_region()) + else { + return vec![outer]; + }; + let bw = i32::from(border_width); + let shape = shape + .clone() + .translate(i32::from(x) + bw, i32::from(y) + bw); + crate::region::Region::rect(outer) + .intersect(&shape) + .to_rects() +} + +/// [`bounding_in_parent`] at the window's current geometry. +pub(super) fn current_bounding_in_parent( + state: &ServerState, + window: ResourceId, +) -> Vec { + state.resources.window(window).map_or_else(Vec::new, |w| { + bounding_in_parent(state, window, (w.x, w.y, w.width, w.height, w.border_width)) + }) +} + +/// The nearest window at or above `window`, short of the root, that is +/// redirected: whose backing `window` draws into. +pub(super) fn redirected_ancestor_or_self( + state: &ServerState, + window: ResourceId, +) -> Option { + let mut cur = window; + while cur != crate::resources::ROOT_WINDOW { + if state.composite_redirects.window_mode(cur).is_some() { + return Some(cur); + } + cur = state.resources.window(cur)?.parent; + } + None +} + +/// Whether any proper ancestor of `window` is redirected, i.e. the +/// window (when not redirected itself) draws into that ancestor's +/// backing rather than onto the screen. +pub(super) fn has_redirected_ancestor(state: &ServerState, window: ResourceId) -> bool { + let mut cur = state.resources.window(window).map(|w| w.parent); + while let Some(ancestor) = cur { + if ancestor == crate::resources::ROOT_WINDOW { + return state.composite_redirects.window_mode(ancestor).is_some(); + } + if state.composite_redirects.window_mode(ancestor).is_some() { + return true; + } + cur = state.resources.window(ancestor).map(|w| w.parent); + } + false +} + +pub(super) fn effective_redirect_mode_for_window( + state: &ServerState, + window: ResourceId, +) -> Option { + state.composite_redirects.window_mode(window) +} diff --git a/crates/yserver-core/src/core_loop/process_request/render.rs b/crates/yserver-core/src/core_loop/process_request/render.rs new file mode 100644 index 000000000..312947223 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/render.rs @@ -0,0 +1,1127 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + damage_fanout::{ + accumulate_damage_clip_by_children_to_state, accumulate_damage_full_to_state, + accumulate_damage_to_state, + }, + process_request::{ + RENDER_LAST_REQUEST, RequestOutcome, emit_x11_error_with_minor, window_unviewable, + write_to_client, + }, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// Clip RENDER `FillRectangles` wire rects (8-byte `xRectangle`s) to a +/// `ClipByChildren` window's effective region — i.e. subtract the +/// window's mapped `InputOutput` children. Returns the surviving rects +/// re-encoded as wire bytes; an empty `Vec` means the paint is a no-op +/// (window fully covered by a child, as with a systray socket under its +/// XEMBED icon — Xorg's empty composite clip → nothing drawn, icon +/// preserved). For pixmaps / childless windows the rects pass through +/// unchanged. +fn clip_fill_rects_by_children( + state: &ServerState, + dst_drawable: ResourceId, + rects: &[u8], +) -> Vec { + use yserver_protocol::x11::xfixes; + + let child_rects = crate::core_loop::damage_fanout::mapped_child_clip_rects(state, dst_drawable); + if child_rects.is_empty() { + return rects.to_vec(); + } + + let requested: Vec = rects + .chunks_exact(8) + .map(|c| xfixes::RegionRect { + x: i16::from_le_bytes([c[0], c[1]]), + y: i16::from_le_bytes([c[2], c[3]]), + width: u16::from_le_bytes([c[4], c[5]]), + height: u16::from_le_bytes([c[6], c[7]]), + }) + .collect(); + + let clipped = crate::nested::subtract_regions(&requested, &child_rects); + + crate::core_loop::damage_fanout::log_clip_by_children_debug( + state, + dst_drawable, + "fill", + &requested, + &clipped, + ); + + let mut out = Vec::with_capacity(clipped.len() * 8); + for r in clipped { + out.extend_from_slice(&r.x.to_le_bytes()); + out.extend_from_slice(&r.y.to_le_bytes()); + out.extend_from_slice(&r.width.to_le_bytes()); + out.extend_from_slice(&r.height.to_le_bytes()); + } + out +} + +#[allow(clippy::too_many_arguments, clippy::too_many_lines)] +pub(super) fn handle_render_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use crate::{ + nested::{ + ChangePictureAttr, change_picture_translate_xids, composite_glyphs_bad_glyphset, + composite_glyphs_translate_glyphsets, + }, + resources::{ARGB_VISUAL, GlyphSetState, PictureState}, + }; + use yserver_protocol::x11::ClientByteOrder; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + // RenderErrBase + BadPicture for the first unknown Picture, in Xorg's per-request order. + macro_rules! verify_pictures { + ($($id:expr),+) => { + if let Some(bad) = first_missing_picture(state, &[$($id),+]) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::RENDER_FIRST_ERROR + 1, + bad.0, + u16::from(minor), + header.opcode, + ); + } + }; + } + match minor { + 0 => { + let (major, minor_ver) = backend.render_query_version(origin).unwrap_or((0, 11)); + let mut buf: Vec = Vec::with_capacity(32); + x11::write_render_query_version_reply( + &mut buf, byte_order, sequence, major, minor_ver, + )?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); + } + 1 => { + let mut buf: Vec = Vec::with_capacity(256); + x11::write_render_query_pict_formats_reply( + &mut buf, + byte_order, + sequence, + crate::resources::ROOT_VISUAL, + ARGB_VISUAL, + crate::resources::GLMARK_VISUAL, + )?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); + } + 2 => { + let mut buf: Vec = Vec::with_capacity(32); + x11::write_render_query_pict_index_values_reply(&mut buf, byte_order, sequence)?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); + } + 4 => { + let Some(req) = x11::render_create_picture_request(body) else { + return Ok(RequestOutcome::Handled); + }; + // Xorg dixLookupDrawable (render.c:575): BadDrawable if unknown, BadMatch for + // an InputOnly window (dix/dixutils.c:208-213). + let input_only = match state.resources.window(req.drawable) { + Some(w) => w.class == crate::resources::WindowClass::InputOnly, + None if state.resources.pixmap(req.drawable).is_some() => false, + None => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable.0, + u16::from(minor), + header.opcode, + ); + } + }; + if input_only { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + req.drawable.0, + u16::from(minor), + header.opcode, + ); + } + let damage_drawable = render_picture_damage_drawable(state, req.drawable); + let values_in_request = req.value_mask.count_ones() as usize; + let complete_values = values_in_request.min(req.values.len() / 4); + let mut complete_value_mask = 0u32; + let mut complete_value_count = 0usize; + for bit in 0..32 { + let bit_mask = 1u32 << bit; + if req.value_mask & bit_mask != 0 && complete_value_count < complete_values { + complete_value_mask |= bit_mask; + complete_value_count += 1; + } + } + let translated_bytes = complete_value_count * 4; + let mut translated_values = change_picture_translate_xids( + complete_value_mask, + &req.values[..translated_bytes], + |attr, xid| { + let resource = ResourceId(xid); + let host_xid = match attr { + ChangePictureAttr::ClipMask => state + .resources + .pixmap(resource) + .and_then(|p| p.host_xid) + .map(|h| h.as_raw()), + ChangePictureAttr::AlphaMap => state + .resources + .picture(resource) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()), + }; + Some(host_xid.unwrap_or(0)) + }, + ) + .unwrap_or_default(); + translated_values.extend_from_slice(&req.values[translated_bytes..]); + let drawable_origin = state + .resources + .window(req.drawable) + .map(|w| (w.x, w.y)) + .unwrap_or((0, 0)); + // A window Picture names the window itself, never its redirect backing: the + // backend resolves the window's current storage or backing at each use. + let picture_window = state.resources.window(req.drawable).map(|_| req.drawable); + let host_drawable_handle = match state.resources.window(req.drawable) { + Some(w) => w.host_xid.map(crate::backend::AnyHandle::Window), + None => state + .resources + .host_drawable_target(req.drawable) + .map(|t| t.host_handle()), + }; + let host_pic = host_drawable_handle.and_then(|host_drawable| { + backend + .render_create_picture( + origin, + host_drawable, + req.format, + req.value_mask, + &translated_values, + ) + .ok() + .flatten() + }); + // Core's registry is authoritative: no X error was sent, so the Picture exists. + match host_pic { + Some(hp) => backend.set_picture_drawable_origin(hp.as_raw(), drawable_origin), + None => debug!( + "client {} #{} RENDER::CreatePicture 0x{:x}: backend could not back it; ops on it are no-ops", + client_id.0, sequence.0, req.picture.0 + ), + } + state.resources.create_picture( + req.picture, + PictureState { + client: client_id, + host_picture_xid: host_pic, + host_owned_pixmap: None, + kind: crate::resources::PictureKind::Drawable, + drawable: Some(damage_drawable), + window: picture_window, + }, + ); + } + 5 => { + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + verify_pictures!(pic_id); + let value_mask = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let translated = change_picture_translate_xids(value_mask, &body[8..], |attr, xid| { + let resource = ResourceId(xid); + match attr { + ChangePictureAttr::ClipMask => state + .resources + .pixmap(resource) + .and_then(|p| p.host_xid) + .map(|h| h.as_raw()), + ChangePictureAttr::AlphaMap => state + .resources + .picture(resource) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()), + } + }); + let Some(translated_values) = translated else { + return Ok(RequestOutcome::Handled); + }; + let mut patched = Vec::with_capacity(8 + translated_values.len()); + patched.extend_from_slice(&body[..8]); + patched.extend_from_slice(&translated_values); + let host_pic = state + .resources + .picture(pic_id) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let Some(hp) = host_pic { + let _ = backend.render_change_picture(origin, hp, &patched); + } + } + 6 => { + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + verify_pictures!(pic_id); + let host_pic = state + .resources + .picture(pic_id) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let Some(hp) = host_pic { + let _ = backend.render_set_picture_clip_rectangles(origin, hp, body); + } + } + 7 => { + let Some(pic_id) = x11::render_free_resource_id(body) else { + return Ok(RequestOutcome::Handled); + }; + verify_pictures!(pic_id); + let st = state.resources.free_picture(pic_id); + if let Some(st) = st { + if let Some(hp) = st.host_picture_xid { + let _ = backend.render_free_picture(origin, hp.as_raw()); + } + if let Some(pix) = st.host_owned_pixmap { + let _ = backend.free_pixmap(origin, pix.as_raw()); + } + } + } + 8 => { + let Some(req) = x11::render_composite_request(body) else { + return Ok(RequestOutcome::Handled); + }; + verify_pictures!(req.dst); + if dst_picture_is_sourceless(state, req.dst) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.dst.0, + u16::from(minor), + header.opcode, + ); + } + verify_pictures!(req.src); + if req.mask.0 != 0 { + verify_pictures!(req.mask); + } + if dst_picture_window_unviewable(state, req.dst) { + return Ok(RequestOutcome::Handled); + } + let host_src = state + .resources + .picture(req.src) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + let host_mask = if req.mask.0 == 0 { + Some(0) + } else { + state + .resources + .picture(req.mask) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()) + }; + let host_dst = state + .resources + .picture(req.dst) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let (Some(host_src), Some(host_mask), Some(host_dst)) = + (host_src, host_mask, host_dst) + { + let painted = backend + .render_composite( + origin, req.op, host_src, host_mask, host_dst, req.src_x, req.src_y, + req.mask_x, req.mask_y, req.dst_x, req.dst_y, req.width, req.height, + ) + .unwrap_or_default(); + if let Some(dst_drawable) = + state.resources.picture(req.dst).and_then(|p| p.drawable) + { + for r in &painted { + let _dropped = accumulate_damage_to_state( + state, + dst_drawable, + r.x, + r.y, + r.width, + r.height, + ); + } + } + } + } + 10..=13 => { + // Trapezoids (10), Triangles (11), TriStrip (12), TriFan (13). + // All four share the same fixed prefix; the variable body + // layout differs and is handled by the backend. + if body.len() < 20 { + return Ok(RequestOutcome::Handled); + } + let op = body[0]; + let src = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let dst = ResourceId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let ynest_mask_format = u32::from_le_bytes([body[12], body[13], body[14], body[15]]); + let src_x = i16::from_le_bytes([body[16], body[17]]); + let src_y = i16::from_le_bytes([body[18], body[19]]); + let primitives = &body[20..]; + verify_pictures!(src, dst); + if dst_picture_is_sourceless(state, dst) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + dst.0, + u16::from(minor), + header.opcode, + ); + } + if dst_picture_window_unviewable(state, dst) { + return Ok(RequestOutcome::Handled); + } + let host_src = state + .resources + .picture(src) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + let host_dst = state + .resources + .picture(dst) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + let host_mask_format = if ynest_mask_format == 0 { + Some(0u32) + } else { + backend.render_format_for_ynest_id(ynest_mask_format) + }; + if let (Some(host_src), Some(host_dst), Some(host_mask_fmt)) = + (host_src, host_dst, host_mask_format) + { + let painted = if minor == 10 { + backend + .render_trapezoids( + origin, + op, + host_src, + host_dst, + host_mask_fmt, + src_x, + src_y, + primitives, + 0, + 0, + ) + .unwrap_or_default() + } else { + backend + .render_triangles_op( + origin, + minor, + op, + host_src, + host_dst, + host_mask_fmt, + src_x, + src_y, + primitives, + 0, + 0, + ) + .unwrap_or_default() + }; + if let Some(dst_drawable) = state.resources.picture(dst).and_then(|p| p.drawable) { + for r in &painted { + let _dropped = accumulate_damage_to_state( + state, + dst_drawable, + r.x, + r.y, + r.width, + r.height, + ); + } + } + } + } + 17 => { + let Some((gs_id, fmt)) = x11::render_create_glyphset_request(body) else { + return Ok(RequestOutcome::Handled); + }; + let host_gs = backend.render_create_glyphset(origin, fmt).ok().flatten(); + if let Some(host_gs) = host_gs { + state.resources.create_glyphset( + gs_id, + GlyphSetState { + client: client_id, + host_glyphset_xid: host_gs, + }, + ); + } + } + 18 => { + let Some((new_glyphset, existing)) = x11::render_reference_glyphset_request(body) + else { + return Ok(RequestOutcome::Handled); + }; + let _ = state + .resources + .reference_glyphset(client_id, new_glyphset, existing); + } + 19 => { + let Some(gs_id) = x11::render_free_resource_id(body) else { + return Ok(RequestOutcome::Handled); + }; + let st = state.resources.free_glyphset(gs_id); + if let Some(st) = st { + let _ = backend.render_free_glyphset(origin, st.host_glyphset_xid.as_raw()); + } + } + 20 => { + let Some((gs_id, tail)) = x11::render_add_glyphs_request(body) else { + return Ok(RequestOutcome::Handled); + }; + let host_gs = state + .resources + .glyphset(gs_id) + .map(|g| g.host_glyphset_xid.as_raw()); + if let Some(host_gs) = host_gs { + let _ = backend.render_add_glyphs(origin, host_gs, &tail); + } + } + 22 => { + let Some((gs_id, glyph_ids)) = x11::render_free_glyphs_request(body) else { + return Ok(RequestOutcome::Handled); + }; + let host_gs = state + .resources + .glyphset(gs_id) + .map(|g| g.host_glyphset_xid.as_raw()); + if let Some(host_gs) = host_gs { + let _ = backend.render_free_glyphs(origin, host_gs, &glyph_ids); + } + } + 23..=25 => { + let Some(req) = x11::render_composite_glyphs_request(body) else { + // Silently dropping this draws nothing and reports no + // error, which looks exactly like "the text is invisible" + // (#137). Say so. + debug!( + "client {} #{} RENDER::CompositeGlyphs{} -> DROPPED (body not parsed, {} bytes)", + client_id.0, + sequence.0, + 8u16 << (u16::from(minor) - 23), + body.len(), + ); + return Ok(RequestOutcome::Handled); + }; + verify_pictures!(req.src, req.dst); + if dst_picture_is_sourceless(state, req.dst) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.dst.0, + u16::from(minor), + header.opcode, + ); + } + let host_src = state + .resources + .picture(req.src) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + let host_dst = state + .resources + .picture(req.dst) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + let host_gs = state + .resources + .glyphset(req.glyphset) + .map(|g| g.host_glyphset_xid.as_raw()); + if host_src.is_none() || host_dst.is_none() || host_gs.is_none() { + debug!( + "client {} #{} RENDER::CompositeGlyphs src=0x{:x}{} dst=0x{:x}{} glyphset=0x{:x}{} \ + -> DROPPED (unresolved resource)", + client_id.0, + sequence.0, + req.src.0, + if host_src.is_none() { " MISSING" } else { "" }, + req.dst.0, + if host_dst.is_none() { " MISSING" } else { "" }, + req.glyphset.0, + if host_gs.is_none() { " MISSING" } else { "" }, + ); + } + let bad_glyphset = host_gs.and_then(|_| { + composite_glyphs_bad_glyphset(minor, &req.items, |xid| { + state.resources.glyphset(ResourceId(xid)).is_some() + }) + }); + if let Some(bad_glyphset) = bad_glyphset { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::RENDER_BAD_GLYPHSET_ERROR, + bad_glyphset, + u16::from(minor), + header.opcode, + ); + } + if dst_picture_window_unviewable(state, req.dst) { + return Ok(RequestOutcome::Handled); + } + if let (Some(host_src), Some(host_dst), Some(host_gs)) = (host_src, host_dst, host_gs) { + let translated_items = + composite_glyphs_translate_glyphsets(minor, &req.items, |xid| { + state + .resources + .glyphset(ResourceId(xid)) + .map(|g| g.host_glyphset_xid.as_raw()) + }); + let mask_fmt = if req.mask_format == 0 { + 0 + } else { + backend + .render_format_for_ynest_id(req.mask_format) + .unwrap_or(0) + }; + let painted = backend + .render_composite_glyphs( + origin, + minor, + req.op, + host_src, + host_dst, + mask_fmt, + host_gs, + req.src_x, + req.src_y, + &translated_items, + 0, + 0, + ) + .unwrap_or_default(); + debug!( + "client {} #{} RENDER::CompositeGlyphs{} op={} src=0x{:x} dst=0x{:x} gs=0x{:x} \ + mask_format={}->{} items={} src_xy=({},{}) -> painted {} rect(s)", + client_id.0, + sequence.0, + 8u16 << (u16::from(minor) - 23), + req.op, + req.src.0, + req.dst.0, + req.glyphset.0, + req.mask_format, + mask_fmt, + req.items.len(), + req.src_x, + req.src_y, + painted.len(), + ); + if let Some(dst_drawable) = + state.resources.picture(req.dst).and_then(|p| p.drawable) + { + for r in &painted { + let _dropped = accumulate_damage_to_state( + state, + dst_drawable, + r.x, + r.y, + r.width, + r.height, + ); + } + } + } + } + 26 => { + let Some(req) = x11::render_fill_rectangles_request(body) else { + return Ok(RequestOutcome::Handled); + }; + verify_pictures!(req.dst); + if dst_picture_is_sourceless(state, req.dst) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.dst.0, + u16::from(minor), + header.opcode, + ); + } + if dst_picture_window_unviewable(state, req.dst) { + return Ok(RequestOutcome::Handled); + } + let host_dst = state + .resources + .picture(req.dst) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let Some(host_dst) = host_dst { + // ClipByChildren: a FillRectangles op=Clear on a window + // fully covered by a mapped child (mate-panel systray + // socket under its XEMBED icon) is a no-op in Xorg — + // empty composite clip → nothing painted, no damage. We + // historically painted + damaged the full drawable, which + // both wiped the embedded icon's backing AND drove the + // per-frame tray recomposite loop. Clip the paint rects to + // window-minus-children; if the result is empty the whole + // op is skipped. Pixmaps / childless windows pass through + // unchanged. + // IncludeInferiors keeps the children in the clip. + let dst_drawable = state.resources.picture(req.dst).and_then(|p| p.drawable); + let include_inferiors = backend.picture_includes_inferiors(host_dst); + let painted_rects = match dst_drawable { + Some(d) if !include_inferiors => { + clip_fill_rects_by_children(state, d, &req.rects) + } + _ => req.rects.clone(), + }; + if !painted_rects.is_empty() { + let _ = backend.render_fill_rectangles( + origin, + host_dst, + req.op, + req.color, + &painted_rects, + 0, + 0, + ); + if let Some(d) = dst_drawable { + let _dropped = if include_inferiors { + accumulate_damage_full_to_state(state, d) + } else { + accumulate_damage_clip_by_children_to_state(state, d) + }; + } + } + } + } + 27 => { + if body.len() < 12 { + return Ok(RequestOutcome::Handled); + } + let cursor_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let src_pic_id = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + verify_pictures!(src_pic_id); + let x = u16::from_le_bytes([body[8], body[9]]); + let y = u16::from_le_bytes([body[10], body[11]]); + let host_src = state + .resources + .picture(src_pic_id) + .and_then(|p| p.host_picture_xid); + if let Some(host_src) = host_src + && let Some(cursor_handle) = backend + .render_create_cursor(origin, host_src, x, y) + .ok() + .flatten() + { + state.resources.create_glyph_cursor(client_id, cursor_id); + state + .resources + .set_cursor_host_xid(cursor_id, cursor_handle); + } + } + 28 => { + if body.len() < 40 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + verify_pictures!(pic_id); + let host_pic = state + .resources + .picture(pic_id) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let Some(hp) = host_pic { + let _ = backend.render_set_picture_transform(origin, hp, body); + } + } + 29 => { + let mut buf: Vec = Vec::with_capacity(64); + x11::write_render_query_filters_reply(&mut buf, byte_order, sequence)?; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &buf)); + } + 30 => { + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + verify_pictures!(pic_id); + let host_pic = state + .resources + .picture(pic_id) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let Some(hp) = host_pic { + let _ = backend.render_set_picture_filter(origin, hp, body); + } + } + 33 => { + let Some((pic_id, color)) = x11::render_create_solid_fill_request(body) else { + return Ok(RequestOutcome::Handled); + }; + let host_pic = backend + .render_create_solid_fill(origin, color) + .ok() + .flatten(); + state.resources.create_picture( + pic_id, + PictureState { + client: client_id, + host_picture_xid: host_pic, + host_owned_pixmap: None, + kind: crate::resources::PictureKind::Sourceless, + drawable: None, + window: None, + }, + ); + } + 34 => { + if body.len() < 24 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let host_pic = backend + .render_create_linear_gradient(origin, body) + .ok() + .flatten(); + state.resources.create_picture( + pic_id, + PictureState { + client: client_id, + host_picture_xid: host_pic, + host_owned_pixmap: None, + kind: crate::resources::PictureKind::Sourceless, + drawable: None, + window: None, + }, + ); + } + 35 => { + if body.len() < 32 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let host_pic = backend + .render_create_radial_gradient(origin, body) + .ok() + .flatten(); + state.resources.create_picture( + pic_id, + PictureState { + client: client_id, + host_picture_xid: host_pic, + host_owned_pixmap: None, + kind: crate::resources::PictureKind::Sourceless, + drawable: None, + window: None, + }, + ); + } + 31 => { + // RENDER::CreateAnimCursor — body: cid(4), [cursor(4), + // delay(4)]*N. Port of Xorg + // `render/render.c::ProcRenderCreateAnimCursor:1783`: + // validate cid is a fresh client-range xid, validate every + // sub-cursor exists, register the cid as a real Cursor + // resource so downstream CWA(CWCursor=this) / + // XFixesSetCursorName / DefineCursor see a live xid. + // + // Validation: odd pair bytes → BadLength; zero frames → + // BadValue; nested animated sub-cursor → BadMatch (Xorg + // animcur.c:316). + // + // Animation is delegated to `backend.create_anim_cursor`; + // backends returning `Ok(None)` (default / ynest) degenerate + // to frame 0's handle. Previously this arm was a stub that + // silently dropped the xid — combined with the BadCursor gate + // in handle_change_window_attributes, that wedged caja / + // thunar on every app launch via marco's busy-cursor path. + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let cursor_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let validation_failed = { + let handle = state.clients.get(&client_id.0).expect("client registered"); + let owned = crate::server::IdAllocator::validate_owned( + cursor_id.0, + handle.resource_id_base, + handle.resource_id_mask, + ); + !owned || state.resources.xid_in_use(cursor_id) + }; + if validation_failed { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + cursor_id.0, + u16::from(minor), + header.opcode, + ); + } + let pairs = &body[4..]; + // Xorg fidelity (render.c:1796,1801): odd request length + // → BadLength; zero frames → BadValue. + if !pairs.len().is_multiple_of(8) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + if pairs.is_empty() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(minor), + header.opcode, + ); + } + let mut first_host: Option = None; + let mut frames: Vec<(crate::backend::CursorHandle, u32)> = + Vec::with_capacity(pairs.len() / 8); + for chunk in pairs.chunks_exact(8) { + let sub = ResourceId(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])); + let delay = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); + if !state.resources.cursor_exists(sub) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + sub.0, + u16::from(minor), + header.opcode, + ); + } + // Xorg refuses nested animated cursors (animcur.c:316). + // bad_value stays 0: AnimCursorCreate returns BadMatch + // without setting client->errorValue. + if state.resources.cursor_is_anim(sub) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(minor), + header.opcode, + ); + } + if let Some(host_raw) = state.resources.cursor_host_xid(sub) { + if first_host.is_none() { + first_host = Some(host_raw); + } + if let Some(h) = crate::backend::CursorHandle::from_raw(host_raw) { + frames.push((h, delay)); + } + } + } + // Backend-side animation. `Ok(None)` (default impl / + // ynest) → static degeneration to frame 0's handle. A + // backend Err is "can't happen" after the validation + // above — log and degenerate rather than swallowing + // silently (spec "Error handling"). + let anim_handle = if frames.is_empty() { + log::warn!( + "client {} RENDER::CreateAnimCursor: no sub-cursor has a host handle; \ + cursor 0x{:x} registered without backend animation", + client_id.0, + cursor_id.0, + ); + None + } else { + match backend.create_anim_cursor(origin, &frames) { + Ok(handle) => handle, + Err(e) => { + log::warn!( + "client {} RENDER::CreateAnimCursor backend failure ({e}); \ + degenerating to first frame", + client_id.0, + ); + None + } + } + }; + state.resources.create_glyph_cursor(client_id, cursor_id); + state.resources.set_cursor_anim(cursor_id); + if let Some(handle) = anim_handle { + state.resources.set_cursor_host_xid(cursor_id, handle); + log::debug!( + "client {} RENDER::CreateAnimCursor cursor=0x{:x} animated \ + ({} frames, backend handle 0x{:x})", + client_id.0, + cursor_id.0, + frames.len(), + handle.as_raw(), + ); + } else if let Some(host_raw) = first_host + && let Some(handle) = crate::backend::CursorHandle::from_raw(host_raw) + { + state.resources.set_cursor_host_xid(cursor_id, handle); + log::debug!( + "client {} RENDER::CreateAnimCursor cursor=0x{:x} (static \ + degeneration to first sub-cursor host_xid=0x{host_raw:x})", + client_id.0, + cursor_id.0, + ); + } + } + 36 => { + // CreateConicalGradient: registered so the client can name it; rendering with it + // is not implemented, so ops that use it stay no-ops. + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let pic_id = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + state.resources.create_picture( + pic_id, + PictureState { + client: client_id, + host_picture_xid: None, + host_owned_pixmap: None, + kind: crate::resources::PictureKind::Sourceless, + drawable: None, + window: None, + }, + ); + } + 32 => { + // AddTraps — backend dispatch is a stub, but match the + // damage pattern of the other paint vectors so a future + // real impl doesn't silently miss compositor wakeups. + // Wasted compositor recomposite on a no-op paint is + // harmless; the alternative (no damage call) is a + // silent gap on a real impl. Body: pic(4) x_off(2) + // y_off(2) then variable trapezoid list. + if body.len() >= 4 { + let pic = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + verify_pictures!(pic); + if let Some(dst_drawable) = state.resources.picture(pic).and_then(|p| p.drawable) { + let _dropped = accumulate_damage_full_to_state(state, dst_drawable); + } + } + } + other if other > RENDER_LAST_REQUEST => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + _ => { + debug!( + "client {} #{} RENDER::known unsupported minor={}", + client_id.0, sequence.0, minor + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// True if the picture exists and was created from a SolidFill / +/// LinearGradient / RadialGradient / ConicalGradient — i.e. has no +/// underlying drawable, so cannot be a Composite/Trapezoids/Triangles/ +/// FillRectangles/CompositeGlyphs destination. Unknown picture ids +/// return false (caller falls through to existing missing-id handling). +fn dst_picture_is_sourceless(state: &ServerState, dst: ResourceId) -> bool { + state + .resources + .picture(dst) + .is_some_and(|p| matches!(p.kind, crate::resources::PictureKind::Sourceless)) +} + +pub(super) fn render_picture_damage_drawable( + state: &ServerState, + drawable: ResourceId, +) -> ResourceId { + state + .resources + .composite_named_pixmap_owner_window(drawable) + .unwrap_or(drawable) +} + +/// Xorg VERIFY_PICTURE (`render/picturestr.h:363`, error value set at +/// `render/render.c:252`): the first of `ids` that names no Picture. +fn first_missing_picture(state: &ServerState, ids: &[ResourceId]) -> Option { + ids.iter() + .copied() + .find(|id| state.resources.picture(*id).is_none()) +} + +/// A RENDER destination Picture on an unviewable window: Xorg's composite clip is the +/// window's clipList/borderClip (`render/mipict.c:114-118`), emptied when it stops being +/// viewable (`mi/mivaltree.c:690-695`, `mi/miwindow.c:738-745`), so nothing is drawn. +fn dst_picture_window_unviewable(state: &ServerState, pic: ResourceId) -> bool { + state + .resources + .picture(pic) + .and_then(|p| p.window) + .is_some_and(|w| window_unviewable(state, w)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/saver_dpms.rs b/crates/yserver-core/src/core_loop/process_request/saver_dpms.rs new file mode 100644 index 000000000..0c933b64c --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/saver_dpms.rs @@ -0,0 +1,1110 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{ + RequestOutcome, drawable_exists, emit_x11_error, emit_x11_error_with_minor, + window_destroy::destroy_window_subtree, + windows::{handle_create_window, handle_map_window}, + write_to_client, + }, + resources::ROOT_WINDOW, + server::{ScreenSaverActive, ServerState}, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +/// Apply a DPMS level transition. Updates `state.dpms.power_level` +/// **first** (so the page-flip gate trips immediately and an +/// interleaved composite tick can't submit a flip into a CRTC the +/// kernel is about to disable), then calls the backend, then emits +/// a notify iff the level actually changed. Backend errors are +/// logged but do not propagate — matches Xorg's "set it anyway" +/// posture (`Xext/dpms.c:262-293`). +pub(crate) fn apply_dpms_transition( + state: &mut ServerState, + backend: &mut dyn Backend, + new_level: u8, +) { + let old = state.dpms.power_level; + // ALWAYS call the backend, even when new_level == old. Matches Xorg + // DPMSSet (dpms.c:262-293), which gates only the notify on level + // change but always runs the per-screen DPMS hook. Two reasons this + // matters: + // (1) Recovery via reissue. If a previous transition advanced + // state.dpms.power_level but the backend errored (per the + // error contract, state advances anyway), a client can send + // DPMSForceLevel(same_level) to retry. The KMS backend's + // kms_outputs_active guard short-circuits idempotently when + // state IS consistent, and re-attempts when desynced. + // (2) Spam suppression is already handled at the backend level: + // KmsBackend::set_dpms_power early-returns when want_active + // equals self.kms_outputs_active. + if new_level != old { + log::info!( + "dpms: apply_dpms_transition {old} → {new_level} (enabled={}, kms_capable={})", + state.dpms.enabled, + state.dpms.kms_capable, + ); + } + state.dpms.power_level = new_level; + + // SS coupling — fires BEFORE backend hook and BEFORE DPMS notify + // (Xorg dpms.c:262-279 ordering). + // non-On + SS Off → SCREEN_SAVER_FORCER + Active → forced=true + // On + SS On → SCREEN_SAVER_OFF + Reset → forced=false + // Neither path resets last_activity (Xorg's NoticeTime only runs + // for the FORCER+Reset combination, window.c:3187-3193). + let dpms_on = new_level == 0; + match (dpms_on, state.screensaver.active) { + (false, ScreenSaverActive::Off) => { + apply_screen_saver_transition( + state, + backend, + ScreenSaverActive::On, + /*forced=*/ true, + ); + } + (true, ScreenSaverActive::On) => { + apply_screen_saver_transition( + state, + backend, + ScreenSaverActive::Off, + /*forced=*/ false, + ); + } + _ => {} + } + + if let Err(e) = backend.set_dpms_power(new_level) { + log::error!("set_dpms_power({new_level}) failed: {e}"); + // Intentionally swallowed: state still advances. See spec + // "Backend hook / Error contract". + } + if new_level != old { + emit_dpms_notify(state); + } +} + +/// Fan a `DPMSInfoNotify` GenericEvent out to every client +/// currently subscribed via `DPMSSelectInput(DPMS_INFO_NOTIFY_MASK)`. +/// Uses the existing `fanout_event_to_clients` helper for sequence +/// + byte-order + per-client write_or_buffer handling. +fn emit_dpms_notify(state: &mut ServerState) { + use crate::nested::DPMS_MAJOR_OPCODE; + use yserver_protocol::x11::dpms as x11dpms; + if state.dpms.selected_by.is_empty() { + return; + } + let ts = state.timestamp_now(); + let level = u16::from(state.dpms.power_level); + let enabled = state.dpms.enabled; + let subscribers: Vec = state.dpms.selected_by.iter().copied().collect(); + let dropped = crate::core_loop::fanout::fanout_event_to_clients( + state, + &subscribers, + |buf, seq, order| { + x11dpms::encode_dpms_info_notify_event( + buf, + order, + seq, + DPMS_MAJOR_OPCODE, + ts, + level, + enabled, + ); + }, + ); + // Reap subscribers whose outbound buffer overflowed — they're + // already on a path to disconnect via run.rs::reconcile_client_ + // writable_interest, and keeping them in selected_by would burn + // CPU on every subsequent notify until that finishes. + for cid in dropped { + state.dpms.selected_by.remove(&cid); + } +} + +/// `ScreenSaverSetAttributes` (`Xext/saver.c:734-1073`): CreateWindow's +/// checks against the root, then BadAccess when another client holds +/// the attributes; else they are this client's, replacing its own. +fn screen_saver_set_attributes( + state: &mut ServerState, + client_id: ClientId, + body: &[u8], +) -> Result<(), (u8, u32)> { + use crate::server::SaverAttributes; + if body.len() < 24 { + return Err((x11::error::BAD_LENGTH, 0)); + } + let u16_at = |i: usize| u16::from_le_bytes([body[i], body[i + 1]]); + let u32_at = |i: usize| u32::from_le_bytes([body[i], body[i + 1], body[i + 2], body[i + 3]]); + let drawable = u32_at(0); + let (x, y) = (u16_at(4) as i16, u16_at(6) as i16); + let (width, height, border_width) = (u16_at(8), u16_at(10), u16_at(12)); + let (class, depth, visual, value_mask) = (body[14], body[15], u32_at(16), u32_at(20)); + if !drawable_exists(state, ResourceId(drawable)) { + return Err((x11::error::BAD_DRAWABLE, drawable)); + } + let values: Vec = body[24..].chunks_exact(4).map(u32_at_slice).collect(); + if usize::try_from(value_mask.count_ones()).ok() != Some(values.len()) { + return Err((x11::error::BAD_LENGTH, 0)); + } + if width == 0 || height == 0 { + return Err((x11::error::BAD_VALUE, 0)); + } + // The root is InputOutput, of the root depth and visual. + let effective_class = match class { + 0 | 1 => 1, + 2 => 2, + other => return Err((x11::error::BAD_VALUE, u32::from(other))), + }; + if effective_class == 2 && (border_width != 0 || depth != 0) { + return Err((x11::error::BAD_MATCH, 0)); + } + let depth = if effective_class == 1 && depth == 0 { + crate::resources::ROOT_DEPTH + } else { + depth + }; + let visual = if visual == 0 { + crate::resources::ROOT_VISUAL.0 + } else { + visual + }; + if (visual != crate::resources::ROOT_VISUAL.0 || depth != crate::resources::ROOT_DEPTH) + && !state.resources.is_known_visual(ResourceId(visual)) + { + return Err((x11::error::BAD_MATCH, 0)); + } + const CW_BORDER: u32 = 0x0004 | 0x0008; + const CW_COLORMAP: u32 = 0x2000; + if value_mask & CW_BORDER == 0 && effective_class != 2 && depth != crate::resources::ROOT_DEPTH + { + return Err((x11::error::BAD_MATCH, 0)); + } + if value_mask & CW_COLORMAP == 0 + && effective_class != 2 + && visual != crate::resources::ROOT_VISUAL.0 + { + return Err((x11::error::BAD_MATCH, 0)); + } + if state + .screensaver + .attributes + .as_ref() + .is_some_and(|a| a.client != client_id) + { + return Err((x11::error::BAD_ACCESS, 0)); + } + state.screensaver.attributes = Some(SaverAttributes { + client: client_id, + x, + y, + width, + height, + border_width, + class, + depth, + visual, + value_mask, + values, + }); + Ok(()) +} + +fn u32_at_slice(c: &[u8]) -> u32 { + u32::from_le_bytes([c[0], c[1], c[2], c[3]]) +} + +/// `ScreenSaverUnsetAttributes` (`Xext/saver.c:1075-1096`), and a client +/// going away (`ScreenSaverFreeAttr`): its attributes are dropped, and +/// the saver window with them. +pub(crate) fn unset_screen_saver_attributes( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, +) { + if state + .screensaver + .attributes + .as_ref() + .is_some_and(|a| a.client == client_id) + { + state.screensaver.attributes = None; + // `ScreenSaverFreeAttr` (`Xext/saver.c:333-355`): a shown window + // goes by resetting the saver and starting it again. + if state.screensaver.window_shown { + apply_screen_saver_transition(state, backend, ScreenSaverActive::Off, true); + apply_screen_saver_transition(state, backend, ScreenSaverActive::On, true); + } + } +} + +/// `CreateSaverWindow` (`Xext/saver.c:466-564`): the attributes as a +/// server-owned, override-redirect child of the root, mapped. +fn create_screen_saver_window(state: &mut ServerState, backend: &mut dyn Backend) { + destroy_screen_saver_window(state, backend); + let Some(attrs) = state.screensaver.attributes.clone() else { + return; + }; + const CW_OVERRIDE_REDIRECT: u32 = 0x0200; + let mask = attrs.value_mask | CW_OVERRIDE_REDIRECT; + let mut values = Vec::with_capacity(attrs.values.len() + 1); + let mut given = attrs.values.iter(); + for bit in 0..15u32 { + let b = 1 << bit; + if mask & b == 0 { + continue; + } + if b == CW_OVERRIDE_REDIRECT { + if attrs.value_mask & b != 0 { + given.next(); + } + values.push(1); + } else if let Some(v) = given.next() { + values.push(*v); + } + } + // Xorg keeps the values as `unsigned long` and hands them to + // CreateWindow as an `XID *` (`Xext/saver.c:494`): on a 64-bit server + // every other XID it reads is the high half of the one before, 0. + // dtsession's mask-0 window (override-redirect alone) is unaffected; + // a mask with background pixel loses its override-redirect. + let values: Vec = values + .iter() + .flat_map(|v| [*v, 0]) + .take(values.len()) + .collect(); + let window = crate::resources::SCREEN_SAVER_WINDOW; + let mut body = Vec::with_capacity(28 + 4 * values.len()); + body.extend_from_slice(&window.0.to_le_bytes()); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + for v in [ + attrs.x as u16, + attrs.y as u16, + attrs.width, + attrs.height, + attrs.border_width, + ] { + body.extend_from_slice(&v.to_le_bytes()); + } + body.extend_from_slice(&u16::from(attrs.class).to_le_bytes()); + body.extend_from_slice(&attrs.visual.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); + for v in &values { + body.extend_from_slice(&v.to_le_bytes()); + } + let header = RequestHeader { + opcode: 1, + data: attrs.depth, + length_units: u32::try_from(1 + body.len() / 4).unwrap_or(u32::MAX), + }; + let server = crate::resources::SERVER_OWNER; + let _ = handle_create_window( + state, + backend, + None, + server, + SequenceNumber(0), + header, + &body, + ); + if state.resources.window(window).is_none() { + return; + } + let _ = handle_map_window( + state, + backend, + None, + server, + SequenceNumber(0), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &window.0.to_le_bytes(), + ); + state.screensaver.window_shown = true; +} + +/// `DestroySaverWindow` (`Xext/saver.c:566-584`). +fn destroy_screen_saver_window(state: &mut ServerState, backend: &mut dyn Backend) { + if !state.screensaver.window_shown { + return; + } + state.screensaver.window_shown = false; + if state + .resources + .window(crate::resources::SCREEN_SAVER_WINDOW) + .is_some() + { + // Never the COW: preparation cannot fail. + let _ = destroy_window_subtree(state, backend, None, crate::resources::SCREEN_SAVER_WINDOW); + } +} + +/// Transition the screensaver to `new` (must be `Off` or `On`). +/// `Cycle` is an event-only value — it never appears in +/// `screensaver.active`. Passing it here is a programmer error; the +/// helper debug-asserts and no-ops in release builds. Idempotent on +/// same-state. On every Off↔On transition updates +/// `screensaver.active`, `screensaver.forced`, and +/// `screensaver.next_cycle`, then fires `ScreenSaverNotify` to +/// `SCREEN_SAVER_NOTIFY_MASK` subscribers. The `backend` parameter +/// is reserved for signature parity with `apply_dpms_transition` +/// and is currently unused (SS is purely server-side bookkeeping). +pub(crate) fn apply_screen_saver_transition( + state: &mut ServerState, + backend: &mut dyn Backend, + new: ScreenSaverActive, + forced: bool, +) { + debug_assert!( + !matches!(new, ScreenSaverActive::Cycle), + "Cycle is event-only and must never be written into screensaver.active — \ + route it through emit_screen_saver_notify instead" + ); + if matches!(new, ScreenSaverActive::Cycle) { + return; // release-build safety net + } + if state.screensaver.active == new { + return; + } + state.screensaver.active = new; + state.screensaver.forced = forced; + state.screensaver.next_cycle = match new { + ScreenSaverActive::On if state.screensaver.interval_ms > 0 => Some( + std::time::Instant::now() + + std::time::Duration::from_millis(u64::from(state.screensaver.interval_ms)), + ), + _ => None, + }; + // `ScreenSaverHandle` (`Xext/saver.c:586-614`): the window first, + // then the notify that names it. + match new { + ScreenSaverActive::On => create_screen_saver_window(state, backend), + _ => destroy_screen_saver_window(state, backend), + } + emit_screen_saver_notify(state, new, forced); +} + +/// `kind` of QueryInfo and ScreenSaverNotify: External while a client's +/// attributes are set (`Xext/saver.c:411-416`). +fn screen_saver_kind(state: &ServerState) -> u8 { + use yserver_protocol::x11::screensaver as x11ss; + if state.screensaver.attributes.is_some() { + x11ss::SCREEN_SAVER_EXTERNAL + } else if state.screensaver.prefer_blanking { + x11ss::SCREEN_SAVER_BLANKED + } else { + x11ss::SCREEN_SAVER_INTERNAL + } +} + +/// Fan a `ScreenSaverNotify` event out to subscribers. `notify_state` +/// and `forced` are passed explicitly so the cycle-timer path can +/// fire `Cycle` events without mutating `screensaver.active`. Cycle +/// events deliver to `CYCLE_MASK` subscribers; Off/On events deliver +/// to `NOTIFY_MASK` subscribers (Xorg `saver.c:389-391`). +pub(crate) fn emit_screen_saver_notify( + state: &mut ServerState, + notify_state: ScreenSaverActive, + forced: bool, +) { + use crate::nested::MIT_SCREEN_SAVER_FIRST_EVENT; + use yserver_protocol::x11::screensaver as x11ss; + let (active_state, deliver_mask) = match notify_state { + ScreenSaverActive::Off => (x11ss::SCREEN_SAVER_OFF, x11ss::SCREEN_SAVER_NOTIFY_MASK), + ScreenSaverActive::On => (x11ss::SCREEN_SAVER_ON, x11ss::SCREEN_SAVER_NOTIFY_MASK), + ScreenSaverActive::Cycle => (x11ss::SCREEN_SAVER_CYCLE, x11ss::SCREEN_SAVER_CYCLE_MASK), + }; + let subs: Vec = state + .screensaver + .selected_by + .iter() + .filter(|(_, mask)| **mask & deliver_mask != 0) + .map(|(c, _)| *c) + .collect(); + if subs.is_empty() { + return; + } + let ts = state.timestamp_now(); + let root = crate::resources::ROOT_WINDOW.0; + let kind = screen_saver_kind(state); + let dropped = + crate::core_loop::fanout::fanout_event_to_clients(state, &subs, |buf, seq, order| { + x11ss::encode_screen_saver_notify_event( + buf, + order, + seq, + MIT_SCREEN_SAVER_FIRST_EVENT, + active_state, + ts, + root, + crate::resources::SCREEN_SAVER_WINDOW.0, + kind, + forced, + ); + }); + for cid in dropped { + state.screensaver.selected_by.remove(&cid); + } +} + +/// Current idle value for an IDLETIME-family counter, expressed as +/// milliseconds since `state.idletime_baseline(counter)`. Used by +/// CREATE_ALARM / CHANGE_ALARM (Relative values, trigger checks) for +/// counter values that aren't stored in `state.sync_counters`. +pub(crate) fn idletime_current_idle(state: &ServerState, counter: u32) -> i64 { + let baseline = state.idletime_baseline(counter); + #[allow(clippy::cast_possible_truncation)] + let v = std::time::Instant::now() + .duration_since(baseline) + .as_millis() + .min(u128::from(u32::MAX)) as i64; + v +} + +/// Evaluate Negative-* alarms on IDLETIME-family counters after input +/// wake. Called from the key + pointer fanout prologues immediately +/// after `last_activity` is updated to "now". The semantic is: +/// `old_idle = (now - prior_last_activity)`, `new_idle = 0`. Fires any +/// alarms whose trigger crosses on this transition. +/// +/// `device_id` identifies which per-device counter to evaluate; pass +/// 2 for pointer events (drives IDLETIME_DEVICE_VCP), 3 for key events +/// (drives IDLETIME_DEVICE_VCK). The global IDLETIME counter is +/// evaluated unconditionally because any input resets the global +/// last_activity. +pub(crate) fn evaluate_idletime_negative_alarms_on_input_wake( + state: &mut ServerState, + device_id: u8, + prior_global_idle_ms: i64, + prior_device_idle_ms: i64, +) { + use yserver_protocol::x11::sync as x11sync; + // Suspend gate (Xorg WaitFor.c:519). When XScreenSaverSuspend is + // held, the unified timer is not armed in either direction — + // including the input-wake firing of Negative-* alarms. Without + // this gate, an input event during fullscreen video would still + // fire MATE's wake alarms and could prompt mate-power-manager to + // re-arm screen-blanking too aggressively. + if !state.screensaver.suspend_counts.is_empty() { + return; + } + // Global IDLETIME: always reset on any input. + crate::core_loop::sync_await::counter_changed( + state, + x11sync::IDLETIME_COUNTER, + prior_global_idle_ms, + 0, + ); + state + .idletime_last_evaluated + .insert(x11sync::IDLETIME_COUNTER, 0); + + // Per-device IDLETIME: only the affected device resets. + let device_counter = match device_id { + 2 => x11sync::IDLETIME_DEVICE_VCP, + 3 => x11sync::IDLETIME_DEVICE_VCK, + _ => return, + }; + crate::core_loop::sync_await::counter_changed(state, device_counter, prior_device_idle_ms, 0); + state.idletime_last_evaluated.insert(device_counter, 0); +} + +/// Reset IDLETIME bookkeeping when the suspend-counts table drains to +/// empty. Must be called at the SAME spot the existing MIT-SCREEN-SAVER +/// code resets `state.dpms.last_activity` (SS Suspend handler + +/// process_disconnect's last-suspender cleanup). +/// +/// Without this, IDLETIME alarms can be skipped post-suspend because +/// `idletime_last_evaluated` holds stale-high values from before the +/// suspend, causing `evaluate_alarms_for_counter`'s +/// `old < wait <= new` Transition check to never hold. +pub(crate) fn reset_idletime_state_after_suspend_release(state: &mut ServerState) { + let now = std::time::Instant::now(); + // dpms.last_activity is already reset by the caller. Reset the + // per-device baselines so post-resume per-device IDLETIME + // computation is consistent. + for entry in state.per_device_last_activity.values_mut() { + *entry = now; + } + // Clear the evaluator's last-seen cache so the next post-poll pass + // computes `(old=0, new=current)` from a clean slate, preserving + // the Transition `old < wait <= new` invariant. + state.idletime_last_evaluated.clear(); +} + +pub(super) fn handle_dpms_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use crate::nested::DPMS_MAJOR_OPCODE; + use yserver_protocol::x11::{ClientByteOrder, dpms as x11dpms}; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + debug!( + "client {} #{} DPMS::minor={} body_len={}", + client_id.0, + sequence.0, + minor, + body.len() + ); + match minor { + x11dpms::GET_VERSION => { + let reply = x11dpms::encode_get_version_reply( + byte_order, + sequence, + x11dpms::MAJOR_VERSION, + x11dpms::MINOR_VERSION, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11dpms::CAPABLE => { + let reply = x11dpms::encode_capable_reply(byte_order, sequence, state.dpms.kms_capable); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11dpms::GET_TIMEOUTS => { + #[allow(clippy::cast_possible_truncation)] + let s = (state.dpms.standby_ms / 1000) as u16; + #[allow(clippy::cast_possible_truncation)] + let su = (state.dpms.suspend_ms / 1000) as u16; + #[allow(clippy::cast_possible_truncation)] + let o = (state.dpms.off_ms / 1000) as u16; + let reply = x11dpms::encode_get_timeouts_reply(byte_order, sequence, s, su, o); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11dpms::SET_TIMEOUTS => { + let Some((standby, suspend, off)) = x11dpms::parse_set_timeouts_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + }; + // Zero = "this level disabled". Among non-zero values + // require off >= suspend >= standby. Xorg `:370-376`. + let nonzero_violates = |a: u16, b: u16| a != 0 && b != 0 && a > b; + // Report the value being compared against (the one that + // "should have been bigger"), matching Xorg dpms.c:373. + if nonzero_violates(suspend, off) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(off), + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + } + if nonzero_violates(standby, suspend) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(suspend), + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + } + state.dpms.standby_ms = u32::from(standby) * 1000; + state.dpms.suspend_ms = u32::from(suspend) * 1000; + state.dpms.off_ms = u32::from(off) * 1000; + } + x11dpms::ENABLE => { + if !state.dpms.enabled { + state.dpms.enabled = true; + emit_dpms_notify(state); + } + } + x11dpms::DISABLE => { + let was_enabled = state.dpms.enabled; + // Force level back to On (calls notify iff level changed). + apply_dpms_transition(state, backend, 0); + if was_enabled { + state.dpms.enabled = false; + emit_dpms_notify(state); + } + } + x11dpms::FORCE_LEVEL => { + if !state.dpms.enabled { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + } + let Some(level) = x11dpms::parse_force_level_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + }; + if level > 3 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(level), + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + } + #[allow(clippy::cast_possible_truncation)] + apply_dpms_transition(state, backend, level as u8); + } + x11dpms::INFO => { + let reply = x11dpms::encode_info_reply( + byte_order, + sequence, + u16::from(state.dpms.power_level), + state.dpms.enabled, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11dpms::SELECT_INPUT => { + let Some(mask) = x11dpms::parse_select_input_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + }; + if mask & !x11dpms::DPMS_INFO_NOTIFY_MASK != 0 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + mask, + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + } + if mask & x11dpms::DPMS_INFO_NOTIFY_MASK != 0 { + state.dpms.selected_by.insert(client_id); + } else { + state.dpms.selected_by.remove(&client_id); + } + } + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(header.data), + DPMS_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_screen_saver_request( + state: &mut ServerState, + _backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use crate::nested::MIT_SCREEN_SAVER_MAJOR_OPCODE; + use yserver_protocol::x11::{ClientByteOrder, screensaver as x11ss}; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + let minor_u16 = u16::from(minor); + debug!( + "client {} #{} ScreenSaver::minor={} body_len={}", + client_id.0, + sequence.0, + minor, + body.len() + ); + + match minor { + x11ss::QUERY_VERSION => { + let reply = x11ss::encode_query_version_reply( + byte_order, + sequence, + x11ss::SERVER_MAJOR_VERSION, + x11ss::SERVER_MINOR_VERSION, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11ss::QUERY_INFO => { + if x11ss::parse_query_info_request(body).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ); + } + debug_assert!( + !matches!(state.screensaver.active, ScreenSaverActive::Cycle), + "Cycle must never appear in screensaver.active — \ + see apply_screen_saver_transition guard" + ); + // X11 timestamps are 32-bit ms; wraps at ~49 days per X11 spec. + #[allow(clippy::cast_possible_truncation)] + let last_input = state.dpms.last_activity.elapsed().as_millis() as u32; + let timeout = state.screensaver.timeout_ms; + let (reply_state, til_or_since) = match state.screensaver.active { + ScreenSaverActive::On => { + let ts = last_input.wrapping_sub(timeout); + (x11ss::SCREEN_SAVER_ON, if timeout > 0 { ts } else { 0 }) + } + ScreenSaverActive::Off | ScreenSaverActive::Cycle => { + if timeout == 0 { + (x11ss::SCREEN_SAVER_DISABLED, 0) + } else if timeout < last_input { + (x11ss::SCREEN_SAVER_OFF, 0) + } else { + (x11ss::SCREEN_SAVER_OFF, timeout - last_input) + } + } + }; + let event_mask = state + .screensaver + .selected_by + .get(&client_id) + .copied() + .unwrap_or(0); + let kind = screen_saver_kind(state); + let reply = x11ss::encode_query_info_reply( + byte_order, + sequence, + reply_state, + crate::resources::SCREEN_SAVER_WINDOW.0, + til_or_since, + last_input, + event_mask, + kind, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11ss::SELECT_INPUT => { + let Some((_drawable, mask)) = x11ss::parse_select_input_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ); + }; + if mask == 0 { + state.screensaver.selected_by.remove(&client_id); + } else { + state.screensaver.selected_by.insert(client_id, mask); + } + } + x11ss::SET_ATTRIBUTES => { + return match screen_saver_set_attributes(state, client_id, body) { + Ok(()) => Ok(RequestOutcome::Handled), + Err((code, value)) => emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ), + }; + } + x11ss::UNSET_ATTRIBUTES => { + let Some(drawable) = x11ss::parse_unset_attributes_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ); + }; + if !drawable_exists(state, ResourceId(drawable)) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + drawable, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ); + } + unset_screen_saver_attributes(state, _backend, client_id); + } + x11ss::SUSPEND => { + let Some(suspend) = x11ss::parse_suspend_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ); + }; + if suspend { + *state + .screensaver + .suspend_counts + .entry(client_id) + .or_insert(0) += 1; + } else { + let drained = match state.screensaver.suspend_counts.get_mut(&client_id) { + Some(c) if *c > 1 => { + *c -= 1; + false + } + Some(_) => { + state.screensaver.suspend_counts.remove(&client_id); + true + } + None => false, + }; + if drained + && state.screensaver.suspend_counts.is_empty() + && matches!(state.screensaver.active, ScreenSaverActive::Off) + && state.dpms.power_level == 0 + { + // Mirrors ScreenSaverFreeSuspend (saver.c:343-378): + // restart the idle clock from now. No notify fires. + state.dpms.last_activity = std::time::Instant::now(); + reset_idletime_state_after_suspend_release(state); + } + } + } + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + minor_u16, + MIT_SCREEN_SAVER_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// GetScreenSaver (108): reflects ScreenSaverState back to the client. +pub(super) fn handle_get_screen_saver( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} GetScreenSaver", client_id.0, sequence.0); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf = x11::fixed_reply(byte_order, sequence, 0, 0); + #[allow(clippy::cast_possible_truncation)] + let timeout = (state.screensaver.timeout_ms / 1000) as u16; + #[allow(clippy::cast_possible_truncation)] + let interval = (state.screensaver.interval_ms / 1000) as u16; + x11::write_u16(byte_order, &mut buf, timeout); + x11::write_u16(byte_order, &mut buf, interval); + buf.push(u8::from(state.screensaver.prefer_blanking)); + buf.push(u8::from(state.screensaver.allow_exposures)); + buf.resize(32, 0); + Ok(write_to_client(client, client_id, &buf)) +} + +/// SetScreenSaver (107): body is `timeout:i16 interval:i16 +/// prefer_blanking:u8 allow_exposures:u8 pad:u16` (8 bytes). +/// +/// Sentinel resolution matches Xorg `dix/globals.c:96-99`: +/// -1 (timeout/interval) → restore 600s default +/// 2 (prefer_blanking/allow_expo) → restore the default value +pub(super) fn handle_set_screen_saver( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + // Body layout: timeout:i16 interval:i16 prefer_blanking:u8 + // allow_exposures:u8 pad:u16 = 8 bytes. + if body.len() < 8 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + header.opcode, + ); + } + let timeout = i16::from_le_bytes([body[0], body[1]]); + let interval = i16::from_le_bytes([body[2], body[3]]); + let prefer_blanking = body[4]; + let allow_exposures = body[5]; + + if !(-1..=0x7fff).contains(&i32::from(timeout)) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(timeout as u16), + header.opcode, + ); + } + if !(-1..=0x7fff).contains(&i32::from(interval)) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(interval as u16), + header.opcode, + ); + } + if prefer_blanking > 2 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(prefer_blanking), + header.opcode, + ); + } + if allow_exposures > 2 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(allow_exposures), + header.opcode, + ); + } + + state.screensaver.timeout_ms = match timeout { + -1 => 600_000, + n => u32::from(n as u16) * 1000, // n is already ≥ 0 (validated above) + }; + state.screensaver.interval_ms = match interval { + -1 => 600_000, + n => u32::from(n as u16) * 1000, // n is already ≥ 0 (validated above) + }; + state.screensaver.prefer_blanking = match prefer_blanking { + 0 => false, + 1 => true, + _ => true, // 2 = Default; Xorg defaultScreenSaverBlanking = PreferBlanking + }; + state.screensaver.allow_exposures = match allow_exposures { + 0 => false, + 1 => true, + _ => true, // 2 = Default; Xorg defaultScreenSaverAllowExposures = AllowExposures + }; + + // No last_activity reset — Xorg's ProcSetScreenSaver only calls + // SetScreenSaverTimer(), which recomputes the deadline from the + // unchanged LastEventTime. yserver computes the deadline lazily + // at every poll iteration; the next iteration sees the new + // timeout_ms against the unchanged last_activity. + + Ok(RequestOutcome::Handled) +} + +/// ForceScreenSaver (115): `mode` lives in the request header's +/// `data` byte (Fixed(1) in the core length table — no body bytes). +/// mode=0 (Reset) → force Off + bump last_activity. +/// mode=1 (Activate) → force On. +pub(super) fn handle_force_screen_saver( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, +) -> io::Result { + let mode = header.data; // u8 stashed in the request header's data byte + if mode > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mode), + header.opcode, + ); + } + if mode == 0 { + apply_screen_saver_transition( + state, + backend, + ScreenSaverActive::Off, + /*forced=*/ true, + ); + state.dpms.last_activity = std::time::Instant::now(); + } else { + apply_screen_saver_transition(state, backend, ScreenSaverActive::On, /*forced=*/ true); + } + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/selection.rs b/crates/yserver-core/src/core_loop/process_request/selection.rs new file mode 100644 index 000000000..a8d7d4d21 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/selection.rs @@ -0,0 +1,759 @@ +use crate::{ + access::{AccessMode, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::Backend, + core_loop::{ + fanout::{ + client_target_id, fanout_event_to_clients, fanout_raw_event_to_clients, + selection_owner_target_id, subscribers_by_id, + }, + process_request::{RequestOutcome, emit_x11_error, write_to_client}, + }, + resources::ROOT_WINDOW, + server::{SelectionOwner, ServerState}, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{AtomId, ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +pub(super) fn handle_set_selection_owner( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 8 { + debug!( + "client {} #{} SetSelectionOwner (short body)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let selection = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let time_val = if body.len() >= 12 { + u32::from_le_bytes([body[8], body[9], body[10], body[11]]) + } else { + 0u32 + }; + + // Xorg `dixSetSelectionOwner` (dix/selection.c:156-211) ordering: + // 1. Reject future timestamps silently (line 166-167) + // 2. Validate the window, check access, then validate the atom + // (line 169-178) — we accept any window here pre-existing + // behaviour; tightening that is a separate audit item + // 3. Reject stale timestamps silently vs prior lastTimeChanged + // (line 192-193) + // 4. Update ownership + lastTimeChanged (line 204-207) + // 5. Call the SelectionCallback → XFixesSelectionNotify + // with timestamp = currentTime, selection_timestamp = the + // *new* lastTimeChanged (xfixes/select.c:88-89) + if time_val != 0 && time_val > state.timestamp_now() { + // Future-shifted: silent no-op (Success per Xorg). + return Ok(RequestOutcome::Handled); + } + // BadWindow if `window != None` and the xid doesn't resolve + // (`dix/selection.c:169-173`). `window == 0` (None) means + // "release ownership" and is the only valid non-existent value. + // The major opcode in the error reply is the core + // SetSelectionOwner opcode (22), not 0 — clients keying on + // `major_opcode` see a malformed error otherwise. + if window.0 != 0 && state.resources.window(window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 22, + ); + } + if window.0 != 0 + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 22); + } + // BadAtom if the selection atom isn't allocated + // (`dix/selection.c:175-178`). `state.atoms.exists` is the + // equivalent of Xorg's `ValidAtom`. + if !state.atoms.exists(selection) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + selection.0, + 22, + ); + } + apply_set_selection_owner(state, client_id, sequence, window, selection, time_val); + Ok(RequestOutcome::Handled) +} + +/// SetSelectionOwner after validation: `window` is `None` or a window +/// `client_id` may set attributes on, and `selection` an atom. A time in +/// the future or before the selection's last change is ignored, as the +/// request's. +pub(crate) fn apply_set_selection_owner( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + window: ResourceId, + selection: AtomId, + time_val: u32, +) { + let current_time = state.timestamp_now(); + // `ClientTimeToServerTime`: X11 time=0 (`CurrentTime`) resolves + // to the server's current time; otherwise the client's value + // wins, unless it is in the future (step 1 of the handler's order), + // which is ignored. + let resolved_time = if time_val == 0 { + current_time + } else { + time_val + }; + if time_val != 0 && time_val > current_time { + return; + } + if let Some(prior) = state.selections.get(&selection) + && resolved_time < prior.last_time_changed + { + // Stale: silent no-op. + return; + } + // Snapshot prior ownership BEFORE we mutate state.selections so + // the SelectionClear gate / event payload sees the previous + // owner: its window and the client that set it. A release (None) + // keeps the record with its time and `client = NullClient` + // (`dix/selection.c:204-207`), creating it if the selection was never + // set (`:196-213`). + let old = state.selections.get(&selection).copied(); + state.selections.insert( + selection, + SelectionOwner { + window, + last_time_changed: resolved_time, + client: (window.0 != 0).then_some(client_id), + }, + ); + let name = state.atoms.name(selection).map(str::to_owned); + debug!( + "client {} #{} SetSelectionOwner {} -> 0x{:x}", + client_id.0, + sequence.0, + name.as_deref().unwrap_or("?"), + window.0 + ); + + // SelectionClear gating per Xorg `dix/selection.c:183-191`: + // if (pSel->client && (!pWin || (pSel->client != client))) + // i.e. fire only when there WAS a prior owner AND either the + // new owner is None OR the setting client differs. `pSel->client` + // is the client that set the prior owner, not the owner window's + // creator, and the SelectionClear goes to it. The event's time field carries the resolved + // server time (`time.milliseconds` post-`ClientTimeToServerTime` + // at line 185), not the raw `time_val` — a client sending + // `CurrentTime`/0 must NOT see 0 in the event payload. + if let Some(old) = old + && let Some(old_client) = old.client + && (window.0 == 0 || old_client != client_id) + { + let old_window = old.window; + // The server's selection window has no connection: its rootless + // host hears the SelectionClear instead. + if !crate::rootless::selection::note_selection_clear(state, &old, selection, resolved_time) + && let Some(old_target) = client_target_id(state, old_client) + { + let _dropped = fanout_event_to_clients(state, &[old_target], |buf, seq, order| { + x11::encode_selection_clear_event( + buf, + seq, + order, + resolved_time, + old_window, + selection, + ); + }); + } + } + + // Audit #9 (docs/protocol-audit-2026-05-19.md) — fire + // XFixesSelectionNotify(SetSelectionOwner) to every client that + // subscribed to this selection via `SelectSelectionInput` with + // the matching mask bit. Xorg fires this from + // `XFixesSelectionCallback` (`xfixes/select.c:158-210`) which + // is registered as a `SelectionCallback` against the core + // selection-mgmt code. Without it, clipboard managers wedge + // forever waiting for the "selection changed" signal. + // + // Wire payload per Xorg `xfixes/select.c:88-89`: + // timestamp = currentTime (NOT the request's time arg) + // selection_timestamp = pSel->lastTimeChanged (= resolved_time + // we just stored) + fanout_xfixes_selection_notify( + state, + selection, + yserver_protocol::x11::xfixes::SELECTION_NOTIFY_SET_OWNER, + window.0, + current_time, + resolved_time, + ); +} + +/// Xorg `DeleteWindowFromAnySelections` (`dix/selection.c:113-125`): every +/// selection owned by one of `owned_windows` fires +/// `XFixesSelectionNotify(subtype)` and is cleared. `destroy_window_subtree` +/// passes `SelectionWindowDestroy`. +pub(super) fn drop_selections_owned_by_windows( + state: &mut ServerState, + owned_windows: &[ResourceId], + subtype: u8, +) { + drop_selections_where(state, subtype, |owner| { + owned_windows.contains(&owner.window) + }); +} + +/// Xorg `DeleteClientFromAnySelections` (`dix/selection.c:128-139`), run by +/// `CloseDownClient` (`dix/dispatch.c:3495`) before the client's resources +/// go: every selection `cid` set fires +/// `XFixesSelectionNotify(SelectionClientClose)` and is cleared, whoever owns +/// its window. A selection another client set on one of `cid`'s windows is +/// left for the window's destruction (SelectionWindowDestroy). +pub(crate) fn fanout_xfixes_selection_client_close_for_client( + state: &mut ServerState, + cid: ClientId, +) { + drop_selections_where( + state, + yserver_protocol::x11::xfixes::SELECTION_NOTIFY_CLIENT_CLOSE, + |owner| owner.client == Some(cid), + ); +} + +fn drop_selections_where( + state: &mut ServerState, + subtype: u8, + matches: impl Fn(&SelectionOwner) -> bool, +) { + // Capture (selection, prior_last_time_changed) BEFORE clearing so + // the notify can carry the prior `selection_timestamp` — Xorg + // fires the callback BEFORE mutating `pSel->window`/`pSel->client`, + // and the callback at `xfixes/select.c:89` reads + // `selection->lastTimeChanged`. + let to_drop: Vec<(AtomId, u32)> = state + .selections + .iter() + .filter(|(_, owner)| matches(owner)) + .map(|(sel, owner)| (*sel, owner.last_time_changed)) + .collect(); + if to_drop.is_empty() { + return; + } + // `timestamp_now()` matches Xorg's `UpdateCurrentTimeIf` shape + // (`dix/dispatch.c:226-236`): bare monotonic-ms snapshot, no + // floor. X11 timestamp 0 only has dedicated semantics on the + // INPUT side (request `time` arg = "use CurrentTime"); event + // payloads emitted in the first ms after server start carry the + // actual `0` per Xorg, so the clamp this used to apply was a + // protocol mismatch. + let now = state.timestamp_now(); + for (sel, prior_last_time_changed) in to_drop { + // owner=0 (None) — see Xorg `xfixes/select.c:85-86`: + // destroy/close subtypes always carry owner=None. + fanout_xfixes_selection_notify(state, sel, subtype, 0, now, prior_last_time_changed); + // Xorg keeps the record and its `lastTimeChanged` + // (`dix/selection.c:120-122`, `:134-136`). + if let Some(owner) = state.selections.get_mut(&sel) { + owner.window = ResourceId(0); + owner.client = None; + } + } +} + +/// Audit #9 fanout helper — emits an `XFixesSelectionNotify` to every +/// `SelectSelectionInput` subscription on this selection whose mask +/// includes the matching subtype bit. Each subscription gets its own +/// event (the `window` field carries the *subscriber's* window, not +/// the owner's, per the X11 protocol). +/// +/// `owner_window` is the new owner (or 0 = `None`). `timestamp` is +/// currentTime and `selection_timestamp` the selection's +/// `lastTimeChanged` (`xfixes/select.c:78-89`). +fn fanout_xfixes_selection_notify( + state: &mut ServerState, + selection: AtomId, + subtype: u8, + owner_window: u32, + timestamp: u32, + selection_timestamp: u32, +) { + use yserver_protocol::x11::xfixes as x11xfixes; + + // Xorg's selection callbacks reach every listener of the change; the + // rootless host is one, for the selections it watches. + crate::rootless::selection::note_owner(state, selection, owner_window, selection_timestamp); + let mask_bit = 1u32 << subtype; + // Snapshot matching subscriptions before mutating `state.clients` + // inside the fanout writer (which needs `&mut state`). + let matched: Vec<(ClientId, u32)> = state + .xfixes_selection_masks + .iter() + .filter_map(|((cid, win, sel), mask)| { + if *sel == selection && mask & mask_bit != 0 { + Some((ClientId(*cid), win.0)) + } else { + None + } + }) + .collect(); + for (cid, subscriber_window) in matched { + let _dropped = fanout_event_to_clients(state, &[cid], |buf, seq, order| { + x11xfixes::encode_selection_notify_event( + buf, + order, + crate::nested::XFIXES_FIRST_EVENT, + subtype, + seq, + subscriber_window, + owner_window, + selection.0, + timestamp, + selection_timestamp, + ); + }); + } +} + +pub(super) fn handle_convert_selection( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if body.len() < 20 { + return Ok(RequestOutcome::Handled); + } + let requestor = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let selection = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let target_atom = AtomId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let property = AtomId(u32::from_le_bytes([body[12], body[13], body[14], body[15]])); + let time_val = u32::from_le_bytes([body[16], body[17], body[18], body[19]]); + + // BadWindow for the requestor, then BadAtom carrying the property as its + // value whichever atom is bad (`dix/selection.c:271-280`). + if state.resources.window(requestor).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + requestor.0, + 24, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: requestor, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 24); + } + if !state.atoms.exists(selection) + || !state.atoms.exists(target_atom) + || (property.0 != 0 && !state.atoms.exists(property)) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ATOM, + property.0, + 24, + ); + } + apply_convert_selection( + state, + client_id, + sequence, + requestor, + [selection, target_atom, property], + time_val, + ); + Ok(RequestOutcome::Handled) +} + +/// ConvertSelection after validation: `requestor` is a window `client_id` +/// may set attributes on, and `selection`, `target_atom` and `property` +/// (unless `None`) are atoms. +pub(crate) fn apply_convert_selection( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + requestor: ResourceId, + [selection, target_atom, property]: [AtomId; 3], + time_val: u32, +) { + // A selection the server's own window owns is answered by the rootless + // host that made it, which has no connection for the SelectionRequest. + if let Some(owner) = state + .selections + .get(&selection) + .copied() + .filter(|owner| owner.window.0 != 0) + && crate::rootless::selection::note_request( + state, + &owner, + crate::rootless::SelectionEvent::Request { + time: time_val, + requestor, + selection, + target: target_atom, + property, + }, + ) + { + debug!( + "client {} #{} ConvertSelection -> the server's window 0x{:x}", + client_id.0, sequence.0, owner.window.0 + ); + return; + } + + if let Some((owner_window, owner_id)) = selection_owner_target_id(state, selection) { + let _dropped = fanout_event_to_clients(state, &[owner_id], |buf, seq, order| { + x11::encode_selection_request_event( + buf, + seq, + order, + time_val, + owner_window, + requestor, + selection, + target_atom, + property, + ); + }); + debug!( + "client {} #{} ConvertSelection -> owner 0x{:x}", + client_id.0, sequence.0, owner_window.0 + ); + } else if crate::rootless::selection::note_refusal(state, requestor, selection, target_atom) { + // No owner, and the server's window asked: its host hears it. + } else { + // No owner, or its setter is gone (`dix/selection.c:297-301`): + // SelectionNotify(None) to the client that issued ConvertSelection + // (`dix/selection.c:304-311`), whoever created the requestor window. + if let Some(rt) = client_target_id(state, client_id) { + let mut template = [0u8; 32]; + template[0] = 31; // SelectionNotify + template[4..8].copy_from_slice(&time_val.to_le_bytes()); + template[8..12].copy_from_slice(&requestor.0.to_le_bytes()); + template[12..16].copy_from_slice(&selection.0.to_le_bytes()); + template[16..20].copy_from_slice(&target_atom.0.to_le_bytes()); + // property = 0 (None): conversion failed. + let _dropped = fanout_raw_event_to_clients( + state, + &[rt], + &template, + yserver_protocol::x11::ClientByteOrder::LittleEndian, + ); + } + debug!( + "client {} #{} ConvertSelection: no owner, sent SelectionNotify(None)", + client_id.0, sequence.0 + ); + } +} + +pub(super) fn handle_send_event( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::ClientByteOrder; + // The 32-byte event template inside SendEvent is in the *sender's* + // byte order. Note: the request body's typed prefix (destination + + // event_mask) was already swapped to LE by request_swap; only the + // template itself stays in the sender's byte order so we can + // re-encode per recipient. + let sender_byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let Some(req) = x11::send_event_request(header.data, body) else { + debug!( + "client {} #{} SendEvent (parse failed)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + }; + // Xorg `ProcSendEvent` (dix/events.c:5563-5590) validates the template + // and mask before resolving the destination. + let event_type = req.event[0] & 0x7f; + if !matches!(event_type, 2..=34 | 64..) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(event_type), + 25, + ); + } + if event_type == 33 && !matches!(req.event[1], 8 | 16 | 32) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.event[1]), + 25, + ); + } + if req.event_mask & !ALL_EVENT_MASKS != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.event_mask, + 25, + ); + } + // A SelectionNotify for the server's own selection window, the answer + // to the rootless host's ConvertSelection: the host takes it, as no + // client can. + if event_type == 31 { + let word = |at: usize| { + let bytes = [ + req.event[at], + req.event[at + 1], + req.event[at + 2], + req.event[at + 3], + ]; + match sender_byte_order { + ClientByteOrder::BigEndian => u32::from_be_bytes(bytes), + ClientByteOrder::LittleEndian => u32::from_le_bytes(bytes), + } + }; + if crate::rootless::selection::note_selection_notify( + state, + req.destination, + [word(12), word(16), word(20)], + ) { + debug!( + "client {} #{} SendEvent SelectionNotify to the server's window 0x{:x}", + client_id.0, sequence.0, req.destination.0 + ); + return Ok(RequestOutcome::Handled); + } + } + let targets = match send_event_recipients(state, req.destination, req.event_mask, header.data) { + Ok(targets) => targets, + Err((code, value)) => return emit_x11_error(state, client_id, sequence, code, value, 25), + }; + // Set the sent-event bit (bit 7 of first byte). + let mut event_copy = *req.event; + event_copy[0] |= 0x80; + let _dropped = fanout_raw_event_to_clients(state, &targets, &event_copy, sender_byte_order); + crate::rootless::note_root_client_message( + state, + backend, + req.destination, + req.event, + sender_byte_order, + ); + let core_type_logged = req.event[0] & 0x7f; + // For synthetic ConfigureNotify (type=22), decode and log x/y/w/h + // so we can see what the WM tells clients about their root + // position. The wire body (after the 4-byte type/seq prefix) is: + // event_window(4) + window(4) + above_sibling(4) + + // x(2) + y(2) + width(2) + height(2) + border(2) + + // override_redirect(1) + pad(1) + if core_type_logged == 22 { + let e = &req.event; + let event_w = u32::from_le_bytes([e[4], e[5], e[6], e[7]]); + let window_w = u32::from_le_bytes([e[8], e[9], e[10], e[11]]); + let above = u32::from_le_bytes([e[12], e[13], e[14], e[15]]); + let x = i16::from_le_bytes([e[16], e[17]]); + let y = i16::from_le_bytes([e[18], e[19]]); + let w = u16::from_le_bytes([e[20], e[21]]); + let h = u16::from_le_bytes([e[22], e[23]]); + let bw = u16::from_le_bytes([e[24], e[25]]); + let or = e[26]; + debug!( + "client {} #{} SendEvent type=22 (ConfigureNotify) dest=0x{:x} \ + ev_win=0x{:x} win=0x{:x} above=0x{:x} pos=({},{}) size=({}x{}) \ + border={} override={} targets={:?}", + client_id.0, + sequence.0, + req.destination.0, + event_w, + window_w, + above, + x, + y, + w, + h, + bw, + or, + targets.iter().map(|c| c.0).collect::>(), + ); + } else { + debug!( + "client {} #{} SendEvent type={} dest=0x{:x} event_mask=0x{:x} propagate={} targets={:?}", + client_id.0, + sequence.0, + core_type_logged, + req.destination.0, + req.event_mask, + req.propagate, + targets.iter().map(|c| c.0).collect::>(), + ); + } + Ok(RequestOutcome::Handled) +} + +/// Xorg `AllEventMasks` (`include/inputstr.h`): the 25 core event-mask bits. +const ALL_EVENT_MASKS: u32 = 0x01FF_FFFF; + +/// The clients a `SendEvent` reaches — Xorg `ProcSendEvent` +/// (`dix/events.c:5592-5640`) with `DeliverEventsToWindow` +/// (`dix/events.c:2364`). A core event template is matched against CORE +/// event masks only: `GetClientsForDelivery` (`dix/events.c:2241`) takes the +/// window's core `OtherClients` for any core type, so an XI2 selection never +/// filters a synthetic core event, and `SendEvent` never produces XI2 events. +/// +/// `Err((code, value))` is the X error to raise. +pub(crate) fn send_event_recipients( + state: &ServerState, + destination: ResourceId, + event_mask: u32, + propagate: u8, +) -> Result, (u8, u32)> { + let sprite = state + .root_pointer_target_at(state.pointer_root.0, state.pointer_root.1) + .map_or(ROOT_WINDOW, |(w, _, _)| w); + let mut effective_focus = None; + let mut window = match destination.0 { + 0 => sprite, + 1 => { + let focus = match state.core_focus.raw { + 0 => return Ok(Vec::new()), + 1 => ROOT_WINDOW, + w => ResourceId(w), + }; + // `IsParent(inputFocus, pSprite->win)`: the pointer is in a + // strict inferior of the focus window. + let window = if is_strict_ancestor(state, focus, sprite) { + sprite + } else { + focus + }; + effective_focus = Some(focus); + window + } + _ => { + if state.resources.window(destination).is_none() { + return Err((x11::error::BAD_WINDOW, destination.0)); + } + destination + } + }; + if propagate > 1 { + return Err((x11::error::BAD_VALUE, u32::from(propagate))); + } + let mut mask = event_mask; + loop { + let targets: Vec = if mask == 0 { + // `CantBeFiltered`: only the window's creator, never the server. + state + .resources + .window_owner(window) + .filter(|_| window != ROOT_WINDOW) + .and_then(|owner| client_target_id(state, owner)) + .into_iter() + .collect() + } else { + subscribers_by_id(state, window, mask) + }; + if !targets.is_empty() || propagate == 0 || effective_focus == Some(window) { + return Ok(targets); + } + let Some(win) = state.resources.window(window) else { + return Ok(Vec::new()); + }; + mask &= !u32::from(win.do_not_propagate_mask); + if mask == 0 || win.parent == window { + return Ok(Vec::new()); + } + window = win.parent; + } +} + +/// Xorg `IsParent(a, b)`: `a` is a strict ancestor of `b`. +fn is_strict_ancestor(state: &ServerState, ancestor: ResourceId, window: ResourceId) -> bool { + let mut current = window; + while let Some(parent) = state.resources.parent_of(current) { + if parent == current { + return false; + } + if parent == ancestor { + return true; + } + current = parent; + } + false +} + +pub(super) fn handle_get_selection_owner( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + let owner = if body.len() >= 4 { + let selection = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + state + .selections + .get(&selection) + .map_or(ResourceId(0), |owner| owner.window) + } else { + ResourceId(0) + }; + debug!( + "client {} #{} GetSelectionOwner -> 0x{:x}", + client_id.0, sequence.0, owner.0 + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_get_selection_owner_reply(&mut buf, byte_order, sequence, owner)?; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/shape_xfixes.rs b/crates/yserver-core/src/core_loop/process_request/shape_xfixes.rs new file mode 100644 index 000000000..5e9d338eb --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/shape_xfixes.rs @@ -0,0 +1,1878 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::fanout_event_to_clients, + process_request::{ + RequestOutcome, XFIXES_MAJOR_OPCODE, XI2_FIRST_ERROR, emit_x11_error, + emit_x11_error_with_minor, gc_pixmap_cursor::release_displaced_gc_pixmaps, + windows::send_exposures, write_to_client, xid_out_of_client_range, + }, + }, + region::Region, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::{debug, trace}; +use std::io; +use yserver_protocol::{ + x11, + x11::{AtomId, ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +pub(super) fn mirror_shape_to_host_state( + state: &ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + kind: u8, +) { + use yserver_protocol::x11::shape as x11shape; + // Mirror Bounding, Clip, AND Input shapes to the backend. Pre-fix + // (2026-05-26 adapta-nokto investigation): only Bounding/Clip were + // mirrored, so the backend's `core.shape_input` never reflected a + // window's SHAPE Input region. That broke v2's `cursor_inside_shape` + // hit-test for windows with non-default Input shapes — notably + // adapta-nokto's MATE panel menu, which sets a shrunken Input shape + // (`{x=16, y=12, w=188, h=227}` inside a 220x260 window) to make + // the CSS box-shadow margin click-through. Without the Input shape + // in the backend, `window_under_cursor` HIT the menu in its shadow + // zone (window-local Y < 12), the protocol-layer fanout's hit-test + // disagreed (it correctly excluded the shadow), and the Enter + // event yserver emitted on the menu's host xid got re-routed by + // the fanout to whatever's structurally under the cursor (the + // panel) — never reaching the menu's client. GTK menu hover + // state machine never engaged → no highlight, no click. + if kind != x11shape::KIND_BOUNDING + && kind != x11shape::KIND_CLIP + && kind != x11shape::KIND_INPUT + { + return; + } + let Some(w) = state.resources.window(window) else { + return; + }; + let Some(host_xid) = w.host_xid else { + return; + }; + // Multi-monitor Bug A: a window with NO explicitly-set Bounding shape + // is unshaped — its effective bounding region is the *live* window + // geometry, which the backend scene already honors via the full-window + // emit path. `shape_rects_for` would instead materialize + // `default_shape_rect` (the geometry at THIS instant) into a concrete + // rect; mirroring that freezes a fixed extent into the backend's + // `shape_bounding` that goes stale when the window is later resized. + // The Composite Overlay Window is the load-bearing case: marco resets + // its Bounding shape to None while the screen is single-head, we froze + // (0,0 2560x1440), then RANDR grew the COW to 5120 on apply — the scene + // kept clipping the now-5120 COW to the stale 2560 rect, so the 2nd + // output sampled the wrong (left) half placed off-screen and screen 2 + // went dark. For an unset Bounding shape, mirror EMPTY rects so the + // backend drops the entry and the scene tracks live geometry (Xorg + // parity: a None bounding region is never materialized into a rect). + // + // CLIP joined Bounding on 2026-09-08 (#133). The note here used to say + // "Clip/Input keep mirroring the default rect — the scene's compose clip + // only consults Bounding"; #133 step 5 made the walk clip DESCENDANTS to + // the parent's clip shape (`SetWinSize` intersects winSize with it, + // `dix/window.c:1735`), which retired that premise and turned the frozen + // rect into a visible defect. Measured in vng: awesome resets its client + // frame's clip shape with `ShapeMask(Clip, src=None)` while the frame is + // 820x583, we froze that rect, and after the tiling resize to 608x734 the + // client was clipped 168 rows short — leaving the frame's uninitialised + // storage on screen as a white block. Xorg on the identical scenario has + // no white pixel at all, because an unset clip region is never + // materialized there either. + // + // Input still mirrors the default rect: it drives the cursor hit-test, + // which wants a concrete region and does not clip descendants. + if (kind == x11shape::KIND_BOUNDING || kind == x11shape::KIND_CLIP) + && !crate::nested::shape_kind_is_set(state, window, kind) + { + // Unset Bounding/Clip shape → None (drop the backend entry; the scene + // tracks live window geometry). Distinct from an explicit empty + // region — see set_shape_rectangles' Option contract (DRIFT 1). + let _ = backend.set_shape_rectangles(origin, host_xid.as_raw(), kind, None); + return; + } + let rects = crate::nested::shape_rects_for(state, window, kind); + // Explicit shape (Some), possibly empty — `Some(&[])` is an empty + // region (click-through / drawn-as-nothing), NOT unset. + let _ = backend.set_shape_rectangles(origin, host_xid.as_raw(), kind, Some(&rects)); +} + +pub(super) fn drawable_full_rect_xfixes( + state: &ServerState, + drawable: ResourceId, +) -> yserver_protocol::x11::xfixes::RegionRect { + use yserver_protocol::x11::xfixes; + if let Some(window) = state.resources.window(drawable) { + return xfixes::RegionRect { + x: 0, + y: 0, + width: window.width, + height: window.height, + }; + } + state.resources.pixmap(drawable).map_or( + xfixes::RegionRect { + x: 0, + y: 0, + width: 0, + height: 0, + }, + |pixmap| xfixes::RegionRect { + x: 0, + y: 0, + width: pixmap.width, + height: pixmap.height, + }, + ) +} + +pub(super) fn normalize_region_rects( + rects: Vec, +) -> Vec { + crate::nested::normalize_region_rects(rects) +} + +pub(super) fn format_region_rects(rects: &[yserver_protocol::x11::xfixes::RegionRect]) -> String { + use std::fmt::Write as _; + + let mut out = String::from("["); + for (i, rect) in rects.iter().enumerate() { + if i > 0 { + out.push(' '); + } + let _ = write!( + out, + "({},{} {}x{})", + rect.x, rect.y, rect.width, rect.height + ); + } + out.push(']'); + out +} + +#[allow(clippy::too_many_arguments)] +/// Emit a `ShapeNotify` event to every client that `ShapeSelectInput`'d +/// `window`, after its `kind` region (bounding/clip/input) changed. Xorg's +/// `SendShapeNotify` does this on every shape mutation; yserver previously +/// applied the change to its own store (so its hit-test stayed correct) but +/// never told subscribers, so a compositing WM's cached input region went +/// permanently stale — clicks over the grown region fell through to the +/// window below (cinnamon "nemo rises"). No-op when nobody selected. +pub(super) fn emit_shape_notify(state: &mut ServerState, window: ResourceId, kind: u8) { + let targets: Vec = state + .shape_select_masks + .iter() + .filter_map(|((cid, w), enabled)| (*enabled && *w == window).then_some(ClientId(*cid))) + .collect(); + if targets.is_empty() { + return; + } + let shaped = crate::nested::shape_kind_is_set(state, window, kind); + let extents = crate::nested::shape_region_or_default(state, window, kind).extents_rect(); + let server_time = state.timestamp_now(); + let _dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { + yserver_protocol::x11::shape::encode_shape_notify_event( + buf, + seq, + order, + crate::nested::SHAPE_FIRST_EVENT, + kind, + window.0, + extents, + shaped, + server_time, + ); + }); +} + +/// Compact one-line dump of a SHAPE region's rectangles for the +/// `shape diag` traces, e.g. `[(0,0 306x49)]`. Truncates past 8 rects. +fn fmt_shape_rects(rects: &[yserver_protocol::x11::xfixes::RegionRect]) -> String { + let mut s = String::from("["); + for (i, r) in rects.iter().enumerate() { + if i > 0 { + s.push(' '); + } + if i == 8 { + s.push_str(&format!("…+{}", rects.len() - 8)); + break; + } + s.push_str(&format!("({},{} {}x{})", r.x, r.y, r.width, r.height)); + } + s.push(']'); + s +} + +/// Combine `source` into `window`'s shape of `kind` with SHAPE `op` +/// (Xorg's `RegionOperate`); `true` iff the stored shape changed. +fn shape_combine( + state: &mut ServerState, + window: ResourceId, + kind: u8, + source: Region, + op: u8, +) -> bool { + let current = crate::nested::shape_region(state, window, kind); + let default = || Region::rect(crate::nested::default_shape_rect(state, window, kind)); + match crate::nested::apply_shape_op(current, default, source, op) { + Some(region) => crate::nested::set_shape_region(state, window, kind, region), + None => false, + } +} + +/// A source region moved by a request's offset, as `RegionOperate` and +/// XFIXES SetWindowShapeRegion do: `RegionTranslate`, only when the offset +/// is not zero. +fn offset_source(source: Region, dx: i16, dy: i16) -> Region { + if dx == 0 && dy == 0 { + source + } else { + source.translate_clipped(i32::from(dx), i32::from(dy)) + } +} + +/// `ProcShapeGetRectangles`: the shape's rects, or for an unshaped window +/// one rect that for Bounding and Input is `[-bw, -bw, w + bw, h + bw]` — +/// Xorg's reply, not the default shape, which is `2 * bw` larger. +fn get_rectangles_rects( + state: &ServerState, + window: ResourceId, + kind: u8, +) -> Vec { + use yserver_protocol::x11::{shape as x11shape, xfixes::RegionRect}; + if let Some(region) = crate::nested::shape_region(state, window, kind) { + return region.to_rects(); + } + let Some(w) = state.resources.window(window) else { + return Vec::new(); + }; + if kind == x11shape::KIND_CLIP { + return vec![RegionRect { + x: 0, + y: 0, + width: w.width, + height: w.height, + }]; + } + let bw = w.border_width; + vec![RegionRect { + x: i16::try_from(bw).map_or(i16::MIN, |b| -b), + y: i16::try_from(bw).map_or(i16::MIN, |b| -b), + width: w.width.wrapping_add(bw), + height: w.height.wrapping_add(bw), + }] +} + +/// SHAPE requests, and the exposures a viewable window's new bounding or clip +/// shape makes: Xorg's `miSetShape` (`mi/miwindow.c:637-677`) revalidates +/// the tree, so what the window no longer covers is exposed beneath it +/// and what it newly covers is exposed to it. GDK clips a native window +/// inside a client-side one with its bounding shape and shifts that +/// shape on every scroll; the dialog repaints its button bar below the +/// viewport only on that Expose. +pub(super) fn handle_shape_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::shape as x11shape; + // Rectangles, Mask and Combine carry the destination kind at byte 1, + // Offset at byte 0; all four the destination window at bytes 4..8. + let kind_at = match header.data { + x11shape::RECTANGLES | x11shape::MASK | x11shape::COMBINE => Some(1), + x11shape::OFFSET => Some(0), + _ => None, + }; + let tree_change = kind_at + .filter(|at| { + body.get(*at) + .is_some_and(|k| *k == x11shape::KIND_BOUNDING || *k == x11shape::KIND_CLIP) + }) + .and_then(|_| body.get(4..8)) + .map(|b| ResourceId(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))) + .and_then(|w| crate::core_loop::clip_list::TreeChange::begin(state, w, None)); + let outcome = + handle_shape_request_ops(state, backend, origin, client_id, sequence, header, body)?; + if let Some(change) = tree_change { + send_exposures(state, backend, origin, change.exposed(state, None), None); + } + Ok(outcome) +} + +fn handle_shape_request_ops( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, shape as x11shape}; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + debug!( + "client {} #{} SHAPE::minor={} body_len={}", + client_id.0, + sequence.0, + minor, + body.len() + ); + match minor { + x11shape::QUERY_VERSION => { + let reply = x11shape::encode_query_version_reply(byte_order, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11shape::RECTANGLES => { + if let Some((req, rects)) = x11shape::parse_rectangles_request(body) { + let window = ResourceId(req.dest); + // `ProcShapeRectangles`: an ordering outside the four is + // BadValue, rects not in the claimed order BadMatch. + if req.ordering > x11shape::ORDERING_YX_BANDED { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.ordering), + u16::from(minor), + header.opcode, + ); + } + if !crate::region::verify_rect_order(&rects, req.ordering) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + u16::from(minor), + header.opcode, + ); + } + debug!( + "client {} SHAPE::Rectangles dest=0x{:x} kind={} op={} off=({},{}) nrects={}", + client_id.0, + req.dest, + req.dest_kind, + req.op, + req.x_off, + req.y_off, + rects.len(), + ); + // `RegionFromRects` keeps YXBanded rects as they are. + let source = if req.ordering == x11shape::ORDERING_YX_BANDED { + Region::from_yx_banded(&rects) + } else { + Region::from_wire_rects(&rects) + }; + let source = offset_source(source, req.x_off, req.y_off); + let changed = shape_combine(state, window, req.dest_kind, source, req.op); + mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); + // Xorg miSetShape re-evaluates the pointer before ShapeNotify + // goes out (`mi/miwindow.c:680`); so do the other SHAPE ops. + backend.windows_restructured(state); + if changed { + emit_shape_notify(state, window, req.dest_kind); + } + } + } + x11shape::MASK => { + if let Some(req) = x11shape::parse_mask_request(body) { + let window = ResourceId(req.dest); + debug!( + "client {} SHAPE::Mask dest=0x{:x} kind={} op={} src=0x{:x} off=({},{})", + client_id.0, req.dest, req.dest_kind, req.op, req.src, req.x_off, req.y_off, + ); + if req.src == 0 { + let changed = crate::nested::clear_shape_rects(state, window, req.dest_kind); + mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); + backend.windows_restructured(state); + if changed { + emit_shape_notify(state, window, req.dest_kind); + } + return Ok(RequestOutcome::Handled); + } + // Read the depth-1 mask pixels and YX-band them into + // rectangles. Falls back to the source pixmap's + // bounding-box rect if the backend can't introspect + // (host-X11 proxy mode), preserving the previous + // best-effort behaviour for that path. + let src_id = ResourceId(req.src); + let host_xid = state.resources.pixmap(src_id).and_then(|p| p.host_xid); + let banded = if let Some(host) = host_xid { + match backend.read_depth1_pixmap(origin, host.as_raw()) { + Ok(Some((w, h, bytes))) => { + let rects = crate::nested::bitmap_to_yx_banded_rects(&bytes, w, h); + log::debug!( + "shape diag: MASK src=0x{:x} read_depth1_pixmap ok ({}x{} \ + bytes={}) banded_rects={}", + req.src, + w, + h, + bytes.len(), + rects.len() + ); + Some(rects) + } + Ok(None) => { + log::warn!( + "SHAPE Mask src=0x{:x}: no readback of the mask; shaping to its \ + bounding rect", + req.src + ); + None + } + Err(e) => { + log::warn!( + "SHAPE Mask src=0x{:x}: mask readback failed ({e}); shaping to \ + its bounding rect", + req.src + ); + None + } + } + } else { + log::warn!( + "SHAPE Mask src=0x{:x}: source pixmap has no storage; shaping to its \ + bounding rect", + req.src + ); + None + }; + let source = + banded.unwrap_or_else(|| crate::nested::shape_mask_source_rects(state, src_id)); + log::debug!( + "shape diag: MASK dest=0x{:x} kind={} op={} source_rects={}", + req.dest, + req.dest_kind, + req.op, + source.len(), + ); + let source = offset_source(Region::from_rects(&source), req.x_off, req.y_off); + let changed = shape_combine(state, window, req.dest_kind, source, req.op); + mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); + backend.windows_restructured(state); + if changed { + emit_shape_notify(state, window, req.dest_kind); + } + } + } + x11shape::COMBINE => { + if let Some(req) = x11shape::parse_combine_request(body) { + let dest = ResourceId(req.dest); + let src = ResourceId(req.src); + debug!( + "client {} SHAPE::Combine dest=0x{:x} dest_kind={} src=0x{:x} src_kind={} op={} off=({},{})", + client_id.0, + req.dest, + req.dest_kind, + req.src, + req.src_kind, + req.op, + req.x_off, + req.y_off, + ); + let source = offset_source( + crate::nested::shape_region_or_default(state, src, req.src_kind), + req.x_off, + req.y_off, + ); + log::debug!( + "shape diag: COMBINE dest=0x{:x}(kind={}) src=0x{:x}(kind={}) op={} \ + src_dims={}", + req.dest, + req.dest_kind, + req.src, + req.src_kind, + req.op, + fmt_shape_rects(&source.to_rects()), + ); + let changed = shape_combine(state, dest, req.dest_kind, source, req.op); + mirror_shape_to_host_state(state, backend, origin, dest, req.dest_kind); + backend.windows_restructured(state); + if changed { + emit_shape_notify(state, dest, req.dest_kind); + } + } + } + x11shape::OFFSET => { + if let Some(req) = x11shape::parse_offset_request(body) { + let dest = ResourceId(req.dest); + if let Some(region) = crate::nested::shape_region(state, dest, req.dest_kind) { + let region = region + .clone() + .translate_clipped(i32::from(req.x_off), i32::from(req.y_off)); + crate::nested::set_shape_region(state, dest, req.dest_kind, region); + mirror_shape_to_host_state(state, backend, origin, dest, req.dest_kind); + backend.windows_restructured(state); + emit_shape_notify(state, dest, req.dest_kind); + } + } + } + x11shape::QUERY_EXTENTS => { + let window = ResourceId(x11shape::parse_window(body).unwrap_or(ROOT_WINDOW.0)); + let extents = + |kind| crate::nested::shape_region_or_default(state, window, kind).extents_rect(); + let bounding = extents(x11shape::KIND_BOUNDING); + let clip = extents(x11shape::KIND_CLIP); + let bounding_shaped = + crate::nested::shape_kind_is_set(state, window, x11shape::KIND_BOUNDING); + let clip_shaped = crate::nested::shape_kind_is_set(state, window, x11shape::KIND_CLIP); + let reply = x11shape::encode_query_extents_reply( + byte_order, + sequence, + bounding_shaped, + clip_shaped, + bounding, + clip, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11shape::SELECT_INPUT => { + if let Some(req) = x11shape::parse_select_input_request(body) { + let key = (client_id.0, ResourceId(req.window)); + if req.enable { + state.shape_select_masks.insert(key, true); + } else { + state.shape_select_masks.remove(&key); + } + } + } + x11shape::INPUT_SELECTED => { + let window = ResourceId(x11shape::parse_window(body).unwrap_or(ROOT_WINDOW.0)); + let enabled = state + .shape_select_masks + .get(&(client_id.0, window)) + .copied() + .unwrap_or(false); + let reply = x11shape::encode_input_selected_reply(byte_order, sequence, enabled); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11shape::GET_RECTANGLES => { + let (window, kind) = x11shape::parse_get_rectangles_request(body) + .map(|(w, k)| (ResourceId(w), k)) + .unwrap_or((ROOT_WINDOW, x11shape::KIND_BOUNDING)); + let rects = get_rectangles_rects(state, window, kind); + let reply = x11shape::encode_get_rectangles_reply( + byte_order, + sequence, + x11shape::ORDERING_YX_BANDED, + &rects, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// Xorg `ProcXFixesDispatch`: a client may only use the requests of the +/// XFIXES major version it negotiated — before its first `QueryVersion` +/// that is `QueryVersion` alone. Anything else is BadRequest. +pub(super) fn dispatch_xfixes_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::xfixes as x11xfixes; + let client_major = state + .xfixes_client_major + .get(&client_id.0) + .copied() + .unwrap_or(0); + if !x11xfixes::request_allowed(client_major, header.data) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(header.data), + header.opcode, + ); + } + handle_xfixes_request(state, backend, origin, client_id, sequence, header, body) +} + +/// Xorg `VERIFY_CURSOR` for XFIXES: resolve a cursor XID to its host +/// handle, or send BadCursor naming it. `Err(outcome)` carries the error +/// already written. +fn xfixes_verify_cursor( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + cursor: u32, +) -> Result, io::Result> { + if state.resources.cursor_exists(ResourceId(cursor)) { + return Ok(state.resources.cursor_host_xid(ResourceId(cursor))); + } + Err(emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor, + u16::from(header.data), + header.opcode, + )) +} + +/// Xorg `ReplaceCursor` for XFIXES `ChangeCursor` / `ChangeCursorByName`: +/// every cursor XID and every displayed use of host cursor `old_host` +/// switches to `source`'s cursor. Replacing a cursor with itself is a +/// no-op, and the old host cursor is released once nothing names it. +fn xfixes_replace_cursor( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + old_host: u32, + source: ResourceId, +) { + let Some(new_host) = state.resources.cursor_host_xid(source) else { + return; + }; + if old_host == new_host { + return; + } + state.resources.retarget_cursor_host(old_host, source); + let _ = backend.replace_cursor(origin, old_host, new_host); + if !state.resources.cursor_host_referenced(old_host) { + state.resources.cursor_host_released(old_host); + let _ = backend.free_cursor(origin, old_host); + } +} + +/// Xorg `ExpandRegion` (`xfixes/region.c`): grow each rectangle of +/// `source` by the four margins and union the results. Coordinates are +/// computed wide and clamped to the protocol's 16-bit range. +fn xfixes_expand_region( + source: &[yserver_protocol::x11::xfixes::RegionRect], + left: u16, + right: u16, + top: u16, + bottom: u16, +) -> Region { + use yserver_protocol::x11::xfixes::RegionRect; + let clamp_i16 = |v: i32| { + i16::try_from(v.clamp(i32::from(i16::MIN), i32::from(i16::MAX))).unwrap_or_default() + }; + let grown: Vec = source + .iter() + .map(|r| { + let x1 = i32::from(r.x) - i32::from(left); + let y1 = i32::from(r.y) - i32::from(top); + let x2 = i32::from(r.x) + i32::from(r.width) + i32::from(right); + let y2 = i32::from(r.y) + i32::from(r.height) + i32::from(bottom); + let (x1, y1, x2, y2) = (clamp_i16(x1), clamp_i16(y1), clamp_i16(x2), clamp_i16(y2)); + RegionRect { + x: x1, + y: y1, + width: u16::try_from(i32::from(x2) - i32::from(x1)).unwrap_or(0), + height: u16::try_from(i32::from(y2) - i32::from(y1)).unwrap_or(0), + } + }) + .collect(); + grown.iter().fold(Region::default(), |acc, rect| { + acc.union(&Region::rect(*rect)) + }) +} + +/// XFIXES region `id`, empty if there is none. +fn xfixes_region(state: &ServerState, id: u32) -> Region { + state + .xfixes_regions + .get(&id) + .map(|r| r.region.clone()) + .unwrap_or_default() +} + +/// Replace a region's contents without changing the owner of an existing +/// XID. A new destination keeps the current requester's ownership. +fn store_xfixes_region(state: &mut ServerState, id: u32, owner: ClientId, region: Region) { + if let Some(existing) = state.xfixes_regions.get_mut(&id) { + existing.region = region; + } else { + state + .xfixes_regions + .insert(id, crate::server::XFixesRegion { owner, region }); + } +} + +/// `ProcXFixesInvertRegion`'s bounds: the far edges stop at `MAXSHORT`. +fn invert_bounds(r: yserver_protocol::x11::xfixes::RegionRect) -> crate::region::Box32 { + let max = i32::from(i16::MAX); + let (x1, y1) = (i32::from(r.x), i32::from(r.y)); + crate::region::Box32 { + x1, + y1, + x2: (x1 + i32::from(r.width)).min(max), + y2: (y1 + i32::from(r.height)).min(max), + } +} + +/// Send XFIXES `DisplayCursorNotify` for a backend-reported sprite change +/// to every (client, window) that selected it — one event per selection, +/// as Xorg's `CursorDisplayCursor` walks its `cursorEvents` list. Called +/// after each request and at the end of each loop iteration. +pub(crate) fn emit_xfixes_cursor_notify(state: &mut ServerState, backend: &mut dyn Backend) { + use yserver_protocol::x11::xfixes as x11xfixes; + let Some(change) = backend.take_displayed_cursor_change() else { + return; + }; + let mut selections: Vec<(u32, u32)> = state + .xfixes_cursor_masks + .iter() + .filter(|(_, mask)| **mask & x11xfixes::DISPLAY_CURSOR_NOTIFY_MASK != 0) + .map(|((client, window), _)| (*client, window.0)) + .collect(); + if selections.is_empty() { + return; + } + selections.sort_unstable(); + let name = state + .resources + .cursor_name_for_host(change.host_xid) + .map_or(0, |atom| atom.0); + let timestamp = state.timestamp_now(); + for (client, window) in selections { + let _dropped = fanout_event_to_clients(state, &[ClientId(client)], |buf, seq, order| { + x11xfixes::encode_cursor_notify_event( + buf, + order, + crate::nested::XFIXES_FIRST_EVENT, + seq, + window, + change.serial, + timestamp, + name, + ); + }); + } +} + +/// Drop `client`'s XFIXES per-client state on disconnect. Xorg frees the +/// client's `CursorHideCountRec` resource, which re-displays the sprite +/// once no other client holds a hide. +pub(crate) fn release_xfixes_client_state( + state: &mut ServerState, + backend: &mut dyn Backend, + client: ClientId, +) { + state.xfixes_client_major.remove(&client.0); + if state.xfixes_cursor_hide_counts.remove(&client.0).is_some() + && state.xfixes_cursor_hide_counts.is_empty() + { + backend.set_cursor_hidden(false); + } +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn handle_xfixes_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, xfixes as x11xfixes}; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + match minor { + x11xfixes::QUERY_VERSION => { + // Xorg `ProcXFixesQueryVersion`: REQUEST_SIZE_MATCH, then the + // lower-of-the-two rule with a sticky per-client major. + let Some((client_major, client_minor)) = + x11xfixes::parse_query_version(byte_order, body) + else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + }; + let previous = state + .xfixes_client_major + .get(&client_id.0) + .copied() + .unwrap_or(0); + let negotiated = x11xfixes::negotiate_version(previous, client_major, client_minor); + state + .xfixes_client_major + .insert(client_id.0, negotiated.client_major); + debug!( + "client {} #{} XFIXES::QueryVersion client={client_major}.{client_minor} -> {}.{}", + client_id.0, sequence.0, negotiated.reply_major, negotiated.reply_minor, + ); + let reply = x11xfixes::encode_query_version_reply( + byte_order, + sequence, + negotiated.reply_major, + negotiated.reply_minor, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11xfixes::SELECT_SELECTION_INPUT => { + if let Some(req) = x11xfixes::parse_select_selection_input(body) { + // Xorg `ProcXFixesSelectSelectionInput` + // (xfixes/select.c:189-196): validate the window + // first, then the mask, before mutating state. + if state.resources.window(ResourceId(req.window)).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + XFIXES_MAJOR_OPCODE, + ); + } + if req.event_mask & !x11xfixes::SELECTION_ALL_EVENTS_MASK != 0 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.event_mask, + XFIXES_MAJOR_OPCODE, + ); + } + let key = ( + client_id.0, + ResourceId(req.window), + yserver_protocol::x11::AtomId(req.selection), + ); + if req.event_mask == 0 { + state.xfixes_selection_masks.remove(&key); + } else { + state.xfixes_selection_masks.insert(key, req.event_mask); + } + } + } + x11xfixes::SELECT_CURSOR_INPUT => { + if let Some(req) = x11xfixes::parse_select_cursor_input(body) { + // Xorg `ProcXFixesSelectCursorInput`: window first, then + // the mask (captured on Xvfb: BadWindow, BadValue). + if state.resources.window(ResourceId(req.window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + u16::from(minor), + header.opcode, + ); + } + if req.event_mask & !x11xfixes::CURSOR_ALL_EVENTS_MASK != 0 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.event_mask, + u16::from(minor), + header.opcode, + ); + } + let key = (client_id.0, ResourceId(req.window)); + if req.event_mask == 0 { + state.xfixes_cursor_masks.remove(&key); + } else { + state.xfixes_cursor_masks.insert(key, req.event_mask); + } + } + } + x11xfixes::GET_CURSOR_IMAGE => { + // Stage 5 unblock for audit #14: source the active + // cursor from the backend. Pre-Stage-5 backends + // (`ynest`, `RecordingBackend`) return `None` — fall + // back to the empty reply so existing client behaviour + // doesn't regress (a 0×0 reply is still a valid X11 + // GetCursorImage response). + let reply = match backend.get_active_cursor_image() { + Some(img) => x11xfixes::encode_get_cursor_image_reply( + byte_order, + sequence, + img.x, + img.y, + img.width, + img.height, + img.hot_x, + img.hot_y, + img.serial, + img.bgra_bytes.as_ref(), + ), + None => x11xfixes::encode_get_cursor_image_empty_reply(byte_order, sequence), + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11xfixes::GET_CURSOR_IMAGE_AND_NAME => { + // Superset of GetCursorImage (opcode 25). Real X screen + // recorders (gpu-screen-recorder, …) call this to grab the + // cursor; with no reply they block forever in poll(). The + // name is the displayed cursor's XFIXES name (Xorg + // `pCursor->name`), empty when it was never named. + let reply = match backend.get_active_cursor_image() { + Some(img) => { + let atom = state + .resources + .cursor_name_for_host(img.host_xid) + .unwrap_or(AtomId(0)); + let name = state.atoms.name(atom).map(str::as_bytes).unwrap_or(&[]); + x11xfixes::encode_get_cursor_image_and_name_reply( + byte_order, + sequence, + img.x, + img.y, + img.width, + img.height, + img.hot_x, + img.hot_y, + img.serial, + atom.0, + name, + img.bgra_bytes.as_ref(), + ) + } + None => { + x11xfixes::encode_get_cursor_image_and_name_empty_reply(byte_order, sequence) + } + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11xfixes::CREATE_REGION => { + if let Some((region, rects)) = x11xfixes::parse_create_region(body) { + if xfixes_region_xid_already_taken(state, region) + || xid_out_of_client_range(state, client_id, region) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + region, + XFIXES_MAJOR_OPCODE, + ); + } + state.xfixes_regions.insert( + region, + crate::server::XFixesRegion { + owner: client_id, + region: Region::from_wire_rects(&rects), + }, + ); + } + } + x11xfixes::CREATE_POINTER_BARRIER => { + if let Some(req) = x11xfixes::parse_create_pointer_barrier(body) { + // Xorg XICreatePointerBarrier validation order: + // geometry -> negative-on-own-axis -> window -> devices -> xid. + let horizontal = req.y1 == req.y2; + let vertical = req.x1 == req.x2; + if horizontal == vertical { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.barrier, + XFIXES_MAJOR_OPCODE, + ); + } + if (horizontal && (req.y1 < 0 || req.y2 < 0)) + || (vertical && (req.x1 < 0 || req.x2 < 0)) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.barrier, + XFIXES_MAJOR_OPCODE, + ); + } + if state.resources.window(ResourceId(req.window)).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + req.window, + XFIXES_MAJOR_OPCODE, + ); + } + for &d in &req.devices { + if !(d == 0 || d == 1 || d == 2) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(d), + u16::from(x11xfixes::CREATE_POINTER_BARRIER), + XFIXES_MAJOR_OPCODE, + ); + } + } + if state.xid_occupied(req.barrier) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.barrier, + XFIXES_MAJOR_OPCODE, + ); + } + if xid_out_of_client_range(state, client_id, req.barrier) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + req.barrier, + XFIXES_MAJOR_OPCODE, + ); + } + let (mut x1, mut x2) = (req.x1, req.x2); + let (mut y1, mut y2) = (req.y1, req.y2); + if x1 >= 0 && x2 >= 0 && x1 > x2 { + std::mem::swap(&mut x1, &mut x2); + } + if y1 >= 0 && y2 >= 0 && y1 > y2 { + std::mem::swap(&mut y1, &mut y2); + } + let directions = if horizontal { + req.directions & !(1 | 4) + } else { + req.directions & !(2 | 8) + }; + state.pointer_barriers.insert( + req.barrier, + crate::server::PointerBarrier { + owner: client_id, + window: ResourceId(req.window), + x1, + y1, + x2, + y2, + directions, + devices: req.devices, + hit: false, + seen: false, + event_id: 1, + release_event_id: 0, + last_timestamp: 0, + }, + ); + log::trace!( + target: "yserver_core::barriers", + "create barrier xid=0x{:x} window=0x{:x} ({x1},{y1})-({x2},{y2}) dirs={directions} -> {} active", + req.barrier, + req.window, + state.pointer_barriers.len(), + ); + } + } + x11xfixes::DELETE_POINTER_BARRIER => { + if let Some(bid) = x11xfixes::parse_delete_pointer_barrier(body) { + match state.pointer_barriers.get(&bid) { + None => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + bid, + XFIXES_MAJOR_OPCODE, + ); + } + Some(b) if b.owner != client_id => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + bid, + XFIXES_MAJOR_OPCODE, + ); + } + Some(barrier) => { + if barrier.hit { + // Xorg BarrierFreeBarrier emits the released leave + // with the CURRENT time + sprite position (not the + // last-hit values), xibarriers.c:668. Copy the + // barrier fields out first to release the borrow. + let (owner, window, eid) = + (barrier.owner, barrier.window, barrier.event_id); + let time = state.timestamp_now(); + let (rx, ry) = state.pointer_root; + let _dropped = crate::core_loop::pointer_fanout::emit_barrier_event( + state, + bid, + owner, + window, + 26, + time, + eid, + 0, + 1, + 0, + i32::from(rx), + i32::from(ry), + 0.0, + 0.0, + ); + } + state.pointer_barriers.remove(&bid); + } + } + } + } + x11xfixes::CREATE_REGION_FROM_BITMAP | x11xfixes::CREATE_REGION_FROM_GC => { + if let Some((region, source)) = x11xfixes::parse_u32_pair(body) { + if xfixes_region_xid_already_taken(state, region) + || xid_out_of_client_range(state, client_id, region) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + region, + XFIXES_MAJOR_OPCODE, + ); + } + if minor == x11xfixes::CREATE_REGION_FROM_GC { + let gc = ResourceId(source); + let Some(g) = state.resources.gc(gc) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_GC, + source, + XFIXES_MAJOR_OPCODE, + ); + }; + let Some(clip) = g.clip_rectangles.clone() else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + source, + XFIXES_MAJOR_OPCODE, + ); + }; + // Audit #7 (docs/protocol-audit-2026-05-19.md): + // copy the GC's clip rects RAW — Xorg's + // `ProcXFixesCreateRegionFromGC` + // (`xfixes/region.c:219-226`) does + // `XFixesRegionCopy(pGC->clientClip)` with no + // translation. `clip.x_origin` / `clip.y_origin` + // are properties of the GC's USE, not part of + // the region's content; otherwise a subsequent + // `SetGcClipRegion(gc, region, x_origin, + // y_origin)` double-translates. + let rects = x11xfixes::parse_rectangles(&clip.rectangles); + state.xfixes_regions.insert( + region, + crate::server::XFixesRegion { + owner: client_id, + region: Region::from_wire_rects(&rects), + }, + ); + } else { + state.xfixes_regions.insert( + region, + crate::server::XFixesRegion { + owner: client_id, + region: Region::default(), + }, + ); + } + } + } + x11xfixes::CREATE_REGION_FROM_WINDOW => { + if let Some((region, window, kind)) = x11xfixes::parse_create_region_from_window(body) { + if xfixes_region_xid_already_taken(state, region) + || xid_out_of_client_range(state, client_id, region) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + region, + XFIXES_MAJOR_OPCODE, + ); + } + // BadWindow on unknown window xid + // (`xfixes/region.c:158-163`) — Xorg sets + // `client->error_value = stuff->window`. + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + XFIXES_MAJOR_OPCODE, + ); + } + // BadValue on `kind` outside {Bounding=0, Clip=1} + // (`xfixes/region.c:164-181`). The SHAPE-shaped + // Input(2) is explicitly rejected by Xorg here. + if kind > 1 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(kind), + XFIXES_MAJOR_OPCODE, + ); + } + let shape = crate::nested::shape_region_or_default(state, ResourceId(window), kind); + trace!( + target: "yserver::xfixes::region", + "CreateRegionFromWindow region=0x{region:08x} window=0x{window:08x} kind={} rects{}", + kind, + format_region_rects(&shape.to_rects()), + ); + state.xfixes_regions.insert( + region, + crate::server::XFixesRegion { + owner: client_id, + region: shape, + }, + ); + } + } + x11xfixes::CREATE_REGION_FROM_PICTURE => { + if let Some((region, picture)) = x11xfixes::parse_create_region_from_picture(body) { + if xfixes_region_xid_already_taken(state, region) + || xid_out_of_client_range(state, client_id, region) + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + region, + XFIXES_MAJOR_OPCODE, + ); + } + // VERIFY_PICTURE (`xfixes/region.c:255`) returns + // `RenderErrBase + BadPicture` on an unknown + // picture xid — NOT BadDrawable. + let bad_picture = crate::nested::RENDER_FIRST_ERROR + 1; + let Some(picture_state) = state.resources.picture(ResourceId(picture)) else { + return emit_x11_error( + state, + client_id, + sequence, + bad_picture, + picture, + XFIXES_MAJOR_OPCODE, + ); + }; + // `if (!pPicture->pDrawable) return RenderErrBase + + // BadPicture` at `xfixes/region.c:257-258`. yserver's + // `PictureKind::Sourceless` (SolidFill / gradient + // pictures) is exactly that case. + if matches!( + picture_state.kind, + crate::resources::PictureKind::Sourceless + ) { + return emit_x11_error( + state, + client_id, + sequence, + bad_picture, + picture, + XFIXES_MAJOR_OPCODE, + ); + } + // An unbacked Picture has no clip set, like a fresh one. + let client_clip = match picture_state.host_picture_xid { + Some(hp) => backend.picture_client_clip_rects(hp.as_raw()), + None => Some(None), + }; + let Some(client_clip) = client_clip else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + picture, + XFIXES_MAJOR_OPCODE, + ); + }; + let Some(rects) = client_clip else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + picture, + XFIXES_MAJOR_OPCODE, + ); + }; + state.xfixes_regions.insert( + region, + crate::server::XFixesRegion { + owner: client_id, + region: Region::from_wire_rects(&rects), + }, + ); + } + } + x11xfixes::DESTROY_REGION => { + if let Some((region, _)) = x11xfixes::parse_u32_pair(body) { + state.xfixes_regions.remove(®ion); + } else if body.len() >= 4 { + let region = u32::from_le_bytes(body[0..4].try_into().unwrap()); + state.xfixes_regions.remove(®ion); + } + } + x11xfixes::SET_REGION => { + if let Some((region, rects)) = x11xfixes::parse_create_region(body) { + store_xfixes_region(state, region, client_id, Region::from_wire_rects(&rects)); + } + } + x11xfixes::COPY_REGION => { + if let Some((source, dest)) = x11xfixes::parse_u32_pair(body) { + let region = xfixes_region(state, source); + trace!( + target: "yserver::xfixes::region", + "CopyRegion src=0x{source:08x} dst=0x{dest:08x} rects{}", + format_region_rects(®ion.to_rects()), + ); + store_xfixes_region(state, dest, client_id, region); + } + } + x11xfixes::UNION_REGION | x11xfixes::INTERSECT_REGION | x11xfixes::SUBTRACT_REGION => { + if let Some((source1, source2, dest)) = x11xfixes::parse_u32_triplet(body) { + let empty = Region::default(); + let a = state + .xfixes_regions + .get(&source1) + .map_or(&empty, |r| &r.region); + let b = state + .xfixes_regions + .get(&source2) + .map_or(&empty, |r| &r.region); + let op_name = match minor { + x11xfixes::UNION_REGION => "UnionRegion", + x11xfixes::INTERSECT_REGION => "IntersectRegion", + x11xfixes::SUBTRACT_REGION => "SubtractRegion", + _ => unreachable!(), + }; + let region = match minor { + x11xfixes::UNION_REGION => a.union(b), + x11xfixes::INTERSECT_REGION => a.intersect(b), + x11xfixes::SUBTRACT_REGION => a.subtract(b), + _ => unreachable!(), + }; + trace!( + target: "yserver::xfixes::region", + "{op_name} a=0x{source1:08x} rects{} b=0x{source2:08x} rects{} dst=0x{dest:08x} rects{}", + format_region_rects(&a.to_rects()), + format_region_rects(&b.to_rects()), + format_region_rects(®ion.to_rects()), + ); + store_xfixes_region(state, dest, client_id, region); + } + } + x11xfixes::INVERT_REGION => { + if let Some((source, bounds, dest)) = x11xfixes::parse_invert_region(body) { + let region = state + .xfixes_regions + .get(&source) + .map_or_else(Region::default, |r| r.region.inverse(invert_bounds(bounds))); + store_xfixes_region(state, dest, client_id, region); + } + } + x11xfixes::TRANSLATE_REGION => { + if let Some((region_id, dx, dy)) = x11xfixes::parse_translate_region(body) + && let Some(region) = state.xfixes_regions.get_mut(®ion_id) + { + region.region = std::mem::take(&mut region.region) + .translate_clipped(i32::from(dx), i32::from(dy)); + trace!( + target: "yserver::xfixes::region", + "TranslateRegion region=0x{region_id:08x} delta=({dx}, {dy}) after{}", + format_region_rects(®ion.rects()), + ); + } + } + x11xfixes::REGION_EXTENTS => { + if let Some((source, dest)) = x11xfixes::parse_u32_pair(body) { + let rect = xfixes_region(state, source).extents_rect(); + store_xfixes_region(state, dest, client_id, Region::rect(rect)); + } + } + x11xfixes::FETCH_REGION => { + let region = body + .get(0..4) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap())) + .unwrap_or(0); + // A fetched damage region can include coalesced paint that did + // not generate another DamageNotify. Submit it before the reply + // lets an external compositor sample the corresponding pixels. + backend.flush_before_damage_notify(); + let (extents, rects) = state.xfixes_regions.get(®ion).map_or_else( + || (Region::default().extents_rect(), Vec::new()), + |r| (r.region.extents_rect(), r.rects()), + ); + let reply = x11xfixes::encode_fetch_region_reply(byte_order, sequence, extents, &rects); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11xfixes::CHANGE_SAVE_SET => { + if let Some(req) = x11xfixes::parse_change_save_set(body) + && let Some(c) = state.clients.get_mut(&client_id.0) + { + let win = ResourceId(req.window); + match req.mode { + 0 => { + c.save_set.insert(win); + } + 1 => { + c.save_set.remove(&win); + } + _ => {} + } + // target (Nearest/Root) and map (Map/Unmap) parameters affect + // disconnect-time reparent/remap behaviour; that path is + // already deferred from the Phase 2 wrap-up. Ignore for now. + } + } + x11xfixes::SET_GC_CLIP_REGION => { + if let Some(req) = x11xfixes::parse_set_gc_clip_region(body) { + let gc_id = ResourceId(req.gc); + // A clip-mask pixmap this displaces is released as by + // SetClipRectangles (`ChangeClip`, `dix/gc.c`). + let displaced = if req.region == 0 { + let displaced = state.resources.clear_gc_clip(gc_id); + state + .resources + .set_gc_clip_origin(gc_id, req.x_origin, req.y_origin); + displaced + } else { + let rects = xfixes_region(state, req.region).to_rects(); + let mut rectangles = Vec::with_capacity(rects.len() * 8); + for rect in &rects { + rectangles.extend_from_slice(&rect.x.to_le_bytes()); + rectangles.extend_from_slice(&rect.y.to_le_bytes()); + rectangles.extend_from_slice(&rect.width.to_le_bytes()); + rectangles.extend_from_slice(&rect.height.to_le_bytes()); + } + state.resources.set_clip_rectangles( + client_id, + yserver_protocol::x11::SetClipRectanglesRequest { + gc: gc_id, + clip: yserver_protocol::x11::ClipRectangles { + ordering: 0, // Unsorted; matches xfixes region semantics. + x_origin: req.x_origin, + y_origin: req.y_origin, + rectangles, + }, + }, + ) + }; + release_displaced_gc_pixmaps(state, backend, origin, displaced); + } + } + x11xfixes::SET_WINDOW_SHAPE_REGION => { + if let Some(req) = x11xfixes::parse_set_window_shape_region(body) { + let window = ResourceId(req.dest); + if req.region == 0 { + crate::nested::clear_shape_rects(state, window, req.dest_kind); + } else { + let source = + offset_source(xfixes_region(state, req.region), req.x_offset, req.y_offset); + crate::nested::set_shape_region(state, window, req.dest_kind, source); + } + mirror_shape_to_host_state(state, backend, origin, window, req.dest_kind); + // Xorg SetWindowShapeRegion goes through miSetShape too. + backend.windows_restructured(state); + } + } + x11xfixes::SET_PICTURE_CLIP_REGION => { + if let Some(req) = x11xfixes::parse_set_picture_clip_region(body) { + let pic_id = ResourceId(req.picture); + let host_pic = state + .resources + .picture(pic_id) + .and_then(|p| p.host_picture_xid) + .map(|h| h.as_raw()); + if let Some(hp) = host_pic { + if req.region == 0 { + // RENDER CPClipMask = 0x40; value=None clears the clip. + let mut out = Vec::with_capacity(12); + out.extend_from_slice(&req.picture.to_le_bytes()); + out.extend_from_slice(&0x40_u32.to_le_bytes()); + out.extend_from_slice(&0_u32.to_le_bytes()); + let _ = backend.render_change_picture(origin, hp, &out); + } else { + let rects = xfixes_region(state, req.region).to_rects(); + trace!( + target: "yserver::xfixes::clip", + "SetPictureClipRegion client_pic=0x{:08x} host_pic=0x{hp:08x} region=0x{:08x} origin=({}, {}) n={} rects{}", + req.picture, + req.region, + req.x_origin, + req.y_origin, + rects.len(), + format_region_rects(&rects), + ); + // RENDER SetPictureClipRectangles body layout: + // picture(4) | x_origin(2) | y_origin(2) | rects(8*N). + let mut out = Vec::with_capacity(8 + rects.len() * 8); + out.extend_from_slice(&req.picture.to_le_bytes()); + out.extend_from_slice(&req.x_origin.to_le_bytes()); + out.extend_from_slice(&req.y_origin.to_le_bytes()); + for rect in &rects { + out.extend_from_slice(&rect.x.to_le_bytes()); + out.extend_from_slice(&rect.y.to_le_bytes()); + out.extend_from_slice(&rect.width.to_le_bytes()); + out.extend_from_slice(&rect.height.to_le_bytes()); + } + let _ = backend.render_set_picture_clip_rectangles(origin, hp, &out); + } + } + } + } + x11xfixes::CHANGE_CURSOR => { + // Xorg `ProcXFixesChangeCursor`: both cursors must exist + // (source checked first), then every use of `destination` — + // its XIDs, window cursors, grabs — becomes `source`. + let Some((source, destination)) = x11xfixes::parse_change_cursor(byte_order, body) + else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + }; + if let Err(outcome) = xfixes_verify_cursor(state, client_id, sequence, header, source) { + return outcome; + } + let dest_host = + match xfixes_verify_cursor(state, client_id, sequence, header, destination) { + Ok(host) => host, + Err(outcome) => return outcome, + }; + if let Some(dest_host) = dest_host { + xfixes_replace_cursor(state, backend, origin, dest_host, ResourceId(source)); + } + } + x11xfixes::CHANGE_CURSOR_BY_NAME => { + // Xorg `ProcXFixesChangeCursorByName`: the source must exist; + // a name that was never interned matches nothing (MakeAtom + // with create=FALSE) and succeeds silently. + if let Some((cursor_xid, name_bytes)) = x11xfixes::parse_change_cursor_by_name(body) { + if let Err(outcome) = + xfixes_verify_cursor(state, client_id, sequence, header, cursor_xid) + { + return outcome; + } + let name = std::str::from_utf8(name_bytes).unwrap_or(""); + let atom = state.atoms.intern(name, true); + if atom.0 != 0 { + for host in state.resources.cursor_hosts_named(atom) { + xfixes_replace_cursor(state, backend, origin, host, ResourceId(cursor_xid)); + } + } + } + } + x11xfixes::EXPAND_REGION => { + let Some(req) = x11xfixes::parse_expand_region(byte_order, body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + }; + // VERIFY_REGION source then destination: XFixes BadRegion + // (error base + 0). + for region in [req.source, req.destination] { + if !state.xfixes_regions.contains_key(®ion) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + crate::nested::XFIXES_FIRST_ERROR, + region, + u16::from(minor), + header.opcode, + ); + } + } + let source = state.xfixes_regions[&req.source].rects(); + // An empty source leaves the destination untouched (Xorg only + // rewrites it inside `if (nBoxes)`; confirmed on Xvfb). + if !source.is_empty() { + let expanded = + xfixes_expand_region(&source, req.left, req.right, req.top, req.bottom); + trace!( + target: "yserver::xfixes::region", + "ExpandRegion src=0x{:08x} dst=0x{:08x} l={} r={} t={} b={} rects{}", + req.source, + req.destination, + req.left, + req.right, + req.top, + req.bottom, + format_region_rects(&expanded.to_rects()), + ); + if let Some(dest) = state.xfixes_regions.get_mut(&req.destination) { + dest.region = expanded; + } + } + } + x11xfixes::SET_CURSOR_NAME => { + // SetCursorName(cursor, name) — XFixes 2.0: tag a cursor + // with a name string. Xorg interns the name as an atom and + // stores it on the cursor (`pCursor->name = atom`) so + // GetCursorName can read it back. yserver mirrors the same + // shape: intern, store on `Cursor.name_atom`. + if let Some((cursor_xid, name_bytes)) = x11xfixes::parse_set_cursor_name(body) { + if let Err(outcome) = + xfixes_verify_cursor(state, client_id, sequence, header, cursor_xid) + { + return outcome; + } + let name = std::str::from_utf8(name_bytes).unwrap_or(""); + let atom = state.atoms.intern(name, false); + state + .resources + .set_cursor_name_atom(ResourceId(cursor_xid), atom); + debug!( + "client {} #{} XFIXES::SetCursorName cursor=0x{:x} atom={} \"{}\"", + client_id.0, sequence.0, cursor_xid, atom.0, name, + ); + } else { + debug!( + "client {} #{} XFIXES::SetCursorName (malformed body, ignored)", + client_id.0, sequence.0, + ); + } + } + x11xfixes::GET_CURSOR_NAME => { + // GetCursorName(cursor) — reply with atom + name string. + // If no name was ever set, return atom=None(0) and an + // empty name, matching Xorg's behaviour for cursors with + // `pCursor->name == 0`. + let cursor_xid = body + .get(0..4) + .map(|b| u32::from_le_bytes(b.try_into().unwrap())) + .unwrap_or(0); + if let Err(outcome) = + xfixes_verify_cursor(state, client_id, sequence, header, cursor_xid) + { + return outcome; + } + let atom = state + .resources + .cursor_name_atom(ResourceId(cursor_xid)) + .unwrap_or(AtomId(0)); + let name = state.atoms.name(atom).map(str::as_bytes).unwrap_or(&[]); + debug!( + "client {} #{} XFIXES::GetCursorName cursor=0x{:x} atom={} ({} bytes)", + client_id.0, + sequence.0, + cursor_xid, + atom.0, + name.len(), + ); + let reply = x11xfixes::encode_get_cursor_name_reply(byte_order, sequence, atom.0, name); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11xfixes::HIDE_CURSOR | x11xfixes::SHOW_CURSOR => { + // Xorg `ProcXFixesHideCursor` / `ProcXFixesShowCursor`: the + // window only names the screen (one here); the hide count is + // per client. The sprite hides on the first count anywhere and + // returns when the last one goes (ShowCursor to zero, or the + // client disconnecting). + let Some(window) = x11xfixes::parse_window(byte_order, body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + }; + if state.resources.window(ResourceId(window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window, + u16::from(minor), + header.opcode, + ); + } + if minor == x11xfixes::HIDE_CURSOR { + let was_visible = state.xfixes_cursor_hide_counts.is_empty(); + *state + .xfixes_cursor_hide_counts + .entry(client_id.0) + .or_insert(0) += 1; + if was_visible { + backend.set_cursor_hidden(true); + } + } else { + // Showing without a prior hide is BadMatch (Xvfb: error 8, + // value = the window). + let Some(count) = state.xfixes_cursor_hide_counts.get_mut(&client_id.0) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + window, + u16::from(minor), + header.opcode, + ); + }; + *count -= 1; + if *count == 0 { + state.xfixes_cursor_hide_counts.remove(&client_id.0); + if state.xfixes_cursor_hide_counts.is_empty() { + backend.set_cursor_hidden(false); + } + } + } + debug!( + "client {} #{} XFIXES::{}Cursor window=0x{window:x} hide_counts={:?}", + client_id.0, + sequence.0, + if minor == x11xfixes::HIDE_CURSOR { + "Hide" + } else { + "Show" + }, + state.xfixes_cursor_hide_counts, + ); + } + other if other > x11xfixes::DELETE_POINTER_BARRIER => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + other => { + // Every 5.0 request has an arm above; the gate in + // `dispatch_xfixes_request` keeps higher minors out. + debug!( + "client {} #{} XFIXES::unexpected minor={}", + client_id.0, sequence.0, other + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// CreateColormap (78): allocate colormap, BadIDChoice on duplicate. +/// `BadIDChoice` fires when a CreateXxx request's resource ID is +/// either already allocated OR outside the client's resource-id range +/// declared in the setup reply. +/// `LEGAL_NEW_RESOURCE` equivalent for XFIXES `CreateRegion*`: the +/// candidate region xid must NOT already name a resource (in the +/// core `resources` table OR in the dedicated `xfixes_regions` +/// map). Xorg's `xfixes/region.c:78,114,157,213` all guard their +/// CreateRegion variants with `LEGAL_NEW_RESOURCE(stuff->region, +/// client)` before doing any work — duplicates surface as +/// BadIDChoice (X error code 14). Returns true if the xid clashes +/// (the caller should emit BadIDChoice). +fn xfixes_region_xid_already_taken(state: &ServerState, rid: u32) -> bool { + state.xfixes_regions.contains_key(&rid) || state.resources.xid_in_use(ResourceId(rid)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/sync_ext.rs b/crates/yserver-core/src/core_loop/process_request/sync_ext.rs new file mode 100644 index 000000000..f7d1e84e3 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/sync_ext.rs @@ -0,0 +1,988 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{RequestOutcome, emit_x11_error_with_minor, write_to_client}, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, SequenceNumber}, +}; + +/// A SYNC protocol error: `code` is either a core error or +/// `SYNC_FIRST_ERROR + x11sync::BAD_*`. +fn sync_error( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + code: u8, + value: u32, +) -> io::Result { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(header.data), + header.opcode, + ) +} + +/// Xorg's lookup of a client-writable counter for SetCounter / +/// ChangeCounter / DestroyCounter: an unknown XID is BadCounter, a system +/// counter BadAccess (both naming the counter; captured on Xvfb). +fn sync_writable_counter( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + counter: u32, +) -> Result> { + use yserver_protocol::x11::sync as x11sync; + if crate::core_loop::sync_await::is_system_counter(counter) { + return Err(sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_ACCESS, + counter, + )); + } + match state.sync_counters.get(&counter) { + Some(c) => Ok(c.value), + None => Err(sync_error( + state, + client_id, + sequence, + header, + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, + counter, + )), + } +} + +/// Xorg `RTFence` lookup: an unknown fence is BadFence naming it. +fn sync_known_fence( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + fence: u32, +) -> Result<(), io::Result> { + use yserver_protocol::x11::sync as x11sync; + if state.sync_fences.contains_key(&fence) { + return Ok(()); + } + Err(sync_error( + state, + client_id, + sequence, + header, + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_FENCE, + fence, + )) +} + +/// Xorg's `RTAlarm` lookup: an alarm that does not exist (never created, +/// None, or destroyed) is BadAlarm naming it. +fn sync_known_alarm( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + alarm: u32, +) -> Result<(), io::Result> { + use yserver_protocol::x11::sync as x11sync; + if state.sync_alarms.contains_key(&alarm) { + return Ok(()); + } + Err(sync_error( + state, + client_id, + sequence, + header, + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_ALARM, + alarm, + )) +} + +pub(super) fn handle_sync_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::{ClientByteOrder, sync as x11sync}; + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + match minor { + x11sync::INITIALIZE => { + // Xorg `ProcSyncInitialize` always answers its own version + // (Xvfb: client 3.1 / 3.0 / 2.0 / 4.0 all get 3.1). + let reply = x11sync::encode_initialize_reply( + byte_order, + sequence, + x11sync::MAJOR_VERSION, + x11sync::MINOR_VERSION, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11sync::LIST_SYSTEM_COUNTERS => { + let reply = x11sync::encode_list_system_counters_reply(byte_order, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11sync::CREATE_COUNTER => { + if let Some((counter, value)) = x11sync::parse_counter_value(body) { + state.sync_counters.insert( + counter, + crate::server::SyncCounter { + owner: client_id, + value, + }, + ); + } + } + x11sync::SET_COUNTER => { + if let Some((counter, value)) = x11sync::parse_counter_value(body) { + let old = match sync_writable_counter(state, client_id, sequence, header, counter) { + Ok(old) => old, + Err(outcome) => return outcome, + }; + if let Some(c) = state.sync_counters.get_mut(&counter) { + c.value = value; + } + crate::core_loop::sync_await::counter_changed(state, counter, old, value); + } + } + x11sync::CHANGE_COUNTER => { + if let Some((counter, delta)) = x11sync::parse_counter_value(body) { + let old = match sync_writable_counter(state, client_id, sequence, header, counter) { + Ok(old) => old, + Err(outcome) => return outcome, + }; + // Xorg: an INT64 overflow is BadValue naming the high half + // of the delta (Xvfb: value 0x7fffffff for i64::MAX). + let Some(new) = old.checked_add(delta) else { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let value_hi = (delta >> 32) as u32; + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_VALUE, + value_hi, + ); + }; + if let Some(c) = state.sync_counters.get_mut(&counter) { + c.value = new; + } + crate::core_loop::sync_await::counter_changed(state, counter, old, new); + } + } + x11sync::QUERY_COUNTER => { + let counter = x11sync::parse_resource(body).unwrap_or(0); + // IDLETIME saturates at u32::MAX ms (~49 days) inside + // `idletime_current_idle`. An unknown counter is BadCounter. + let Some(value) = crate::core_loop::sync_await::counter_value(state, counter) else { + return sync_error( + state, + client_id, + sequence, + header, + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, + counter, + ); + }; + let reply = x11sync::encode_query_counter_reply(byte_order, sequence, value); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11sync::DESTROY_COUNTER => { + if let Some(counter) = x11sync::parse_resource(body) { + let last = match sync_writable_counter(state, client_id, sequence, header, counter) + { + Ok(last) => last, + Err(outcome) => return outcome, + }; + state.sync_counters.remove(&counter); + crate::core_loop::sync_await::counter_destroyed(state, counter, last); + } + } + x11sync::AWAIT => { + // Xorg `ProcSyncAwait`: validate every wait condition, then + // suspend the client until one of the triggers fires. Its later + // requests stay queued behind this one (see `sync_await`). + let Some(conditions) = x11sync::parse_await(byte_order, body) else { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + 0, + ); + }; + if conditions.is_empty() { + return sync_error(state, client_id, sequence, header, x11::error::BAD_VALUE, 0); + } + let mut waits = Vec::with_capacity(conditions.len()); + for c in conditions { + // `SyncInitTrigger` order: counter, value type, value, test + // type. Captured on Xvfb: None / unknown → BadCounter, + // bad value type / test type → BadValue naming it, relative + // overflow → BadValue naming the high half of the wait. + let current = if c.counter == 0 { + None + } else { + crate::core_loop::sync_await::counter_value(state, c.counter) + }; + let Some(current) = current else { + return sync_error( + state, + client_id, + sequence, + header, + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, + c.counter, + ); + }; + let test_value = match c.value_type { + x11sync::VALUE_TYPE_ABSOLUTE => c.wait_value, + x11sync::VALUE_TYPE_RELATIVE => { + let Some(v) = current.checked_add(c.wait_value) else { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let value_hi = (c.wait_value >> 32) as u32; + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_VALUE, + value_hi, + ); + }; + v + } + other => { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_VALUE, + other, + ); + } + }; + if c.test_type > x11sync::TEST_NEGATIVE_COMPARISON { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_VALUE, + c.test_type, + ); + } + waits.push(crate::server::SyncAwaitCondition::Counter { + counter: c.counter, + test_type: c.test_type, + test_value, + event_threshold: c.event_threshold, + }); + } + debug!( + "client {} #{} SYNC::Await {} condition(s)", + client_id.0, + sequence.0, + waits.len() + ); + crate::core_loop::sync_await::begin_await(state, &*backend, client_id, waits); + } + x11sync::CREATE_ALARM => { + // Xorg `ProcSyncCreateAlarm`: the value list must match the mask. + let Some((alarm, mask)) = x11sync::parse_alarm_with_mask(body) else { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + 0, + ); + }; + if body.len() != x11sync::alarm_request_len(mask) { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + alarm, + ); + } + // Xorg's defaults (`ProcSyncCreateAlarm` + `SyncInitTrigger` on + // None): no counter, Absolute 0, PositiveComparison, delta 1, + // the owner selected for events. An error discards the alarm. + let mut a = crate::server::SyncAlarm { + owner: client_id, + state: x11sync::ALARM_STATE_INACTIVE, + events: true, + test_type: x11sync::TEST_POSITIVE_COMPARISON, + check_type: x11sync::TEST_POSITIVE_COMPARISON, + delta: 1, + ..crate::server::SyncAlarm::default() + }; + let values = alarm_value_words(body); + if let Err((code, value)) = + change_alarm_attributes(state, alarm, &mut a, client_id, mask, &values) + { + return sync_error(state, client_id, sequence, header, code, value); + } + let counter = a.counter; + let class = state + .client_wm_class + .get(&client_id.0) + .map(String::as_str) + .unwrap_or(""); + log::trace!( + "sync: client {}/{class:?} CreateAlarm 0x{alarm:x} \ + counter={cname}(0x{counter:x}) test={test} \ + wait_value={wait} delta={delta} events={events}", + client_id.0, + cname = sync_counter_name(counter), + test = sync_test_type_name(a.test_type), + wait = a.wait_value, + delta = a.delta, + events = a.events, + ); + if counter == 0 { + // "NULL counter will not trigger in CreateAlarm and sets + // alarm state to Inactive" (Xorg). + a.state = x11sync::ALARM_STATE_INACTIVE; + state.sync_alarms.insert(alarm, a); + return Ok(RequestOutcome::Handled); + } + state.sync_alarms.insert(alarm, a); + // The trigger is tested at creation: a comparison whose + // condition already holds fires at once. System counters + // (SERVERTIME, IDLETIME) read the clock. + check_new_alarm_trigger(state, alarm, counter); + } + x11sync::CHANGE_ALARM => { + // Xorg `ProcSyncChangeAlarm`: minimum size, then the alarm + // lookup (BadAlarm), then the value list against the mask + // (BadLength naming the alarm, captured on Xvfb). + let Some((alarm, mask)) = x11sync::parse_alarm_with_mask(body) else { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + 0, + ); + }; + if let Err(outcome) = sync_known_alarm(state, client_id, sequence, header, alarm) { + return outcome; + } + if body.len() != x11sync::alarm_request_len(mask) { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + alarm, + ); + } + // Xorg `SyncChangeAlarmAttributes`: any client may change an + // alarm; `events` selects AlarmNotify for the requesting client + // (the owner's own flag, or the event-client list). A failure + // part-way keeps what Xorg keeps (see change_alarm_attributes), + // so the copy is written back either way. + let Some(mut a) = state.sync_alarms.get(&alarm).cloned() else { + return Ok(RequestOutcome::Handled); + }; + let values = alarm_value_words(body); + let outcome = change_alarm_attributes(state, alarm, &mut a, client_id, mask, &values); + if let Err((code, value)) = outcome { + state.sync_alarms.insert(alarm, a); + return sync_error(state, client_id, sequence, header, code, value); + } + let counter = a.counter; + let class = state + .client_wm_class + .get(&client_id.0) + .map(String::as_str) + .unwrap_or(""); + log::trace!( + "sync: client {}/{class:?} ChangeAlarm 0x{alarm:x} \ + counter={cname}(0x{counter:x}) test={test} \ + wait_value={wait} delta={delta} events={events}", + client_id.0, + cname = sync_counter_name(counter), + test = sync_test_type_name(a.test_type), + wait = a.wait_value, + delta = a.delta, + events = a.events, + ); + state.sync_alarms.insert(alarm, a); + if counter == 0 { + // "NULL counter WILL trigger in ChangeAlarm" (Xorg): the + // alarm goes Inactive with an AlarmNotify. + alarm_trigger_fired(state, alarm, 0); + } else { + check_new_alarm_trigger(state, alarm, counter); + } + } + x11sync::QUERY_ALARM => { + // Xorg `ProcSyncQueryAlarm`: exact size, then the lookup. + if body.len() != 4 { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + 0, + ); + } + let alarm_id = x11sync::parse_resource(body).unwrap_or(0); + if let Err(outcome) = sync_known_alarm(state, client_id, sequence, header, alarm_id) { + return outcome; + } + let alarm = state + .sync_alarms + .get(&alarm_id) + .cloned() + .unwrap_or_default(); + let reply = x11sync::encode_query_alarm_reply( + byte_order, + sequence, + alarm.counter, + alarm.wait_value, + alarm.test_type, + alarm.delta, + alarm.events, + alarm.state, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + x11sync::DESTROY_ALARM => { + // Xorg `ProcSyncDestroyAlarm`: exact size, then the lookup. + if body.len() != 4 { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + 0, + ); + } + let alarm = x11sync::parse_resource(body).unwrap_or(0); + if let Err(outcome) = sync_known_alarm(state, client_id, sequence, header, alarm) { + return outcome; + } + // Xorg `FreeAlarm`: any client may destroy it; a Destroyed + // AlarmNotify goes to the owner and the selecting clients. + crate::core_loop::sync_await::destroy_alarm(state, alarm); + } + x11sync::CREATE_FENCE => { + if let Some(req) = x11sync::parse_create_fence(body) { + state.sync_fences.insert( + req.fence, + crate::server::SyncFence { + owner: client_id, + triggered: req.initially_triggered, + }, + ); + debug!( + "client {} #{} SYNC::CreateFence fence=0x{:x} initially_triggered={}", + client_id.0, sequence.0, req.fence, req.initially_triggered + ); + } + } + x11sync::DESTROY_FENCE => { + if let Some(fence) = x11sync::parse_resource(body) { + if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { + return outcome; + } + crate::core_loop::sync_await::fence_destroyed(state, fence); + state.sync_fences.remove(&fence); + backend.dri3_destroy_fence(fence); + debug!( + "client {} #{} SYNC::DestroyFence fence=0x{:x}", + client_id.0, sequence.0, fence + ); + } + } + x11sync::TRIGGER_FENCE => { + if let Some(fence) = x11sync::parse_resource(body) { + if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { + return outcome; + } + // For DRI3-imported xshmfence-backed fences, the + // server-side triggered bit is invisible to Mesa's local + // `xshmfence_await`. Forward the trigger to the backend so + // it writes the shared 4-byte counter + futex-wakes any + // local waiter — Mesa's `loader_dri3_copy_drawable` blocks + // on exactly that. + if let Err(e) = backend.dri3_trigger_fence(fence) { + log::warn!("SYNC::TriggerFence 0x{fence:x}: backend trigger failed: {e}"); + } + debug!( + "client {} #{} SYNC::TriggerFence fence=0x{:x}", + client_id.0, sequence.0, fence + ); + // Xorg `miSyncTriggerFence`: wakes every AwaitFence on it. + crate::core_loop::sync_await::fence_triggered(state, fence); + } + } + x11sync::RESET_FENCE => { + if let Some(fence) = x11sync::parse_resource(body) { + if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { + return outcome; + } + // Xorg `ProcSyncResetFence`: only a triggered fence can be + // reset (Xvfb: BadMatch naming the fence); a shared-memory + // fence is tested, and reset, in that memory. + if !crate::core_loop::sync_await::fence_is_triggered(state, &*backend, fence) { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_MATCH, + fence, + ); + } + backend.dri3_reset_fence(fence); + if let Some(f) = state.sync_fences.get_mut(&fence) { + f.triggered = false; + } + } + } + x11sync::QUERY_FENCE => { + let fence = x11sync::parse_resource(body).unwrap_or(0); + if let Err(outcome) = sync_known_fence(state, client_id, sequence, header, fence) { + return outcome; + } + // Xorg `ProcSyncQueryFence` → `CheckTriggered`: shared memory + // for a DRI3 xshmfence, the server's bit otherwise. + let triggered = + crate::core_loop::sync_await::fence_is_triggered(state, &*backend, fence); + let reply = x11sync::encode_query_fence_reply(byte_order, sequence, triggered); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &reply)); + } + x11sync::AWAIT_FENCE => { + // Xorg `ProcSyncAwaitFence`: suspend the client until any of + // the fences triggers (or is destroyed). Captured on Xvfb: + // empty list → BadValue, None / unknown fence → BadFence. + let Some(fences) = x11sync::parse_await_fence(byte_order, body) else { + return sync_error( + state, + client_id, + sequence, + header, + x11::error::BAD_LENGTH, + 0, + ); + }; + if fences.is_empty() { + return sync_error(state, client_id, sequence, header, x11::error::BAD_VALUE, 0); + } + for &fence in &fences { + if !state.sync_fences.contains_key(&fence) { + return sync_error( + state, + client_id, + sequence, + header, + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_FENCE, + fence, + ); + } + } + debug!( + "client {} #{} SYNC::AwaitFence n={}", + client_id.0, + sequence.0, + fences.len() + ); + let waits = fences + .into_iter() + .map(|fence| crate::server::SyncAwaitCondition::Fence { fence }) + .collect(); + crate::core_loop::sync_await::begin_await(state, &*backend, client_id, waits); + } + x11sync::SET_PRIORITY => { + // Stub. + } + x11sync::GET_PRIORITY => { + let reply = x11sync::encode_get_priority_reply(byte_order, sequence, 0); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + return Ok(write_to_client(client, client_id, &reply)); + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// Xorg `SyncChangeAlarmAttributes` + `SyncInitTrigger` for CreateAlarm +/// (on a fresh alarm) and ChangeAlarm (on a copy the caller writes back +/// whatever the outcome). `values` is the value list, one word each and +/// two for VALUE and DELTA, already length-checked against `mask`. +/// +/// Order and partial effects, as Xorg (captured on Xvfb): +/// 1. The list is walked in mask-bit order; an `events` word other than +/// True/False is BadValue naming it, an unknown bit BadValue naming the +/// mask bits above it. Nothing is changed yet. +/// 2. `events` selects AlarmNotify for `client` — it stays selected even +/// if the request then fails. +/// 3. With DELTA or TEST_TYPE in the mask, a positive test with a +/// negative delta or a negative test with a positive delta is +/// BadMatch; nothing else is changed. +/// 4. Delta, value type, value and test type are stored. +/// 5. The trigger is initialised: an unknown counter is BadCounter, an +/// invalid value type BadValue naming it; the wait value resolves +/// (Relative without a counter is BadMatch; an INT64 overflow is +/// BadValue naming the value's high word, with the wrapped sum stored); +/// an invalid test type is BadValue naming it. Only then do the counter +/// and the test the trigger runs change, and the alarm goes Active. +/// +/// So a failing ChangeAlarm can leave step 4 behind: a stored bad test +/// type is what QueryAlarm reports, while the alarm keeps running its old +/// test. +fn change_alarm_attributes( + state: &ServerState, + alarm_id: u32, + alarm: &mut crate::server::SyncAlarm, + client: ClientId, + mask: u32, + values: &[u32], +) -> Result<(), (u8, u32)> { + use yserver_protocol::x11::sync as x11sync; + let int64 = |hi: u32, lo: u32| (i64::from(hi.cast_signed()) << 32) | i64::from(lo); + let mut words = values.iter().copied(); + let mut next = || words.next().unwrap_or(0); + let (mut counter, mut value_type, mut raw_wait, mut test_type, mut delta) = ( + alarm.counter, + alarm.value_type, + alarm.raw_wait, + alarm.test_type, + alarm.delta, + ); + let mut select = None; + let mut remaining = mask; + while remaining != 0 { + let bit = 1u32 << remaining.trailing_zeros(); + remaining &= !bit; + match bit { + x11sync::CA_COUNTER => counter = next(), + x11sync::CA_VALUE_TYPE => value_type = next(), + x11sync::CA_VALUE => raw_wait = int64(next(), next()), + x11sync::CA_TEST_TYPE => test_type = next(), + x11sync::CA_DELTA => delta = int64(next(), next()), + x11sync::CA_EVENTS => { + let events = next(); + if events > 1 { + return Err((x11::error::BAD_VALUE, events)); + } + select = Some(events == 1); + } + _ => return Err((x11::error::BAD_VALUE, remaining)), + } + } + if let Some(want) = select { + crate::core_loop::sync_await::select_alarm_events(alarm, client, want); + } + if mask & (x11sync::CA_DELTA | x11sync::CA_TEST_TYPE) != 0 { + let positive = matches!( + test_type, + x11sync::TEST_POSITIVE_COMPARISON | x11sync::TEST_POSITIVE_TRANSITION + ); + let negative = matches!( + test_type, + x11sync::TEST_NEGATIVE_COMPARISON | x11sync::TEST_NEGATIVE_TRANSITION + ); + if (positive && delta < 0) || (negative && delta > 0) { + return Err((x11::error::BAD_MATCH, alarm_id)); + } + } + alarm.delta = delta; + alarm.value_type = value_type; + alarm.raw_wait = raw_wait; + alarm.test_type = test_type; + + let mut new_counter = alarm.counter; + if mask & x11sync::CA_COUNTER != 0 { + if counter != 0 + && !crate::core_loop::sync_await::is_system_counter(counter) + && !state.sync_counters.contains_key(&counter) + { + return Err(( + crate::nested::SYNC_FIRST_ERROR + x11sync::BAD_COUNTER, + counter, + )); + } + new_counter = counter; + } + let current = if new_counter == 0 { + None + } else { + crate::core_loop::sync_await::counter_value(state, new_counter) + }; + if mask & x11sync::CA_VALUE_TYPE != 0 + && value_type != x11sync::VALUE_TYPE_ABSOLUTE + && value_type != x11sync::VALUE_TYPE_RELATIVE + { + return Err((x11::error::BAD_VALUE, value_type)); + } + if mask & (x11sync::CA_VALUE_TYPE | x11sync::CA_VALUE) != 0 { + if value_type == x11sync::VALUE_TYPE_ABSOLUTE { + alarm.wait_value = raw_wait; + } else { + let Some(value) = current else { + return Err((x11::error::BAD_MATCH, alarm_id)); + }; + let (sum, overflow) = value.overflowing_add(raw_wait); + alarm.wait_value = sum; + if overflow { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + return Err((x11::error::BAD_VALUE, (raw_wait >> 32) as u32)); + } + } + } + if mask & x11sync::CA_TEST_TYPE != 0 { + if test_type > x11sync::TEST_NEGATIVE_COMPARISON { + return Err((x11::error::BAD_VALUE, test_type)); + } + alarm.check_type = test_type; + } + alarm.counter = new_counter; + alarm.state = x11sync::ALARM_STATE_ACTIVE; + Ok(()) +} + +/// The value list of a length-checked CreateAlarm / ChangeAlarm body. +fn alarm_value_words(body: &[u8]) -> Vec { + body.get(8..) + .unwrap_or_default() + .chunks_exact(4) + .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])) + .collect() +} + +/// Evaluate every active alarm watching `counter` after it moved from +/// `old` to `new`, firing `AlarmNotify` to each alarm's owner when its +/// trigger test crosses. +/// +/// Re-arm behaviour (Xorg sync.c:548-555, 589-597): +/// - `delta != 0`: advance `wait_value` past the current value so the +/// next crossing re-fires; on `i64` overflow transition to Inactive. +/// - `delta == 0` + Comparison test type: transition to Inactive. +/// - `delta == 0` + Transition test type: stay Active with `wait_value` +/// unchanged — the alarm quiesces until the next edge crossing. +/// +/// Human-friendly name for a SYNC counter id (system counters land +/// here; client-allocated counters fall through to ``). +fn sync_counter_name(counter: u32) -> &'static str { + use yserver_protocol::x11::sync as x11sync; + match counter { + x11sync::SERVERTIME_COUNTER => "SERVERTIME", + x11sync::IDLETIME_COUNTER => "IDLETIME", + x11sync::IDLETIME_DEVICE_VCP => "IDLETIME-VCP", + x11sync::IDLETIME_DEVICE_VCK => "IDLETIME-VCK", + _ => "", + } +} + +/// Human-friendly name for a SYNC alarm test type. +fn sync_test_type_name(test_type: u32) -> &'static str { + use yserver_protocol::x11::sync as x11sync; + match test_type { + x11sync::TEST_POSITIVE_TRANSITION => "PosTransition", + x11sync::TEST_NEGATIVE_TRANSITION => "NegTransition", + x11sync::TEST_POSITIVE_COMPARISON => "PosComparison", + x11sync::TEST_NEGATIVE_COMPARISON => "NegComparison", + _ => "?", + } +} + +/// Human-friendly name for a SYNC alarm state. +fn sync_alarm_state_name(state: u8) -> &'static str { + use yserver_protocol::x11::sync as x11sync; + match state { + x11sync::ALARM_STATE_ACTIVE => "Active", + x11sync::ALARM_STATE_INACTIVE => "Inactive", + x11sync::ALARM_STATE_DESTROYED => "Destroyed", + _ => "?", + } +} + +/// Run the alarms watching `counter` for a change from `old` to `new` +/// (Xorg `SyncChangeCounter` → each alarm trigger's `CheckTrigger`). This +/// is the frame-timing signal mutter/muffin waits on before compositing a +/// client frame and emitting `_NET_WM_FRAME_DRAWN`, and also the +/// idle/wake pair used by mate-power-manager. +pub(crate) fn evaluate_alarms_for_counter( + state: &mut ServerState, + counter: u32, + old: i64, + new: i64, +) { + use yserver_protocol::x11::sync as x11sync; + let mut candidates: Vec = state + .sync_alarms + .iter() + .filter(|(_, a)| { + a.counter == counter + && a.state == x11sync::ALARM_STATE_ACTIVE + && x11sync::trigger_fires(a.check_type, old, new, a.wait_value) + }) + .map(|(id, _)| *id) + .collect(); + candidates.sort_unstable(); + for alarm_id in candidates { + alarm_trigger_fired(state, alarm_id, new); + } +} + +/// The trigger test CreateAlarm / ChangeAlarm run on the one alarm they +/// set up: its counter's current value, as both old and new (so only a +/// comparison can already hold). +fn check_new_alarm_trigger(state: &mut ServerState, alarm_id: u32, counter: u32) { + use yserver_protocol::x11::sync as x11sync; + let now_value = crate::core_loop::sync_await::counter_value(state, counter).unwrap_or(0); + if counter == x11sync::SERVERTIME_COUNTER { + state.sync_servertime_last = Some(now_value); + } + let holds = state + .sync_alarms + .get(&alarm_id) + .is_some_and(|a| x11sync::trigger_fires(a.check_type, now_value, now_value, a.wait_value)); + if holds { + alarm_trigger_fired(state, alarm_id, now_value); + } +} + +/// Xorg `SyncAlarmTriggerFired`: alarm `alarm_id` went off with its +/// counter at `value` (0 and no counter for a counterless alarm). A +/// counterless alarm, or a comparison with delta 0, goes Inactive; +/// otherwise the wait value advances by delta until the test no longer +/// holds (Inactive, value kept, on INT64 overflow). The `AlarmNotify` +/// carries the new state and the old wait value; the new wait value is +/// stored after it is sent. +fn alarm_trigger_fired(state: &mut ServerState, alarm_id: u32, value: i64) { + use yserver_protocol::x11::sync as x11sync; + let Some(a) = state.sync_alarms.get(&alarm_id) else { + return; + }; + if a.state != x11sync::ALARM_STATE_ACTIVE { + return; + } + // Xorg reads the stored test type for the "delta 0 on a comparison" + // rule but re-arms with the trigger's check function; the two differ + // only after a ChangeAlarm that failed on an invalid test type. + let (test_type, check_type) = (a.test_type, a.check_type); + let (owner, counter, fired_wait, delta) = (a.owner, a.counter, a.wait_value, a.delta); + let is_comparison = matches!( + test_type, + x11sync::TEST_POSITIVE_COMPARISON | x11sync::TEST_NEGATIVE_COMPARISON + ); + let (new_wait, new_state) = if counter == 0 || (delta == 0 && is_comparison) { + (fired_wait, x11sync::ALARM_STATE_INACTIVE) + } else if delta == 0 { + // Transition + delta 0: stays Active with the same wait value; + // it fires again on the next crossing. + (fired_wait, x11sync::ALARM_STATE_ACTIVE) + } else { + let mut w = fired_wait; + let mut guard = 0u32; + let mut overflowed = false; + // The guard bounds what Xorg does not: after that failed + // ChangeAlarm a delta of the wrong sign passes the (unmatched) + // sign check, and Xorg's loop then steps toward INT64 overflow + // one delta at a time — a hung server (seen on Xvfb). + while x11sync::comparison_satisfied(check_type, value, w) && guard < 1_000_000 { + match w.checked_add(delta) { + Some(next) => { + w = next; + guard += 1; + } + None => { + overflowed = true; + break; + } + } + } + if overflowed { + (fired_wait, x11sync::ALARM_STATE_INACTIVE) + } else { + (w, x11sync::ALARM_STATE_ACTIVE) + } + }; + let owner_class = state + .client_wm_class + .get(&owner.0) + .map(String::as_str) + .unwrap_or(""); + log::debug!( + "sync: alarm 0x{alarm_id:x} fired client {owner_id}/{owner_class:?} \ + counter={counter_name}(0x{counter:x}) test={test} \ + value={value} wait={fired_wait} → state={state_name}", + owner_id = owner.0, + counter_name = sync_counter_name(counter), + test = sync_test_type_name(test_type), + state_name = sync_alarm_state_name(new_state), + ); + if let Some(a) = state.sync_alarms.get_mut(&alarm_id) { + a.state = new_state; + } + crate::core_loop::sync_await::send_alarm_notify(state, alarm_id, value); + if let Some(a) = state.sync_alarms.get_mut(&alarm_id) { + a.wait_value = new_wait; + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_grabs.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_grabs.rs new file mode 100644 index 000000000..7fc8f1242 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_grabs.rs @@ -0,0 +1,764 @@ +use super::*; +use crate::access::{ + AccessContext, AccessMode, AccessPolicy, Decision, DenyError, RequestOpcodes, ResourceKind, + ResourceTarget, +}; + +const CLIENT: ClientId = ClientId(1); +const OTHER_CLIENT: ClientId = ClientId(2); +const BAD_VALUE: u8 = yserver_protocol::x11::error::BAD_VALUE; +const BAD_ATOM: u8 = yserver_protocol::x11::error::BAD_ATOM; +const DENY_VALUE: u32 = 0x55; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct ExpectedCheck { + id: ResourceId, + kind: ResourceKind, + mode: AccessMode, +} + +impl ExpectedCheck { + fn target(self) -> ResourceTarget { + ResourceTarget { + id: self.id, + kind: self.kind, + creation: None, + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct RecordedCheck { + client: ClientId, + request: Option, + target: ResourceTarget, + mode: AccessMode, + owner: Option, +} + +struct ResourceRecorder { + calls: Arc>>, + deny: Option, +} + +impl AccessPolicy for ResourceRecorder { + fn resource( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.calls.lock().unwrap().push(RecordedCheck { + client, + request: ctx.request(), + target: *target, + mode, + owner: ctx.owner(target.id, target.kind), + }); + if self.deny + == Some(ExpectedCheck { + id: target.id, + kind: target.kind, + mode, + }) + { + Decision::Deny(DenyError { + code: BAD_VALUE, + value: DENY_VALUE, + }) + } else { + Decision::Allow + } + } +} + +struct Fixture { + state: ServerState, + backend: RecordingBackend, + peer: UnixStream, + _other_peer: UnixStream, + window: ResourceId, + other_window: ResourceId, + confine: ResourceId, + foreign_window: ResourceId, + cursor: ResourceId, +} + +impl Fixture { + fn new() -> Self { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let other_peer = install_client(&mut state, OTHER_CLIENT.0); + let window = ResourceId(0x0055_0001); + let other_window = ResourceId(0x0055_0002); + let confine = ResourceId(0x0055_0003); + let foreign_parent = ResourceId(0x0055_0004); + let foreign_window = ResourceId(0x0055_0005); + let pixmap = ResourceId(0x0055_0006); + let cursor = ResourceId(0x0055_0007); + for (owner, id, parent) in [ + (CLIENT, window, ROOT_WINDOW), + (CLIENT, other_window, ROOT_WINDOW), + (CLIENT, confine, ROOT_WINDOW), + (OTHER_CLIENT, foreign_parent, ROOT_WINDOW), + (OTHER_CLIENT, foreign_window, foreign_parent), + ] { + state.resources.create_window( + owner, + CreateWindowRequest { + depth: 24, + window: id, + parent, + width: 32, + height: 32, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + state.resources.window_mut(window).unwrap().map_state = + crate::resources::MapState::Viewable; + state.resources.window_mut(confine).unwrap().map_state = + crate::resources::MapState::Viewable; + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: CLIENT, + grab_window: window, + button: 1, + modifiers: 0, + owner_events: false, + event_mask: 4, + pointer_mode: 0, + keyboard_mode: 0, + confine_to: ResourceId(0), + via_xi2: false, + }); + state.key_grabs.push(crate::server::KeyGrab { + device_id: 0, + owner: CLIENT, + grab_window: window, + keycode: 24, + modifiers: 0, + owner_events: false, + pointer_mode: 0, + keyboard_mode: 0, + via_xi2: false, + xi2_mask: 0, + }); + state.set_pointer_grab(crate::server::ActivePointerGrab { + owner: CLIENT, + grab_window: window, + event_mask: 0, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + + let mut backend = RecordingBackend::new(); + let pixmap_body = words(&[pixmap.0, ROOT_WINDOW.0, 16 | (16 << 16)]); + let bytes = issue_request( + &mut state, + &mut backend, + &mut peer, + CLIENT, + 1, + 53, + 24, + &pixmap_body, + ); + assert_no_error(&bytes, "access grab fixture CreatePixmap"); + let mut cursor_body = words(&[cursor.0, pixmap.0, 0]); + cursor_body.extend_from_slice(&[0; 16]); + let bytes = issue_request( + &mut state, + &mut backend, + &mut peer, + CLIENT, + 2, + 93, + 0, + &cursor_body, + ); + assert_no_error(&bytes, "access grab fixture CreateCursor"); + + Self { + state, + backend, + peer, + _other_peer: other_peer, + window, + other_window, + confine, + foreign_window, + cursor, + } + } + + fn install_policy( + &mut self, + calls: Arc>>, + deny: Option, + ) { + self.state + .install_access_policy(Arc::new(ResourceRecorder { calls, deny })); + } + + fn run(&mut self, sequence: u16, opcode: u8, data: u8, body: &[u8]) -> Vec { + issue_request( + &mut self.state, + &mut self.backend, + &mut self.peer, + CLIENT, + sequence, + opcode, + data, + body, + ) + } +} + +fn issue_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + client: ClientId, + sequence: u16, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + process_request( + state, + backend, + client, + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("request through process_request"); + read_all_available(peer) +} + +fn words(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +fn append_u16(body: &mut Vec, value: u16) { + body.extend_from_slice(&value.to_le_bytes()); +} + +fn assert_x11_error(bytes: &[u8], code: u8, value: u32, opcode: u8, sequence: u16) { + let mut expected = vec![0, code]; + expected.extend_from_slice(&sequence.to_le_bytes()); + expected.extend_from_slice(&value.to_le_bytes()); + expected.extend_from_slice(&0u16.to_le_bytes()); + expected.push(opcode); + expected.extend_from_slice(&[0; 21]); + assert_eq!(bytes, expected, "request {opcode} denial packet"); +} + +fn access_cases(fixture: &Fixture) -> Vec<(u8, u8, Vec, Vec)> { + let mut grab_pointer = words(&[fixture.window.0]); + append_u16(&mut grab_pointer, 0); + grab_pointer.extend_from_slice(&[1, 1]); + grab_pointer.extend_from_slice(&fixture.confine.0.to_le_bytes()); + grab_pointer.extend_from_slice(&fixture.cursor.0.to_le_bytes()); + grab_pointer.extend_from_slice(&0u32.to_le_bytes()); + + let mut grab_button = words(&[fixture.window.0]); + append_u16(&mut grab_button, 0); + grab_button.extend_from_slice(&[1, 1]); + grab_button.extend_from_slice(&fixture.confine.0.to_le_bytes()); + grab_button.extend_from_slice(&fixture.cursor.0.to_le_bytes()); + grab_button.extend_from_slice(&[1, 0]); + append_u16(&mut grab_button, 0); + + let mut ungrab_button = words(&[fixture.window.0]); + append_u16(&mut ungrab_button, 0); + let mut change_pointer_grab = words(&[fixture.cursor.0, 0]); + append_u16(&mut change_pointer_grab, 4); + append_u16(&mut change_pointer_grab, 0); + let mut grab_keyboard = words(&[fixture.window.0, 0]); + grab_keyboard.extend_from_slice(&[1, 1, 0, 0]); + let mut grab_key = words(&[fixture.window.0]); + append_u16(&mut grab_key, 0); + grab_key.extend_from_slice(&[24, 1, 1, 0, 0, 0]); + let mut ungrab_key = words(&[fixture.window.0]); + append_u16(&mut ungrab_key, 0); + ungrab_key.extend_from_slice(&[0, 0]); + let set_focus = words(&[fixture.window.0, 0]); + let set_selection_owner = words(&[fixture.other_window.0, 1, 0]); + let convert_selection = words(&[fixture.window.0, 1, 31, 0, 0]); + + vec![ + ( + 6, + 0, + words(&[fixture.foreign_window.0]), + vec![ExpectedCheck { + id: fixture.foreign_window, + kind: ResourceKind::Window, + mode: AccessMode::MANAGE, + }], + ), + ( + 22, + 0, + set_selection_owner, + vec![ExpectedCheck { + id: fixture.other_window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }], + ), + ( + 24, + 0, + convert_selection, + vec![ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }], + ), + ( + 26, + 0, + grab_pointer, + vec![ + ExpectedCheck { + id: fixture.confine, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }, + ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }, + ExpectedCheck { + id: fixture.cursor, + kind: ResourceKind::Cursor, + mode: AccessMode::USE, + }, + ], + ), + ( + 28, + 0, + grab_button, + vec![ + ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }, + ExpectedCheck { + id: fixture.confine, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }, + ExpectedCheck { + id: fixture.cursor, + kind: ResourceKind::Cursor, + mode: AccessMode::USE, + }, + ], + ), + ( + 29, + 1, + ungrab_button, + vec![ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::READ, + }], + ), + ( + 30, + 0, + change_pointer_grab, + vec![ExpectedCheck { + id: fixture.cursor, + kind: ResourceKind::Cursor, + mode: AccessMode::USE, + }], + ), + ( + 31, + 0, + grab_keyboard, + vec![ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }], + ), + ( + 33, + 0, + grab_key, + vec![ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }], + ), + ( + 34, + 24, + ungrab_key, + vec![ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + }], + ), + ( + 42, + 0, + set_focus, + vec![ExpectedCheck { + id: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }], + ), + ( + 113, + 0, + words(&[ROOT_WINDOW.0]), + vec![ExpectedCheck { + id: ROOT_WINDOW, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + }], + ), + ] +} + +fn snapshot(state: &ServerState) -> String { + format!( + "{:?}", + ( + &state.clients[&CLIENT.0].save_set, + &state.selections, + &state.button_grabs, + &state.key_grabs, + state.active_pointer_grab, + state.active_keyboard_grab, + state.pointer_confine_to, + state.core_focus, + ) + ) +} + +fn expected_owner(fixture: &Fixture, id: ResourceId) -> Option { + if id == ROOT_WINDOW { + Some(crate::resources::SERVER_OWNER) + } else if id == fixture.foreign_window { + Some(OTHER_CLIENT) + } else { + Some(CLIENT) + } +} + +#[test] +fn task8_core_resource_requests_deny_before_effects() { + // Mutation: remove or move a listed access check past its first effect; that row's denial or snapshot assertion must fail. + for (opcode, data, body, checks) in access_cases(&Fixture::new()) { + for (index, denied) in checks.iter().copied().enumerate() { + let mut fixture = Fixture::new(); + match opcode { + 26 => { + assert_eq!( + fixture + .state + .resources + .window(fixture.confine) + .unwrap() + .map_state, + crate::resources::MapState::Viewable + ); + assert!(fixture.state.active_pointer_grab.is_some()); + } + 29 => assert!(fixture.state.button_grabs.iter().any(|grab| { + grab.owner == CLIENT + && grab.grab_window == fixture.window + && grab.button == 1 + && grab.modifiers == 0 + })), + 30 => assert!(fixture.state.active_pointer_grab.is_some()), + 33 => assert!(fixture.state.key_grabs.iter().any(|grab| { + grab.owner == CLIENT + && grab.grab_window == fixture.window + && grab.keycode == 24 + && grab.modifiers == 0 + })), + 34 => assert!(fixture.state.key_grabs.iter().any(|grab| { + grab.owner == CLIENT + && grab.grab_window == fixture.window + && grab.keycode == 24 + && grab.modifiers == 0 + })), + _ => {} + } + let calls = Arc::new(Mutex::new(Vec::new())); + fixture.install_policy(Arc::clone(&calls), Some(denied)); + let state_before = snapshot(&fixture.state); + let backend_before = fixture.backend.calls(); + let bytes = fixture.run(50, opcode, data, &body); + assert_x11_error(&bytes, BAD_VALUE, DENY_VALUE, opcode, 50); + assert_eq!(fixture.backend.calls(), backend_before, "opcode {opcode}"); + assert_eq!(snapshot(&fixture.state), state_before, "opcode {opcode}"); + let recorded = calls.lock().unwrap().clone(); + assert_eq!( + recorded.len(), + index + 1, + "opcode {opcode} must stop at denied operand" + ); + for (actual, expected) in recorded.iter().zip(checks.iter()) { + assert_eq!(actual.client, CLIENT, "opcode {opcode}"); + assert_eq!( + actual.request, + Some(RequestOpcodes { + major: opcode, + minor: 0, + }), + "opcode {opcode} request" + ); + assert_eq!(actual.target, expected.target(), "opcode {opcode} target"); + assert_eq!(actual.mode, expected.mode, "opcode {opcode} mode"); + assert_eq!( + actual.owner, + expected_owner(&fixture, expected.id), + "opcode {opcode} owner" + ); + } + } + } +} + +#[test] +fn task8_core_resource_requests_ask_in_protocol_order() { + // Mutation: change a checked target, mode, request opcode, or operand order; the recorded call sequence must fail. + for (index, (opcode, data, body, checks)) in + access_cases(&Fixture::new()).into_iter().enumerate() + { + let mut fixture = Fixture::new(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture.install_policy(Arc::clone(&calls), None); + let bytes = fixture.run(u16::try_from(80 + index).unwrap(), opcode, data, &body); + assert!( + bytes.is_empty() || bytes[0] != 0, + "opcode {opcode} unexpectedly errored" + ); + let recorded = calls.lock().unwrap().clone(); + assert_eq!(recorded.len(), checks.len(), "opcode {opcode} call count"); + for (actual, expected) in recorded.iter().zip(checks) { + assert_eq!(actual.client, CLIENT, "opcode {opcode} client"); + assert_eq!( + actual.request, + Some(RequestOpcodes { + major: opcode, + minor: 0, + }), + "opcode {opcode} request" + ); + assert_eq!(actual.target, expected.target(), "opcode {opcode} target"); + assert_eq!(actual.mode, expected.mode, "opcode {opcode} mode"); + assert_eq!( + actual.owner, + expected_owner(&fixture, expected.id), + "opcode {opcode} owner" + ); + } + } +} + +#[test] +fn change_save_set_denied_leaves_save_set_unchanged() { + // Mutation: bypass the ChangeSaveSet MANAGE check; the denial and unchanged save-set assertions must fail. + let mut fixture = Fixture::new(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture.install_policy( + Arc::clone(&calls), + Some(ExpectedCheck { + id: fixture.foreign_window, + kind: ResourceKind::Window, + mode: AccessMode::MANAGE, + }), + ); + let original_parent = fixture + .state + .resources + .window(fixture.foreign_window) + .unwrap() + .parent; + let bytes = fixture.run(90, 6, 0, &words(&[fixture.foreign_window.0])); + assert_x11_error(&bytes, BAD_VALUE, DENY_VALUE, 6, 90); + assert!( + !fixture.state.clients[&CLIENT.0] + .save_set + .contains(&fixture.foreign_window) + ); + // Limitation: yserver does not consume save-set entries at disconnect today; this pre-existing behavior is out of scope. + crate::core_loop::process_disconnect::process_disconnect( + &mut fixture.state, + &mut fixture.backend, + CLIENT, + ); + let window = fixture + .state + .resources + .window(fixture.foreign_window) + .expect("the other client's save-set window survives"); + assert_eq!(window.parent, original_parent); + assert_ne!(window.parent, ROOT_WINDOW); +} + +#[test] +fn kill_client_resource_check_precedes_kill() { + // Mutation: bypass the KillClient resource check; the policy error and owner-connected assertions must fail. + let mut fixture = Fixture::new(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture.install_policy( + Arc::clone(&calls), + Some(ExpectedCheck { + id: fixture.foreign_window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + }), + ); + let backend_before = fixture.backend.calls(); + let bytes = fixture.run(91, 113, 0, &words(&[fixture.foreign_window.0])); + assert_x11_error(&bytes, BAD_VALUE, DENY_VALUE, 113, 91); + assert_eq!(fixture.backend.calls(), backend_before); + assert!(fixture.state.clients.contains_key(&OTHER_CLIENT.0)); + assert_eq!( + fixture.state.resources.window_owner(fixture.foreign_window), + Some(OTHER_CLIENT) + ); + assert_eq!( + calls.lock().unwrap().as_slice(), + &[RecordedCheck { + client: CLIENT, + request: Some(RequestOpcodes { + major: 113, + minor: 0, + }), + target: ResourceTarget { + id: fixture.foreign_window, + kind: ResourceKind::Window, + creation: None, + }, + mode: AccessMode::GET_ATTR, + owner: Some(OTHER_CLIENT), + }] + ); +} + +#[test] +fn task8_set_selection_owner_access_check_precedes_invalid_atom() { + // Mutation: move SetSelectionOwner's SET_ATTR check below atom validation; the policy-error assertion must fail. + let invalid_atom = u32::MAX; + let mut denied = Fixture::new(); + let calls = Arc::new(Mutex::new(Vec::new())); + denied.install_policy( + Arc::clone(&calls), + Some(ExpectedCheck { + id: denied.other_window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }), + ); + let body = words(&[denied.other_window.0, invalid_atom, 0]); + let bytes = denied.run(92, 22, 0, &body); + assert_x11_error(&bytes, BAD_VALUE, DENY_VALUE, 22, 92); + assert_eq!(calls.lock().unwrap().len(), 1); + + let mut no_policy = Fixture::new(); + let body = words(&[no_policy.other_window.0, invalid_atom, 0]); + let bytes = no_policy.run(93, 22, 0, &body); + assert_x11_error(&bytes, BAD_ATOM, invalid_atom, 22, 93); +} + +#[test] +fn task8_convert_selection_access_check_precedes_invalid_atom() { + // Mutation: move ConvertSelection's SET_ATTR check below atom validation; the policy-error assertion must fail. + let invalid_atom = u32::MAX; + let mut denied = Fixture::new(); + let calls = Arc::new(Mutex::new(Vec::new())); + denied.install_policy( + Arc::clone(&calls), + Some(ExpectedCheck { + id: denied.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }), + ); + let body = words(&[denied.window.0, invalid_atom, 1, 0, 0]); + let bytes = denied.run(94, 24, 0, &body); + assert_x11_error(&bytes, BAD_VALUE, DENY_VALUE, 24, 94); + assert_eq!(calls.lock().unwrap().len(), 1); + + let mut no_policy = Fixture::new(); + let body = words(&[no_policy.window.0, invalid_atom, 1, 0, 0]); + let bytes = no_policy.run(95, 24, 0, &body); + assert_x11_error(&bytes, BAD_ATOM, 0, 24, 95); +} + +#[test] +fn task8_stale_set_selection_owner_still_checks_window() { + // Mutation: keep the stale-time return before SetSelectionOwner's SET_ATTR check; the policy-error assertion must fail. + let mut denied = Fixture::new(); + denied.state.start_instant = std::time::Instant::now() - std::time::Duration::from_secs(1); + let selection = AtomId(1); + let prior_time = denied.state.timestamp_now(); + let prior = crate::server::SelectionOwner { + window: denied.other_window, + last_time_changed: prior_time, + client: Some(OTHER_CLIENT), + }; + denied.state.selections.insert(selection, prior); + let calls = Arc::new(Mutex::new(Vec::new())); + denied.install_policy( + Arc::clone(&calls), + Some(ExpectedCheck { + id: denied.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + }), + ); + let body = words(&[denied.window.0, selection.0, prior_time - 1]); + let bytes = denied.run(96, 22, 0, &body); + assert_x11_error(&bytes, BAD_VALUE, DENY_VALUE, 22, 96); + assert_eq!(calls.lock().unwrap().len(), 1); + assert_eq!(denied.state.selections.get(&selection), Some(&prior)); + + let mut no_policy = Fixture::new(); + no_policy.state.start_instant = std::time::Instant::now() - std::time::Duration::from_secs(1); + let prior_time = no_policy.state.timestamp_now(); + let prior = crate::server::SelectionOwner { + window: no_policy.other_window, + last_time_changed: prior_time, + client: Some(OTHER_CLIENT), + }; + no_policy.state.selections.insert(selection, prior); + let body = words(&[no_policy.window.0, selection.0, prior_time - 1]); + let bytes = no_policy.run(97, 22, 0, &body); + assert!(bytes.is_empty(), "stale SetSelectionOwner stays silent"); + assert_eq!(no_policy.state.selections.get(&selection), Some(&prior)); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_properties.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_properties.rs new file mode 100644 index 000000000..80e8df3c7 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_properties.rs @@ -0,0 +1,523 @@ +use super::*; +use crate::{ + access::{ + AccessContext, AccessMode, AccessPolicy, Decision, DenyError, RequestOpcodes, ResourceKind, + ResourceTarget, + }, + properties::{PropertyFormat, PropertyValue}, +}; +use yserver_protocol::x11::AtomId; + +const CLIENT: ClientId = ClientId(1); +const WINDOW: ResourceId = ResourceId(0x0059_0001); +const DENY_ERROR: DenyError = DenyError { + code: yserver_protocol::x11::error::BAD_VALUE, + value: 0x55, +}; + +#[derive(Clone, Debug, Eq, PartialEq)] +enum AccessCall { + Resource { + client: ClientId, + request: Option, + target: ResourceTarget, + mode: AccessMode, + }, + Property { + client: ClientId, + request: Option, + window: ResourceId, + property: AtomId, + mode: AccessMode, + }, +} + +struct PropertyPolicy { + calls: Arc>>, + deny_at: Option, + deny_all: bool, +} + +impl PropertyPolicy { + fn record(&self, call: AccessCall) -> Decision { + let mut calls = self.calls.lock().unwrap(); + let index = calls.len(); + calls.push(call); + if self.deny_all || self.deny_at == Some(index) { + Decision::Deny(DENY_ERROR) + } else { + Decision::Allow + } + } +} + +impl AccessPolicy for PropertyPolicy { + fn resource( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.record(AccessCall::Resource { + client, + request: ctx.request(), + target: *target, + mode, + }) + } + + fn property( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + window: ResourceId, + property: AtomId, + mode: AccessMode, + ) -> Decision { + self.record(AccessCall::Property { + client, + request: ctx.request(), + window, + property, + mode, + }) + } +} + +struct Fixture { + state: ServerState, + backend: RecordingBackend, + peer: UnixStream, + window: ResourceId, + type_atom: AtomId, + properties: Vec, +} + +impl Fixture { + fn new(property_count: usize) -> Self { + let mut state = ServerState::new(); + let peer = install_client(&mut state, CLIENT.0); + create_root_child(&mut state, WINDOW.0); + let type_atom = state.atoms.intern("TASK9_PROPERTY_TYPE", false); + let properties = (0..property_count) + .map(|i| state.atoms.intern(&format!("TASK9_PROPERTY_{i}"), false)) + .collect::>(); + for (index, property) in properties.iter().copied().enumerate() { + state.resources.set_window_property( + WINDOW, + property, + PropertyValue { + r#type: type_atom, + format: PropertyFormat::F8, + data: vec![u8::try_from(index + 1).unwrap()], + }, + ); + } + Self { + state, + backend: RecordingBackend::new(), + peer, + window: WINDOW, + type_atom, + properties, + } + } + + fn atom(&mut self, name: &str) -> AtomId { + self.state.atoms.intern(name, false) + } + + fn request(&mut self, sequence: u16, opcode: u8, data: u8, body: &[u8]) -> Vec { + process_request( + &mut self.state, + &mut self.backend, + CLIENT, + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("request through process_request"); + read_all_available(&mut self.peer) + } + + fn install_policy(&mut self, deny_at: Option) -> Arc>> { + self.install_policy_with_deny(deny_at, false) + } + + fn install_policy_with_deny( + &mut self, + deny_at: Option, + deny_all: bool, + ) -> Arc>> { + let calls = Arc::new(Mutex::new(Vec::new())); + self.state.install_access_policy(Arc::new(PropertyPolicy { + calls: Arc::clone(&calls), + deny_at, + deny_all, + })); + calls + } + + fn property_snapshot(&self) -> HashMap { + self.state + .resources + .window(self.window) + .unwrap() + .properties + .clone() + } +} + +fn words(values: &[u32]) -> Vec { + values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect() +} + +fn resource_call(opcode: u8, mode: AccessMode) -> AccessCall { + AccessCall::Resource { + client: CLIENT, + request: Some(RequestOpcodes { + major: opcode, + minor: 0, + }), + target: ResourceTarget { + id: WINDOW, + kind: ResourceKind::Window, + creation: None, + }, + mode, + } +} + +fn property_call(opcode: u8, property: AtomId, mode: AccessMode) -> AccessCall { + AccessCall::Property { + client: CLIENT, + request: Some(RequestOpcodes { + major: opcode, + minor: 0, + }), + window: WINDOW, + property, + mode, + } +} + +fn change_body(fixture: &Fixture, property: AtomId) -> Vec { + let mut body = words(&[fixture.window.0, property.0, fixture.type_atom.0]); + body.extend_from_slice(&[8, 0, 0, 0]); + body.extend_from_slice(&1u32.to_le_bytes()); + body.push(0x7f); + body.resize(body.len().div_ceil(4) * 4, 0); + body +} + +fn get_body(fixture: &Fixture, property: AtomId) -> Vec { + words(&[fixture.window.0, property.0, 0, 0, 100]) +} + +fn assert_policy_error(bytes: &[u8], opcode: u8, sequence: u16) { + let mut expected = vec![0, DENY_ERROR.code]; + expected.extend_from_slice(&sequence.to_le_bytes()); + expected.extend_from_slice(&DENY_ERROR.value.to_le_bytes()); + expected.extend_from_slice(&0u16.to_le_bytes()); + expected.push(opcode); + expected.extend_from_slice(&[0; 21]); + assert_eq!(bytes, expected, "denial for core request {opcode}"); +} + +#[derive(Clone, Copy, Debug)] +enum AccessCase { + Replace, + Append, + Prepend, + AbsentAppend, + Delete, + Get, + GetDelete, + ListWindow, + RotateWindow, +} + +fn run_access_case(fixture: &mut Fixture, case: AccessCase) -> (u8, u8, Vec, Vec) { + match case { + AccessCase::Replace => { + let property = fixture.properties[0]; + ( + 18, + 0, + change_body(fixture, property), + vec![ + resource_call(18, AccessMode::SET_PROP), + property_call(18, property, AccessMode::WRITE), + ], + ) + } + AccessCase::Append => { + let property = fixture.properties[0]; + ( + 18, + 2, + change_body(fixture, property), + vec![ + resource_call(18, AccessMode::SET_PROP), + property_call(18, property, AccessMode::BLEND), + ], + ) + } + AccessCase::Prepend => { + let property = fixture.properties[0]; + ( + 18, + 1, + change_body(fixture, property), + vec![ + resource_call(18, AccessMode::SET_PROP), + property_call(18, property, AccessMode::BLEND), + ], + ) + } + AccessCase::AbsentAppend => { + let property = fixture.atom("TASK9_ABSENT_PROPERTY"); + ( + 18, + 2, + change_body(fixture, property), + vec![ + resource_call(18, AccessMode::SET_PROP), + property_call(18, property, AccessMode::CREATE | AccessMode::WRITE), + ], + ) + } + AccessCase::Delete => { + let property = fixture.properties[0]; + ( + 19, + 0, + words(&[fixture.window.0, property.0]), + vec![ + resource_call(19, AccessMode::SET_PROP), + property_call(19, property, AccessMode::DESTROY), + ], + ) + } + AccessCase::Get => { + let property = fixture.properties[0]; + ( + 20, + 0, + get_body(fixture, property), + vec![ + resource_call(20, AccessMode::GET_PROP), + property_call(20, property, AccessMode::READ), + ], + ) + } + AccessCase::GetDelete => { + let property = fixture.properties[0]; + ( + 20, + 1, + get_body(fixture, property), + vec![ + resource_call(20, AccessMode::GET_PROP | AccessMode::SET_PROP), + property_call(20, property, AccessMode::READ | AccessMode::DESTROY), + ], + ) + } + AccessCase::ListWindow => ( + 21, + 0, + words(&[fixture.window.0]), + vec![resource_call(21, AccessMode::LIST_PROP)], + ), + AccessCase::RotateWindow => ( + 114, + 0, + words(&[fixture.window.0, 0]), + vec![resource_call(114, AccessMode::SET_PROP)], + ), + } +} + +#[test] +fn property_request_access_modes_are_asked_and_denied_before_effects() { + // Mutation: omit the Append property's BLEND check; the exact call row and denied Append result must fail. + let cases = [ + AccessCase::Replace, + AccessCase::Append, + AccessCase::Prepend, + AccessCase::AbsentAppend, + AccessCase::Delete, + AccessCase::Get, + AccessCase::GetDelete, + AccessCase::ListWindow, + AccessCase::RotateWindow, + ]; + for case in cases { + let property_count = if matches!( + case, + AccessCase::ListWindow | AccessCase::RotateWindow | AccessCase::AbsentAppend + ) { + 0 + } else { + 1 + }; + let mut allowed = Fixture::new(property_count); + let (opcode, data, body, expected) = run_access_case(&mut allowed, case); + let calls = allowed.install_policy(None); + let reply = allowed.request(51, opcode, data, &body); + assert!( + reply.is_empty() || reply[0] != 0, + "allowed {opcode} reply: {reply:?}" + ); + assert_eq!(*calls.lock().unwrap(), expected, "asked modes for {case:?}"); + + for deny_at in 0..expected.len() { + let mut denied = Fixture::new(property_count); + let (deny_opcode, deny_data, deny_body, deny_expected) = + run_access_case(&mut denied, case); + assert_eq!(deny_opcode, opcode); + let before_properties = denied.property_snapshot(); + let before_backend = denied.backend.calls(); + let calls = denied.install_policy(Some(deny_at)); + let sequence = u16::try_from(60 + deny_at).unwrap(); + let reply = denied.request(sequence, opcode, deny_data, &deny_body); + assert_policy_error(&reply, opcode, sequence); + assert_eq!( + denied.property_snapshot(), + before_properties, + "denied {opcode} state" + ); + assert_eq!( + denied.backend.calls(), + before_backend, + "denied {opcode} backend" + ); + assert_eq!( + *calls.lock().unwrap(), + deny_expected[..=deny_at], + "denied {opcode} check order" + ); + } + } +} + +#[test] +fn list_properties_omits_denied_property() { + // Mutation: deny the whole request when one property is denied; the filtered success reply and matching length fail. + let mut fixture = Fixture::new(3); + let order = fixture + .state + .resources + .window(fixture.window) + .unwrap() + .properties + .keys() + .copied() + .collect::>(); + // Use the order the request handler enumerates, then deny its middle entry. + let denied = order[1]; + let calls = fixture.install_policy(Some(2)); // window, first property, middle property + let before_backend = fixture.backend.calls(); + let reply = fixture.request(71, 21, 0, &words(&[fixture.window.0])); + + assert_eq!(reply[0], 1, "ListProperties succeeds: {reply:?}"); + assert_eq!(reply.len(), 32 + 2 * 4); + assert_eq!(u32::from_le_bytes(reply[4..8].try_into().unwrap()), 2); + assert_eq!(u16::from_le_bytes(reply[8..10].try_into().unwrap()), 2); + let listed = reply[32..] + .chunks_exact(4) + .map(|bytes| AtomId(u32::from_le_bytes(bytes.try_into().unwrap()))) + .collect::>(); + assert_eq!(listed, [order[0], order[2]]); + assert_eq!(fixture.backend.calls(), before_backend); + assert_eq!( + *calls.lock().unwrap(), + [ + resource_call(21, AccessMode::LIST_PROP), + property_call(21, order[0], AccessMode::GET_ATTR), + property_call(21, denied, AccessMode::GET_ATTR), + property_call(21, order[2], AccessMode::GET_ATTR), + ] + ); +} + +#[test] +fn rotate_properties_denied_item_rotates_nothing() { + // Mutation: skip per-item READ|WRITE denial; the state changes and PropertyNotify events make this fail. + let mut fixture = Fixture::new(3); + let properties = fixture.properties.clone(); + let before_properties = fixture.property_snapshot(); + fixture + .state + .clients + .get_mut(&CLIENT.0) + .unwrap() + .event_masks + .insert(fixture.window, 0x0040_0000); + let _ = read_all_available(&mut fixture.peer); + let calls = fixture.install_policy(Some(3)); // window then first, second and denied third property + let before_backend = fixture.backend.calls(); + let mut body = words(&[fixture.window.0]); + body.extend_from_slice(&3u16.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend( + properties + .iter() + .flat_map(|property| property.0.to_le_bytes()), + ); + + let reply = fixture.request(72, 114, 0, &body); + assert_policy_error(&reply, 114, 72); + assert_eq!(fixture.property_snapshot(), before_properties); + assert_eq!(fixture.backend.calls(), before_backend); + assert_eq!( + *calls.lock().unwrap(), + [ + resource_call(114, AccessMode::SET_PROP), + property_call(114, properties[0], AccessMode::READ | AccessMode::WRITE), + property_call(114, properties[1], AccessMode::READ | AccessMode::WRITE), + property_call(114, properties[2], AccessMode::READ | AccessMode::WRITE), + ] + ); +} + +#[test] +fn server_property_writes_are_not_checked() { + // Mutation: route the server helper through check_property; the deny-all policy must still see no calls. + let mut fixture = Fixture::new(0); + let property = fixture.atom("_XKB_RULES_NAMES"); + let calls = fixture.install_policy_with_deny(None, true); + let value = PropertyValue { + r#type: fixture.type_atom, + format: PropertyFormat::F8, + data: b"evdev\0pc105\0us\0".to_vec(), + }; + + change_property_as_server( + &mut fixture.state, + &mut fixture.backend, + fixture.window, + property, + value.r#type, + value.format, + value.data.clone(), + ); + + assert_eq!( + fixture + .state + .resources + .window_property(fixture.window, property), + Some(&value) + ); + assert!(calls.lock().unwrap().is_empty()); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_resources.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_resources.rs new file mode 100644 index 000000000..3f711d9d4 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_resources.rs @@ -0,0 +1,5919 @@ +use super::{ + extensions::{ExtensionHook, RecordedExtensionCheck, RecordingExtensionPolicy}, + *, +}; +use crate::access::{ + AccessContext, AccessMode, AccessPolicy, Creation, Decision, DenyError, RequestOpcodes, + ResourceKind, ResourceTarget, +}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +const CLIENT: ClientId = ClientId(1); +const REQUEST: RequestOpcodes = RequestOpcodes { major: 1, minor: 0 }; +type ExpectedResourceAccess = (ResourceId, ResourceKind, AccessMode); +type WindowAccessCase = (u8, u8, Vec, Vec); + +fn ask_owner( + state: &ServerState, + id: ResourceId, + kind: ResourceKind, + calls: &Arc>>, +) -> Option { + let before = calls.lock().unwrap().len(); + assert_eq!( + state.check_resource( + CLIENT, + &ResourceTarget { + id, + kind, + creation: None, + }, + AccessMode::READ, + Some(REQUEST), + ), + Decision::Allow + ); + let calls = calls.lock().unwrap(); + assert_eq!(calls.len(), before + 1); + let call = &calls[before]; + assert_eq!(call.hook, ExtensionHook::Resource); + assert_eq!( + call.target.as_ref().map(|target| (target.id, target.kind)), + Some((id, kind)) + ); + assert_eq!(call.request, Some(REQUEST)); + call.owner +} + +fn resource_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + sequence: u16, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + process_request( + state, + backend, + CLIENT, + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("resource creation request through process_request"); + read_all_available(peer) +} + +#[cfg(unix)] +fn resource_request_with_fd( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + sequence: u16, + opcode: u8, + data: u8, + body: &[u8], + fd: std::os::fd::OwnedFd, +) -> Vec { + process_request( + state, + backend, + CLIENT, + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + Some(fd), + ) + .expect("fd-backed resource creation request through process_request"); + read_all_available(peer) +} + +fn words(words: &[u32]) -> Vec { + words + .iter() + .fold( + WireBody(ClientByteOrder::LittleEndian, Vec::new()), + |body, word| body.u32(*word), + ) + .1 +} + +fn create_owner_rows( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, +) -> Vec<(ResourceKind, ResourceId, ClientId)> { + let id = |offset: u32| ResourceId(0x0050_0000 + offset); + let mut sequence = 1; + let mut rows = Vec::new(); + macro_rules! request { + ($opcode:expr, $data:expr, $body:expr $(,)?) => {{ + let bytes = resource_request(state, backend, peer, sequence, $opcode, $data, $body); + assert_no_error(&bytes, "resource creation request"); + sequence += 1; + }}; + } + + let window = id(1); + let create_window = words(&[ + window.0, + ROOT_WINDOW.0, + 0, + 8 | (8 << 16), + 0, + crate::resources::ROOT_VISUAL.0, + 0, + ]); + request!(1, 24, &create_window); + rows.push((ResourceKind::Window, window, CLIENT)); + + let pixmap = id(2); + request!(53, 24, &words(&[pixmap.0, ROOT_WINDOW.0, 8 | (8 << 16)]),); + rows.push((ResourceKind::Pixmap, pixmap, CLIENT)); + + let gc = id(3); + request!(55, 0, &words(&[gc.0, ROOT_WINDOW.0, 0])); + rows.push((ResourceKind::Gc, gc, CLIENT)); + + let font = id(4); + let mut open_font = font.0.to_le_bytes().to_vec(); + open_font.extend_from_slice(&5u16.to_le_bytes()); + open_font.extend_from_slice(&[0, 0]); + open_font.extend_from_slice(b"fixed"); + open_font.resize(open_font.len().div_ceil(4) * 4, 0); + request!(45, 0, &open_font); + rows.push((ResourceKind::Font, font, CLIENT)); + + let cursor = id(5); + let mut create_cursor = words(&[cursor.0, pixmap.0, 0]); + create_cursor.extend_from_slice(&[0; 16]); + request!(93, 0, &create_cursor); + rows.push((ResourceKind::Cursor, cursor, CLIENT)); + + let colormap = id(6); + request!( + 78, + 0, + &words(&[colormap.0, ROOT_WINDOW.0, crate::resources::ROOT_VISUAL.0,]), + ); + rows.push((ResourceKind::Colormap, colormap, CLIENT)); + + let picture = id(7); + request!( + 133, + 4, + &words(&[ + picture.0, + ROOT_WINDOW.0, + yserver_protocol::x11::RENDER_FMT_XRGB32, + 0, + ]), + ); + rows.push((ResourceKind::Picture, picture, CLIENT)); + + let glyphset = id(8); + // Mutation: make the recording renderer return no glyphset; this row's owner assertion must fail. + backend.render_create_glyphset_returns_handle = true; + request!( + 133, + 17, + &words(&[glyphset.0, yserver_protocol::x11::RENDER_FMT_XRGB32]), + ); + rows.push((ResourceKind::GlyphSet, glyphset, CLIENT)); + + state.xfixes_client_major.insert(CLIENT.0, 5); + let region = id(9); + request!( + 140, + yserver_protocol::x11::xfixes::CREATE_REGION, + ®ion.0.to_le_bytes() + ); + rows.push((ResourceKind::Region, region, CLIENT)); + + let barrier = id(10); + let mut create_barrier = words(&[barrier.0, ROOT_WINDOW.0]); + create_barrier.extend_from_slice(&0i16.to_le_bytes()); + create_barrier.extend_from_slice(&0i16.to_le_bytes()); + create_barrier.extend_from_slice(&1i16.to_le_bytes()); + create_barrier.extend_from_slice(&0i16.to_le_bytes()); + create_barrier.extend_from_slice(&0u32.to_le_bytes()); + create_barrier.extend_from_slice(&[0; 4]); + request!( + 140, + yserver_protocol::x11::xfixes::CREATE_POINTER_BARRIER, + &create_barrier, + ); + rows.push((ResourceKind::PointerBarrier, barrier, CLIENT)); + + let counter = id(11); + request!( + 142, + yserver_protocol::x11::sync::CREATE_COUNTER, + &words(&[counter.0, 0, 0]), + ); + rows.push((ResourceKind::SyncCounter, counter, CLIENT)); + + let alarm = id(12); + request!( + 142, + yserver_protocol::x11::sync::CREATE_ALARM, + &words(&[alarm.0, 0]), + ); + rows.push((ResourceKind::SyncAlarm, alarm, CLIENT)); + + let fence = id(13); + request!( + 142, + yserver_protocol::x11::sync::CREATE_FENCE, + &[ROOT_WINDOW.0.to_le_bytes(), fence.0.to_le_bytes(), [0; 4],].concat(), + ); + rows.push((ResourceKind::SyncFence, fence, CLIENT)); + + let damage = id(14); + request!( + 143, + yserver_protocol::x11::damage::CREATE, + &words(&[damage.0, ROOT_WINDOW.0, 0]) + ); + rows.push((ResourceKind::Damage, damage, CLIENT)); + + let present_selection = id(15); + request!( + 145, + yserver_protocol::x11::present::SELECT_INPUT, + &words(&[present_selection.0, ROOT_WINDOW.0, 0]), + ); + rows.push(( + ResourceKind::PresentEventSelection, + present_selection, + CLIENT, + )); + + #[cfg(unix)] + { + let shmseg = id(16); + let path = std::env::temp_dir().join(format!( + "yserver-access-owner-{}-{}", + std::process::id(), + std::thread::current().name().unwrap_or("test") + )); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&path) + .unwrap(); + file.set_len(4096).unwrap(); + let mut shm_attach = shmseg.0.to_le_bytes().to_vec(); + shm_attach.extend_from_slice(&[0; 4]); + let bytes = resource_request_with_fd( + state, + backend, + peer, + sequence, + 130, + yserver_protocol::x11::mit_shm::ATTACH_FD, + &shm_attach, + file.into(), + ); + assert_no_error(&bytes, "MIT-SHM AttachFd"); + sequence += 1; + std::fs::remove_file(path).unwrap(); + rows.push((ResourceKind::ShmSegment, shmseg, CLIENT)); + } + + let context = id(17); + request!( + crate::nested::GLX_MAJOR_OPCODE, + yserver_protocol::x11::glx::CREATE_CONTEXT, + &words(&[context.0, crate::resources::ROOT_VISUAL.0, 0, 0, 1]), + ); + rows.push((ResourceKind::GlxContext, context, CLIENT)); + + let glx_drawable = id(18); + request!( + crate::nested::GLX_MAJOR_OPCODE, + yserver_protocol::x11::glx::CREATE_WINDOW, + &words(&[0, 0x101, ROOT_WINDOW.0, glx_drawable.0,]), + ); + rows.push((ResourceKind::GlxDrawable, glx_drawable, CLIENT)); + + #[cfg(unix)] + { + let syncobj = id(19); + backend.dri3_caps = crate::backend::Dri3Caps { + version: (1, 4), + modifiers: false, + fence_fd: false, + syncobj: true, + }; + let path = std::env::temp_dir().join(format!( + "yserver-access-syncobj-{}-{}", + std::process::id(), + std::thread::current().name().unwrap_or("test") + )); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&path) + .unwrap(); + file.set_len(4096).unwrap(); + let bytes = resource_request_with_fd( + state, + backend, + peer, + sequence, + crate::nested::DRI3_MAJOR_OPCODE, + yserver_protocol::x11::dri3::IMPORT_SYNCOBJ, + &words(&[syncobj.0, ROOT_WINDOW.0]), + file.into(), + ); + assert_no_error(&bytes, "DRI3 ImportSyncobj"); + sequence += 1; + std::fs::remove_file(path).unwrap(); + rows.push((ResourceKind::Dri3Syncobj, syncobj, CLIENT)); + } + + let record = id(20); + let mut create_record = words(&[record.0]); + create_record.extend_from_slice(&[0; 4]); + create_record.extend_from_slice(&words(&[0, 0])); + let bytes = resource_request( + state, + backend, + peer, + sequence, + crate::nested::RECORD_MAJOR_OPCODE, + yserver_protocol::x11::record::CREATE_CONTEXT, + &create_record, + ); + assert_no_error(&bytes, "RECORD CreateContext"); + rows.push((ResourceKind::RecordContext, record, CLIENT)); + + rows +} + +#[test] +fn owner_resolver_answers_every_kind() { + // Mutation: drop the Colormap resolver arm; the server-owned default-colormap row must fail. + // Mutation: skip the property hook; the recorded property assertion must fail. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + crate::core_loop::process_request::install_default_font(&mut state, &mut backend) + .expect("install server default font"); + let mut rows = create_owner_rows(&mut state, &mut backend, &mut peer); + let default_font = crate::resources::DEFAULT_FONT; + state.randr.set_providers(vec![crate::randr::RandrProvider { + provider_id: 4, + name: "server-provider".to_owned(), + capabilities: 0, + is_gpu: false, + crtcs: vec![2], + outputs: vec![1], + associations: Vec::new(), + }]); + rows.extend([ + ( + ResourceKind::Window, + ROOT_WINDOW, + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::Colormap, + crate::resources::ROOT_COLORMAP, + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::Font, + default_font, + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::SyncCounter, + ResourceId(yserver_protocol::x11::sync::SERVERTIME_COUNTER), + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::RandrOutput, + ResourceId(1), + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::RandrCrtc, + ResourceId(2), + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::RandrMode, + ResourceId(3), + crate::resources::SERVER_OWNER, + ), + ( + ResourceKind::RandrProvider, + ResourceId(4), + crate::resources::SERVER_OWNER, + ), + ]); + + let expected_kinds = [ + ResourceKind::Window, + ResourceKind::Pixmap, + ResourceKind::Gc, + ResourceKind::Font, + ResourceKind::Cursor, + ResourceKind::Colormap, + ResourceKind::Picture, + ResourceKind::GlyphSet, + ResourceKind::Region, + ResourceKind::PointerBarrier, + ResourceKind::SyncCounter, + ResourceKind::SyncAlarm, + ResourceKind::SyncFence, + ResourceKind::Damage, + ResourceKind::PresentEventSelection, + ResourceKind::ShmSegment, + ResourceKind::GlxContext, + ResourceKind::GlxDrawable, + ResourceKind::Dri3Syncobj, + ResourceKind::RecordContext, + ResourceKind::RandrOutput, + ResourceKind::RandrCrtc, + ResourceKind::RandrMode, + ResourceKind::RandrProvider, + ]; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + + for kind in expected_kinds { + assert!( + rows.iter().any(|(row_kind, _, _)| *row_kind == kind), + "missing live owner row for {kind:?}" + ); + } + for &(kind, id, expected) in &rows { + assert_eq!( + ask_owner(&state, id, kind, &calls), + Some(expected), + "owner for {kind:?} 0x{:x}", + id.0 + ); + } + for kind in expected_kinds { + assert_eq!( + ask_owner(&state, ResourceId(0x6fff_ffff), kind, &calls), + None, + "unused {kind:?}" + ); + } + + let property = AtomId(69); + let mode = AccessMode::GET_PROP | AccessMode::SET_PROP; + assert_eq!( + state.check_property(CLIENT, ROOT_WINDOW, property, mode, Some(REQUEST)), + Decision::Allow + ); + let calls = calls.lock().unwrap(); + let property_call = calls.last().expect("property hook call"); + assert_eq!(property_call.hook, ExtensionHook::Property); + assert_eq!(property_call.property, Some((ROOT_WINDOW, property))); + assert_eq!(property_call.mode, Some(mode)); + assert_eq!(property_call.request, Some(REQUEST)); +} + +#[test] +fn owner_resolver_keeps_retained_owner() { + // Mutation: resolve owners only while their client is connected; retained resources still belong to client 1. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let pixmap = ResourceId(0x0051_0001); + let colormap = ResourceId(0x0051_0002); + + dispatch_wire_request(&mut state, &mut peer, 1, 112, 1, &[]); + let mut pixmap_body = Vec::new(); + pixmap_body.extend_from_slice(&pixmap.0.to_le_bytes()); + pixmap_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + pixmap_body.extend_from_slice(&8u16.to_le_bytes()); + pixmap_body.extend_from_slice(&8u16.to_le_bytes()); + dispatch_wire_request(&mut state, &mut peer, 2, 53, 24, &pixmap_body); + let mut colormap_body = Vec::new(); + colormap_body.extend_from_slice(&colormap.0.to_le_bytes()); + colormap_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + colormap_body.extend_from_slice(&crate::resources::ROOT_VISUAL.0.to_le_bytes()); + dispatch_wire_request(&mut state, &mut peer, 3, 78, 0, &colormap_body); + + drop(peer); + let mut backend = RecordingBackend::new(); + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, CLIENT); + assert!(state.zombie_clients.contains_key(&CLIENT.0)); + + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + assert_eq!( + ask_owner(&state, pixmap, ResourceKind::Pixmap, &calls), + Some(CLIENT) + ); + assert_eq!( + ask_owner(&state, colormap, ResourceKind::Colormap, &calls), + Some(CLIENT) + ); +} + +fn kill_client_colormap_result(with_policy: bool) -> (Vec, Vec) { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let calls = Arc::new(Mutex::new(Vec::new())); + if with_policy { + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + } + + let colormap = ResourceId(0x0052_0001); + let mut create_body = Vec::new(); + create_body.extend_from_slice(&colormap.0.to_le_bytes()); + create_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + create_body.extend_from_slice(&crate::resources::ROOT_VISUAL.0.to_le_bytes()); + dispatch_wire_request(&mut state, &mut peer, 1, 78, 0, &create_body); + assert!(state.resources.colormap(colormap).is_some()); + calls.lock().unwrap().clear(); + let mut backend = RecordingBackend::new(); + let _outcome = process_request( + &mut state, + &mut backend, + CLIENT, + SequenceNumber(2), + RequestHeader { + opcode: 113, + data: 0, + length_units: 2, + }, + &colormap.0.to_le_bytes(), + None, + ) + .expect("KillClient"); + (read_all_available(&mut peer), calls.lock().unwrap().clone()) +} + +#[test] +fn kill_client_on_a_colormap_keeps_bad_value_with_a_policy() { + // Mutation: resolve KillClient through the typed owner resolver; the colormap must stop returning BadValue. + let baseline = kill_client_colormap_result(false).0; + let (with_policy, calls) = kill_client_colormap_result(true); + assert_eq!(baseline[1], yserver_protocol::x11::error::BAD_VALUE); + assert_eq!(with_policy, baseline); + assert_eq!(with_policy[1], yserver_protocol::x11::error::BAD_VALUE); + assert!(calls.is_empty()); +} + +#[test] +fn server_owner_is_never_checked() { + // Mutation: remove either SERVER_OWNER fast path; its matching Allow assertion must fail. + let mut state = ServerState::new(); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Deny(DenyError { + code: yserver_protocol::x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::clone(&calls), + })); + let server = crate::resources::SERVER_OWNER; + assert_eq!( + state.check_resource( + server, + &ResourceTarget { + id: ROOT_WINDOW, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::DESTROY, + Some(REQUEST), + ), + Decision::Allow + ); + assert_eq!( + state.check_property( + server, + ROOT_WINDOW, + AtomId(69), + AccessMode::SET_PROP, + Some(REQUEST), + ), + Decision::Allow + ); + assert!(calls.lock().unwrap().is_empty()); +} + +#[test] +fn empty_policy_list_checks_allow() { + // Mutations: deny the no-policy resource or property check; the matching Allow assertion must fail. + let state = ServerState::new(); + assert!(!state.policies_installed()); + assert_eq!( + state.check_resource( + CLIENT, + &ResourceTarget { + id: ResourceId(0x0060_0001), + kind: ResourceKind::Pixmap, + creation: None, + }, + AccessMode::READ, + Some(REQUEST), + ), + Decision::Allow + ); + assert_eq!( + state.check_property( + CLIENT, + ROOT_WINDOW, + AtomId(69), + AccessMode::GET_PROP, + Some(REQUEST), + ), + Decision::Allow + ); +} + +struct DrawingResourcePolicy { + label: &'static str, + calls: Arc>>, + deny_id: Option>, + deny_all: bool, + decision: Decision, +} + +impl AccessPolicy for DrawingResourcePolicy { + fn resource( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.calls.lock().unwrap().push(RecordedExtensionCheck { + hook: ExtensionHook::Resource, + client, + extension: self.label.to_owned(), + request: ctx.request(), + peer: None, + admission: None, + owner: ctx.owner(target.id, target.kind), + target: Some(*target), + property: None, + mode: Some(mode), + }); + if self.deny_all + || self + .deny_id + .as_ref() + .is_some_and(|deny_id| deny_id.load(Ordering::SeqCst) == target.id.0) + { + self.decision + } else { + Decision::Allow + } + } +} + +struct DrawingResources { + window: ResourceId, + src: ResourceId, + dst: ResourceId, + gc: ResourceId, +} + +fn drawing_resources( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, +) -> DrawingResources { + let resources = DrawingResources { + window: ResourceId(0x0053_0001), + src: ResourceId(0x0053_0002), + dst: ResourceId(0x0053_0003), + gc: ResourceId(0x0053_0004), + }; + let create_window = words(&[ + resources.window.0, + ROOT_WINDOW.0, + 0, + 16 | (16 << 16), + 0, + crate::resources::ROOT_VISUAL.0, + 0, + ]); + assert_no_error( + &resource_request(state, backend, peer, 1, 1, 24, &create_window), + "drawing test window", + ); + for (sequence, pixmap) in [(2, resources.src), (3, resources.dst)] { + assert_no_error( + &resource_request( + state, + backend, + peer, + sequence, + 53, + 24, + &words(&[pixmap.0, ROOT_WINDOW.0, 16 | (16 << 16)]), + ), + "drawing test pixmap", + ); + } + assert_no_error( + &resource_request( + state, + backend, + peer, + 4, + 55, + 0, + &words(&[resources.gc.0, resources.src.0, 0]), + ), + "drawing test GC", + ); + resources +} + +fn unbacked_drawing_resources(state: &mut ServerState) -> DrawingResources { + let resources = DrawingResources { + window: ResourceId(0x0054_0001), + src: ResourceId(0x0054_0002), + dst: ResourceId(0x0054_0003), + gc: ResourceId(0x0054_0004), + }; + state.resources.create_window( + CLIENT, + CreateWindowRequest { + depth: 24, + window: resources.window, + parent: ROOT_WINDOW, + width: 16, + height: 16, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + for pixmap in [resources.src, resources.dst] { + state.resources.create_pixmap( + CLIENT, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap, + drawable: ROOT_WINDOW, + width: 16, + height: 16, + }, + ); + } + state.resources.create_gc( + CLIENT, + x11::create_gc_request(&words(&[resources.gc.0, resources.src.0, 0])) + .expect("unbacked test GC request"), + ); + resources +} + +#[derive(Clone)] +struct DrawingRequestCase { + opcode: u8, + data: u8, + body: Vec, + targets: Vec<(ResourceId, ResourceKind, AccessMode)>, +} + +fn drawing_request_cases(resources: &DrawingResources) -> Vec { + let drawable_gc = |opcode, body: Vec, data| DrawingRequestCase { + opcode, + data, + body, + targets: vec![ + (resources.src, ResourceKind::Pixmap, AccessMode::WRITE), + (resources.gc, ResourceKind::Gc, AccessMode::USE), + ], + }; + let mut image = words(&[resources.src.0, resources.gc.0, 1 | (1 << 16), 0]); + image.extend_from_slice(&[0, 24, 0, 0, 0, 0, 0, 0]); + vec![ + DrawingRequestCase { + opcode: 61, + data: 0, + body: words(&[resources.window.0, 0, 1 | (1 << 16)]), + targets: vec![(resources.window, ResourceKind::Window, AccessMode::WRITE)], + }, + DrawingRequestCase { + opcode: 62, + data: 0, + body: words(&[ + resources.src.0, + resources.dst.0, + resources.gc.0, + 0, + 0, + 1 | (1 << 16), + ]), + targets: vec![ + (resources.src, ResourceKind::Pixmap, AccessMode::READ), + (resources.dst, ResourceKind::Pixmap, AccessMode::WRITE), + (resources.gc, ResourceKind::Gc, AccessMode::USE), + ], + }, + DrawingRequestCase { + opcode: 63, + data: 0, + body: words(&[ + resources.src.0, + resources.dst.0, + resources.gc.0, + 0, + 0, + 1 | (1 << 16), + 1, + ]), + targets: vec![ + (resources.src, ResourceKind::Pixmap, AccessMode::READ), + (resources.dst, ResourceKind::Pixmap, AccessMode::WRITE), + (resources.gc, ResourceKind::Gc, AccessMode::USE), + ], + }, + drawable_gc(64, words(&[resources.src.0, resources.gc.0, 0]), 0), + drawable_gc(65, words(&[resources.src.0, resources.gc.0, 0]), 0), + drawable_gc(66, words(&[resources.src.0, resources.gc.0, 0, 0, 0, 0]), 0), + drawable_gc( + 67, + words(&[resources.src.0, resources.gc.0, 0, 1 | (1 << 16)]), + 0, + ), + drawable_gc( + 68, + words(&[resources.src.0, resources.gc.0, 0, 1 | (1 << 16), 0]), + 0, + ), + drawable_gc(69, words(&[resources.src.0, resources.gc.0, 0]), 0), + drawable_gc( + 70, + words(&[resources.src.0, resources.gc.0, 0, 1 | (1 << 16)]), + 0, + ), + drawable_gc( + 71, + words(&[resources.src.0, resources.gc.0, 0, 1 | (1 << 16), 0]), + 0, + ), + drawable_gc(72, image, 2), + DrawingRequestCase { + opcode: 73, + data: 2, + body: words(&[resources.src.0, 0, 1 | (1 << 16), u32::MAX]), + targets: vec![(resources.src, ResourceKind::Pixmap, AccessMode::READ)], + }, + drawable_gc(74, words(&[resources.src.0, resources.gc.0, 0]), 0), + drawable_gc(75, words(&[resources.src.0, resources.gc.0, 0]), 0), + drawable_gc(76, words(&[resources.src.0, resources.gc.0, 0]), 0), + drawable_gc(77, words(&[resources.src.0, resources.gc.0, 0]), 0), + ] +} + +fn run_drawing_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + sequence: u16, + request: &DrawingRequestCase, +) -> Vec { + process_request( + state, + backend, + CLIENT, + SequenceNumber(sequence), + RequestHeader { + opcode: request.opcode, + data: request.data, + length_units: u32::try_from(1 + request.body.len().div_ceil(4)).unwrap(), + }, + &request.body, + None, + ) + .expect("drawing request through process_request"); + read_all_available(peer) +} + +fn assert_x11_error(bytes: &[u8], code: u8, value: u32, opcode: u8, sequence: u16) { + let mut expected = vec![0, code]; + expected.extend_from_slice(&sequence.to_le_bytes()); + expected.extend_from_slice(&value.to_le_bytes()); + expected.extend_from_slice(&0u16.to_le_bytes()); + expected.push(opcode); + expected.extend_from_slice(&[0; 21]); + assert_eq!(bytes, expected, "request {opcode} denial packet"); +} + +fn assert_policy_error(bytes: &[u8], opcode: u8, sequence: u16) { + assert_x11_error(bytes, x11::error::BAD_ACCESS, 0x55, opcode, sequence); +} + +#[test] +fn get_image_checks_read_before_bounds_validation() { + // Mutation: move GetImage's READ check after rectangle/viewability validation; the denial must win over BadMatch. + const DRAWABLE: ResourceId = ResourceId(0x0053_00f0); + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT.0); + state.resources.create_pixmap( + CLIENT, + x11::CreatePixmapRequest { + depth: 24, + pixmap: DRAWABLE, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + }, + ); + let body = words(&[DRAWABLE.0, 8, 1 | (1 << 16), u32::MAX]); + + let baseline = resource_request(&mut state, &mut backend, &mut peer, 1, 73, 2, &body); + assert_x11_error(&baseline, x11::error::BAD_MATCH, DRAWABLE.0, 73, 1); + + let calls = Arc::new(Mutex::new(Vec::new())); + let drawable_before = format!("{:?}", state.resources.pixmap(DRAWABLE)); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "GetImage bounds order", + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(DRAWABLE.0))), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let backend_before = backend.calls(); + let denied = resource_request(&mut state, &mut backend, &mut peer, 2, 73, 2, &body); + + assert_policy_error(&denied, 73, 2); + assert_eq!(backend.calls(), backend_before); + assert_eq!( + format!("{:?}", state.resources.pixmap(DRAWABLE)), + drawable_before + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + DRAWABLE, + ResourceKind::Pixmap, + AccessMode::READ, + Some(RequestOpcodes { + major: 73, + minor: 0, + }), + )] + ); +} + +#[test] +fn set_dashes_checks_gc_before_zero_dash_validation() { + // Mutation: move SetDashes' SET_ATTR check after zero-dash validation; the policy denial must win over BadValue. + let mut baseline = gc_font_access_fixture(); + let dashes = [baseline.gc.0.to_le_bytes().as_slice(), &[0, 0, 1, 0, 0]].concat(); + let baseline_bytes = resource_request( + &mut baseline.state, + &mut baseline.backend, + &mut baseline.peer, + 110, + 58, + 0, + &dashes, + ); + assert_x11_error(&baseline_bytes, x11::error::BAD_VALUE, 0, 58, 110); + + let mut fixture = gc_font_access_fixture(); + let gc_before = format!("{:?}", fixture.state.resources.gc(fixture.gc)); + let backend_before = fixture.backend.calls(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(DrawingResourcePolicy { + label: "SetDashes zero value order", + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.gc.0))), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let denied = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 111, + 58, + 0, + &dashes, + ); + + assert_policy_error(&denied, 58, 111); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + format!("{:?}", fixture.state.resources.gc(fixture.gc)), + gc_before + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + fixture.gc, + ResourceKind::Gc, + AccessMode::SET_ATTR, + Some(RequestOpcodes { + major: 58, + minor: 0, + }), + )] + ); +} + +fn expected_resource_checks( + calls: &[RecordedExtensionCheck], +) -> Vec<( + ClientId, + ResourceId, + ResourceKind, + AccessMode, + Option, +)> { + calls + .iter() + .map(|call| { + let target = call.target.expect("resource target"); + ( + call.client, + target.id, + target.kind, + call.mode.expect("resource mode"), + call.request, + ) + }) + .collect() +} + +#[test] +fn every_drawing_request_denial_reports_policy_error() { + // Mutation: remove any drawing target check, including CopyArea/CopyPlane destination; that target must stop returning the policy error. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = drawing_resources(&mut state, &mut backend, &mut peer); + let calls = Arc::new(Mutex::new(Vec::new())); + let denied_id = Arc::new(AtomicU32::new(0)); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "drawing deny", + calls: Arc::clone(&calls), + deny_id: Some(Arc::clone(&denied_id)), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + + let cases = drawing_request_cases(&resources); + let mut sequence = 10; + for request in &cases { + for (target, _, _) in &request.targets { + denied_id.store(target.0, Ordering::SeqCst); + let before = backend.calls(); + let window_before = format!("{:?}", state.resources.window(resources.window).unwrap()); + let gc_before = format!("{:?}", state.resources.gc(resources.gc).unwrap()); + let damage_before = state.damage_objects.clone(); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, sequence, request); + assert_policy_error(&bytes, request.opcode, sequence); + assert_eq!( + backend.calls(), + before, + "request {} drew after target denial", + request.opcode + ); + assert_eq!( + format!("{:?}", state.resources.window(resources.window).unwrap()), + window_before, + "request {} changed window state after denial", + request.opcode + ); + assert_eq!( + format!("{:?}", state.resources.gc(resources.gc).unwrap()), + gc_before, + "request {} changed GC state after denial", + request.opcode + ); + assert_eq!( + state.damage_objects, damage_before, + "request {} changed damage state", + request.opcode + ); + sequence += 1; + } + } +} + +#[test] +fn denied_drawable_precedes_missing_gc() { + // Mutation: move drawable authorization after GC lookup; the policy denial must still win over BadGC. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = drawing_resources(&mut state, &mut backend, &mut peer); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "drawable precedence", + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(resources.src.0))), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let missing_gc = ResourceId(0x0053_00ff); + let request = DrawingRequestCase { + opcode: 64, + data: 0, + body: words(&[resources.src.0, missing_gc.0, 0]), + targets: Vec::new(), + }; + let before = backend.calls(); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, 50, &request); + assert_policy_error(&bytes, 64, 50); + assert_eq!(backend.calls(), before); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + resources.src, + ResourceKind::Pixmap, + AccessMode::WRITE, + Some(RequestOpcodes { + major: 64, + minor: 0, + }), + )] + ); +} + +#[test] +fn allowed_drawable_keeps_missing_gc_error() { + // Mutation: skip missing-GC validation after an allowed drawable; BadGC with the GC id must remain observable. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = unbacked_drawing_resources(&mut state); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "drawable allow", + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(0))), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let missing_gc = ResourceId(0x0053_00ff); + let request = DrawingRequestCase { + opcode: 64, + data: 0, + body: words(&[resources.src.0, missing_gc.0, 0]), + targets: Vec::new(), + }; + let before = backend.calls(); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, 51, &request); + assert_x11_error(&bytes, x11::error::BAD_GC, missing_gc.0, 64, 51); + assert_eq!(backend.calls(), before); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + resources.src, + ResourceKind::Pixmap, + AccessMode::WRITE, + Some(RequestOpcodes { + major: 64, + minor: 0, + }), + )] + ); +} + +#[test] +fn denied_gc_precedes_depth_mismatch() { + // Mutation: move GC authorization after the depth check; the policy denial must beat BadMatch. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = drawing_resources(&mut state, &mut backend, &mut peer); + let narrow_pixmap = ResourceId(0x0053_0010); + assert_no_error( + &resource_request( + &mut state, + &mut backend, + &mut peer, + 5, + 53, + 1, + &words(&[narrow_pixmap.0, ROOT_WINDOW.0, 8 | (8 << 16)]), + ), + "depth-mismatch pixmap", + ); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "GC precedence", + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(resources.gc.0))), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let request = DrawingRequestCase { + opcode: 64, + data: 0, + body: words(&[narrow_pixmap.0, resources.gc.0, 0]), + targets: Vec::new(), + }; + let before = backend.calls(); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, 52, &request); + assert_policy_error(&bytes, 64, 52); + assert_eq!(backend.calls(), before); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + narrow_pixmap, + ResourceKind::Pixmap, + AccessMode::WRITE, + Some(RequestOpcodes { + major: 64, + minor: 0, + }), + ), + ( + CLIENT, + resources.gc, + ResourceKind::Gc, + AccessMode::USE, + Some(RequestOpcodes { + major: 64, + minor: 0, + }), + ), + ] + ); +} + +#[test] +fn every_drawing_request_asks_with_expected_target() { + // Mutation: pass the wrong drawable, GC, kind, mode, or request context; the literal target list must fail. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = unbacked_drawing_resources(&mut state); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "drawing recorder", + calls: Arc::clone(&calls), + deny_id: None, + deny_all: false, + decision: Decision::Allow, + })); + + for (index, request) in drawing_request_cases(&resources).iter().enumerate() { + calls.lock().unwrap().clear(); + let sequence = u16::try_from(100 + index).unwrap(); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, sequence, request); + assert!( + bytes.is_empty() || bytes[0] != 0, + "request {} unexpectedly errored", + request.opcode + ); + let expected: Vec<_> = request + .targets + .iter() + .map(|(id, kind, mode)| { + ( + CLIENT, + *id, + *kind, + *mode, + Some(RequestOpcodes { + major: request.opcode, + minor: 0, + }), + ) + }) + .collect(); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + expected, + "request {}", + request.opcode + ); + } +} + +#[test] +fn gc_mutators_and_query_best_size_check_their_targets() { + // Mutation: move a check after a GC mutation or QueryBestSize reply; the exact denial and unchanged GC state must fail. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = drawing_resources(&mut state, &mut backend, &mut peer); + let calls = Arc::new(Mutex::new(Vec::new())); + let denied_id = Arc::new(AtomicU32::new(0)); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "GC and size denial", + calls: Arc::clone(&calls), + deny_id: Some(Arc::clone(&denied_id)), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let mut dashes = words(&[resources.gc.0, 2 << 16]); + dashes.extend_from_slice(&[3, 5, 0, 0]); + let clip_rectangles = words(&[resources.gc.0, 0, 1 | (1 << 16), 0]); + let cases = [ + (58, resources.gc, dashes), + (59, resources.gc, clip_rectangles), + (97, resources.src, words(&[resources.src.0, 8 | (8 << 16)])), + ]; + for (index, (opcode, target, body)) in cases.into_iter().enumerate() { + let sequence = u16::try_from(60 + index).unwrap(); + denied_id.store(target.0, Ordering::SeqCst); + calls.lock().unwrap().clear(); + let before = backend.calls(); + let request = DrawingRequestCase { + opcode, + data: 0, + body, + targets: Vec::new(), + }; + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, sequence, &request); + assert_policy_error(&bytes, opcode, sequence); + assert_eq!( + backend.calls(), + before, + "request {opcode} has no backend effect" + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + target, + if opcode == 97 { + ResourceKind::Pixmap + } else { + ResourceKind::Gc + }, + if opcode == 97 { + AccessMode::GET_ATTR + } else { + AccessMode::SET_ATTR + }, + Some(RequestOpcodes { + major: opcode, + minor: 0 + }), + )], + "request {opcode} access target" + ); + if opcode == 58 || opcode == 59 { + let gc = state.resources.gc(resources.gc).unwrap(); + assert_eq!(gc.dashes, vec![4, 4]); + assert_eq!(gc.dash_offset, 0); + assert_eq!(gc.clip_rectangles, None); + } + } +} + +#[test] +fn poly_text_denied_inline_font_draws_nothing() { + // Mutation: check inline fonts while drawing; a denied second font must prevent the draw and GC font update. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = drawing_resources(&mut state, &mut backend, &mut peer); + let font_ids = [ResourceId(0x0053_0005), ResourceId(0x0053_0006)]; + for (index, font) in font_ids.iter().enumerate() { + let mut body = font.0.to_le_bytes().to_vec(); + body.extend_from_slice(&5u16.to_le_bytes()); + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(b"fixed"); + body.resize(body.len().div_ceil(4) * 4, 0); + assert_no_error( + &resource_request( + &mut state, + &mut backend, + &mut peer, + u16::try_from(5 + index).unwrap(), + 45, + 0, + &body, + ), + "inline font", + ); + } + let original_gc_font = state.resources.gc(resources.gc).unwrap().font; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "second inline font deny", + calls, + deny_id: Some(Arc::new(AtomicU32::new(font_ids[1].0))), + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let mut body = words(&[resources.src.0, resources.gc.0, 0]); + body.push(255); + body.extend_from_slice(&font_ids[0].0.to_be_bytes()); + body.extend_from_slice(&[3, 0, b'o', b'n', b'e']); + body.push(255); + body.extend_from_slice(&font_ids[1].0.to_be_bytes()); + body.extend_from_slice(&[3, 0, b't', b'w', b'o']); + body.resize(body.len().div_ceil(4) * 4, 0); + let before = backend.calls(); + let request = DrawingRequestCase { + opcode: 74, + data: 0, + body, + targets: Vec::new(), + }; + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, 20, &request); + assert_policy_error(&bytes, 74, 20); + assert_eq!( + backend.calls(), + before, + "denied inline font reached drawing backend" + ); + assert_eq!( + state.resources.gc(resources.gc).unwrap().font, + original_gc_font + ); +} + +#[test] +fn several_policies_resource_order() { + // Mutation: continue asking policies after a denial or return a later policy's error; first-denier order must hold. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = unbacked_drawing_resources(&mut state); + let request = DrawingRequestCase { + opcode: 64, + data: 0, + body: words(&[resources.src.0, resources.gc.0, 0]), + targets: Vec::new(), + }; + + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "allow before deny", + calls: Arc::clone(&calls), + deny_id: None, + deny_all: false, + decision: Decision::Allow, + })); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "first denier", + calls: Arc::clone(&calls), + deny_id: None, + deny_all: true, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "must not run after denial", + calls: Arc::clone(&calls), + deny_id: None, + deny_all: true, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x66, + }), + })); + let before = backend.calls(); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, 30, &request); + assert_policy_error(&bytes, 64, 30); + assert_eq!(backend.calls(), before); + assert_eq!( + calls + .lock() + .unwrap() + .iter() + .map(|call| call.extension.as_str()) + .collect::>(), + ["allow before deny", "first denier"] + ); + + let mut second_state = ServerState::new(); + let mut second_peer = install_client(&mut second_state, CLIENT.0); + let mut second_backend = RecordingBackend::new(); + let second_resources = unbacked_drawing_resources(&mut second_state); + let second_request = DrawingRequestCase { + opcode: 64, + data: 0, + body: words(&[second_resources.src.0, second_resources.gc.0, 0]), + targets: Vec::new(), + }; + let second_calls = Arc::new(Mutex::new(Vec::new())); + second_state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "denier first", + calls: Arc::clone(&second_calls), + deny_id: None, + deny_all: true, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x66, + }), + })); + second_state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "allow after denial", + calls: Arc::clone(&second_calls), + deny_id: None, + deny_all: false, + decision: Decision::Allow, + })); + let second_before = second_backend.calls(); + let bytes = run_drawing_request( + &mut second_state, + &mut second_backend, + &mut second_peer, + 31, + &second_request, + ); + let mut expected = vec![0, x11::error::BAD_VALUE]; + expected.extend_from_slice(&31u16.to_le_bytes()); + expected.extend_from_slice(&0x66u32.to_le_bytes()); + expected.extend_from_slice(&0u16.to_le_bytes()); + expected.extend_from_slice(&[64, 0]); + expected.extend_from_slice(&[0; 20]); + assert_eq!(bytes, expected); + assert_eq!(second_backend.calls(), second_before); + assert_eq!( + second_calls + .lock() + .unwrap() + .iter() + .map(|call| call.extension.as_str()) + .collect::>(), + ["denier first"] + ); +} + +struct RevocableDrawingPolicy { + revoked: Arc, + calls: Arc>>, +} + +impl AccessPolicy for RevocableDrawingPolicy { + fn resource( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.calls.lock().unwrap().push(RecordedExtensionCheck { + hook: ExtensionHook::Resource, + client, + extension: "revocable drawing".to_owned(), + request: ctx.request(), + peer: None, + admission: None, + owner: ctx.owner(target.id, target.kind), + target: Some(*target), + property: None, + mode: Some(mode), + }); + if self.revoked.load(Ordering::SeqCst) { + Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }) + } else { + Decision::Allow + } + } +} + +#[test] +fn revoked_drawable_denies_the_next_request() { + // Mutation: cache an earlier Allow; revoking the same drawable must affect its next PolyPoint. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let resources = unbacked_drawing_resources(&mut state); + let request = DrawingRequestCase { + opcode: 64, + data: 0, + body: words(&[resources.src.0, resources.gc.0, 0]), + targets: Vec::new(), + }; + let revoked = Arc::new(AtomicBool::new(false)); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RevocableDrawingPolicy { + revoked: Arc::clone(&revoked), + calls: Arc::clone(&calls), + })); + assert!(run_drawing_request(&mut state, &mut backend, &mut peer, 40, &request).is_empty()); + let before = backend.calls(); + revoked.store(true, Ordering::SeqCst); + let bytes = run_drawing_request(&mut state, &mut backend, &mut peer, 41, &request); + assert_policy_error(&bytes, 64, 41); + assert_eq!(backend.calls(), before); + assert_eq!( + calls.lock().unwrap().len(), + 3, + "first check visits drawable and GC, revoked request stops at drawable" + ); +} + +#[test] +fn server_owner_drawing_stays_unchecked() { + // Mutation: remove the SERVER_OWNER fast path; server work through PolyPoint must remain unchecked. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, crate::resources::SERVER_OWNER.0); + let resources = unbacked_drawing_resources(&mut state); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "deny server work", + calls: Arc::clone(&calls), + deny_id: None, + deny_all: true, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + let body = words(&[resources.src.0, resources.gc.0, 0]); + process_request( + &mut state, + &mut RecordingBackend::new(), + crate::resources::SERVER_OWNER, + SequenceNumber(70), + RequestHeader { + opcode: 64, + data: 0, + length_units: 4, + }, + &body, + None, + ) + .expect("server-owned PolyPoint"); + assert!(read_all_available(&mut peer).is_empty()); + assert!(calls.lock().unwrap().is_empty()); +} + +struct WindowResourcePolicy { + calls: Arc>>, + deny_id: Option>, + deny_mode: Option, + deny_hides: bool, +} + +impl AccessPolicy for WindowResourcePolicy { + fn resource( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.calls.lock().unwrap().push(RecordedExtensionCheck { + hook: ExtensionHook::Resource, + client, + extension: "window resources".to_owned(), + request: ctx.request(), + peer: None, + admission: None, + owner: ctx.owner(target.id, target.kind), + target: Some(*target), + property: None, + mode: Some(mode), + }); + let deny_id = self + .deny_id + .as_ref() + .is_some_and(|deny_id| deny_id.load(Ordering::SeqCst) == target.id.0); + if self.deny_hides && mode == AccessMode::HIDE + || deny_id && self.deny_mode.is_none_or(|deny_mode| deny_mode == mode) + { + Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }) + } else { + Decision::Allow + } + } +} + +struct WindowAccessFixture { + state: ServerState, + backend: RecordingBackend, + peer: UnixStream, + parent: ResourceId, + window: ResourceId, + destroy_parent: ResourceId, + destroy_window: ResourceId, + subwindows_parent: ResourceId, + subwindow_children: [ResourceId; 2], + background: ResourceId, + border: ResourceId, + colormap: ResourceId, + cursor: ResourceId, +} + +fn simple_window_body(window: ResourceId, parent: ResourceId) -> Vec { + words(&[ + window.0, + parent.0, + 0, + 32 | (32 << 16), + 0, + crate::resources::ROOT_VISUAL.0, + 0, + ]) +} + +fn create_test_window( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + sequence: &mut u16, + window: ResourceId, + parent: ResourceId, +) { + let bytes = resource_request( + state, + backend, + peer, + *sequence, + 1, + 24, + &simple_window_body(window, parent), + ); + assert_no_error(&bytes, "window access fixture CreateWindow"); + *sequence += 1; +} + +fn create_window_with_access_attributes( + window: ResourceId, + parent: ResourceId, + background: ResourceId, + border: ResourceId, + colormap: ResourceId, + cursor: ResourceId, +) -> Vec { + let mask = 0x0001 | 0x0004 | 0x2000 | 0x4000; + words(&[ + window.0, + parent.0, + 0, + 32 | (32 << 16), + 0, + crate::resources::ROOT_VISUAL.0, + mask, + background.0, + border.0, + colormap.0, + cursor.0, + ]) +} + +fn change_window_attributes_with_access_operands( + window: ResourceId, + background: ResourceId, + border: ResourceId, + colormap: ResourceId, + cursor: ResourceId, +) -> Vec { + let mask = 0x0001 | 0x0004 | 0x0200 | 0x0800 | 0x2000 | 0x4000; + words(&[ + window.0, + mask, + background.0, + border.0, + 0, + 1, + colormap.0, + cursor.0, + ]) +} + +fn window_access_fixture() -> WindowAccessFixture { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut backend = RecordingBackend::new(); + let parent = ResourceId(0x0054_0001); + let window = ResourceId(0x0054_0002); + let destroy_parent = ResourceId(0x0054_0003); + let destroy_window = ResourceId(0x0054_0004); + let subwindows_parent = ResourceId(0x0054_0005); + let subwindow_children = [ResourceId(0x0054_0006), ResourceId(0x0054_0007)]; + let background = ResourceId(0x0054_0008); + let border = ResourceId(0x0054_0009); + let colormap = ResourceId(0x0054_000a); + let cursor = ResourceId(0x0054_000b); + let mut sequence = 1; + + create_test_window( + &mut state, + &mut backend, + &mut peer, + &mut sequence, + parent, + ROOT_WINDOW, + ); + create_test_window( + &mut state, + &mut backend, + &mut peer, + &mut sequence, + window, + parent, + ); + create_test_window( + &mut state, + &mut backend, + &mut peer, + &mut sequence, + destroy_parent, + ROOT_WINDOW, + ); + create_test_window( + &mut state, + &mut backend, + &mut peer, + &mut sequence, + destroy_window, + destroy_parent, + ); + create_test_window( + &mut state, + &mut backend, + &mut peer, + &mut sequence, + subwindows_parent, + ROOT_WINDOW, + ); + for child in subwindow_children { + create_test_window( + &mut state, + &mut backend, + &mut peer, + &mut sequence, + child, + subwindows_parent, + ); + } + for pixmap in [background, border] { + let bytes = resource_request( + &mut state, + &mut backend, + &mut peer, + sequence, + 53, + 24, + &words(&[pixmap.0, ROOT_WINDOW.0, 16 | (16 << 16)]), + ); + assert_no_error(&bytes, "window access fixture CreatePixmap"); + sequence += 1; + } + let bytes = resource_request( + &mut state, + &mut backend, + &mut peer, + sequence, + 78, + 0, + &words(&[colormap.0, ROOT_WINDOW.0, crate::resources::ROOT_VISUAL.0]), + ); + assert_no_error(&bytes, "window access fixture CreateColormap"); + sequence += 1; + let mut cursor_body = words(&[cursor.0, background.0, 0]); + cursor_body.extend_from_slice(&[0; 16]); + let bytes = resource_request( + &mut state, + &mut backend, + &mut peer, + sequence, + 93, + 0, + &cursor_body, + ); + assert_no_error(&bytes, "window access fixture CreateCursor"); + + WindowAccessFixture { + state, + backend, + peer, + parent, + window, + destroy_parent, + destroy_window, + subwindows_parent, + subwindow_children, + background, + border, + colormap, + cursor, + } +} + +struct WindowDenyCase { + label: &'static str, + opcode: u8, + data: u8, + body: Vec, + target: ResourceId, + kind: ResourceKind, + mode: AccessMode, + creation: Option, +} + +#[test] +fn window_resource_request_denials_match_modes_and_stop_before_effects() { + // Mutation: remove a listed check or use the wrong CWA mode; its row's error/mode assertion must fail. + // Mutation: authorize an unresolved ChangeSaveSet window; it must keep its current no-check success behavior. + // Mutation: apply the CWA event-mask selection before checking CW operands; the event-mask snapshot must fail. + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + let denied_id = Arc::new(AtomicU32::new(0)); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::clone(&denied_id)), + deny_mode: None, + deny_hides: false, + })); + let created = ResourceId(0x0054_000c); + let create_body = create_window_with_access_attributes( + created, + ROOT_WINDOW, + fixture.background, + fixture.border, + fixture.colormap, + fixture.cursor, + ); + let attrs_body = change_window_attributes_with_access_operands( + fixture.window, + fixture.background, + fixture.border, + fixture.colormap, + fixture.cursor, + ); + let cases = vec![ + WindowDenyCase { + label: "CreateWindow parent ADD", + opcode: 1, + data: 24, + body: create_body.clone(), + target: ROOT_WINDOW, + kind: ResourceKind::Window, + mode: AccessMode::ADD, + creation: None, + }, + WindowDenyCase { + label: "CreateWindow background READ", + opcode: 1, + data: 24, + body: create_body.clone(), + target: fixture.background, + kind: ResourceKind::Pixmap, + mode: AccessMode::READ, + creation: None, + }, + WindowDenyCase { + label: "CreateWindow colormap USE", + opcode: 1, + data: 24, + body: create_body.clone(), + target: fixture.colormap, + kind: ResourceKind::Colormap, + mode: AccessMode::USE, + creation: None, + }, + WindowDenyCase { + label: "CreateWindow cursor USE", + opcode: 1, + data: 24, + body: create_body.clone(), + target: fixture.cursor, + kind: ResourceKind::Cursor, + mode: AccessMode::USE, + creation: None, + }, + WindowDenyCase { + label: "CreateWindow border pixmap READ", + opcode: 1, + data: 24, + body: create_body.clone(), + target: fixture.border, + kind: ResourceKind::Pixmap, + mode: AccessMode::READ, + creation: None, + }, + WindowDenyCase { + label: "CreateWindow creation", + opcode: 1, + data: 24, + body: create_body, + target: created, + kind: ResourceKind::Window, + mode: AccessMode::CREATE | AccessMode::SET_ATTR, + creation: Some(Creation { + parent: Some(ROOT_WINDOW), + owner: CLIENT, + }), + }, + WindowDenyCase { + label: "ChangeWindowAttributes window", + opcode: 2, + data: 0, + body: attrs_body.clone(), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::RECEIVE | AccessMode::SET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "ChangeWindowAttributes event mask only", + opcode: 2, + data: 0, + body: words(&[fixture.window.0, 0x0800, 1]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::RECEIVE, + creation: None, + }, + WindowDenyCase { + label: "ChangeWindowAttributes non-event attribute only", + opcode: 2, + data: 0, + body: words(&[fixture.window.0, 0x0200, 1]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::SET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "ChangeWindowAttributes background READ", + opcode: 2, + data: 0, + body: attrs_body.clone(), + target: fixture.background, + kind: ResourceKind::Pixmap, + mode: AccessMode::READ, + creation: None, + }, + WindowDenyCase { + label: "ChangeWindowAttributes colormap USE", + opcode: 2, + data: 0, + body: attrs_body.clone(), + target: fixture.colormap, + kind: ResourceKind::Colormap, + mode: AccessMode::USE, + creation: None, + }, + WindowDenyCase { + label: "ChangeWindowAttributes cursor USE", + opcode: 2, + data: 0, + body: attrs_body.clone(), + target: fixture.cursor, + kind: ResourceKind::Cursor, + mode: AccessMode::USE, + creation: None, + }, + WindowDenyCase { + label: "ChangeWindowAttributes border pixmap READ", + opcode: 2, + data: 0, + body: attrs_body, + target: fixture.border, + kind: ResourceKind::Pixmap, + mode: AccessMode::READ, + creation: None, + }, + WindowDenyCase { + label: "GetWindowAttributes", + opcode: 3, + data: 0, + body: words(&[fixture.window.0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "DestroyWindow target", + opcode: 4, + data: 0, + body: words(&[fixture.destroy_window.0]), + target: fixture.destroy_window, + kind: ResourceKind::Window, + mode: AccessMode::DESTROY, + creation: None, + }, + WindowDenyCase { + label: "DestroyWindow parent", + opcode: 4, + data: 0, + body: words(&[fixture.destroy_window.0]), + target: fixture.destroy_parent, + kind: ResourceKind::Window, + mode: AccessMode::REMOVE, + creation: None, + }, + WindowDenyCase { + label: "DestroySubwindows parent", + opcode: 5, + data: 0, + body: words(&[fixture.parent.0]), + target: fixture.parent, + kind: ResourceKind::Window, + mode: AccessMode::REMOVE, + creation: None, + }, + WindowDenyCase { + label: "ChangeSaveSet", + opcode: 6, + data: 0, + body: words(&[fixture.window.0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::MANAGE, + creation: None, + }, + ]; + + let mut sequence = 50; + for case in cases { + denied_id.store(case.target.0, Ordering::SeqCst); + let backend_before = fixture.backend.calls(); + let mut windows_before = fixture + .state + .resources + .windows_iter() + .map(|window| format!("{window:?}")) + .collect::>(); + windows_before.sort(); + let save_set_before = fixture.state.clients[&CLIENT.0].save_set.clone(); + let event_masks_before = fixture.state.clients[&CLIENT.0].event_masks.clone(); + let calls_before = calls.lock().unwrap().len(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + sequence, + case.opcode, + case.data, + &case.body, + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, case.opcode, sequence); + assert_eq!( + fixture.backend.calls(), + backend_before, + "{} backend", + case.label + ); + let mut windows_after = fixture + .state + .resources + .windows_iter() + .map(|window| format!("{window:?}")) + .collect::>(); + windows_after.sort(); + assert_eq!(windows_after, windows_before, "{} window state", case.label); + assert_eq!( + fixture.state.clients[&CLIENT.0].save_set, save_set_before, + "{} save set", + case.label + ); + assert_eq!( + fixture.state.clients[&CLIENT.0].event_masks, event_masks_before, + "{} event selections", + case.label + ); + if case.opcode == 1 { + assert!( + fixture.state.resources.window(created).is_none(), + "{} created a window", + case.label + ); + } + let calls = calls.lock().unwrap(); + assert!(calls.len() > calls_before, "{} check count", case.label); + let call = calls.last().expect("denial was recorded"); + assert_eq!(call.client, CLIENT, "{} client", case.label); + assert_eq!( + call.request, + Some(RequestOpcodes { + major: case.opcode, + minor: 0 + }), + "{} request", + case.label + ); + assert_eq!(call.mode, Some(case.mode), "{} mode", case.label); + assert_eq!( + call.target, + Some(ResourceTarget { + id: case.target, + kind: case.kind, + creation: case.creation, + }), + "{} target", + case.label + ); + drop(calls); + sequence += 1; + } + let unresolved_window = ResourceId(0x0054_00ff); + denied_id.store(unresolved_window.0, Ordering::SeqCst); + let calls_before = calls.lock().unwrap().len(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + sequence, + 6, + 0, + &words(&[unresolved_window.0]), + ); + assert_no_error( + &bytes, + "unresolved ChangeSaveSet keeps its no-error behavior", + ); + assert_eq!( + calls.lock().unwrap().len(), + calls_before, + "unresolved window is not checked" + ); + assert!( + fixture.state.clients[&CLIENT.0] + .save_set + .contains(&unresolved_window) + ); +} + +const COLORMAP: ResourceId = ResourceId(0x0030_0001); +const NEW_COLORMAP: ResourceId = ResourceId(0x0030_0002); + +struct ColormapAccessCase { + label: &'static str, + opcode: u8, + data: u8, + body: Vec, + checks: Vec<(ResourceTarget, AccessMode)>, + installed_colormaps: Option>, +} + +fn colormap_target(id: ResourceId, creation: Option) -> ResourceTarget { + ResourceTarget { + id, + kind: ResourceKind::Colormap, + creation, + } +} + +fn colormap_access_cases() -> Vec { + let window = ResourceTarget { + id: ROOT_WINDOW, + kind: ResourceKind::Window, + creation: None, + }; + let colormap = colormap_target(COLORMAP, None); + let created = colormap_target( + NEW_COLORMAP, + Some(Creation { + parent: None, + owner: CLIENT, + }), + ); + let child_colormap = colormap_target( + NEW_COLORMAP, + Some(Creation { + parent: Some(ROOT_WINDOW), + owner: CLIENT, + }), + ); + let mut alloc_color = COLORMAP.0.to_le_bytes().to_vec(); + alloc_color.extend_from_slice(&[0; 8]); + let alloc_named_color = named_color_body(COLORMAP, b"red"); + let mut alloc_color_cells = COLORMAP.0.to_le_bytes().to_vec(); + alloc_color_cells.extend_from_slice(&[1, 0, 0, 0]); + let mut alloc_color_planes = COLORMAP.0.to_le_bytes().to_vec(); + alloc_color_planes.extend_from_slice(&[1, 0, 1, 0, 1, 0, 1, 0]); + let mut free_colors = COLORMAP.0.to_le_bytes().to_vec(); + free_colors.extend_from_slice(&[0; 4]); + let mut store_named_color = COLORMAP.0.to_le_bytes().to_vec(); + store_named_color.extend_from_slice(&[0; 4]); + store_named_color.extend_from_slice(&[3, 0, 0, 0]); + store_named_color.extend_from_slice(b"red\0"); + let mut query_colors = COLORMAP.0.to_le_bytes().to_vec(); + query_colors.extend_from_slice(&[0; 4]); + + vec![ + ColormapAccessCase { + label: "CreateColormap", + opcode: 78, + data: 0, + body: words(&[ + NEW_COLORMAP.0, + ROOT_WINDOW.0, + crate::resources::ROOT_VISUAL.0, + ]), + checks: vec![ + (window, AccessMode::GET_ATTR), + (child_colormap, AccessMode::CREATE), + ], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "FreeColormap", + opcode: 79, + data: 0, + body: words(&[COLORMAP.0]), + checks: vec![(colormap, AccessMode::DESTROY)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "CopyColormapAndFree", + opcode: 80, + data: 0, + body: words(&[NEW_COLORMAP.0, COLORMAP.0]), + checks: vec![ + (colormap, AccessMode::READ | AccessMode::REMOVE), + (created, AccessMode::CREATE), + ], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "InstallColormap", + opcode: 81, + data: 0, + body: words(&[COLORMAP.0]), + checks: vec![(colormap, AccessMode::INSTALL)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "UninstallColormap", + opcode: 82, + data: 0, + body: words(&[COLORMAP.0]), + checks: vec![(colormap, AccessMode::UNINSTALL)], + installed_colormaps: Some(vec![COLORMAP]), + }, + ColormapAccessCase { + label: "ListInstalledColormaps", + opcode: 83, + data: 0, + body: words(&[ROOT_WINDOW.0]), + checks: vec![(window, AccessMode::GET_ATTR)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "AllocColor", + opcode: 84, + data: 0, + body: alloc_color, + checks: vec![(colormap, AccessMode::ADD)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "AllocNamedColor", + opcode: 85, + data: 0, + body: alloc_named_color, + checks: vec![(colormap, AccessMode::ADD)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "AllocColorCells", + opcode: 86, + data: 0, + body: alloc_color_cells, + checks: vec![(colormap, AccessMode::ADD)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "AllocColorPlanes", + opcode: 87, + data: 0, + body: alloc_color_planes, + checks: vec![(colormap, AccessMode::ADD)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "FreeColors", + opcode: 88, + data: 0, + body: free_colors, + checks: vec![(colormap, AccessMode::REMOVE)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "StoreColors", + opcode: 89, + data: 0, + body: words(&[COLORMAP.0]), + checks: vec![(colormap, AccessMode::WRITE)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "StoreNamedColor", + opcode: 90, + data: 0, + body: store_named_color, + checks: vec![(colormap, AccessMode::WRITE)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "QueryColors", + opcode: 91, + data: 0, + body: query_colors, + checks: vec![(colormap, AccessMode::READ)], + installed_colormaps: None, + }, + ColormapAccessCase { + label: "LookupColor", + opcode: 92, + data: 0, + body: named_color_body(COLORMAP, b"red"), + checks: vec![(colormap, AccessMode::READ)], + installed_colormaps: None, + }, + ] +} + +fn named_color_body(colormap: ResourceId, name: &[u8]) -> Vec { + let mut body = colormap.0.to_le_bytes().to_vec(); + body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0; 2]); + body.extend_from_slice(name); + body.resize(body.len().div_ceil(4) * 4, 0); + body +} + +struct ColormapAccessFixture { + state: ServerState, + backend: RecordingBackend, + peer: UnixStream, +} + +fn colormap_access_fixture() -> ColormapAccessFixture { + let mut state = ServerState::new(); + let peer = install_client(&mut state, CLIENT.0); + state + .resources + .create_colormap(CLIENT, COLORMAP, crate::resources::ROOT_VISUAL); + ColormapAccessFixture { + state, + backend: RecordingBackend::new(), + peer, + } +} + +fn colormap_request( + fixture: &mut ColormapAccessFixture, + sequence: u16, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + process_request( + &mut fixture.state, + &mut fixture.backend, + CLIENT, + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("colormap request through process_request"); + read_all_available(&mut fixture.peer) +} + +#[test] +fn colormap_resource_requests_deny_each_target_before_effects() { + // Mutation: remove FreeColormap's resource check; its denial and retained-colormap assertions must fail. + for case in colormap_access_cases() { + for (deny_index, (denied_target, denied_mode)) in case.checks.iter().enumerate() { + let mut fixture = colormap_access_fixture(); + if let Some(installed) = &case.installed_colormaps { + fixture.state.installed_colormaps.clone_from(installed); + } + let calls = Arc::new(Mutex::new(Vec::new())); + let denied_id = Arc::new(AtomicU32::new(denied_target.id.0)); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::clone(&denied_id)), + deny_mode: Some(*denied_mode), + deny_hides: false, + })); + + let colormap_before = fixture + .state + .resources + .colormap(COLORMAP) + .map(|colormap| format!("{colormap:?}")); + let new_colormap_before = fixture + .state + .resources + .colormap(NEW_COLORMAP) + .map(|colormap| format!("{colormap:?}")); + let installed_before = fixture.state.installed_colormaps.clone(); + let backend_before = fixture.backend.calls(); + let sequence = 200 + u16::try_from(deny_index).unwrap(); + let bytes = + colormap_request(&mut fixture, sequence, case.opcode, case.data, &case.body); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, case.opcode, sequence); + assert_eq!( + fixture.backend.calls(), + backend_before, + "{} backend", + case.label + ); + assert_eq!( + fixture + .state + .resources + .colormap(COLORMAP) + .map(|colormap| format!("{colormap:?}")), + colormap_before, + "{} source colormap", + case.label + ); + assert_eq!( + fixture + .state + .resources + .colormap(NEW_COLORMAP) + .map(|colormap| format!("{colormap:?}")), + new_colormap_before, + "{} new colormap", + case.label + ); + assert_eq!( + fixture.state.installed_colormaps, installed_before, + "{} installed colormaps", + case.label + ); + + let recorded = calls.lock().unwrap(); + let expected = &case.checks[..=deny_index]; + assert_eq!( + recorded.len(), + expected.len(), + "{} checked prefix", + case.label + ); + for (call, (target, mode)) in recorded.iter().zip(expected) { + assert_eq!(call.client, CLIENT, "{} client", case.label); + assert_eq!( + call.request, + Some(RequestOpcodes { + major: case.opcode, + minor: 0 + }), + "{} request", + case.label + ); + assert_eq!(call.target, Some(*target), "{} target", case.label); + assert_eq!(call.mode, Some(*mode), "{} mode", case.label); + } + } + } +} + +#[test] +fn colormap_resource_requests_ask_every_expected_target() { + // Mutation: change QueryColors from READ to WRITE; its recorded-mode assertion must fail. + for case in colormap_access_cases() { + let mut fixture = colormap_access_fixture(); + if let Some(installed) = &case.installed_colormaps { + fixture.state.installed_colormaps.clone_from(installed); + } + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: None, + deny_mode: None, + deny_hides: false, + })); + let _ = colormap_request(&mut fixture, 240, case.opcode, case.data, &case.body); + let recorded = calls.lock().unwrap(); + assert_eq!( + recorded.len(), + case.checks.len(), + "{} check count", + case.label + ); + for (call, (target, mode)) in recorded.iter().zip(&case.checks) { + assert_eq!(call.client, CLIENT, "{} client", case.label); + assert_eq!( + call.request, + Some(RequestOpcodes { + major: case.opcode, + minor: 0 + }), + "{} request", + case.label + ); + assert_eq!(call.target, Some(*target), "{} target", case.label); + assert_eq!(call.mode, Some(*mode), "{} mode", case.label); + } + } +} + +#[test] +fn colormap_unconditional_errors_survive_allow_all_policy() { + // Mutation: skip AllocColorCells' unconditional BadAlloc after Allow; byte equality with the no-policy reply must fail. + for (opcode, data, body, expected_code) in [ + ( + 86, + 0, + words(&[COLORMAP.0, 1 | (1 << 16)]), + x11::error::BAD_ALLOC, + ), + ( + 87, + 0, + words(&[COLORMAP.0, 1 | (1 << 16), 1 | (1 << 16)]), + x11::error::BAD_ALLOC, + ), + (89, 0, words(&[COLORMAP.0]), x11::error::BAD_ACCESS), + ( + 90, + 0, + { + let mut body = COLORMAP.0.to_le_bytes().to_vec(); + body.extend_from_slice(&[0; 4]); + body.extend_from_slice(&[0; 4]); + body + }, + x11::error::BAD_ACCESS, + ), + ] { + let mut baseline = colormap_access_fixture(); + let baseline_bytes = colormap_request(&mut baseline, 250, opcode, data, &body); + assert_x11_error(&baseline_bytes, expected_code, 0, opcode, 250); + + let mut allowed = colormap_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + allowed + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: None, + deny_mode: None, + deny_hides: false, + })); + let allowed_bytes = colormap_request(&mut allowed, 250, opcode, data, &body); + assert_eq!( + allowed_bytes, baseline_bytes, + "opcode {opcode} allow-all bytes" + ); + assert_eq!( + calls.lock().unwrap().len(), + 1, + "opcode {opcode} access check" + ); + } +} + +#[test] +fn window_resource_requests_present_expected_checks() { + // Mutation: remove or reorder any row's check; the exact policy call sequence must fail. + // Mutation: erase CreateWindow's Creation record; its parent/owner assertion must fail. + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + let created = ResourceId(0x0054_000c); + let create_body = create_window_with_access_attributes( + created, + ROOT_WINDOW, + fixture.background, + fixture.border, + fixture.colormap, + fixture.cursor, + ); + let attrs_body = change_window_attributes_with_access_operands( + fixture.window, + fixture.background, + fixture.border, + fixture.colormap, + fixture.cursor, + ); + for (sequence, (opcode, data, body)) in (70u16..).zip([ + (1, 24, create_body), + (2, 0, attrs_body), + (2, 0, words(&[fixture.window.0, 0x0800, 1])), + (2, 0, words(&[fixture.window.0, 0x0200, 1])), + (3, 0, words(&[fixture.window.0])), + (4, 0, words(&[fixture.destroy_window.0])), + (5, 0, words(&[fixture.subwindows_parent.0])), + (6, 0, words(&[fixture.window.0])), + ]) { + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + sequence, + opcode, + data, + &body, + ); + if opcode == 3 { + assert_eq!(bytes.first(), Some(&1), "GetWindowAttributes reply"); + } else { + assert_no_error(&bytes, "allowed window access request"); + } + } + + let expected = vec![ + ( + CLIENT, + ROOT_WINDOW, + ResourceKind::Window, + AccessMode::ADD, + Some(RequestOpcodes { major: 1, minor: 0 }), + ), + ( + CLIENT, + fixture.background, + ResourceKind::Pixmap, + AccessMode::READ, + Some(RequestOpcodes { major: 1, minor: 0 }), + ), + ( + CLIENT, + fixture.colormap, + ResourceKind::Colormap, + AccessMode::USE, + Some(RequestOpcodes { major: 1, minor: 0 }), + ), + ( + CLIENT, + fixture.cursor, + ResourceKind::Cursor, + AccessMode::USE, + Some(RequestOpcodes { major: 1, minor: 0 }), + ), + ( + CLIENT, + fixture.border, + ResourceKind::Pixmap, + AccessMode::READ, + Some(RequestOpcodes { major: 1, minor: 0 }), + ), + ( + CLIENT, + created, + ResourceKind::Window, + AccessMode::CREATE | AccessMode::SET_ATTR, + Some(RequestOpcodes { major: 1, minor: 0 }), + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::RECEIVE | AccessMode::SET_ATTR, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.background, + ResourceKind::Pixmap, + AccessMode::READ, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.colormap, + ResourceKind::Colormap, + AccessMode::USE, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.cursor, + ResourceKind::Cursor, + AccessMode::USE, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.border, + ResourceKind::Pixmap, + AccessMode::READ, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::RECEIVE, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::SET_ATTR, + Some(RequestOpcodes { major: 2, minor: 0 }), + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::GET_ATTR, + Some(RequestOpcodes { major: 3, minor: 0 }), + ), + ( + CLIENT, + fixture.destroy_window, + ResourceKind::Window, + AccessMode::DESTROY, + Some(RequestOpcodes { major: 4, minor: 0 }), + ), + ( + CLIENT, + fixture.destroy_parent, + ResourceKind::Window, + AccessMode::REMOVE, + Some(RequestOpcodes { major: 4, minor: 0 }), + ), + ( + CLIENT, + fixture.subwindows_parent, + ResourceKind::Window, + AccessMode::REMOVE, + Some(RequestOpcodes { major: 5, minor: 0 }), + ), + ( + CLIENT, + fixture.subwindow_children[0], + ResourceKind::Window, + AccessMode::DESTROY, + Some(RequestOpcodes { major: 5, minor: 0 }), + ), + ( + CLIENT, + fixture.subwindow_children[1], + ResourceKind::Window, + AccessMode::DESTROY, + Some(RequestOpcodes { major: 5, minor: 0 }), + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE, + Some(RequestOpcodes { major: 6, minor: 0 }), + ), + ]; + assert_eq!(expected_resource_checks(&calls.lock().unwrap()), expected); + let recorded = calls.lock().unwrap(); + let creation = recorded + .iter() + .find(|call| call.target.is_some_and(|target| target.id == created)) + .expect("CreateWindow creation check"); + assert_eq!( + creation.target.unwrap().creation, + Some(Creation { + parent: Some(ROOT_WINDOW), + owner: CLIENT, + }) + ); + assert!(fixture.state.resources.window(created).is_some()); +} + +struct DestroySubwindowsFixture { + state: ServerState, + backend: RecordingBackend, + requester: UnixStream, + observer: UnixStream, + parent: ResourceId, + children: Vec, +} + +fn mapped_destroy_subwindows_fixture() -> DestroySubwindowsFixture { + let mut state = ServerState::new(); + let mut requester = install_client(&mut state, CLIENT.0); + let observer = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let parent = ResourceId(0x0055_0001); + let children = [ + ResourceId(0x0055_0002), + ResourceId(0x0055_0003), + ResourceId(0x0055_0004), + ]; + let mut sequence = 1; + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + parent, + ROOT_WINDOW, + ); + for child in children { + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + child, + parent, + ); + } + for window in [parent, children[0], children[1], children[2]] { + let bytes = resource_request( + &mut state, + &mut backend, + &mut requester, + sequence, + 8, + 0, + &words(&[window.0]), + ); + assert_no_error(&bytes, "DestroySubwindows fixture MapWindow"); + sequence += 1; + } + let children = state.resources.children(parent).to_vec(); + let observer_state = state.clients.get_mut(&2).expect("observer client"); + for child in &children { + observer_state.event_masks.insert(*child, 0x0002_0000); + } + DestroySubwindowsFixture { + state, + backend, + requester, + observer, + parent, + children, + } +} + +fn event_type_and_window(bytes: &[u8]) -> Vec<(u8, ResourceId)> { + assert_eq!(bytes.len() % 32, 0, "event stream has complete X11 events"); + bytes + .chunks_exact(32) + .map(|event| { + ( + event[0] & 0x7f, + ResourceId(u32::from_le_bytes(event[8..12].try_into().unwrap())), + ) + }) + .collect() +} + +fn destroy_subwindows_wire_bytes(child_count: usize, allow_policy: bool) -> (Vec, Vec) { + let mut state = ServerState::new(); + let mut requester = install_client(&mut state, CLIENT.0); + let mut observer = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let parent = ResourceId(0x0056_0001); + let children = [ + ResourceId(0x0056_0002), + ResourceId(0x0056_0003), + ResourceId(0x0056_0004), + ]; + let mut sequence = 1; + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + parent, + ROOT_WINDOW, + ); + for child in children.iter().take(child_count) { + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + *child, + parent, + ); + } + for window in std::iter::once(parent).chain(children.into_iter().take(child_count)) { + let bytes = resource_request( + &mut state, + &mut backend, + &mut requester, + sequence, + 8, + 0, + &words(&[window.0]), + ); + assert_no_error(&bytes, "DestroySubwindows byte fixture MapWindow"); + sequence += 1; + } + for child in state.resources.children(parent).to_vec() { + state + .clients + .get_mut(&2) + .expect("observer client") + .event_masks + .insert(child, 0x0002_0000); + } + if allow_policy { + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::new(Mutex::new(Vec::new())), + })); + } + let request_bytes = resource_request( + &mut state, + &mut backend, + &mut requester, + sequence, + 5, + 0, + &words(&[parent.0]), + ); + let event_bytes = read_all_available(&mut observer); + (request_bytes, event_bytes) +} + +#[test] +fn destroy_subwindows_denied_child_stops_the_loop() { + // Mutation: check before the bulk unmap, or continue after the first child denial; each changes these event/state assertions. + let mut fixture = mapped_destroy_subwindows_fixture(); + let [c1, c2, c3] = fixture.children.as_slice() else { + panic!("three children"); + }; + let c1 = *c1; + let c2 = *c2; + let c3 = *c3; + let child_hosts = fixture + .children + .iter() + .map(|child| { + ( + *child, + fixture + .state + .resources + .window(*child) + .and_then(|window| window.host_xid) + .expect("mapped fixture host window") + .as_raw(), + ) + }) + .collect::>(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(c2.0))), + deny_mode: Some(AccessMode::DESTROY), + deny_hides: false, + })); + let backend_before = fixture.backend.calls(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 20, + 5, + 0, + &words(&[fixture.parent.0]), + ); + assert!(bytes.is_empty(), "derived-target denial returns Success"); + let events = read_all_available(&mut fixture.observer); + assert_eq!( + event_type_and_window(&events), + [(18, c1), (18, c2), (18, c3), (17, c1)], + "bulk UnmapNotify events precede the allowed child's DestroyNotify" + ); + assert!( + fixture.state.resources.window(c1).is_none(), + "first child destroyed" + ); + for child in [c2, c3] { + assert_eq!( + fixture + .state + .resources + .window(child) + .map(|window| window.map_state), + Some(crate::resources::MapState::Unmapped), + "remaining child stays present and unmapped" + ); + } + assert_eq!(fixture.state.resources.children(fixture.parent), &[c2, c3]); + let calls_after = fixture.backend.calls(); + let new_calls = &calls_after[backend_before.len()..]; + let unmapped = new_calls + .iter() + .filter_map(|call| match call { + RecordedCall::UnmapSubwindow(host) => Some(*host), + _ => None, + }) + .collect::>(); + assert_eq!( + unmapped, + fixture + .children + .iter() + .map(|child| child_hosts.iter().find(|(id, _)| id == child).unwrap().1) + .collect::>(), + "all children are unmapped before the destroy loop" + ); + let destroyed = new_calls + .iter() + .filter_map(|call| match call { + RecordedCall::DestroySubwindow(host) => Some(*host), + _ => None, + }) + .collect::>(); + assert_eq!( + destroyed, + [child_hosts.iter().find(|(id, _)| *id == c1).unwrap().1] + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.parent, + ResourceKind::Window, + AccessMode::REMOVE, + Some(RequestOpcodes { major: 5, minor: 0 }) + ), + ( + CLIENT, + c1, + ResourceKind::Window, + AccessMode::DESTROY, + Some(RequestOpcodes { major: 5, minor: 0 }) + ), + ( + CLIENT, + c2, + ResourceKind::Window, + AccessMode::DESTROY, + Some(RequestOpcodes { major: 5, minor: 0 }) + ), + ] + ); + + let empty_without_policy = destroy_subwindows_wire_bytes(0, false); + let empty_with_policy = destroy_subwindows_wire_bytes(0, true); + assert_eq!( + empty_with_policy, empty_without_policy, + "empty list preserves today's bytes" + ); + let populated_without_policy = destroy_subwindows_wire_bytes(3, false); + let populated_with_policy = destroy_subwindows_wire_bytes(3, true); + assert_eq!( + populated_with_policy, populated_without_policy, + "allow-all policy preserves today's event bytes" + ); +} + +#[test] +fn destroy_subwindows_bulk_unmap_ignores_hide() { + // Mutation: put a HIDE check in the shared unmap helper; denying HIDE must not keep a child mapped here. + let mut fixture = mapped_destroy_subwindows_fixture(); + let [c1, c2, c3] = fixture.children.as_slice() else { + panic!("three children"); + }; + let (c1, c2, c3) = (*c1, *c2, *c3); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(c2.0))), + deny_mode: Some(AccessMode::DESTROY), + deny_hides: true, + })); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 21, + 5, + 0, + &words(&[fixture.parent.0]), + ); + assert!(bytes.is_empty(), "derived-target denial returns Success"); + assert_eq!( + event_type_and_window(&read_all_available(&mut fixture.observer)), + [(18, c1), (18, c2), (18, c3), (17, c1)] + ); + assert!(fixture.state.resources.window(c1).is_none()); + for child in [c2, c3] { + assert_eq!( + fixture + .state + .resources + .window(child) + .map(|window| window.map_state), + Some(crate::resources::MapState::Unmapped) + ); + } + assert!( + expected_resource_checks(&calls.lock().unwrap()) + .iter() + .all(|(_, _, _, mode, _)| *mode != AccessMode::HIDE), + "DestroySubwindows asks only REMOVE and DESTROY" + ); +} + +#[test] +fn map_window_denied_show_returns_success_and_maps_nothing() { + // Mutation: report the MapWindow SHOW denial as an X error; this request must instead succeed without mapping or notifying. + let mut fixture = window_access_fixture(); + fixture + .state + .clients + .get_mut(&CLIENT.0) + .expect("requesting client") + .event_masks + .insert(fixture.window, 0x0002_0000); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.window.0))), + deny_mode: Some(AccessMode::SHOW), + deny_hides: false, + })); + let backend_before = fixture.backend.calls(); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 80, + 8, + 0, + &words(&[fixture.window.0]), + ); + + assert!( + bytes.is_empty(), + "denied MapWindow has no error or MapNotify" + ); + assert_eq!( + fixture + .state + .resources + .window(fixture.window) + .unwrap() + .map_state, + crate::resources::MapState::Unmapped + ); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::SHOW, + Some(RequestOpcodes { major: 8, minor: 0 }), + )] + ); +} + +#[test] +fn window_tree_resource_request_access_calls_follow_site_order() { + // Mutation: omit or reorder any scoped whole-request or derived-target check; its recorded target/mode sequence must differ. + let labels = [ + "reparent", + "map_window", + "map_subwindows", + "unmap_window", + "unmap_subwindows", + "configure_window", + "circulate_window", + "get_geometry_window", + "get_geometry_pixmap", + "query_tree", + "query_pointer", + "get_motion_events", + "translate_coordinates", + "warp_pointer", + ]; + + for (index, label) in labels.into_iter().enumerate() { + let mut fixture = window_access_fixture(); + let mut setup_sequence = 1; + let mut map = |window: ResourceId| { + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + setup_sequence, + 8, + 0, + &words(&[window.0]), + ); + assert_no_error(&bytes, "window tree access fixture MapWindow"); + setup_sequence += 1; + }; + let (opcode, data, body, expected): WindowAccessCase = match label { + "reparent" => { + map(fixture.parent); + map(fixture.window); + ( + 7, + 0, + words(&[fixture.window.0, fixture.destroy_parent.0, 0]), + vec![ + (fixture.window, ResourceKind::Window, AccessMode::MANAGE), + ( + fixture.destroy_parent, + ResourceKind::Window, + AccessMode::ADD, + ), + (fixture.window, ResourceKind::Window, AccessMode::SHOW), + ], + ) + } + "map_window" => ( + 8, + 0, + words(&[fixture.window.0]), + vec![(fixture.window, ResourceKind::Window, AccessMode::SHOW)], + ), + "map_subwindows" => ( + 9, + 0, + words(&[fixture.subwindows_parent.0]), + vec![ + ( + fixture.subwindows_parent, + ResourceKind::Window, + AccessMode::LIST, + ), + ( + fixture.subwindow_children[1], + ResourceKind::Window, + AccessMode::SHOW, + ), + ( + fixture.subwindow_children[0], + ResourceKind::Window, + AccessMode::SHOW, + ), + ], + ), + "unmap_window" => { + map(fixture.parent); + map(fixture.window); + ( + 10, + 0, + words(&[fixture.window.0]), + vec![(fixture.window, ResourceKind::Window, AccessMode::HIDE)], + ) + } + "unmap_subwindows" => { + map(fixture.subwindows_parent); + for child in fixture.subwindow_children { + map(child); + } + ( + 11, + 0, + words(&[fixture.subwindows_parent.0]), + vec![ + ( + fixture.subwindows_parent, + ResourceKind::Window, + AccessMode::LIST, + ), + ( + fixture.subwindow_children[0], + ResourceKind::Window, + AccessMode::HIDE, + ), + ( + fixture.subwindow_children[1], + ResourceKind::Window, + AccessMode::HIDE, + ), + ], + ) + } + "configure_window" => { + let sibling = ResourceId(0x0054_000c); + create_test_window( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + &mut setup_sequence, + sibling, + fixture.parent, + ); + ( + 12, + 0, + words(&[fixture.window.0, 0x0060, sibling.0, 0]), + vec![ + ( + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE | AccessMode::SET_ATTR, + ), + (sibling, ResourceKind::Window, AccessMode::GET_ATTR), + ], + ) + } + "circulate_window" => { + map(fixture.subwindows_parent); + for child in fixture.subwindow_children { + map(child); + } + let child = fixture + .state + .circulate_candidate(fixture.subwindows_parent, 0) + .expect("overlapping mapped child is a CirculateWindow target"); + ( + 13, + 0, + words(&[fixture.subwindows_parent.0]), + vec![ + ( + fixture.subwindows_parent, + ResourceKind::Window, + AccessMode::MANAGE, + ), + ( + child, + ResourceKind::Window, + AccessMode::MANAGE | AccessMode::SET_ATTR, + ), + ], + ) + } + "get_geometry_window" => ( + 14, + 0, + words(&[fixture.window.0]), + vec![(fixture.window, ResourceKind::Window, AccessMode::GET_ATTR)], + ), + "get_geometry_pixmap" => ( + 14, + 0, + words(&[fixture.border.0]), + vec![(fixture.border, ResourceKind::Pixmap, AccessMode::GET_ATTR)], + ), + "query_tree" => ( + 15, + 0, + words(&[fixture.window.0]), + vec![(fixture.window, ResourceKind::Window, AccessMode::LIST)], + ), + "query_pointer" => ( + 38, + 0, + words(&[fixture.window.0]), + vec![(fixture.window, ResourceKind::Window, AccessMode::GET_ATTR)], + ), + "get_motion_events" => ( + 39, + 0, + words(&[fixture.window.0, 0, 0]), + vec![(fixture.window, ResourceKind::Window, AccessMode::GET_ATTR)], + ), + "translate_coordinates" => ( + 40, + 0, + words(&[fixture.window.0, fixture.parent.0, 0]), + vec![ + (fixture.window, ResourceKind::Window, AccessMode::GET_ATTR), + (fixture.parent, ResourceKind::Window, AccessMode::GET_ATTR), + ], + ), + "warp_pointer" => { + let mut body = words(&[fixture.parent.0, fixture.window.0]); + body.extend_from_slice(&[0; 12]); + ( + 41, + 0, + body, + vec![ + (fixture.window, ResourceKind::Window, AccessMode::GET_ATTR), + (fixture.parent, ResourceKind::Window, AccessMode::GET_ATTR), + ], + ) + } + _ => unreachable!(), + }; + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: None, + deny_mode: None, + deny_hides: false, + })); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 80 + u16::try_from(index).unwrap(), + opcode, + data, + &body, + ); + + assert!( + bytes.first().is_none_or(|first| *first != 0), + "{label} unexpectedly returned an X error: {bytes:02x?}" + ); + let actual = expected_resource_checks(&calls.lock().unwrap()); + let expected = expected + .into_iter() + .map(|(id, kind, mode)| { + ( + CLIENT, + id, + kind, + mode, + Some(RequestOpcodes { + major: opcode, + minor: 0, + }), + ) + }) + .collect::>(); + assert_eq!(actual, expected, "{label} check order"); + } +} + +#[test] +fn window_tree_resource_request_denials_match_modes_and_stop_before_effects() { + // Mutation: remove or change a whole-request target check; the policy error, request opcode, backend log, or window snapshot must fail. + let mut fixture = window_access_fixture(); + let mut setup_sequence = 1; + for window in [fixture.parent, fixture.window, fixture.subwindows_parent] { + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + setup_sequence, + 8, + 0, + &words(&[window.0]), + ); + assert_no_error(&bytes, "window request denial fixture MapWindow"); + setup_sequence += 1; + } + for child in fixture.subwindow_children { + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + setup_sequence, + 8, + 0, + &words(&[child.0]), + ); + assert_no_error(&bytes, "window request denial fixture MapWindow child"); + setup_sequence += 1; + } + let sibling = ResourceId(0x0054_000c); + create_test_window( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + &mut setup_sequence, + sibling, + fixture.parent, + ); + let reparent_body = words(&[fixture.window.0, fixture.destroy_parent.0, 0]); + let configure_body = words(&[fixture.window.0, 0x0001, 17]); + let configure_sibling_body = words(&[fixture.window.0, 0x0060, sibling.0, 0]); + let mut warp_body = words(&[fixture.parent.0, fixture.window.0]); + warp_body.extend_from_slice(&[0; 12]); + let cases = vec![ + WindowDenyCase { + label: "ReparentWindow window", + opcode: 7, + data: 0, + body: reparent_body.clone(), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::MANAGE, + creation: None, + }, + WindowDenyCase { + label: "ReparentWindow new parent", + opcode: 7, + data: 0, + body: reparent_body, + target: fixture.destroy_parent, + kind: ResourceKind::Window, + mode: AccessMode::ADD, + creation: None, + }, + WindowDenyCase { + label: "MapSubwindows parent", + opcode: 9, + data: 0, + body: words(&[fixture.subwindows_parent.0]), + target: fixture.subwindows_parent, + kind: ResourceKind::Window, + mode: AccessMode::LIST, + creation: None, + }, + WindowDenyCase { + label: "UnmapWindow", + opcode: 10, + data: 0, + body: words(&[fixture.window.0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::HIDE, + creation: None, + }, + WindowDenyCase { + label: "UnmapSubwindows parent", + opcode: 11, + data: 0, + body: words(&[fixture.subwindows_parent.0]), + target: fixture.subwindows_parent, + kind: ResourceKind::Window, + mode: AccessMode::LIST, + creation: None, + }, + WindowDenyCase { + label: "ConfigureWindow", + opcode: 12, + data: 0, + body: configure_body, + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::MANAGE | AccessMode::SET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "ConfigureWindow sibling", + opcode: 12, + data: 0, + body: configure_sibling_body, + target: sibling, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "CirculateWindow container", + opcode: 13, + data: 0, + body: words(&[fixture.subwindows_parent.0]), + target: fixture.subwindows_parent, + kind: ResourceKind::Window, + mode: AccessMode::MANAGE, + creation: None, + }, + WindowDenyCase { + label: "GetGeometry window", + opcode: 14, + data: 0, + body: words(&[fixture.window.0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "GetGeometry pixmap", + opcode: 14, + data: 0, + body: words(&[fixture.border.0]), + target: fixture.border, + kind: ResourceKind::Pixmap, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "QueryTree", + opcode: 15, + data: 0, + body: words(&[fixture.window.0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::LIST, + creation: None, + }, + WindowDenyCase { + label: "QueryPointer", + opcode: 38, + data: 0, + body: words(&[fixture.window.0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "GetMotionEvents", + opcode: 39, + data: 0, + body: words(&[fixture.window.0, 0, 0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "TranslateCoordinates source", + opcode: 40, + data: 0, + body: words(&[fixture.window.0, fixture.parent.0, 0]), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "TranslateCoordinates destination", + opcode: 40, + data: 0, + body: words(&[fixture.window.0, fixture.parent.0, 0]), + target: fixture.parent, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "WarpPointer destination", + opcode: 41, + data: 0, + body: warp_body.clone(), + target: fixture.window, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + WindowDenyCase { + label: "WarpPointer source", + opcode: 41, + data: 0, + body: warp_body, + target: fixture.parent, + kind: ResourceKind::Window, + mode: AccessMode::GET_ATTR, + creation: None, + }, + ]; + let calls = Arc::new(Mutex::new(Vec::new())); + let denied_id = Arc::new(AtomicU32::new(0)); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::clone(&denied_id)), + deny_mode: None, + deny_hides: false, + })); + + for (index, case) in cases.into_iter().enumerate() { + denied_id.store(case.target.0, Ordering::SeqCst); + let sequence = 100 + u16::try_from(index).unwrap(); + let backend_before = fixture.backend.calls(); + let mut windows_before = fixture + .state + .resources + .windows_iter() + .map(|window| format!("{window:?}")) + .collect::>(); + windows_before.sort(); + let calls_before = calls.lock().unwrap().len(); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + sequence, + case.opcode, + case.data, + &case.body, + ); + + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, case.opcode, sequence); + assert_eq!( + fixture.backend.calls(), + backend_before, + "{} backend", + case.label + ); + let mut windows_after = fixture + .state + .resources + .windows_iter() + .map(|window| format!("{window:?}")) + .collect::>(); + windows_after.sort(); + assert_eq!(windows_after, windows_before, "{} state", case.label); + let checks = calls.lock().unwrap(); + assert!(checks.len() > calls_before, "{} check count", case.label); + let denied = checks.last().expect("denial was recorded"); + assert_eq!(denied.client, CLIENT, "{} client", case.label); + assert_eq!( + denied.target.map(|target| (target.id, target.kind)), + Some((case.target, case.kind)), + "{} target", + case.label + ); + assert_eq!(denied.mode, Some(case.mode), "{} mode", case.label); + assert_eq!( + denied.request, + Some(RequestOpcodes { + major: case.opcode, + minor: 0 + }), + "{} request", + case.label + ); + } +} + +fn three_child_window_access_fixture(map_children: bool) -> DestroySubwindowsFixture { + let mut state = ServerState::new(); + let mut requester = install_client(&mut state, CLIENT.0); + let mut observer = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let parent = ResourceId(0x0057_0001); + let children = [ + ResourceId(0x0057_0002), + ResourceId(0x0057_0003), + ResourceId(0x0057_0004), + ]; + let mut sequence = 1; + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + parent, + ROOT_WINDOW, + ); + for child in children { + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + child, + parent, + ); + } + for window in + std::iter::once(parent).chain(map_children.then_some(children).into_iter().flatten()) + { + let bytes = resource_request( + &mut state, + &mut backend, + &mut requester, + sequence, + 8, + 0, + &words(&[window.0]), + ); + assert_no_error(&bytes, "three-child access fixture MapWindow"); + sequence += 1; + } + for child in children { + state + .clients + .get_mut(&2) + .expect("observer client") + .event_masks + .insert(child, 0x0002_0000); + } + let _ = read_all_available(&mut observer); + DestroySubwindowsFixture { + state, + backend, + requester, + observer, + parent, + children: children.to_vec(), + } +} + +#[test] +fn map_subwindows_skips_denied_child() { + // Mutation: map the denied middle child or stop the loop there; only the two allowed children may map and notify. + let mut fixture = three_child_window_access_fixture(false); + let [c1, c2, c3] = fixture.children.as_slice() else { + panic!("three children"); + }; + let (c1, c2, c3) = (*c1, *c2, *c3); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(c2.0))), + deny_mode: Some(AccessMode::SHOW), + deny_hides: false, + })); + let host_c1 = fixture + .state + .resources + .window(c1) + .and_then(|window| window.host_xid) + .expect("child has a backend window") + .as_raw(); + let host_c3 = fixture + .state + .resources + .window(c3) + .and_then(|window| window.host_xid) + .expect("child has a backend window") + .as_raw(); + let backend_before = fixture.backend.calls(); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 20, + 9, + 0, + &words(&[fixture.parent.0]), + ); + + assert!(bytes.is_empty(), "denied child is a successful skip"); + assert_eq!( + event_type_and_window(&read_all_available(&mut fixture.observer)), + [(19, c3), (19, c1)] + ); + assert_eq!( + fixture.state.resources.window(c1).unwrap().map_state, + crate::resources::MapState::Viewable + ); + assert_eq!( + fixture.state.resources.window(c2).unwrap().map_state, + crate::resources::MapState::Unmapped + ); + assert_eq!( + fixture.state.resources.window(c3).unwrap().map_state, + crate::resources::MapState::Viewable + ); + let mapped = fixture.backend.calls()[backend_before.len()..] + .iter() + .filter_map(|call| match call { + RecordedCall::MapSubwindow(host) => Some(*host), + _ => None, + }) + .collect::>(); + assert_eq!(mapped, [host_c3, host_c1]); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.parent, + ResourceKind::Window, + AccessMode::LIST, + Some(RequestOpcodes { major: 9, minor: 0 }) + ), + ( + CLIENT, + c3, + ResourceKind::Window, + AccessMode::SHOW, + Some(RequestOpcodes { major: 9, minor: 0 }) + ), + ( + CLIENT, + c2, + ResourceKind::Window, + AccessMode::SHOW, + Some(RequestOpcodes { major: 9, minor: 0 }) + ), + ( + CLIENT, + c1, + ResourceKind::Window, + AccessMode::SHOW, + Some(RequestOpcodes { major: 9, minor: 0 }) + ), + ] + ); +} + +#[test] +fn unmap_subwindows_skips_denied_child() { + // Mutation: unmap the denied middle child or stop the loop there; the two allowed children must still unmap. + let mut fixture = three_child_window_access_fixture(true); + let [c1, c2, c3] = fixture.children.as_slice() else { + panic!("three children"); + }; + let (c1, c2, c3) = (*c1, *c2, *c3); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(c2.0))), + deny_mode: Some(AccessMode::HIDE), + deny_hides: false, + })); + let host_c1 = fixture + .state + .resources + .window(c1) + .and_then(|window| window.host_xid) + .expect("child has a backend window") + .as_raw(); + let host_c3 = fixture + .state + .resources + .window(c3) + .and_then(|window| window.host_xid) + .expect("child has a backend window") + .as_raw(); + let backend_before = fixture.backend.calls(); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 21, + 11, + 0, + &words(&[fixture.parent.0]), + ); + + assert!(bytes.is_empty(), "denied child is a successful skip"); + assert_eq!( + event_type_and_window(&read_all_available(&mut fixture.observer)), + [(18, c1), (18, c3)] + ); + assert_eq!( + fixture.state.resources.window(c1).unwrap().map_state, + crate::resources::MapState::Unmapped + ); + assert_eq!( + fixture.state.resources.window(c2).unwrap().map_state, + crate::resources::MapState::Viewable + ); + assert_eq!( + fixture.state.resources.window(c3).unwrap().map_state, + crate::resources::MapState::Unmapped + ); + let unmapped = fixture.backend.calls()[backend_before.len()..] + .iter() + .filter_map(|call| match call { + RecordedCall::UnmapSubwindow(host) => Some(*host), + _ => None, + }) + .collect::>(); + assert_eq!(unmapped, [host_c1, host_c3]); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.parent, + ResourceKind::Window, + AccessMode::LIST, + Some(RequestOpcodes { + major: 11, + minor: 0 + }) + ), + ( + CLIENT, + c1, + ResourceKind::Window, + AccessMode::HIDE, + Some(RequestOpcodes { + major: 11, + minor: 0 + }) + ), + ( + CLIENT, + c2, + ResourceKind::Window, + AccessMode::HIDE, + Some(RequestOpcodes { + major: 11, + minor: 0 + }) + ), + ( + CLIENT, + c3, + ResourceKind::Window, + AccessMode::HIDE, + Some(RequestOpcodes { + major: 11, + minor: 0 + }) + ), + ] + ); +} + +#[test] +fn circulate_denied_child_is_not_restacked() { + // Mutation: restack the chosen child before or despite its MANAGE+SET_ATTR denial; order, events, and backend calls must stay unchanged. + let mut fixture = three_child_window_access_fixture(true); + let child = fixture + .state + .circulate_candidate(fixture.parent, 0) + .expect("mapped overlapping child is selected"); + for window in fixture.children.iter().copied().chain([fixture.parent]) { + fixture + .state + .clients + .get_mut(&2) + .expect("observer client") + .event_masks + .insert(window, 0x0002_0000 | 0x0008_0000); + } + let _ = read_all_available(&mut fixture.observer); + let children_before = fixture.state.resources.children(fixture.parent).to_vec(); + let backend_before = fixture.backend.calls(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(child.0))), + deny_mode: Some(AccessMode::MANAGE | AccessMode::SET_ATTR), + deny_hides: false, + })); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 22, + 13, + 0, + &words(&[fixture.parent.0]), + ); + + assert!(bytes.is_empty(), "denied chosen child is a successful skip"); + assert_eq!( + fixture.state.resources.children(fixture.parent), + children_before + ); + assert!(read_all_available(&mut fixture.observer).is_empty()); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.parent, + ResourceKind::Window, + AccessMode::MANAGE, + Some(RequestOpcodes { + major: 13, + minor: 0 + }) + ), + ( + CLIENT, + child, + ResourceKind::Window, + AccessMode::MANAGE | AccessMode::SET_ATTR, + Some(RequestOpcodes { + major: 13, + minor: 0 + }) + ), + ] + ); +} + +struct ReparentAccessFixture { + state: ServerState, + backend: RecordingBackend, + requester: UnixStream, + observer: UnixStream, + new_parent: ResourceId, + window: ResourceId, + child: ResourceId, +} + +fn reparent_access_fixture(with_pointer_grab: bool) -> ReparentAccessFixture { + let mut state = ServerState::new(); + let mut requester = install_client(&mut state, CLIENT.0); + let mut observer = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let old_parent = ResourceId(0x0058_0001); + let new_parent = ResourceId(0x0058_0002); + let window = ResourceId(0x0058_0003); + let child = ResourceId(0x0058_0004); + let mut sequence = 1; + for (id, parent) in [ + (old_parent, ROOT_WINDOW), + (new_parent, ROOT_WINDOW), + (window, old_parent), + (child, window), + ] { + create_test_window( + &mut state, + &mut backend, + &mut requester, + &mut sequence, + id, + parent, + ); + } + for id in [old_parent, new_parent, window, child] { + let bytes = resource_request( + &mut state, + &mut backend, + &mut requester, + sequence, + 8, + 0, + &words(&[id.0]), + ); + assert_no_error(&bytes, "ReparentWindow access fixture MapWindow"); + sequence += 1; + } + for (window_id, mask) in [ + (window, 0x0002_0000), + (old_parent, 0x0008_0000), + (new_parent, 0x0008_0000), + ] { + state + .clients + .get_mut(&2) + .expect("observer client") + .event_masks + .insert(window_id, mask); + } + let _ = read_all_available(&mut requester); + let _ = read_all_available(&mut observer); + state.core_focus.raw = child.0; + for client in state.clients.values_mut() { + client.focused_window = child; + } + if with_pointer_grab { + set_test_pointer_grab(&mut state, CLIENT.0, child.0, false, false); + } + ReparentAccessFixture { + state, + backend, + requester, + observer, + new_parent, + window, + child, + } +} + +fn unmap_then_reparent_baseline(with_pointer_grab: bool) -> (Vec, u32, u8) { + let mut fixture = reparent_access_fixture(with_pointer_grab); + let start = fixture.backend.calls().len(); + let unmap = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 30, + 10, + 0, + &words(&[fixture.window.0]), + ); + assert!(unmap.is_empty()); + let reparent = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 31, + 7, + 0, + &words(&[fixture.window.0, fixture.new_parent.0, 0]), + ); + assert!(reparent.is_empty()); + let calls = fixture.backend.calls()[start..].to_vec(); + ( + calls, + fixture.state.core_focus.raw, + fixture.state.core_focus.revert_to, + ) +} + +#[test] +fn reparent_denied_remap_leaves_window_reparented_and_unmapped() { + // Mutation: set only W's map state instead of running UnmapWindow's subtree/focus/grab transition; C or focus/grab state must diverge. + for with_pointer_grab in [false, true] { + let (expected_backend, expected_focus, expected_revert) = + unmap_then_reparent_baseline(with_pointer_grab); + let mut fixture = reparent_access_fixture(with_pointer_grab); + let start = fixture.backend.calls().len(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.window.0))), + deny_mode: Some(AccessMode::SHOW), + deny_hides: false, + })); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 40, + 7, + 0, + &words(&[fixture.window.0, fixture.new_parent.0, 0]), + ); + + assert!(bytes.is_empty(), "denied remap returns Success"); + assert_eq!( + event_type_and_window(&read_all_available(&mut fixture.observer)), + [ + (18, fixture.window), + (18, fixture.window), + (21, fixture.window), + (21, fixture.window), + (21, fixture.window), + ] + ); + assert_eq!( + fixture + .state + .resources + .window(fixture.window) + .unwrap() + .parent, + fixture.new_parent + ); + assert_eq!( + fixture + .state + .resources + .window(fixture.window) + .unwrap() + .map_state, + crate::resources::MapState::Unmapped + ); + assert_eq!( + fixture + .state + .resources + .window(fixture.child) + .unwrap() + .map_state, + crate::resources::MapState::Unviewable + ); + assert_eq!(fixture.state.core_focus.raw, expected_focus); + assert_eq!(fixture.state.core_focus.revert_to, expected_revert); + assert!(fixture.state.active_pointer_grab.is_none()); + assert_eq!(fixture.backend.calls()[start..], expected_backend); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE, + Some(RequestOpcodes { major: 7, minor: 0 }) + ), + ( + CLIENT, + fixture.new_parent, + ResourceKind::Window, + AccessMode::ADD, + Some(RequestOpcodes { major: 7, minor: 0 }) + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::SHOW, + Some(RequestOpcodes { major: 7, minor: 0 }) + ), + ] + ); + } +} + +fn reparent_wire_with_allow_policy(install_policy: bool) -> (Vec, Vec, Vec) { + let mut fixture = reparent_access_fixture(false); + if install_policy { + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::new(Mutex::new(Vec::new())), + deny_id: None, + deny_mode: None, + deny_hides: false, + })); + } + let start = fixture.backend.calls().len(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.requester, + 50, + 7, + 0, + &words(&[fixture.window.0, fixture.new_parent.0, 0]), + ); + let events = read_all_available(&mut fixture.observer); + let backend = fixture.backend.calls()[start..].to_vec(); + (bytes, events, backend) +} + +#[test] +fn reparent_with_allow_all_policy_keeps_todays_bytes() { + // Mutation: take a policy-installed remap branch or change its event/backend sequence; allow-all must match no-policy bytes. + let without_policy = reparent_wire_with_allow_policy(false); + let with_policy = reparent_wire_with_allow_policy(true); + assert_eq!(with_policy, without_policy); + assert_eq!( + event_type_and_window(&with_policy.1), + [ + (18, ResourceId(0x0058_0003)), + (18, ResourceId(0x0058_0003)), + (21, ResourceId(0x0058_0003)), + (21, ResourceId(0x0058_0003)), + (21, ResourceId(0x0058_0003)), + (19, ResourceId(0x0058_0003)), + (19, ResourceId(0x0058_0003)), + ] + ); +} + +#[test] +fn destroy_window_checks_parent_remove() { + // Mutation: omit the parent REMOVE check; DestroyWindow must then destroy the target instead of returning this denial. + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.destroy_parent.0))), + deny_mode: Some(AccessMode::REMOVE), + deny_hides: false, + })); + let target_before = format!( + "{:?}", + fixture.state.resources.window(fixture.destroy_window) + ); + let backend_before = fixture.backend.calls(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 30, + 4, + 0, + &words(&[fixture.destroy_window.0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 4, 30); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + format!( + "{:?}", + fixture.state.resources.window(fixture.destroy_window) + ), + target_before + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.destroy_window, + ResourceKind::Window, + AccessMode::DESTROY, + Some(RequestOpcodes { major: 4, minor: 0 }) + ), + ( + CLIENT, + fixture.destroy_parent, + ResourceKind::Window, + AccessMode::REMOVE, + Some(RequestOpcodes { major: 4, minor: 0 }) + ), + ] + ); +} + +#[test] +fn configure_window_access_checks_precede_later_validation() { + // Mutation: defer ConfigureWindow's window or sibling check until after sibling validation; the earlier policy denial must win. + let invalid_sibling = ResourceId(0x0054_00ff); + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.window.0))), + deny_mode: Some(AccessMode::MANAGE | AccessMode::SET_ATTR), + deny_hides: false, + })); + let backend_before = fixture.backend.calls().to_vec(); + let window_before = format!("{:?}", fixture.state.resources.window(fixture.window)); + let stacking_before = fixture.state.resources.children(fixture.parent).to_vec(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 80, + 12, + 0, + &words(&[fixture.window.0, 0x0060, invalid_sibling.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 12, 80); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + format!("{:?}", fixture.state.resources.window(fixture.window)), + window_before + ); + assert_eq!( + fixture.state.resources.children(fixture.parent), + stacking_before + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE | AccessMode::SET_ATTR, + Some(RequestOpcodes { + major: 12, + minor: 0 + }), + )] + ); + + let mut no_policy = window_access_fixture(); + let bytes = resource_request( + &mut no_policy.state, + &mut no_policy.backend, + &mut no_policy.peer, + 81, + 12, + 0, + &words(&[no_policy.window.0, 0x0060, invalid_sibling.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_WINDOW, invalid_sibling.0, 12, 81); + + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.destroy_parent.0))), + deny_mode: Some(AccessMode::GET_ATTR), + deny_hides: false, + })); + let backend_before = fixture.backend.calls().to_vec(); + let window_before = format!("{:?}", fixture.state.resources.window(fixture.window)); + let stacking_before = fixture.state.resources.children(fixture.parent).to_vec(); + let body = words(&[fixture.window.0, 0x0060, fixture.destroy_parent.0, 0]); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 82, + 12, + 0, + &body, + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 12, 82); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + format!("{:?}", fixture.state.resources.window(fixture.window)), + window_before + ); + assert_eq!( + fixture.state.resources.children(fixture.parent), + stacking_before + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE | AccessMode::SET_ATTR, + Some(RequestOpcodes { + major: 12, + minor: 0 + }), + ), + ( + CLIENT, + fixture.destroy_parent, + ResourceKind::Window, + AccessMode::GET_ATTR, + Some(RequestOpcodes { + major: 12, + minor: 0 + }), + ), + ] + ); + + let mut no_policy = window_access_fixture(); + let bytes = resource_request( + &mut no_policy.state, + &mut no_policy.backend, + &mut no_policy.peer, + 83, + 12, + 0, + &words(&[no_policy.window.0, 0x0060, no_policy.destroy_parent.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_MATCH, 0, 12, 83); +} + +#[test] +fn warp_pointer_checks_destination_before_invalid_source() { + // Mutation: validate the source before checking the already-resolved destination; the destination's policy error must win. + let mut fixture = window_access_fixture(); + let invalid_source = ResourceId(0x0054_00fe); + let mut body = words(&[invalid_source.0, fixture.window.0]); + body.extend_from_slice(&[0; 12]); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.window.0))), + deny_mode: Some(AccessMode::GET_ATTR), + deny_hides: false, + })); + let backend_before = fixture.backend.calls().to_vec(); + let pointer_before = format!("{:?}", fixture.state.pointer_root); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 84, + 41, + 0, + &body, + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 41, 84); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!(format!("{:?}", fixture.state.pointer_root), pointer_before); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::GET_ATTR, + Some(RequestOpcodes { + major: 41, + minor: 0 + }), + )] + ); + + let mut no_policy = window_access_fixture(); + let mut body = words(&[invalid_source.0, no_policy.window.0]); + body.extend_from_slice(&[0; 12]); + let bytes = resource_request( + &mut no_policy.state, + &mut no_policy.backend, + &mut no_policy.peer, + 85, + 41, + 0, + &body, + ); + assert_x11_error(&bytes, x11::error::BAD_WINDOW, invalid_source.0, 41, 85); +} + +#[test] +fn reparent_access_checks_precede_later_operand_validation() { + // Mutation: keep ReparentWindow checks behind check_reparent_window; MANAGE and ADD denials must beat later BadWindow/BadMatch. + let mut fixture = window_access_fixture(); + let invalid_parent = ResourceId(0x0054_00fd); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.window.0))), + deny_mode: Some(AccessMode::MANAGE), + deny_hides: false, + })); + let backend_before = fixture.backend.calls().to_vec(); + let window_before = format!("{:?}", fixture.state.resources.window(fixture.window)); + let old_parent = fixture + .state + .resources + .window(fixture.window) + .expect("fixture window") + .parent; + let old_parent_children = fixture.state.resources.children(old_parent).to_vec(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 86, + 7, + 0, + &words(&[fixture.window.0, invalid_parent.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 7, 86); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + format!("{:?}", fixture.state.resources.window(fixture.window)), + window_before + ); + assert_eq!( + fixture.state.resources.children(old_parent), + old_parent_children + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE, + Some(RequestOpcodes { major: 7, minor: 0 }), + )] + ); + + let mut no_policy = window_access_fixture(); + let bytes = resource_request( + &mut no_policy.state, + &mut no_policy.backend, + &mut no_policy.peer, + 87, + 7, + 0, + &words(&[no_policy.window.0, invalid_parent.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_WINDOW, no_policy.window.0, 7, 87); + + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.window.0))), + deny_mode: Some(AccessMode::ADD), + deny_hides: false, + })); + let backend_before = fixture.backend.calls().to_vec(); + let window_before = format!("{:?}", fixture.state.resources.window(fixture.window)); + let old_parent = fixture + .state + .resources + .window(fixture.window) + .expect("fixture window") + .parent; + let old_parent_children = fixture.state.resources.children(old_parent).to_vec(); + let target_children = fixture.state.resources.children(fixture.window).to_vec(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 88, + 7, + 0, + &words(&[fixture.window.0, fixture.window.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 7, 88); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + format!("{:?}", fixture.state.resources.window(fixture.window)), + window_before + ); + assert_eq!( + fixture.state.resources.children(old_parent), + old_parent_children + ); + assert_eq!( + fixture.state.resources.children(fixture.window), + target_children + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [ + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::MANAGE, + Some(RequestOpcodes { major: 7, minor: 0 }), + ), + ( + CLIENT, + fixture.window, + ResourceKind::Window, + AccessMode::ADD, + Some(RequestOpcodes { major: 7, minor: 0 }), + ), + ] + ); + + let mut no_policy = window_access_fixture(); + let bytes = resource_request( + &mut no_policy.state, + &mut no_policy.backend, + &mut no_policy.peer, + 89, + 7, + 0, + &words(&[no_policy.window.0, no_policy.window.0, 0]), + ); + assert_x11_error(&bytes, x11::error::BAD_MATCH, no_policy.window.0, 7, 89); +} + +#[test] +fn circulate_core_policy_context_uses_zero_minor() { + // Mutation: use header.data as the minor for a core request; direction 1 must still reach policy as minor 0 and the error packet must encode 0. + let mut fixture = window_access_fixture(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(fixture.subwindows_parent.0))), + deny_mode: Some(AccessMode::MANAGE), + deny_hides: false, + })); + let backend_before = fixture.backend.calls().to_vec(); + let children_before = fixture + .state + .resources + .children(fixture.subwindows_parent) + .to_vec(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 90, + 13, + 1, + &words(&[fixture.subwindows_parent.0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 13, 90); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + fixture.state.resources.children(fixture.subwindows_parent), + children_before + ); + assert_eq!( + expected_resource_checks(&calls.lock().unwrap()), + [( + CLIENT, + fixture.subwindows_parent, + ResourceKind::Window, + AccessMode::MANAGE, + Some(RequestOpcodes { + major: 13, + minor: 0 + }), + )] + ); +} + +struct GcFontAccessFixture { + state: ServerState, + backend: RecordingBackend, + peer: UnixStream, + font: ResourceId, + second_font: ResourceId, + source: ResourceId, + destination: ResourceId, + tile: ResourceId, + stipple: ResourceId, + clip_mask: ResourceId, + free_pixmap: ResourceId, + gc: ResourceId, + copy_gc: ResourceId, + free_gc: ResourceId, + cursor: ResourceId, + free_cursor: ResourceId, +} + +fn gc_font_access_fixture() -> GcFontAccessFixture { + const FONT: ResourceId = ResourceId(0x0055_0020); + const SECOND_FONT: ResourceId = ResourceId(0x0055_0021); + const SOURCE: ResourceId = ResourceId(0x0055_0001); + const DESTINATION: ResourceId = ResourceId(0x0055_0002); + const TILE: ResourceId = ResourceId(0x0055_0003); + const STIPPLE: ResourceId = ResourceId(0x0055_0004); + const CLIP_MASK: ResourceId = ResourceId(0x0055_0005); + const FREE_PIXMAP: ResourceId = ResourceId(0x0055_0006); + const GC: ResourceId = ResourceId(0x0055_0010); + const COPY_GC: ResourceId = ResourceId(0x0055_0011); + const FREE_GC: ResourceId = ResourceId(0x0055_0012); + const CURSOR: ResourceId = ResourceId(0x0055_0030); + const FREE_CURSOR: ResourceId = ResourceId(0x0055_0031); + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT.0); + let mut sequence = 1; + + for (font, name) in [(FONT, "fixed"), (SECOND_FONT, "cursor")] { + let mut body = font.0.to_le_bytes().to_vec(); + body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(name.as_bytes()); + body.resize(body.len().next_multiple_of(4), 0); + let bytes = resource_request(&mut state, &mut backend, &mut peer, sequence, 45, 0, &body); + assert_no_error(&bytes, "GC access fixture OpenFont"); + sequence += 1; + } + + for (pixmap, depth) in [ + (SOURCE, 24), + (DESTINATION, 24), + (TILE, 24), + (STIPPLE, 1), + (CLIP_MASK, 1), + (FREE_PIXMAP, 24), + ] { + let body = words(&[pixmap.0, ROOT_WINDOW.0, 8 | (8 << 16)]); + let bytes = resource_request( + &mut state, + &mut backend, + &mut peer, + sequence, + 53, + depth, + &body, + ); + assert_no_error(&bytes, "GC access fixture CreatePixmap"); + sequence += 1; + } + + for gc in [GC, COPY_GC, FREE_GC] { + let foreground = match gc { + GC => 0x0011_2233, + COPY_GC => 0x0044_5566, + _ => 0x0077_8899, + }; + let body = words(&[ + gc.0, + ROOT_WINDOW.0, + (1 << 2) | (1 << 14), + foreground, + FONT.0, + ]); + let bytes = resource_request(&mut state, &mut backend, &mut peer, sequence, 55, 0, &body); + assert_no_error(&bytes, "GC access fixture CreateGC"); + sequence += 1; + } + + for cursor in [CURSOR, FREE_CURSOR] { + let body = words(&[cursor.0, SOURCE.0, STIPPLE.0, 0, 0, 0, 0]); + let bytes = resource_request(&mut state, &mut backend, &mut peer, sequence, 93, 0, &body); + assert_no_error(&bytes, "GC access fixture CreateCursor"); + sequence += 1; + } + + let glyph_cursor = ResourceId(0x0055_0032); + let glyph_body = words(&[glyph_cursor.0, FONT.0, SECOND_FONT.0, 0, 0, 0, 0]); + let bytes = resource_request( + &mut state, + &mut backend, + &mut peer, + sequence, + 94, + 0, + &glyph_body, + ); + assert_no_error(&bytes, "GC access fixture CreateGlyphCursor"); + + GcFontAccessFixture { + state, + backend, + peer, + font: FONT, + second_font: SECOND_FONT, + source: SOURCE, + destination: DESTINATION, + tile: TILE, + stipple: STIPPLE, + clip_mask: CLIP_MASK, + free_pixmap: FREE_PIXMAP, + gc: GC, + copy_gc: COPY_GC, + free_gc: FREE_GC, + cursor: CURSOR, + free_cursor: FREE_CURSOR, + } +} + +#[derive(Clone)] +struct GcFontAccessRequest { + label: &'static str, + opcode: u8, + data: u8, + body: Vec, + expected: Vec<(ResourceId, ResourceKind, AccessMode, Option)>, + deny_index: usize, +} + +fn gc_font_access_target( + id: ResourceId, + kind: ResourceKind, + mode: AccessMode, +) -> (ResourceId, ResourceKind, AccessMode, Option) { + (id, kind, mode, None) +} + +fn gc_font_access_requests(fx: &GcFontAccessFixture) -> Vec { + let creation = |parent| { + Some(Creation { + parent, + owner: CLIENT, + }) + }; + let gc_mask = (1 << 10) | (1 << 11) | (1 << 14) | (1 << 19); + let create_gc_values = words(&[ + 0x0055_0013, + ROOT_WINDOW.0, + gc_mask, + fx.tile.0, + fx.stipple.0, + fx.font.0, + fx.clip_mask.0, + ]); + let change_gc_values = words(&[ + fx.gc.0, + gc_mask, + fx.tile.0, + fx.stipple.0, + fx.font.0, + fx.clip_mask.0, + ]); + let mut set_dashes = fx.gc.0.to_le_bytes().to_vec(); + set_dashes.extend_from_slice(&0u16.to_le_bytes()); + set_dashes.extend_from_slice(&2u16.to_le_bytes()); + set_dashes.extend_from_slice(&[1, 2, 0, 0]); + let mut recolor_cursor = fx.cursor.0.to_le_bytes().to_vec(); + recolor_cursor.extend_from_slice(&[0; 12]); + + let mut open_font = 0x0055_0022u32.to_le_bytes().to_vec(); + open_font.extend_from_slice(&5u16.to_le_bytes()); + open_font.extend_from_slice(&[0, 0]); + open_font.extend_from_slice(b"fixed"); + open_font.resize(open_font.len().next_multiple_of(4), 0); + + let create_pixmap_id = ResourceId(0x0055_0007); + let create_cursor_id = ResourceId(0x0055_0033); + let create_glyph_cursor_id = ResourceId(0x0055_0034); + let cases = vec![ + GcFontAccessRequest { + label: "OpenFont", + opcode: 45, + data: 0, + body: open_font, + expected: vec![( + ResourceId(0x0055_0022), + ResourceKind::Font, + AccessMode::CREATE, + creation(None), + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "QueryFont", + opcode: 47, + data: 0, + body: words(&[fx.font.0]), + expected: vec![gc_font_access_target( + fx.font, + ResourceKind::Font, + AccessMode::GET_ATTR, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "QueryFont(GC fontable)", + opcode: 47, + data: 0, + body: words(&[fx.gc.0]), + expected: vec![gc_font_access_target( + fx.gc, + ResourceKind::Gc, + AccessMode::GET_ATTR, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "QueryTextExtents", + opcode: 48, + data: 0, + body: words(&[fx.font.0]), + expected: vec![gc_font_access_target( + fx.font, + ResourceKind::Font, + AccessMode::GET_ATTR, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "QueryTextExtents(GC fontable)", + opcode: 48, + data: 0, + body: words(&[fx.gc.0]), + expected: vec![gc_font_access_target( + fx.gc, + ResourceKind::Gc, + AccessMode::GET_ATTR, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "CreatePixmap", + opcode: 53, + data: 24, + body: words(&[create_pixmap_id.0, ROOT_WINDOW.0, 8 | (8 << 16)]), + expected: vec![ + gc_font_access_target(ROOT_WINDOW, ResourceKind::Window, AccessMode::GET_ATTR), + ( + create_pixmap_id, + ResourceKind::Pixmap, + AccessMode::CREATE, + creation(Some(ROOT_WINDOW)), + ), + ], + deny_index: 1, + }, + GcFontAccessRequest { + label: "CreateGC", + opcode: 55, + data: 0, + body: create_gc_values, + expected: vec![ + gc_font_access_target(ROOT_WINDOW, ResourceKind::Window, AccessMode::GET_ATTR), + gc_font_access_target(fx.tile, ResourceKind::Pixmap, AccessMode::READ), + gc_font_access_target(fx.stipple, ResourceKind::Pixmap, AccessMode::READ), + gc_font_access_target(fx.font, ResourceKind::Font, AccessMode::USE), + gc_font_access_target(fx.clip_mask, ResourceKind::Pixmap, AccessMode::READ), + ( + ResourceId(0x0055_0013), + ResourceKind::Gc, + AccessMode::CREATE | AccessMode::SET_ATTR, + creation(Some(ROOT_WINDOW)), + ), + ], + deny_index: 5, + }, + GcFontAccessRequest { + label: "ChangeGC", + opcode: 56, + data: 0, + body: change_gc_values, + expected: vec![ + gc_font_access_target(fx.gc, ResourceKind::Gc, AccessMode::SET_ATTR), + gc_font_access_target(fx.tile, ResourceKind::Pixmap, AccessMode::READ), + gc_font_access_target(fx.stipple, ResourceKind::Pixmap, AccessMode::READ), + gc_font_access_target(fx.font, ResourceKind::Font, AccessMode::USE), + gc_font_access_target(fx.clip_mask, ResourceKind::Pixmap, AccessMode::READ), + ], + deny_index: 0, + }, + GcFontAccessRequest { + label: "CopyGC", + opcode: 57, + data: 0, + body: words(&[fx.gc.0, fx.copy_gc.0, 1 << 2]), + expected: vec![ + gc_font_access_target(fx.gc, ResourceKind::Gc, AccessMode::GET_ATTR), + gc_font_access_target(fx.copy_gc, ResourceKind::Gc, AccessMode::SET_ATTR), + ], + deny_index: 0, + }, + GcFontAccessRequest { + label: "SetDashes", + opcode: 58, + data: 0, + body: set_dashes, + expected: vec![gc_font_access_target( + fx.gc, + ResourceKind::Gc, + AccessMode::SET_ATTR, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "SetClipRectangles", + opcode: 59, + data: 0, + body: words(&[fx.gc.0, 0]), + expected: vec![gc_font_access_target( + fx.gc, + ResourceKind::Gc, + AccessMode::SET_ATTR, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "CreateCursor", + opcode: 93, + data: 0, + body: words(&[create_cursor_id.0, fx.source.0, fx.stipple.0, 0, 0, 0, 0]), + expected: vec![ + gc_font_access_target(fx.source, ResourceKind::Pixmap, AccessMode::READ), + gc_font_access_target(fx.stipple, ResourceKind::Pixmap, AccessMode::READ), + ( + create_cursor_id, + ResourceKind::Cursor, + AccessMode::CREATE, + creation(None), + ), + ], + deny_index: 2, + }, + GcFontAccessRequest { + label: "CreateGlyphCursor", + opcode: 94, + data: 0, + body: words(&[ + create_glyph_cursor_id.0, + fx.font.0, + fx.second_font.0, + 0, + 0, + 0, + 0, + ]), + expected: vec![ + gc_font_access_target(fx.font, ResourceKind::Font, AccessMode::USE), + gc_font_access_target(fx.second_font, ResourceKind::Font, AccessMode::USE), + ( + create_glyph_cursor_id, + ResourceKind::Cursor, + AccessMode::CREATE, + creation(None), + ), + ], + deny_index: 2, + }, + GcFontAccessRequest { + label: "RecolorCursor", + opcode: 96, + data: 0, + body: recolor_cursor, + expected: vec![gc_font_access_target( + fx.cursor, + ResourceKind::Cursor, + AccessMode::WRITE, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "CloseFont", + opcode: 46, + data: 0, + body: words(&[fx.second_font.0]), + expected: vec![gc_font_access_target( + fx.second_font, + ResourceKind::Font, + AccessMode::DESTROY, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "FreePixmap", + opcode: 54, + data: 0, + body: words(&[fx.free_pixmap.0]), + expected: vec![gc_font_access_target( + fx.free_pixmap, + ResourceKind::Pixmap, + AccessMode::DESTROY, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "FreeGC", + opcode: 60, + data: 0, + body: words(&[fx.free_gc.0]), + expected: vec![gc_font_access_target( + fx.free_gc, + ResourceKind::Gc, + AccessMode::DESTROY, + )], + deny_index: 0, + }, + GcFontAccessRequest { + label: "FreeCursor", + opcode: 95, + data: 0, + body: words(&[fx.free_cursor.0]), + expected: vec![gc_font_access_target( + fx.free_cursor, + ResourceKind::Cursor, + AccessMode::DESTROY, + )], + deny_index: 0, + }, + ]; + cases +} + +fn access_target_snapshot( + state: &ServerState, + id: ResourceId, + kind: ResourceKind, +) -> Option { + match kind { + ResourceKind::Pixmap => state.resources.pixmap(id).map(|entry| format!("{entry:?}")), + ResourceKind::Gc => state.resources.gc(id).map(|entry| format!("{entry:?}")), + ResourceKind::Font => state.resources.font(id).map(|entry| format!("{entry:?}")), + ResourceKind::Cursor => state + .resources + .cursor_exists(id) + .then(|| format!("host={:?}", state.resources.cursor_host_xid(id))), + ResourceKind::Window => state.resources.window(id).map(|entry| format!("{entry:?}")), + _ => panic!("unexpected GC/font access fixture kind: {kind:?}"), + } +} + +#[test] +fn gc_pixmap_cursor_font_requests_ask_expected_targets() { + // Mutation: remove or reorder a GC, pixmap, font, or cursor check; the recorded target, mode, creation, and core minor must differ. + let mut fixture = gc_font_access_fixture(); + let cases = gc_font_access_requests(&fixture); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + + let mut expected = Vec::new(); + for (sequence, case) in (70u16..).zip(cases) { + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + sequence, + case.opcode, + case.data, + &case.body, + ); + if matches!(case.opcode, 47 | 48) { + assert_eq!(bytes.first(), Some(&1), "{} reply", case.label); + } else { + assert_no_error(&bytes, case.label); + } + for (id, kind, mode, creation) in case.expected { + let owner = if creation.is_some() { + None + } else if id == ROOT_WINDOW { + Some(crate::resources::SERVER_OWNER) + } else { + Some(CLIENT) + }; + expected.push(( + CLIENT, + ResourceTarget { id, kind, creation }, + mode, + Some(RequestOpcodes { + major: case.opcode, + minor: 0, + }), + owner, + )); + } + } + let actual: Vec<_> = calls + .lock() + .unwrap() + .iter() + .map(|call| { + ( + call.client, + call.target.expect("resource target"), + call.mode.expect("resource mode"), + call.request, + call.owner, + ) + }) + .collect(); + assert_eq!(actual, expected); + assert_eq!( + fixture + .state + .resources + .pixmap(ResourceId(0x0055_0007)) + .map(|_| true), + Some(true), + "CreatePixmap created its checked ID" + ); + assert!( + fixture + .state + .resources + .gc(ResourceId(0x0055_0013)) + .is_some() + ); + for cursor in [ResourceId(0x0055_0033), ResourceId(0x0055_0034)] { + assert!(fixture.state.resources.cursor_exists(cursor)); + } +} + +#[test] +fn gc_pixmap_cursor_font_requests_deny_before_effects() { + // Mutation: remove the selected target check from a request row; that row must stop returning the policy error before changing state or calling the backend. + for case in gc_font_access_requests(&gc_font_access_fixture()) { + let mut fixture = gc_font_access_fixture(); + let (target_id, target_kind, target_mode, creation) = case.expected[case.deny_index]; + let before_resource = access_target_snapshot(&fixture.state, target_id, target_kind); + let before_backend = fixture.backend.calls(); + let calls = Arc::new(Mutex::new(Vec::new())); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::clone(&calls), + deny_id: Some(Arc::new(AtomicU32::new(target_id.0))), + deny_mode: Some(target_mode), + deny_hides: false, + })); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 90, + case.opcode, + case.data, + &case.body, + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, case.opcode, 90); + assert_eq!( + fixture.backend.calls(), + before_backend, + "{} backend", + case.label + ); + assert_eq!( + access_target_snapshot(&fixture.state, target_id, target_kind), + before_resource, + "{} target state", + case.label + ); + if creation.is_some() { + assert!( + access_target_snapshot(&fixture.state, target_id, target_kind).is_none(), + "{} denied creation installed a resource", + case.label + ); + } + let recorded = calls.lock().unwrap(); + assert!( + recorded.iter().any(|call| { + call.client == CLIENT + && call + .target + .is_some_and(|target| target.id == target_id && target.kind == target_kind) + && call.mode == Some(target_mode) + }), + "{} selected check was not asked", + case.label + ); + } +} + +struct DenyPixmapReads; + +impl AccessPolicy for DenyPixmapReads { + fn resource( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + if target.kind == ResourceKind::Pixmap && mode == AccessMode::READ { + Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }) + } else { + Decision::Allow + } + } +} + +#[test] +fn close_font_and_free_pixmap_denied_keep_the_object() { + // Mutation: perform the CloseFont and FreePixmap removals before checking DESTROY; after denial the still-open font and pixmap must remain usable. + let mut fixture = gc_font_access_fixture(); + let denied_id = Arc::new(AtomicU32::new(fixture.font.0)); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::new(Mutex::new(Vec::new())), + deny_id: Some(Arc::clone(&denied_id)), + deny_mode: Some(AccessMode::DESTROY), + deny_hides: false, + })); + + let close_backend_before = fixture.backend.calls(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 100, + 46, + 0, + &words(&[fixture.font.0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 46, 100); + assert_eq!(fixture.backend.calls(), close_backend_before); + assert!(fixture.state.resources.font(fixture.font).is_some()); + let query_font = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 101, + 47, + 0, + &words(&[fixture.font.0]), + ); + assert_eq!(query_font.first(), Some(&1), "font remains queryable"); + + denied_id.store(fixture.source.0, Ordering::SeqCst); + let free_backend_before = fixture.backend.calls(); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 102, + 54, + 0, + &words(&[fixture.source.0]), + ); + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 54, 102); + assert_eq!(fixture.backend.calls(), free_backend_before); + assert!(fixture.state.resources.pixmap(fixture.source).is_some()); + + let before_copy = fixture.backend.calls(); + let mut copy_body = words(&[fixture.source.0, fixture.destination.0, fixture.gc.0]); + copy_body.extend_from_slice(&0i16.to_le_bytes()); + copy_body.extend_from_slice(&0i16.to_le_bytes()); + copy_body.extend_from_slice(&0i16.to_le_bytes()); + copy_body.extend_from_slice(&0i16.to_le_bytes()); + copy_body.extend_from_slice(&8u16.to_le_bytes()); + copy_body.extend_from_slice(&8u16.to_le_bytes()); + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 103, + 62, + 0, + ©_body, + ); + assert_no_error(&bytes, "CopyArea from retained pixmap"); + assert!( + fixture.backend.calls()[before_copy.len()..] + .iter() + .any(|call| matches!(call, RecordedCall::CopyArea { .. })) + ); +} + +#[test] +fn create_gc_unresolved_tile_keeps_todays_behaviour() { + // Mutation: check the CreateGC tile XID without first resolving it as a pixmap; the deny-pixmap policy must then reject the request. + let mut fixture = gc_font_access_fixture(); + fixture + .state + .install_access_policy(Arc::new(DenyPixmapReads)); + let gc = ResourceId(0x0055_0040); + let missing_tile = ResourceId(0x0055_00ff); + let body = words(&[gc.0, ROOT_WINDOW.0, 1 << 10, missing_tile.0]); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 110, + 55, + 0, + &body, + ); + + assert!( + bytes.is_empty(), + "unresolved tile changed CreateGC bytes: {bytes:02x?}" + ); + assert!(fixture.state.resources.gc(gc).is_some()); +} + +#[test] +fn copy_gc_denial_preserves_destination_for_source_and_destination_denial() { + // Mutation: copy the selected foreground before checking either GC; each denied row must leave the destination snapshot unchanged. + for deny_source in [true, false] { + let mut fixture = gc_font_access_fixture(); + let (denied_id, denied_mode) = if deny_source { + (fixture.gc, AccessMode::GET_ATTR) + } else { + (fixture.copy_gc, AccessMode::SET_ATTR) + }; + let destination_before = + access_target_snapshot(&fixture.state, fixture.copy_gc, ResourceKind::Gc); + assert_ne!( + fixture.state.resources.gc_foreground(fixture.gc), + fixture.state.resources.gc_foreground(fixture.copy_gc), + "CopyGC source and destination start with different foregrounds" + ); + let backend_before = fixture.backend.calls(); + fixture + .state + .install_access_policy(Arc::new(WindowResourcePolicy { + calls: Arc::new(Mutex::new(Vec::new())), + deny_id: Some(Arc::new(AtomicU32::new(denied_id.0))), + deny_mode: Some(denied_mode), + deny_hides: false, + })); + + let bytes = resource_request( + &mut fixture.state, + &mut fixture.backend, + &mut fixture.peer, + 120, + 57, + 0, + &words(&[fixture.gc.0, fixture.copy_gc.0, 1 << 2]), + ); + + assert_x11_error(&bytes, x11::error::BAD_VALUE, 0x55, 57, 120); + assert_eq!(fixture.backend.calls(), backend_before); + assert_eq!( + access_target_snapshot(&fixture.state, fixture.copy_gc, ResourceKind::Gc), + destination_before, + "denied CopyGC changed its destination" + ); + } +} + +#[test] +#[ignore] +fn bench_poly_point_with_and_without_policy() { + const REQUESTS: u32 = 100_000; + + /// An allow-all policy that only counts its calls, so the timing is the + /// layer's own cost rather than the recording policy's bookkeeping. + struct CountingAllow(std::sync::atomic::AtomicUsize); + + impl crate::access::AccessPolicy for CountingAllow { + fn resource( + &self, + _ctx: &crate::access::AccessContext<'_>, + _client: ClientId, + _target: &ResourceTarget, + _mode: AccessMode, + ) -> Decision { + self.0.fetch_add(1, Ordering::Relaxed); + Decision::Allow + } + } + const GC_ID: ResourceId = ResourceId(0x0055_0090); + + let run = |with_policy: bool, counting: Option>| { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT.0); + state.resources.create_gc( + CLIENT, + CreateGcRequest { + gc: GC_ID, + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + state + .resources + .window_mut(ROOT_WINDOW) + .expect("root window") + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(0x100)); + let calls = Arc::new(Mutex::new(Vec::new())); + if let Some(counting) = counting { + state.install_access_policy(counting); + } else if with_policy { + state.install_access_policy(Arc::new(DrawingResourcePolicy { + label: "PolyPoint benchmark allow-all", + calls: Arc::clone(&calls), + deny_id: None, + deny_all: false, + decision: Decision::Deny(DenyError { + code: x11::error::BAD_ACCESS, + value: 0x55, + }), + })); + } + + let mut backend = RecordingBackend::new(); + let mut body = [0u8; 12]; + body[..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body[4..8].copy_from_slice(&GC_ID.0.to_le_bytes()); + let start = std::time::Instant::now(); + for sequence in 0..REQUESTS { + // Mutation: make `handle_poly_point` propagate an I/O error + // instead of `Handled`; this request-level expect must fail. + process_request( + &mut state, + &mut backend, + CLIENT, + SequenceNumber(sequence as u16), + RequestHeader { + opcode: 64, + data: 0, + length_units: 4, + }, + &body, + None, + ) + .expect("valid one-point PolyPoint request"); + } + let elapsed = start.elapsed(); + let wire_bytes = read_all_available(&mut peer); + let point_draws = backend + .calls + .lock() + .unwrap() + .iter() + .filter(|call| matches!(call, RecordedCall::PolyPoint { .. })) + .count(); + let access_counts = { + let calls = calls.lock().unwrap(); + let drawable_checks = calls + .iter() + .filter(|call| { + call.client == CLIENT + && call.request + == Some(RequestOpcodes { + major: 64, + minor: 0, + }) + && call.target.is_some_and(|target| { + target.id == ROOT_WINDOW && target.kind == ResourceKind::Window + }) + && call.mode == Some(AccessMode::WRITE) + }) + .count(); + let gc_checks = calls + .iter() + .filter(|call| { + call.client == CLIENT + && call.request + == Some(RequestOpcodes { + major: 64, + minor: 0, + }) + && call.target.is_some_and(|target| { + target.id == GC_ID && target.kind == ResourceKind::Gc + }) + && call.mode == Some(AccessMode::USE) + }) + .count(); + (calls.len(), drawable_checks, gc_checks) + }; + (elapsed, wire_bytes, point_draws, access_counts) + }; + + let without_policy = run(false, None); + let with_policy = run(true, None); + let counter = Arc::new(CountingAllow(std::sync::atomic::AtomicUsize::new(0))); + let counting = run(true, Some(Arc::clone(&counter))); + assert!( + counting.1.is_empty(), + "counting-policy PolyPoint requests wrote an error or reply" + ); + assert_eq!(counting.2, REQUESTS as usize, "counting-policy point draws"); + assert_eq!( + counter.0.load(Ordering::Relaxed), + REQUESTS as usize * 2, + "counting policy asked once for drawable and once for GC per request" + ); + assert!( + without_policy.1.is_empty(), + "no-policy PolyPoint requests wrote an error or reply" + ); + assert!( + with_policy.1.is_empty(), + "allow-all-policy PolyPoint requests wrote an error or reply" + ); + // Mutation: skip RecordingBackend::poly_point recording; each phase must record all request draws. + assert_eq!(without_policy.2, REQUESTS as usize, "no-policy point draws"); + assert_eq!(with_policy.2, REQUESTS as usize, "policy point draws"); + assert_eq!(without_policy.3, (0, 0, 0), "no-policy resource checks"); + assert_eq!( + with_policy.3, + (REQUESTS as usize * 2, REQUESTS as usize, REQUESTS as usize,), + "allow-all policy asks once for drawable and once for GC per request" + ); + println!( + "PolyPoint ({REQUESTS} requests): no policy = {:.1} ns/request; counting allow-all = {:.1} ns/request; recording allow-all = {:.1} ns/request", + without_policy.0.as_nanos() as f64 / f64::from(REQUESTS), + counting.0.as_nanos() as f64 / f64::from(REQUESTS), + with_policy.0.as_nanos() as f64 / f64::from(REQUESTS), + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/composite.rs b/crates/yserver-core/src/core_loop/process_request/tests/composite.rs new file mode 100644 index 000000000..30e40472f --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/composite.rs @@ -0,0 +1,4132 @@ +use super::*; +use crate::{ + core_loop::process_request::render::render_picture_damage_drawable, resources::MapState, +}; + +/// GetImage of a window partly off the screen: BadMatch unless the +/// window is redirected, when its bound is its backing (`DoGetImage`, +/// `dix/dispatch.c:2176-2210`; measured by +/// tools/vng-scenarios/draw-clip-probe.c, `F at x=-50`). +#[test] +fn get_image_of_a_redirected_window_off_the_screen_reads_its_backing() { + let mut state = ServerState::new(); + // The image reply can exceed a Unix socket's buffer before this test reads it. + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let window = ResourceId(0x1100); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window, + parent: ROOT_WINDOW, + x: -50, + y: 0, + width: 200, + height: 150, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.window_mut(window).unwrap().map_state = MapState::Viewable; + let mut body = window.0.to_le_bytes().to_vec(); + for v in [0i16, 0] { + body.extend_from_slice(&v.to_le_bytes()); + } + for v in [200u16, 150] { + body.extend_from_slice(&v.to_le_bytes()); + } + body.extend_from_slice(&u32::MAX.to_le_bytes()); + let mut get_image = |state: &mut ServerState| { + process_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 73, + data: 2, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + read_all_available(&mut peer) + }; + let unredirected = get_image(&mut state); + assert_eq!( + (unredirected[0], unredirected[1]), + (0, x11::error::BAD_MATCH) + ); + state + .composite_redirects + .redirect_window( + window, + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); + let redirected = get_image(&mut state); + assert_eq!(redirected.first(), Some(&1), "a reply, not an error"); +} + +// ---- L2 plan B.1: COMPOSITE redirect dispatch policy -------- + +fn composite_redirect_request_body(window: u32, mode: u8) -> Vec { + let mut body = vec![0u8; 8]; + body[0..4].copy_from_slice(&window.to_le_bytes()); + body[4] = mode; + body +} + +fn dispatch_composite_redirect( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + client_id: ClientId, + window: u32, + mode: u8, +) -> RequestOutcome { + dispatch_composite_window_update(state, backend, client_id, 1, window, mode) +} + +/// Any of Redirect/UnredirectWindow/Subwindows (minor 1-4). +fn dispatch_composite_window_update( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + client_id: ClientId, + minor: u8, + window: u32, + mode: u8, +) -> RequestOutcome { + let body = composite_redirect_request_body(window, mode); + process_request( + state, + backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 144, + data: minor, + length_units: 3, + }, + &body, + None, + ) + .unwrap() +} + +/// The error code a client got, or `None` when nothing was written. +fn read_error_code(peer: &mut std::os::unix::net::UnixStream) -> Option { + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + match peer.read(&mut buf) { + Ok(32) if buf[0] == 0 => Some(buf[1]), + Ok(0) | Err(_) => None, + Ok(n) => panic!("unexpected {n} bytes: {buf:02x?}"), + } +} + +#[test] +fn second_manual_redirect_from_another_client_is_bad_access() { + let mut state = ServerState::new(); + let mut peer_a = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + create_root_child(&mut state, 0x0010_0001); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0x0010_0001, 1); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(2), 0x0010_0001, 1); + assert_eq!(read_error_code(&mut peer_a), None); + assert_eq!(read_error_code(&mut peer_b), Some(x11::error::BAD_ACCESS)); +} + +#[test] +fn automatic_redirects_from_several_clients_coexist() { + // Xorg compRedirectWindow refuses only a second Manual redirect. + let mut state = ServerState::new(); + let mut peer_a = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + create_root_child(&mut state, 0x0010_0001); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0x0010_0001, 0); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(2), 0x0010_0001, 1); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(2), 0x0010_0001, 0); + assert_eq!(read_error_code(&mut peer_a), None); + assert_eq!(read_error_code(&mut peer_b), None); + assert_eq!( + state + .composite_redirects + .window_records(ResourceId(0x0010_0001)) + .len(), + 3 + ); +} + +#[test] +fn redirect_of_an_unknown_window_is_bad_window() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0xDEAD, 1); + assert_eq!(read_error_code(&mut peer), Some(x11::error::BAD_WINDOW)); + assert!(state.composite_redirects.is_empty()); +} + +#[test] +fn redirect_window_of_the_root_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), ROOT_WINDOW.0, 1); + assert_eq!(read_error_code(&mut peer), Some(x11::error::BAD_MATCH)); +} + +#[test] +fn fullscreen_unredirect_and_re_redirect_under_root_subwindows_redirect() { + // Measured on Xvfb 21.1 (tools/vng-scenarios/composite-reredirect). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let w = 0x0010_0001; + dispatch_composite_window_update(&mut state, &mut backend, ClientId(1), 2, ROOT_WINDOW.0, 1); + create_root_child(&mut state, w); + state + .composite_redirects + .redirect_new_subwindow(ROOT_WINDOW, ResourceId(w)); + let codes = [ + (3, None), // UnredirectWindow(W) + (3, Some(x11::error::BAD_VALUE)), // again + (1, None), // RedirectWindow(W, Manual) + (1, Some(x11::error::BAD_ACCESS)), // again + (4, None), // UnredirectSubwindows(root) + (3, Some(x11::error::BAD_VALUE)), // its free took W's record too + ]; + for (minor, want) in codes { + let target = if minor == 4 { ROOT_WINDOW.0 } else { w }; + dispatch_composite_window_update(&mut state, &mut backend, ClientId(1), minor, target, 1); + assert_eq!(read_error_code(&mut peer), want, "minor {minor}"); + } + assert!(state.composite_redirects.is_empty()); +} + +#[test] +fn redirect_window_manual_conflicts_with_inherited_manual() { + use crate::server::{CompositeRedirectMode, RedirectRecord}; + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let window = ResourceId(0x0100_0042); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window, + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .composite_redirects + .redirect_subwindows( + ROOT_WINDOW, + state.resources.children(ROOT_WINDOW), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); + + // Muffin issues this redundant request for a root child that + // already inherited root RedirectSubwindows(Manual). Xorg's + // compRedirectWindow rejects it even for the same client. + dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), window.0, 1); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("BadAccess delivered"); + assert_eq!(buf[0], 0); + assert_eq!(buf[1], x11::error::BAD_ACCESS); + assert_eq!( + state.composite_redirects.window_records(window).len(), + 1, + "rejected probe must not install a second redirect", + ); +} + +#[test] +fn redirect_window_cow_is_success_noop() { + // RedirectWindow(COW) must succeed silently (no X error on the wire) + // and must NOT install a redirect — matching Xorg compalloc.c:145-147. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state + .resources + .materialize_cow_resource(crate::backend::WindowHandle::from_raw_for_test(0xC0C0)); + + dispatch_composite_redirect( + &mut state, + &mut backend, + ClientId(1), + crate::resources::COMPOSITE_OVERLAY_WINDOW.0, + 1, // Manual + ); + + // No X11 error should have been queued to the client. + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + let n = peer.read(&mut buf).unwrap_or(0); + assert_eq!(n, 0, "no error bytes expected, got {n} bytes: {buf:02x?}"); + + // The COW must not be marked redirected: no redirect record exists. + assert!( + state.composite_redirects.is_empty(), + "RedirectWindow(COW) is a Success no-op, COW stays unredirected" + ); +} + +// ---------------- end extract_shm_zpixmap_region ---------------- + +#[test] +fn redirect_invalid_mode_returns_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Anything outside {0, 1} is a spec violation → BadValue. + create_root_child(&mut state, 0x0010_0001); + dispatch_composite_redirect(&mut state, &mut backend, ClientId(1), 0x0010_0001, 2); + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error delivered"); + assert_eq!(buf[0], 0); + // BAD_VALUE = 2 + assert_eq!(buf[1], 2, "expected BadValue (2), got {}", buf[1]); + assert!(state.composite_redirects.is_empty()); +} + +#[test] +fn name_window_pixmap_uses_redirected_backing_geometry() { + use crate::{ + backend::{PixmapHandle, WindowHandle}, + resources::RedirectedBacking, + server::{CompositeRedirectMode, RedirectRecord}, + }; + use yserver_protocol::x11::CreateWindowRequest; + + const WINDOW: ResourceId = ResourceId(0x10004a); + const PIXMAP: ResourceId = ResourceId(0x300225); + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new().with_composite_support(); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 32, + window: WINDOW, + parent: ROOT_WINDOW, + width: 646, + height: 501, + border_width: 2, + class: 1, + visual: crate::resources::ARGB_VISUAL, + ..Default::default() + }, + ); + assert!(state.resources.map_window(WINDOW).mapping_changed); + let window = state + .resources + .window_mut(WINDOW) + .expect("window installed"); + window.host_xid = Some(WindowHandle::from_raw_for_test(0x40008a)); + window.redirected_backing = Some(RedirectedBacking { + host_pixmap: PixmapHandle::from_raw_for_test(0x4000d), + width: 650, + height: 505, + depth: 32, + }); + state + .composite_redirects + .redirect_window( + WINDOW, + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&WINDOW.0.to_le_bytes()); + body.extend_from_slice(&PIXMAP.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::NAME_WINDOW_PIXMAP, + &body, + ); + + let pixmap = state.resources.pixmap(PIXMAP).expect("named pixmap exists"); + assert_eq!((pixmap.width, pixmap.height), (650, 505)); + let aliases = &state + .resources + .window(WINDOW) + .expect("window remains installed") + .composite_named_pixmaps; + assert_eq!(aliases.len(), 1); + assert_eq!((aliases[0].width, aliases[0].height), (650, 505)); +} + +#[test] +fn get_overlay_window_wires_cow_host_xid() { + // Pre-condition: COW resource record does NOT exist (post-Task-2.1 + // the pre-seed is gone; COW materialises only on GetOverlayWindow). + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_none(), + "COW must NOT be pre-seeded; the materialise-on-GET model \ + owns the entire COW lifecycle (Task 2.1 + Task 2.4)", + ); + + // GetOverlayWindow body: window xid (we use root, marco ignores + // the reply's input and just trusts whatever XID we hand back). + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + + // Load-bearing assertion: after GET, host_drawable_target must + // resolve. This is what makes PresentPixmap → COW actually paint. + let target = state + .resources + .host_drawable_target(crate::resources::COMPOSITE_OVERLAY_WINDOW); + match target { + Some(crate::resources::HostDrawableTarget::Window { + nested, + host_xid, + depth, + }) => { + assert_eq!(nested, crate::resources::COMPOSITE_OVERLAY_WINDOW); + assert_eq!( + host_xid.as_raw(), + crate::resources::COMPOSITE_OVERLAY_WINDOW.0, + "COW host_xid must equal its protocol xid (0x103)", + ); + assert_eq!(depth, 24, "COW is depth-24"); + } + other => panic!( + "host_drawable_target(COW) must resolve to Window after \ + GetOverlayWindow — got {other:?}. Pre-fix shape returned \ + None (host_xid still unset on the resource record), which \ + dropped every PresentPixmap → COW.", + ), + } + + // Dimensions: COW should track the root extent (the backend's + // COW storage is screen-extent per the Stage 4d plan). + let cow = state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .expect("COW record"); + let root = state + .resources + .window(crate::resources::ROOT_WINDOW) + .expect("ROOT record"); + assert_eq!(cow.width, root.width, "COW must match root extent"); + assert_eq!(cow.height, root.height, "COW must match root extent"); +} + +#[test] +fn repeated_get_reuses_materialized_host_overlay() { + // A compositor may emit GetOverlayWindow multiple times (e.g. + // re-registration on a window-manager hand-off). What is stable + // across those calls is the identity of the already-materialized + // host overlay: the `host_xid.is_none()` guard prevents repeated + // allocation and host_xid stays wired. + // + // The *request* is deliberately NOT idempotent — each call + // records another claim in `state.cow_claims` (Xorg's N-record + // model) and each needs its own ReleaseOverlayWindow. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + + let cow = state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .expect("COW record"); + assert_eq!( + cow.host_xid.map(crate::backend::WindowHandle::as_raw), + Some(crate::resources::COMPOSITE_OVERLAY_WINDOW.0), + "host_xid stays wired across repeated GETs", + ); + assert_eq!( + state.cow_claims, + vec![ClientId(1), ClientId(1)], + "each GET records its own claim — what moved to the core claim \ + list is exactly what the backend refcount used to count", + ); +} + +/// Xorg `compCreateOverlayWindow` (`composite/compoverlay.c:149`) gives the +/// overlay no input shape, so it takes the pointer over the whole screen +/// until the compositor empties its input region, and again after a reset +/// to None (measured on Xvfb 21.1, tools/vng-scenarios/cow-input-shape). +#[test] +fn overlay_window_takes_the_pointer_until_its_input_region_is_emptied() { + use yserver_protocol::x11::{shape as x11shape, xfixes as x11xfixes}; + + const APP: ResourceId = ResourceId(0x0020_0001); + const REGION: u32 = 0x0010_0042; + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: APP, + parent: ROOT_WINDOW, + x: 100, + y: 100, + width: 200, + height: 200, + ..Default::default() + }, + ); + let _ = state.resources.map_window(APP); + let hit = |state: &ServerState| state.root_pointer_target_at(150, 150).map(|h| h.0); + assert_eq!(hit(&state), Some(APP)); + + let mut body = ROOT_WINDOW.0.to_le_bytes().to_vec(); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + assert_eq!(hit(&state), Some(cow), "an unshaped COW takes the pointer"); + + let mut xfixes = |state: &mut ServerState, minor: u8, body: Vec| { + let header = yserver_protocol::x11::RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }; + handle_xfixes_request( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + header, + &body, + ) + .expect("XFIXES request"); + }; + let input_region = |region: u32| { + let mut body = cow.0.to_le_bytes().to_vec(); + body.extend_from_slice(&[x11shape::KIND_INPUT, 0, 0, 0, 0, 0, 0, 0]); + body.extend_from_slice(®ion.to_le_bytes()); + body + }; + xfixes( + &mut state, + x11xfixes::CREATE_REGION, + REGION.to_le_bytes().to_vec(), + ); + xfixes( + &mut state, + x11xfixes::SET_WINDOW_SHAPE_REGION, + input_region(REGION), + ); + assert_eq!( + hit(&state), + Some(APP), + "an empty input region passes through" + ); + xfixes( + &mut state, + x11xfixes::SET_WINDOW_SHAPE_REGION, + input_region(0), + ); + assert_eq!(hit(&state), Some(cow), "None restores the default region"); + + body[0..4].copy_from_slice(&cow.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 3, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &body, + ); + assert_eq!(hit(&state), Some(APP)); +} + +#[test] +fn overlay_window_create_and_release_notify_root_substructure_listeners() { + // Xorg compCreateOverlayWindow / DeleteWindow, measured on Xvfb 21.1 + // (tools/vng-scenarios/composite-reredirect): CreateNotify, MapNotify; + // then UnmapNotify, DestroyNotify after the last release. + const SUBSTRUCTURE_NOTIFY: u32 = 0x0008_0000; + const STRUCTURE_NOTIFY: u32 = 0x0002_0000; + let mut state = ServerState::new(); + let _compositor = install_client(&mut state, 1); + let mut listener = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + state + .clients + .get_mut(&2) + .expect("listener") + .event_masks + .insert(ROOT_WINDOW, SUBSTRUCTURE_NOTIFY); + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let events = |bytes: &[u8]| -> Vec<(u8, u32, u32)> { + let word = + |e: &[u8], at: usize| u32::from_le_bytes([e[at], e[at + 1], e[at + 2], e[at + 3]]); + bytes + .chunks_exact(32) + .map(|e| (e[0], word(e, 4), word(e, 8))) + .collect() + }; + let root_body = ROOT_WINDOW.0.to_le_bytes(); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &root_body, + ); + assert_eq!( + events(&read_all_available(&mut listener)), + vec![(16, ROOT_WINDOW.0, cow.0), (19, ROOT_WINDOW.0, cow.0)], + "CreateNotify(parent=root, window=COW), MapNotify(event=root)" + ); + state + .clients + .get_mut(&2) + .expect("listener") + .event_masks + .insert(cow, STRUCTURE_NOTIFY); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &root_body, + ); + assert_eq!( + events(&read_all_available(&mut listener)), + vec![ + (18, cow.0, cow.0), + (18, ROOT_WINDOW.0, cow.0), + (17, cow.0, cow.0), + (17, ROOT_WINDOW.0, cow.0), + ], + ); +} + +#[test] +fn release_overlay_window_destroys_cow_resource_on_final_release() { + // Final release (backend returns Ok(true)) must DESTROY the COW + // resource record entirely (record removed from `windows`, edge + // removed from `root.children`) so a subsequent `GetOverlayWindow` + // re-materialises fresh storage via the 0→1 backend path. The + // pre-Task-2.5 shape merely cleared `host_xid` on the still-existing + // record; that diverged from Xorg (no record between + // release-and-next-claim) and silently retained per-COW state + // (event masks, properties) across the release boundary. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Wire COW via GET first. + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .and_then(|w| w.host_xid) + .is_some(), + ); + let old_generation = + state.present_window_generation(crate::resources::COMPOSITE_OVERLAY_WINDOW.0); + state.present_window_msc.insert( + crate::resources::COMPOSITE_OVERLAY_WINDOW.0, + crate::server::PresentWindowMsc { + last_crtc: 2, + last_crtc_epoch: 1, + msc_offset: 10, + last_raw_msc: 20, + }, + ); + state.present_event_selections.insert( + 0x0001_c0e1, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: crate::resources::COMPOSITE_OVERLAY_WINDOW, + event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + state + .present_pending_msc + .push(crate::server::PendingNotifyMsc { + owner: ClientId(1), + window: crate::resources::COMPOSITE_OVERLAY_WINDOW.0, + crtc_id: 2, + crtc_epoch: 1, + msc_offset: 10, + serial: 1, + target_msc: 30, + divisor: 0, + remainder: 0, + byte_order: ClientByteOrder::LittleEndian, + }); + let stale_event = crate::backend::CompletedPresentEvent { + client_id: ClientId(1), + serial: 1, + host_xid: 0x0001_c002, + dst_host_xid: crate::resources::COMPOSITE_OVERLAY_WINDOW.0, + options: 0, + present_id: 0x_c0, + window_generation: old_generation, + crtc_id: 2, + crtc_epoch: 1, + msc_offset: 10, + completion_clock: None, + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }; + + // Final release — client 1 holds the only claim. + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_none(), + "final release (backend.Ok(true)) must destroy the COW resource \ + record entirely so the next GetOverlayWindow re-materialises \ + fresh storage", + ); + assert!( + !state + .resources + .window(crate::resources::ROOT_WINDOW) + .unwrap() + .children + .contains(&crate::resources::COMPOSITE_OVERLAY_WINDOW), + "final release must remove COW from root.children too", + ); + assert!( + !state + .present_window_generations + .contains_key(&crate::resources::COMPOSITE_OVERLAY_WINDOW.0) + ); + assert!( + !state + .present_window_msc + .contains_key(&crate::resources::COMPOSITE_OVERLAY_WINDOW.0) + ); + assert!(state.present_pending_msc.is_empty()); + assert!(state.present_event_selections.is_empty()); + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 3, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + let new_generation = + state.present_window_generation(crate::resources::COMPOSITE_OVERLAY_WINDOW.0); + assert_ne!(new_generation, old_generation); + state.present_event_selections.insert( + 0x0001_c0e2, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: crate::resources::COMPOSITE_OVERLAY_WINDOW, + event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + backend.completed_present_events_to_drain.push(stale_event); + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + assert_eq!(backend.signalled_present_wakes, vec![0x_c0]); + assert!(read_all_available(&mut peer).is_empty()); +} + +#[test] +fn release_overlay_window_keeps_host_xid_on_non_final_release() { + // Non-final release (a claim remains): storage is still live on + // the backend, host_xid must stay wired so any remaining + // compositor's PresentPixmap → COW keeps landing. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let _peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + // A second claimant, so client 2's release below is not the final + // one. Which release is final is core's decision, taken from the + // claim list — the backend has no say and no counter. + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(2), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(2), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + let cow = state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .expect("COW record"); + assert_eq!( + cow.host_xid.map(crate::backend::WindowHandle::as_raw), + Some(crate::resources::COMPOSITE_OVERLAY_WINDOW.0), + "non-final release must keep host_xid wired — \ + storage is still alive on the backend", + ); +} + +/// Get by A, Release by B ⇒ `BadMatch`, and A's claim survives. +/// Xorg's `ProcCompositeReleaseOverlayWindow` looks the caller up +/// with `compFindOverlayClient` and refuses when it holds no record. +#[test] +fn release_overlay_window_by_non_claimant_is_badmatch() { + let mut state = ServerState::new(); + let _peer_a = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + let _ = read_all_available(&mut peer_b); + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(2), + 1, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + + assert_error_code( + &read_all_available(&mut peer_b), + yserver_protocol::x11::error::BAD_MATCH, + "ReleaseOverlayWindow from a client holding no claim", + ); + assert!( + backend.cow_materialized, + "B's refused release must not tear the overlay out from under A", + ); + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_some(), + "A's claim must survive B's refused release", + ); +} + +/// `ReleaseOverlayWindow` from a client that never claimed anything, +/// with no claim outstanding anywhere, is `BadMatch` and changes +/// nothing. Xorg answers the same via `compFindOverlayClient`. +#[test] +fn release_overlay_window_with_no_claim_anywhere_is_badmatch() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + + assert_error_code( + &read_all_available(&mut peer), + yserver_protocol::x11::error::BAD_MATCH, + "unpaired ReleaseOverlayWindow", + ); + assert!(state.cow_claims.is_empty()); + assert!( + !backend.cow_materialized, + "a refused release must not touch the backend at all", + ); +} + +/// N Gets need N Releases: Get and Release pair 1:1, as Xorg's +/// per-Get `CompOverlayClientRec` records do. The overlay survives +/// every release but the last. +#[test] +fn repeated_gets_need_matching_releases() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + for seq in 1..=3 { + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + seq, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + } + assert_eq!(state.cow_claims.len(), 3); + + for seq in 4..=5 { + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + seq, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + } + assert_eq!(state.cow_claims.len(), 1); + assert!( + backend.cow_materialized, + "two of three claims released — the overlay must still be up", + ); + let _ = read_all_available(&mut peer); + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 6, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert!(state.cow_claims.is_empty()); + assert!( + !backend.cow_materialized, + "the third release is the final one" + ); + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_none(), + ); + + // A fourth release has nothing left to pair with. + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 7, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert_error_code( + &read_all_available(&mut peer), + yserver_protocol::x11::error::BAD_MATCH, + "one release too many", + ); +} + +/// Two claimants: the first Release is not the final one, so the +/// backend is not called and the overlay stays up for the other +/// claimant. +#[test] +fn two_claimants_first_release_is_not_final() { + let mut state = ServerState::new(); + let _peer_a = install_client(&mut state, 1); + let _peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + for client in [1u32, 2] { + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(client), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + } + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + + assert_eq!( + state.cow_claims, + vec![ClientId(2)], + "A released exactly its own claim; B's is untouched", + ); + assert!(backend.cow_materialized); + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(2), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert!(state.cow_claims.is_empty()); + assert!(!backend.cow_materialized); +} + +/// Transactional first Get: if materialization fails, the claim is +/// rolled back and the caller gets `BadAlloc`. A claim recorded +/// against an overlay that does not exist is the desynchronisation +/// this model removes. +#[test] +fn first_get_materialization_failure_records_no_claim() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.cow_materialize_fails = true; + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + + assert_error_code( + &read_all_available(&mut peer), + yserver_protocol::x11::error::BAD_ALLOC, + "GetOverlayWindow whose materialization failed", + ); + assert!( + state.cow_claims.is_empty(), + "the claim must be rolled back — never leave one recorded \ + against an overlay that does not exist", + ); + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_none(), + ); + + // And the server is not poisoned: a retry that succeeds works. + backend.cow_materialize_fails = false; + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + assert_eq!(state.cow_claims, vec![ClientId(1)]); + assert!(backend.cow_materialized); +} + +/// The headline case, and the bug at its own level: a compositor +/// takes the overlay and **disconnects without releasing**. Its claim +/// must be gone and the overlay torn down. No reset anywhere in this +/// test. +/// +/// Not to be confused with `scene.root_overlay` / +/// `root_overlay_on_disconnect` (`kms/render/backend.rs`), a +/// different concept with a confusingly similar name that +/// `Backend::client_disconnected` already handles correctly — +/// finding that call is what makes this leak look handled. +#[test] +fn disconnect_releases_overlay_claim_and_tears_down_cow() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + assert_eq!(state.cow_claims, vec![ClientId(1)]); + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + + assert!( + state.cow_claims.is_empty(), + "no claim may outlive its owner", + ); + assert!( + !backend.cow_materialized, + "the departing claimant held the last claim — the backend COW \ + must be torn down", + ); + assert!( + state + .resources + .window(crate::resources::COMPOSITE_OVERLAY_WINDOW) + .is_none(), + "the resources-side COW record must come down with it", + ); +} + +/// Repeated Gets from one client, then it disconnects: all of its +/// claims go, matching Xorg's N-records model where the resource +/// system frees every `CompOverlayClientRec` the client owns. +#[test] +fn disconnect_releases_all_of_a_clients_repeated_overlay_claims() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + for seq in 1..=3 { + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + seq, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + } + assert_eq!(state.cow_claims.len(), 3); + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + + assert!(state.cow_claims.is_empty(), "all three claims must go"); + assert!(!backend.cow_materialized); +} + +/// Two claimants: the overlay survives the first departure and comes +/// down on the second. +#[test] +fn overlay_survives_first_claimants_disconnect_and_dies_with_the_second() { + let mut state = ServerState::new(); + let _peer_a = install_client(&mut state, 1); + let _peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + for client in [1u32, 2] { + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(client), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + } + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + assert_eq!(state.cow_claims, vec![ClientId(2)]); + assert!( + backend.cow_materialized, + "B still holds a claim — the overlay must survive A's departure", + ); + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(2)); + assert!(state.cow_claims.is_empty()); + assert!(!backend.cow_materialized); +} + +/// `KillClient` on another client's resource calls +/// `process_disconnect` inline, bypassing +/// `disconnect_with_pending_cleanup`. That is exactly why the claim +/// release lives in `process_disconnect` and not in the funnel. +#[test] +fn kill_client_releases_the_victims_overlay_claim() { + let mut state = ServerState::new(); + let _peer_a = install_client(&mut state, 1); + let _peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + // Client 2 owns a window, so client 1 can name it in KillClient. + let victim_window = ResourceId(0x2000_0001); + state.resources.create_window( + ClientId(2), + CreateWindowRequest { + depth: 24, + window: victim_window, + parent: ROOT_WINDOW, + width: 64, + height: 64, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(2), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + assert_eq!(state.cow_claims, vec![ClientId(2)]); + + handle_kill_client( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 113, + minor: 0, + }, + &victim_window.0.to_le_bytes(), + ) + .expect("KillClient"); + + assert!( + !state.clients.contains_key(&2), + "precondition: the victim was force-disconnected", + ); + assert!( + state.cow_claims.is_empty(), + "the killed compositor's claim must go with it — KillClient \ + bypasses disconnect_with_pending_cleanup, so the release has \ + to live in process_disconnect", + ); + assert!(!backend.cow_materialized); +} + +/// A `RetainPermanent` claimant's overlay claims are released anyway +/// when its connection goes. The overlay is a screen-wide singleton; +/// a zombie holding it would block every future compositor. +#[test] +fn retained_clients_overlay_claims_are_released_anyway() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // RetainPermanent. + state.close_down_modes.insert(1, 1); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + + assert!( + state.zombie_clients.contains_key(&1), + "precondition: the client was retained, not destroyed", + ); + assert!( + state.cow_claims.is_empty(), + "a claim is not a retainable resource", + ); + assert!(!backend.cow_materialized); +} + +/// Protocol path, final release, teardown fails: `BadAlloc`, and the +/// caller **keeps** its claim — the release did not happen, so a +/// compositor can retry. Xorg maps allocation failure in this +/// extension to `BadAlloc` (`composite/compext.c:216,220,263,297`), +/// and a shadow-buffer allocation failing is exactly that. +/// +/// The pre-fix handler swallowed the backend `Err` into `false` and +/// reported protocol success for a teardown that did not occur. +#[test] +fn final_release_teardown_failure_is_badalloc_and_keeps_the_claim() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + let _ = read_all_available(&mut peer); + backend.cow_teardown_fails = true; + + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + + assert_error_code( + &read_all_available(&mut peer), + yserver_protocol::x11::error::BAD_ALLOC, + "ReleaseOverlayWindow whose teardown failed", + ); + assert_eq!( + state.cow_claims, + vec![ClientId(1)], + "the caller keeps its claim — the claim is what keeps the \ + overlay alive, so dropping it here is precisely the leak", + ); + assert!(backend.cow_materialized, "the overlay is still up"); + assert!( + !state.cow_teardown_failed, + "the protocol path is retryable: no session-fatal state", + ); + + // And the retry works. + backend.cow_teardown_fails = false; + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 3, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert!(state.cow_claims.is_empty()); + assert!(!backend.cow_materialized); +} + +/// Disconnect path, final release, teardown fails: the claims are +/// released **and** `cow_teardown_failed` is set. The two are not +/// alternatives — a leftover claim would be indistinguishable from a +/// live one and the next compositor would wait on a dead client. +/// +/// A later `GetOverlayWindow` from a fresh client is then `BadAlloc`: +/// whatever it would receive is inherited from a session that could +/// not be torn down. +#[test] +fn disconnect_teardown_failure_sets_cow_teardown_failed() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&crate::resources::ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + backend.cow_teardown_fails = true; + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + + assert!( + state.cow_claims.is_empty(), + "no claim outlives its owner, teardown failure or not", + ); + assert!( + state.cow_teardown_failed, + "the orphaned overlay needs an owner that is not a claim", + ); + assert!( + backend.cow_materialized, + "the overlay really is still up — that is the whole problem", + ); + + let _ = read_all_available(&mut peer_b); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(2), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + assert_error_code( + &read_all_available(&mut peer_b), + yserver_protocol::x11::error::BAD_ALLOC, + "GetOverlayWindow under cow_teardown_failed", + ); + assert!( + state.cow_claims.is_empty(), + "the refused Get records no claim", + ); +} + +// ---------------- the COW on the destroy executor ---------------- +// +// Expected streams are Xorg `DeleteWindow` (`dix/window.c:1070-1086`): +// UnmapNotify of the top (`:2854`, `DeliverEvents` = the window's +// StructureNotify, then the parent's SubstructureNotify), then +// `CrushTree`'s DestroyNotify per inferior (`:1037-1042`), then the top's +// (`:1080-1084`). A COW destroy leaves the claims (`compwindow.c:624-626`). + +const COW_COMPOSITOR: u32 = 1; +const COW_APP: u32 = 2; +const COW_LISTENER: u32 = 3; +const COW_CHILD: ResourceId = ResourceId(0x0020_0001); +const COW_CHILD_HOST: u32 = 0xC1; +const COW_SIBLING: ResourceId = ResourceId(0x0020_0002); +const COW_SIBLING_HOST: u32 = 0xD1; + +struct CowFixture { + state: ServerState, + backend: RecordingBackend, + compositor: std::os::unix::net::UnixStream, + app: std::os::unix::net::UnixStream, + listener: std::os::unix::net::UnixStream, +} + +/// The compositor holds the COW; another client's mapped child sits under +/// it and a mapped root sibling under the COW; direct scanout is active +/// (the backend defers retirement). The listener selects SubstructureNotify +/// on root and StructureNotify on the COW and the child. +fn cow_fixture() -> CowFixture { + const STRUCTURE_NOTIFY: u32 = 0x0002_0000; + const SUBSTRUCTURE_NOTIFY: u32 = 0x0008_0000; + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut state = ServerState::new(); + let mut compositor = install_client(&mut state, COW_COMPOSITOR); + let mut app = install_client(&mut state, COW_APP); + let mut listener = install_client(&mut state, COW_LISTENER); + let mut backend = RecordingBackend::new(); + for (window, parent, host) in [ + (COW_SIBLING, ROOT_WINDOW, COW_SIBLING_HOST), + (COW_CHILD, cow, COW_CHILD_HOST), + ] { + if parent == cow { + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(COW_COMPOSITOR), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &ROOT_WINDOW.0.to_le_bytes(), + ); + } + state.resources.create_window( + ClientId(COW_APP), + CreateWindowRequest { + depth: 24, + window, + parent, + width: 64, + height: 64, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.window_mut(window).expect("window").host_xid = + Some(crate::backend::WindowHandle::from_raw_for_test(host)); + let _ = state.resources.map_window(window); + } + let masks = &mut state + .clients + .get_mut(&COW_LISTENER) + .expect("listener") + .event_masks; + masks.insert(ROOT_WINDOW, SUBSTRUCTURE_NOTIFY); + masks.insert(cow, STRUCTURE_NOTIFY); + masks.insert(COW_CHILD, STRUCTURE_NOTIFY); + backend.cow_release_defers = true; + let _ = take_calls(&backend); + for peer in [&mut compositor, &mut app, &mut listener] { + let _ = read_all_available(peer); + } + CowFixture { + state, + backend, + compositor, + app, + listener, + } +} + +fn take_calls(backend: &RecordingBackend) -> Vec { + std::mem::take(&mut *backend.calls.lock().unwrap()) +} + +/// `(code, event window, window)` of each event; replies and errors kept +/// as their code so nothing slips through unseen. +fn notify_events(bytes: &[u8]) -> Vec<(u8, u32, u32)> { + let word = |e: &[u8], at: usize| u32::from_le_bytes([e[at], e[at + 1], e[at + 2], e[at + 3]]); + bytes + .chunks_exact(32) + .map(|e| (e[0] & 0x7f, word(e, 4), word(e, 8))) + .collect() +} + +/// DeleteWindow(COW) with the fixture's child, as the listener sees it. +fn cow_teardown_stream() -> Vec<(u8, u32, u32)> { + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW.0; + vec![ + (18, cow, cow), + (18, ROOT_WINDOW.0, cow), + (17, COW_CHILD.0, COW_CHILD.0), + (17, cow, cow), + (17, ROOT_WINDOW.0, cow), + ] +} + +fn assert_cow_intact(f: &CowFixture) { + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let record = f.state.resources.window(cow).expect("COW record kept"); + assert_eq!(record.map_state, MapState::Viewable); + assert_eq!( + f.state.resources.window(COW_CHILD).map(|w| w.parent), + Some(cow), + "the child is still under the COW" + ); + assert!(f.backend.cow_materialized && !f.backend.cow_release_deferred); + assert_eq!(f.state.cow_claims, vec![ClientId(COW_COMPOSITOR)]); +} + +fn destroy_window_request(f: &mut CowFixture, window: ResourceId) { + handle_destroy_window( + &mut f.state, + &mut f.backend, + None, + ClientId(COW_APP), + SequenceNumber(5), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &window.0.to_le_bytes(), + ) + .expect("DestroyWindow"); +} + +fn destroy_subwindows_request(f: &mut CowFixture) { + handle_destroy_subwindows( + &mut f.state, + &mut f.backend, + None, + ClientId(COW_APP), + SequenceNumber(5), + RequestHeader { + opcode: 5, + data: 0, + length_units: 2, + }, + &ROOT_WINDOW.0.to_le_bytes(), + ) + .expect("DestroySubwindows"); +} + +/// The COW's backend step is the retirement, after the child's ordinary +/// teardown, and the COW never takes `destroy_subwindow`. +fn assert_overlay_backend_path(calls: &[crate::backend::recording::RecordedCall]) { + use crate::backend::recording::RecordedCall; + let child = calls + .iter() + .position(|c| *c == RecordedCall::DestroySubwindow(COW_CHILD_HOST)) + .expect("child destroyed in the backend"); + let retire = calls + .iter() + .position(|c| *c == RecordedCall::RetireOverlayWindow) + .expect("COW retired"); + assert!(child < retire, "children go while the backend COW exists"); + assert!(!calls.contains(&RecordedCall::DestroySubwindow( + crate::resources::COMPOSITE_OVERLAY_WINDOW.0 + ))); +} + +#[test] +fn final_release_whose_preparation_fails_changes_nothing() { + let mut f = cow_fixture(); + f.backend.cow_teardown_fails = true; + dispatch_composite_minor( + &mut f.state, + &mut f.backend, + ClientId(COW_COMPOSITOR), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert_error_code( + &read_all_available(&mut f.compositor), + yserver_protocol::x11::error::BAD_ALLOC, + "ReleaseOverlayWindow whose preparation failed", + ); + assert_cow_intact(&f); + assert!(read_all_available(&mut f.listener).is_empty(), "no event"); + assert!(take_calls(&f.backend).is_empty(), "backend untouched"); +} + +#[test] +fn destroy_window_of_the_cow_keeps_claims_and_next_get_recreates_it() { + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut f = cow_fixture(); + destroy_window_request(&mut f, cow); + + assert!(read_all_available(&mut f.app).is_empty(), "no error"); + assert_eq!( + notify_events(&read_all_available(&mut f.listener)), + cow_teardown_stream() + ); + assert!(f.state.resources.window(cow).is_none()); + assert!(f.state.resources.window(COW_CHILD).is_none()); + assert_eq!(f.state.cow_claims, vec![ClientId(COW_COMPOSITOR)]); + assert!( + f.backend.cow_release_deferred, + "retirement waits for scanout" + ); + assert_overlay_backend_path(&take_calls(&f.backend)); + + // `compext.c:303`: no overlay, so this Get creates one, whatever the claims. + dispatch_composite_minor( + &mut f.state, + &mut f.backend, + ClientId(COW_COMPOSITOR), + 6, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &ROOT_WINDOW.0.to_le_bytes(), + ); + let reply = read_all_available(&mut f.compositor); + assert_eq!(reply[0], 1, "reply"); + assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), cow.0); + let record = f.state.resources.window(cow).expect("core COW record"); + assert_eq!(record.map_state, MapState::Viewable); + assert!( + record.children.is_empty(), + "the old child does not come back" + ); + assert_eq!( + f.state.cow_claims, + vec![ClientId(COW_COMPOSITOR), ClientId(COW_COMPOSITOR)] + ); + assert!( + !f.backend.cow_release_deferred, + "backend re-adopted its COW" + ); + // `compCreateOverlayWindow` (`compoverlay.c:125-141`): CreateWindow, MapWindow. + assert_eq!( + notify_events(&read_all_available(&mut f.listener)), + vec![(16, ROOT_WINDOW.0, cow.0), (19, ROOT_WINDOW.0, cow.0)] + ); +} + +#[test] +fn destroy_window_of_the_cow_whose_preparation_fails_is_badalloc() { + let mut f = cow_fixture(); + f.backend.cow_teardown_fails = true; + destroy_window_request(&mut f, crate::resources::COMPOSITE_OVERLAY_WINDOW); + assert_error_code( + &read_all_available(&mut f.app), + yserver_protocol::x11::error::BAD_ALLOC, + "DestroyWindow(COW) whose preparation failed", + ); + assert_cow_intact(&f); + assert!(read_all_available(&mut f.listener).is_empty(), "no event"); + assert!(take_calls(&f.backend).is_empty(), "backend untouched"); +} + +#[test] +fn destroy_subwindows_of_root_destroys_the_cow_through_the_overlay_path() { + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut f = cow_fixture(); + destroy_subwindows_request(&mut f); + + assert!(read_all_available(&mut f.app).is_empty(), "no error"); + // `DestroySubwindows` (`dix/window.c:1104-1124`): `UnmapSubwindows` + // stops at `RealChildHead` (the COW), then `lastChild` (bottom) first. + let mut expected = vec![ + (18, ROOT_WINDOW.0, COW_SIBLING.0), + (17, ROOT_WINDOW.0, COW_SIBLING.0), + ]; + expected.extend(cow_teardown_stream()); + assert_eq!( + notify_events(&read_all_available(&mut f.listener)), + expected + ); + assert!(f.state.resources.children(ROOT_WINDOW).is_empty()); + assert!(f.state.resources.window(cow).is_none()); + assert_eq!(f.state.cow_claims, vec![ClientId(COW_COMPOSITOR)]); + assert!(f.backend.cow_release_deferred); + let calls = take_calls(&f.backend); + assert!( + calls.contains(&crate::backend::recording::RecordedCall::DestroySubwindow( + COW_SIBLING_HOST + )) + ); + assert_overlay_backend_path(&calls); +} + +#[test] +fn destroy_subwindows_of_root_whose_cow_preparation_fails_changes_nothing() { + let mut f = cow_fixture(); + f.backend.cow_teardown_fails = true; + destroy_subwindows_request(&mut f); + assert_error_code( + &read_all_available(&mut f.app), + yserver_protocol::x11::error::BAD_ALLOC, + "DestroySubwindows(root) whose COW preparation failed", + ); + assert_cow_intact(&f); + assert_eq!( + f.state.resources.window(COW_SIBLING).map(|w| w.map_state), + Some(MapState::Viewable), + "no child unmapped" + ); + assert!(read_all_available(&mut f.listener).is_empty(), "no event"); + assert!(take_calls(&f.backend).is_empty(), "backend untouched"); +} + +#[test] +fn failed_recreation_after_the_cow_was_destroyed_rolls_back_only_its_own_claim() { + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut f = cow_fixture(); + f.backend.cow_release_defers = false; + destroy_window_request(&mut f, cow); + assert!(!f.backend.cow_materialized); + f.backend.cow_materialize_fails = true; + let _ = read_all_available(&mut f.app); + + dispatch_composite_minor( + &mut f.state, + &mut f.backend, + ClientId(COW_APP), + 6, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &ROOT_WINDOW.0.to_le_bytes(), + ); + // `compext.c:303-307`: BadAlloc, and only this Get's claim is freed. + assert_error_code( + &read_all_available(&mut f.app), + yserver_protocol::x11::error::BAD_ALLOC, + "GetOverlayWindow whose recreation failed", + ); + assert_eq!(f.state.cow_claims, vec![ClientId(COW_COMPOSITOR)]); + assert!(f.state.resources.window(cow).is_none(), "no partial COW"); + assert!(!f.state.resources.children(ROOT_WINDOW).contains(&cow)); +} + +#[test] +fn last_release_after_the_cow_was_destroyed_just_drops_the_claim() { + let mut f = cow_fixture(); + destroy_window_request(&mut f, crate::resources::COMPOSITE_OVERLAY_WINDOW); + let _ = read_all_available(&mut f.listener); + let _ = take_calls(&f.backend); + + dispatch_composite_minor( + &mut f.state, + &mut f.backend, + ClientId(COW_COMPOSITOR), + 6, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert!(read_all_available(&mut f.compositor).is_empty(), "success"); + assert!(f.state.cow_claims.is_empty()); + assert!( + read_all_available(&mut f.listener).is_empty(), + "no teardown" + ); + assert!(take_calls(&f.backend).is_empty(), "no teardown"); +} + +/// Divergence 7: the last release crushes the COW's subtree, a child owned +/// by another client included (`compDestroyOverlayWindow` → `DeleteWindow`). +#[test] +fn last_release_destroys_another_clients_child_under_the_cow() { + let mut f = cow_fixture(); + dispatch_composite_minor( + &mut f.state, + &mut f.backend, + ClientId(COW_COMPOSITOR), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &[], + ); + assert!(read_all_available(&mut f.compositor).is_empty(), "success"); + assert_eq!( + notify_events(&read_all_available(&mut f.listener)), + cow_teardown_stream() + ); + assert!(f.state.cow_claims.is_empty()); + assert!(f.state.resources.window(COW_CHILD).is_none()); + let mut left = Vec::new(); + f.state + .resources + .collect_owned_window_roots(ClientId(COW_APP), &mut left); + assert_eq!(left, vec![COW_SIBLING], "only the root sibling survives"); + assert_overlay_backend_path(&take_calls(&f.backend)); +} + +/// The same through the last claimant's disconnect; the departing +/// compositor gets nothing, the listener the whole stream. +#[test] +fn last_claimants_disconnect_destroys_another_clients_child_under_the_cow() { + let mut f = cow_fixture(); + crate::core_loop::process_disconnect::process_disconnect( + &mut f.state, + &mut f.backend, + ClientId(COW_COMPOSITOR), + ); + assert_eq!( + notify_events(&read_all_available(&mut f.listener)), + cow_teardown_stream() + ); + assert!(f.state.cow_claims.is_empty()); + assert!(f.state.resources.window(COW_CHILD).is_none()); + assert!(!f.state.cow_teardown_failed); + assert_overlay_backend_path(&take_calls(&f.backend)); +} + +// ---------------- rotate_redirected_backing_on_resize ---------------- +// +// Marco-with-compositing resizes the top mate-panel from 25 → 28 px +// tall after `RedirectSubwindows(root, Manual)`. The subsequent +// `NameWindowPixmap(panel)` must succeed against fresh storage at +// the new size. Pre-fix v2 returned `NotFound` because the rotate +// path allocated-then-released against an idempotent +// `host_window_to_backing[W]` cache and freed the very pixmap it +// had just chosen to keep. This test pins release-then-allocate +// ORDER — flipping it back would regress the hardware smoke bug. +#[test] +fn rotate_redirected_backing_on_resize_reallocates_and_returns_old_retained() { + use crate::backend::recording::RecordedCall; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + const OLD_BACKING: u32 = 0x0050_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Install a top-level child of root, then prime it with a + // pretend-existing redirected backing (the state we'd be in + // after `RedirectSubwindows` + activation but before the + // resize). 100x50 → resize target 100x75. + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 32, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), + width: 100, + height: 50, + depth: 32, + }); + } + + let old = rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + 100, + 75, + false, + 0, + ); + + // compReallocPixmap: OLD is retained, a new backing is made, and OLD + // comes back still held for the content copy and gravity carries. + let calls = backend.calls(); + assert_eq!(calls[0], RecordedCall::RetainBackingStorage(OLD_BACKING)); + assert_eq!( + calls[1], + RecordedCall::ReallocateRedirectedBacking { + host_window: HOST_XID, + old: OLD_BACKING, + width: 100, + height: 75, + depth: 32, + }, + ); + assert!( + !calls + .iter() + .any(|c| matches!(c, RecordedCall::ReleaseRedirectedBacking(_))), + "a resize must not unredirect (no leaf round trip): {calls:?}", + ); + assert_eq!(old.map(|h| h.as_raw()), Some(OLD_BACKING)); + assert!( + !calls + .iter() + .any(|c| matches!(c, RecordedCall::DropBackingStorage(_))), + "OLD stays retained until the caller finishes the rotate: {calls:?}", + ); + + // Window resource now points at the freshly-allocated backing + // (RecordingBackend hands back fresh handles per allocate). + let backing = state + .resources + .window(ResourceId(WINDOW_XID)) + .and_then(|w| w.redirected_backing) + .expect("redirected_backing repointed after rotate"); + assert_ne!( + backing.host_pixmap.as_raw(), + OLD_BACKING, + "redirected_backing must point at the NEW pixmap, not the old one", + ); + assert_eq!(backing.width, 100); + assert_eq!(backing.height, 75); + assert_eq!(backing.depth, 32); +} + +/// How a GLX-TFP compositor lets go of a named, resized window. +#[derive(Clone, Copy, Debug)] +enum GlxTeardown { + DestroyGlxThenFree, + FreeThenDestroyGlx, + DestroyWindowFirst, + Disconnect, +} + +fn drive( + state: &mut ServerState, + backend: &mut RecordingBackend, + opcode: u8, + data: u8, + body: &[u8], +) { + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + process_request( + state, + backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode, + data, + length_units, + }, + body, + None, + ) + .expect("process_request"); +} + +/// picom-glx under a WM: NameWindowPixmap + glXCreatePixmap, `resizes` resizes, then teardown. +fn glx_export_ref_after_resizes(resizes: u16, teardown: GlxTeardown) -> RecordingBackend { + use yserver_protocol::x11::glx as x11glx; + const WIN: u32 = 0x0077_0001; + const PIX: u32 = 0x0077_0002; + const GLXPIX: u32 = 0x0077_0003; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new() + .with_composite_support() + .with_redirect_activation(); + let mut cw = Vec::new(); + cw.extend_from_slice(&WIN.to_le_bytes()); + cw.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + cw.extend_from_slice(&[0, 0, 0, 0]); // x, y + cw.extend_from_slice(&100u16.to_le_bytes()); + cw.extend_from_slice(&50u16.to_le_bytes()); + cw.extend_from_slice(&0u16.to_le_bytes()); // border + cw.extend_from_slice(&1u16.to_le_bytes()); // InputOutput + cw.extend_from_slice(&0u32.to_le_bytes()); // CopyFromParent visual + cw.extend_from_slice(&0u32.to_le_bytes()); // no values + drive(&mut state, &mut backend, 1, 0, &cw); + let mut redirect = ROOT_WINDOW.0.to_le_bytes().to_vec(); + redirect.extend_from_slice(&[1, 0, 0, 0]); // Manual + drive( + &mut state, + &mut backend, + 144, + yserver_protocol::x11::composite::REDIRECT_SUBWINDOWS, + &redirect, + ); + drive(&mut state, &mut backend, 8, 0, &WIN.to_le_bytes()); + let mut name = WIN.to_le_bytes().to_vec(); + name.extend_from_slice(&PIX.to_le_bytes()); + drive( + &mut state, + &mut backend, + 144, + yserver_protocol::x11::composite::NAME_WINDOW_PIXMAP, + &name, + ); + let mut glx = Vec::new(); + glx.extend_from_slice(&0u32.to_le_bytes()); // screen + glx.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig + glx.extend_from_slice(&PIX.to_le_bytes()); + glx.extend_from_slice(&GLXPIX.to_le_bytes()); + drive(&mut state, &mut backend, 148, x11glx::CREATE_PIXMAP, &glx); + let first = state + .resources + .pixmap(ResourceId(PIX)) + .and_then(|p| p.host_xid) + .expect("named pixmap") + .as_raw(); + assert_eq!( + backend.glx_pixmap_exports.get(&first), + Some(&1), + "glXCreatePixmap holds one export ref on the named backing", + ); + + for i in 1..=resizes { + let mut cfg = WIN.to_le_bytes().to_vec(); + cfg.extend_from_slice(&0x0cu16.to_le_bytes()); + cfg.extend_from_slice(&0u16.to_le_bytes()); + cfg.extend_from_slice(&u32::from(100 + 10 * i).to_le_bytes()); + cfg.extend_from_slice(&u32::from(50 + 10 * i).to_le_bytes()); + drive(&mut state, &mut backend, 12, 0, &cfg); + let current = state + .resources + .window(ResourceId(WIN)) + .and_then(|w| w.redirected_backing) + .expect("redirected backing") + .host_pixmap + .as_raw(); + assert_ne!(current, first, "resize {i} rotated the backing"); + assert_eq!( + state + .glx_drawables + .get(&GLXPIX) + .and_then(|d| d.glx_export_host_xid), + Some(current), + "resize {i}: the GLX pixmap follows the retargeted alias", + ); + assert_eq!( + backend + .glx_pixmap_exports + .clone() + .into_iter() + .collect::>(), + vec![(current, 1)], + "resize {i}: the export ref lives on the backing the GLX pixmap names", + ); + } + + let destroy_glx = |state: &mut ServerState, backend: &mut RecordingBackend| { + drive( + state, + backend, + 148, + x11glx::DESTROY_PIXMAP, + &GLXPIX.to_le_bytes(), + ); + }; + let free = |state: &mut ServerState, backend: &mut RecordingBackend| { + drive(state, backend, 54, 0, &PIX.to_le_bytes()); + }; + let destroy_win = |state: &mut ServerState, backend: &mut RecordingBackend| { + drive(state, backend, 4, 0, &WIN.to_le_bytes()); + }; + match teardown { + GlxTeardown::DestroyGlxThenFree => { + destroy_glx(&mut state, &mut backend); + free(&mut state, &mut backend); + destroy_win(&mut state, &mut backend); + } + GlxTeardown::FreeThenDestroyGlx => { + free(&mut state, &mut backend); + destroy_glx(&mut state, &mut backend); + destroy_win(&mut state, &mut backend); + } + GlxTeardown::DestroyWindowFirst => { + destroy_win(&mut state, &mut backend); + destroy_glx(&mut state, &mut backend); + free(&mut state, &mut backend); + } + GlxTeardown::Disconnect => { + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(1), + ); + } + } + backend +} + +/// A resize retargets picom's GLX pixmap; the export ref must move with it, or OLD leaks. +#[test] +fn glx_pixmap_export_ref_follows_the_resize_retarget() { + for resizes in [0, 1, 2] { + for teardown in [ + GlxTeardown::DestroyGlxThenFree, + GlxTeardown::FreeThenDestroyGlx, + GlxTeardown::DestroyWindowFirst, + GlxTeardown::Disconnect, + ] { + let backend = glx_export_ref_after_resizes(resizes, teardown); + assert!( + backend.glx_pixmap_exports.is_empty(), + "resizes={resizes} {teardown:?}: export refs left behind: {:?}", + backend.glx_pixmap_exports, + ); + } + } +} + +// compCopyWindow analog: when a redirected window resizes, the +// pre-existing backing's contents must be carried over into the new +// backing for the overlap region — otherwise any compositor that +// re-Names the post-resize backing (marco on mate-panel-top during +// the 25→28-px grow, etc.) samples an empty buffer and the panel +// renders without the icons that were already painted into the old +// backing. Xorg lands this via `compReallocPixmap` (save old +// pixmap) + `compCopyWindow` (copy_area old→new). See +// /home/jos/Projects/xserver/composite/compalloc.c:680-712 and +// compwindow.c:376-388. +#[test] +fn rotate_redirected_backing_on_resize_copies_old_contents_to_new() { + use crate::backend::recording::RecordedCall; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + const OLD_BACKING: u32 = 0x0050_0001; + const OLD_W: u16 = 100; + const OLD_H: u16 = 50; + const NEW_W: u16 = 100; + const NEW_H: u16 = 75; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 32, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: OLD_W, + height: OLD_H, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), + width: OLD_W, + height: OLD_H, + depth: 32, + }); + } + + rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + NEW_W, + NEW_H, + false, + 0, + ); + + // NEW handle is whatever the RecordingBackend's allocate + // handed back; pull it from the resource state. + let new_backing = state + .resources + .window(ResourceId(WINDOW_XID)) + .and_then(|w| w.redirected_backing) + .expect("redirected_backing repointed after rotate"); + let new_raw = new_backing.host_pixmap.as_raw(); + + let calls = backend.calls(); + // Expected overlap = min(old, new) per dimension. + let expected_w = OLD_W.min(NEW_W); + let expected_h = OLD_H.min(NEW_H); + let copy = calls.iter().find(|c| { + matches!( + c, + RecordedCall::CopyArea { + src_host_xid, + dst_host_xid, + src_x: 0, + src_y: 0, + dst_x: 0, + dst_y: 0, + width, + height, + } if *src_host_xid == OLD_BACKING + && *dst_host_xid == new_raw + && *width == expected_w + && *height == expected_h + ) + }); + assert!( + copy.is_some(), + "expected CopyArea(OLD=0x{OLD_BACKING:x} → NEW=0x{new_raw:x}, \ + src=(0,0), dst=(0,0), {expected_w}x{expected_h}) — \ + missing the compCopyWindow analog that carries pre-resize \ + contents into the freshly-allocated backing. Calls: {calls:?}", + ); +} + +// #143 (rendering half) — a SHRINK must rotate exactly like a grow. +// +// Measured under awesome+picom: switching tiling layout shrank a +// mate-terminal frame (`bw = 2`) from 1278x704 to 1276x704 and the +// render module logged NOTHING — `redirected_backing_can_fit` was a +// high-water-mark test, so the 1282x708 backing was kept and only its +// metadata was rewritten. The backing's ring stayed laid out for the +// OLD 1278-px content (2-px ring at columns 1280..1281) and nothing +// re-seeded it, leaving an alpha-0 band where content should be. +// +// Xorg reallocates on inequality in EITHER direction: +// `compReallocPixmap` (../xserver/composite/compalloc.c:698), whose +// replacement is always freshly seeded from the parent +// (`compNewPixmap`, compalloc.c:539-605). +// +// The backend predicate is where the fix lives (its own unit test is +// `redirected_backing_reuse_requires_the_exact_storage_extent`); +// what this test pins is the core half — that the realloc path +// allocates at the NEW bordered extent and carries only the CONTENT +// overlap, leaving the freshly painted ring of NEW alone. +#[test] +fn rotate_redirected_backing_on_shrink_allocates_the_new_bordered_extent() { + use crate::backend::recording::RecordedCall; + + const BW: u16 = 2; + // Content 1278x704 → backing 1282x708 (the pre-switch state). + const OLD_BACKING_W: u16 = 1282; + const OLD_BACKING_H: u16 = 708; + // Shrink to content 1276x704 → backing 1280x708. + const NEW_CONTENT_W: u16 = 1276; + const NEW_CONTENT_H: u16 = 704; + + let (mut state, mut backend, old_backing) = + redirected_window_fixture(OLD_BACKING_W, OLD_BACKING_H, BW); + + rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(ROTATE_WINDOW_XID), + NEW_CONTENT_W, + NEW_CONTENT_H, + false, + BW, + ); + + let new_backing = state + .resources + .window(ResourceId(ROTATE_WINDOW_XID)) + .and_then(|w| w.redirected_backing) + .expect("redirected_backing repointed after the shrink rotate"); + assert_ne!( + new_backing.host_pixmap.as_raw(), + old_backing, + "a shrink must rotate onto a FRESH backing, not keep the oversized one", + ); + assert_eq!( + (new_backing.width, new_backing.height), + (1280, 708), + "the new backing is the new BORDERED extent (1276 + 2*2, 704 + 2*2)", + ); + + let calls = backend.calls(); + assert!( + calls.contains(&RecordedCall::ReallocateRedirectedBacking { + host_window: ROTATE_HOST_XID, + old: old_backing, + width: 1280, + height: 708, + depth: 32, + }), + "the shrink must allocate storage at the new bordered extent \ + 1280x708, not keep 1282x708. Calls: {calls:?}", + ); + + // Content-only copy: both backings hold content at `(bw, bw)`, + // and the overlap is min(1278, 1276) x min(704, 704). + let new_raw = new_backing.host_pixmap.as_raw(); + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::CopyArea { + src_host_xid, + dst_host_xid, + src_x: 2, + src_y: 2, + dst_x: 2, + dst_y: 2, + width: 1276, + height: 704, + } if *src_host_xid == old_backing && *dst_host_xid == new_raw + )), + "the rotate copy must carry the CONTENT overlap inset by the \ + border width — a full-extent copy would repaint NEW's \ + right/bottom ring columns with OLD's interior pixels. \ + Calls: {calls:?}", + ); +} + +// The over-correction guard for the test above: a bordered GROW must +// keep rotating the way it always did, and its copy is inset the same +// way (the ring of NEW is painted by `allocate_redirected_backing`; +// Xorg repaints it too, via the `compRepaintBorder` work proc queued +// from `compSetPixmap`, ../xserver/composite/compwindow.c:137-139). +#[test] +fn rotate_redirected_backing_on_bordered_grow_still_rotates_and_copies_content() { + use crate::backend::recording::RecordedCall; + + const BW: u16 = 2; + // Content 1276x704 → backing 1280x708, growing to content + // 1278x704 → backing 1282x708. + const OLD_BACKING_W: u16 = 1280; + const OLD_BACKING_H: u16 = 708; + const NEW_CONTENT_W: u16 = 1278; + const NEW_CONTENT_H: u16 = 704; + + let (mut state, mut backend, old_backing) = + redirected_window_fixture(OLD_BACKING_W, OLD_BACKING_H, BW); + + rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(ROTATE_WINDOW_XID), + NEW_CONTENT_W, + NEW_CONTENT_H, + false, + BW, + ); + + let new_backing = state + .resources + .window(ResourceId(ROTATE_WINDOW_XID)) + .and_then(|w| w.redirected_backing) + .expect("redirected_backing repointed after the grow rotate"); + assert_eq!((new_backing.width, new_backing.height), (1282, 708)); + + let calls = backend.calls(); + assert!( + calls.contains(&RecordedCall::ReallocateRedirectedBacking { + host_window: ROTATE_HOST_XID, + old: old_backing, + width: 1282, + height: 708, + depth: 32, + }), + "the grow must allocate at the new bordered extent. Calls: {calls:?}", + ); + let new_raw = new_backing.host_pixmap.as_raw(); + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::CopyArea { + src_host_xid, + dst_host_xid, + src_x: 2, + src_y: 2, + dst_x: 2, + dst_y: 2, + width: 1276, + height: 704, + } if *src_host_xid == old_backing && *dst_host_xid == new_raw + )), + "the grow copy carries the same content overlap, inset by the \ + border width. Calls: {calls:?}", + ); +} + +const ROTATE_WINDOW_XID: u32 = 0x0010_0001; +const ROTATE_HOST_XID: u32 = 0x0040_0001; + +/// A root child already redirected, with a backing whose recorded +/// extent is `(backing_w, backing_h)` — i.e. the post-activation +/// state, before the resize under test. Returns the OLD backing's +/// raw xid alongside the fixture. +fn redirected_window_fixture( + backing_w: u16, + backing_h: u16, + border_width: u16, +) -> (ServerState, RecordingBackend, u32) { + const OLD_BACKING: u32 = 0x0050_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 32, + window: ResourceId(ROTATE_WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: backing_w.saturating_sub(border_width.saturating_mul(2)), + height: backing_h.saturating_sub(border_width.saturating_mul(2)), + border_width, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(ROTATE_WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + ROTATE_HOST_XID, + )); + w.border_width = border_width; + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), + width: backing_w, + height: backing_h, + depth: 32, + }); + } + (state, backend, OLD_BACKING) +} + +// Storage-alive invariant for the rotate copy. Observed in HW +// smoke (yserver-hw-mate.log 17:28:10Z) that the rotate path +// dropped tiny 1×1 CopyAreas with `copy_area dropped — src +// unknown` whenever OLD had no `NameWindowPixmap` aliases: the +// existing `release_redirected_backing` decref'd alias_registry +// to 0 → `free_pixmap` → store entry gone → `store.lookup(OLD)` +// returned None at the copy site → silent drop. +// +// Fix shape: take a rotate-scoped retain on OLD's storage +// BEFORE the release (so release's decref doesn't hit 0), drop +// it AFTER the copy (frees storage only if no other aliases +// hold it). This test pins the call ordering on +// RecordingBackend; the v2-side alias_registry incref/decref +// semantics are exercised by the v2 backend's own tests. +#[test] +fn rotate_redirected_backing_retains_old_storage_until_finish() { + use crate::backend::recording::RecordedCall; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + const OLD_BACKING: u32 = 0x0050_0001; + const OLD_W: u16 = 1; + const OLD_H: u16 = 1; + const NEW_W: u16 = 1; + const NEW_H: u16 = 1; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 32, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: OLD_W, + height: OLD_H, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), + width: OLD_W, + height: OLD_H, + depth: 32, + }); + } + + let old = rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + NEW_W, + NEW_H, + true, + 0, + ); + finish_redirected_backing_rotate(&mut backend, None, old); + + let calls = backend.calls(); + let pos = |f: &dyn Fn(&RecordedCall) -> bool| calls.iter().position(f); + let r = pos(&|c| matches!(c, RecordedCall::RetainBackingStorage(x) if *x == OLD_BACKING)) + .expect("retain OLD"); + let a = pos(&|c| { + matches!(c, RecordedCall::ReallocateRedirectedBacking { host_window, old, .. } + if *host_window == HOST_XID && *old == OLD_BACKING) + }) + .expect("reallocate"); + let c = pos(&|c| { + matches!(c, RecordedCall::CopyArea { src_host_xid, .. } if *src_host_xid == OLD_BACKING) + }) + .expect("copy OLD→NEW"); + let d = pos(&|c| matches!(c, RecordedCall::DropBackingStorage(x) if *x == OLD_BACKING)) + .expect("finish drops the retain"); + assert!( + r < a && a < c && c < d, + "retain < realloc < copy < drop: {calls:?}" + ); +} + +#[test] +fn rotate_redirected_backing_on_move_forces_reallocate_even_when_size_matches() { + use crate::backend::recording::RecordedCall; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + const OLD_BACKING: u32 = 0x0050_0001; + const W: u16 = 100; + const H: u16 = 50; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 32, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: W, + height: H, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), + width: W, + height: H, + depth: 32, + }); + } + + rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + W, + H, + true, + 0, + ); + + let calls = backend.calls(); + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::ReallocateRedirectedBacking { + host_window, + old, + width, + height, + depth: 32, + } if *host_window == HOST_XID && *old == OLD_BACKING && *width == W && *height == H + )), + "forced move-rotate must reallocate at the same size; got {calls:?}", + ); + let new_backing = state + .resources + .window(ResourceId(WINDOW_XID)) + .and_then(|w| w.redirected_backing) + .expect("redirected_backing repointed after forced rotate"); + assert_ne!( + new_backing.host_pixmap.as_raw(), + OLD_BACKING, + "forced move-rotate must repoint to a fresh backing even at identical size", + ); +} + +/// Resize rotates the redirected backing by releasing the old +/// backing and allocating a new one. The fresh allocation must +/// preserve the effective redirect mode's scene-participation +/// flags; otherwise a Manual-redirected frame can become visible +/// through normal scene traversal after a ConfigureWindow resize. +#[test] +fn rotate_redirected_backing_preserves_manual_scene_participation() { + use crate::backend::recording::RecordedCall; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + const OLD_BACKING: u32 = 0x0050_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 32, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD_BACKING), + width: 100, + height: 50, + depth: 32, + }); + } + state + .composite_redirects + .redirect_window( + ResourceId(WINDOW_XID), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: yserver_protocol::x11::ClientId(CLIENT_ID), + }, + ) + .unwrap(); + + rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + 100, + 75, + false, + 0, + ); + + let calls = backend.calls(); + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::SetWindowSceneParticipation { + host_window: HOST_XID, + participating: false, + } + )), + "rotate must reapply Manual W scene_participating=false; got {calls:?}", + ); + // The fresh backing must be scene-participating so the + // scene's `redirected_target` damage-peek sees paints into + // it post-resize — same invariant as + // `manual_redirect_marks_backing_scene_participating_so_paints_emit_damage`. + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::SetBackingSceneParticipation { + participating: true, + .. + } + )), + "rotate must mark the fresh Manual backing scene-participating; got {calls:?}", + ); +} + +// ──────────────────────────────────────────────────────────── +// Phase 2 reparent-redirect-reconciliation pins (Task 7). +// +// Mirrors Xorg's `compReparentWindow` (xserver/composite/ +// compwindow.c:453-454) — which dispatches to +// `compUnredirectOneSubwindow` (revoke inherited redirect), +// `compRedirectOneSubwindow` (grant inherited redirect), and +// `flip_redirect_target_mode` (mode flip across redirected +// parents). Direct RedirectWindow(W) is per-window so the +// backing is not touched by reparent. +// +// The fifth, user-visible pin lives in +// `crates/yserver/src/kms/render/backend.rs` — it drives the v2 +// `resolve_paint_target` ancestor walk through the full +// `process_request` dispatcher. +// ──────────────────────────────────────────────────────────── + +fn make_test_state() -> ServerState { + ServerState::new() +} + +/// Attach a `RedirectedBacking` to an already-seeded window. +/// The `backend` argument keeps the helper's signature +/// symmetrical with the (eventual) production path which +/// allocates a real backing through the backend; the recording +/// backend doesn't need to be consulted for the test +/// pre-condition, so we just synthesise a PixmapHandle. +fn seed_redirected_window( + state: &mut ServerState, + _backend: &mut crate::backend::recording::RecordingBackend, + xid: ResourceId, +) { + use crate::resources::RedirectedBacking; + if let Some(w) = state.resources.window_mut(xid) { + w.redirected_backing = Some(RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw(0x9000_0000 | xid.0) + .expect("non-zero PixmapHandle"), + width: w.width, + height: w.height, + depth: w.depth, + }); + } +} + +/// Drive a ReparentWindow through `handle_reparent_window` (the +/// module-private dispatch path) via `process_request`'s public +/// entry. ReparentWindow body = window(4 LE) + parent(4 LE) + +/// x(2 LE i16) + y(2 LE i16) = 12 bytes; length_units = 4 +/// (header + body = 16 bytes / 4). +fn dispatch_reparent_window( + state: &mut ServerState, + backend: &mut crate::backend::recording::RecordingBackend, + window: ResourceId, + parent: ResourceId, + x: i16, + y: i16, +) { + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.0.to_le_bytes()); + body.extend_from_slice(&parent.0.to_le_bytes()); + body.extend_from_slice(&x.to_le_bytes()); + body.extend_from_slice(&y.to_le_bytes()); + process_request( + state, + backend, + ClientId(14), + SequenceNumber(1), + RequestHeader { + opcode: 7, // ReparentWindow + data: 0, + length_units: 4, + }, + &body, + None, + ) + .expect("process_request(ReparentWindow) must succeed"); +} + +#[test] +fn reparent_out_of_redirected_subtree_revokes_inherited_redirect() { + // Phase 2: mirrors compUnredirectOneSubwindow in + // /home/jos/Projects/xserver/composite/compwindow.c:453. + // A window that inherited redirect from its parent's + // RedirectSubwindows must lose its backing when reparented + // to a parent without RedirectSubwindows. + // + // The actual regression: nm-applet (created as a direct + // child of root with RedirectSubwindows(root, Manual) + // active, then reparented into mate-panel's notification + // socket) keeps a stale backing. Paints land there instead + // of in mate-panel's pixmap; the compositor reads mate- + // panel's pixmap and sees an empty tray area. + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + + let root_xid = crate::resources::ROOT_WINDOW; + let mate_panel_xid = ResourceId(0x110_0003); + let socket_xid = ResourceId(0x210_0013); + let nm_applet_xid = ResourceId(0x180_000b); + + // root has RedirectSubwindows(Manual); socket does not. + state + .composite_redirects + .redirect_subwindows( + root_xid, + state.resources.children(root_xid), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: ClientId(14), + }, + ) + .unwrap(); + + seed_window(&mut state, mate_panel_xid, root_xid, 2560, 28); + seed_redirected_window(&mut state, &mut backend, mate_panel_xid); + seed_window(&mut state, socket_xid, mate_panel_xid, 26, 27); + seed_window(&mut state, nm_applet_xid, root_xid, 26, 27); + seed_redirected_window(&mut state, &mut backend, nm_applet_xid); + + assert!( + state + .resources + .window(nm_applet_xid) + .unwrap() + .redirected_backing + .is_some(), + "pre-condition: nm-applet has an inherited-redirect backing" + ); + + dispatch_reparent_window(&mut state, &mut backend, nm_applet_xid, socket_xid, 0, 0); + + assert_eq!( + state.resources.window(nm_applet_xid).unwrap().parent, + socket_xid, + ); + assert!( + state + .resources + .window(nm_applet_xid) + .unwrap() + .redirected_backing + .is_none(), + "post-condition: nm-applet's inherited-redirect backing is freed after \ + reparenting out of the redirected subtree" + ); +} + +#[test] +fn muffin_manual_probe_cannot_pin_redirect_across_reparent() { + // Live Warframe transition: while temporarily a root child, W + // inherits RedirectSubwindows(root, Manual). Muffin then probes + // RedirectWindow(W, Manual), which Xorg rejects with BadAccess. + // If accepted, that direct record makes the subsequent reparent + // into Muffin's frame skip inherited-redirect teardown and W keeps + // painting a stale inner backing that Muffin never samples. + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + let root = crate::resources::ROOT_WINDOW; + let frame = ResourceId(0x510_0040); + let window = ResourceId(0x530_0003); + + state + .composite_redirects + .redirect_subwindows( + root, + state.resources.children(root), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: ClientId(14), + }, + ) + .unwrap(); + seed_window(&mut state, frame, root, 1024, 768); + seed_window(&mut state, window, root, 1024, 768); + seed_redirected_window(&mut state, &mut backend, window); + + dispatch_composite_redirect(&mut state, &mut backend, ClientId(14), window.0, 1); + assert_eq!( + state.composite_redirects.window_records(window).len(), + 1, + "BadAccess probe must not add a redirect", + ); + + dispatch_reparent_window(&mut state, &mut backend, window, frame, 0, 0); + assert!( + state + .resources + .window(window) + .unwrap() + .redirected_backing + .is_none(), + "reparent into Muffin frame must revoke W's inherited Manual backing", + ); +} + +#[test] +fn reparent_into_redirected_subtree_grants_inherited_redirect() { + // Phase 2: mirrors compRedirectOneSubwindow at + // /home/jos/Projects/xserver/composite/compwindow.c:454. A + // window with no own redirect, no parent RedirectSubwindows, + // gains a backing when reparented under a parent with active + // RedirectSubwindows. + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + + let root_xid = crate::resources::ROOT_WINDOW; + let mate_panel_xid = ResourceId(0x110_0003); + let unredirected_parent_xid = ResourceId(0x300_0001); + let target_xid = ResourceId(0x300_0010); + + state + .composite_redirects + .redirect_subwindows( + mate_panel_xid, + state.resources.children(mate_panel_xid), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Automatic, + owner: ClientId(14), + }, + ) + .unwrap(); + + seed_window(&mut state, mate_panel_xid, root_xid, 2560, 28); + seed_window(&mut state, unredirected_parent_xid, root_xid, 100, 100); + seed_window(&mut state, target_xid, unredirected_parent_xid, 50, 50); + // Viewable throughout: an unviewable window gets its backing at realize instead. + for w in [mate_panel_xid, unredirected_parent_xid, target_xid] { + let _ = state.resources.map_window(w); + } + + assert!( + state + .resources + .window(target_xid) + .unwrap() + .redirected_backing + .is_none(), + "pre-condition: target has no backing" + ); + + dispatch_reparent_window(&mut state, &mut backend, target_xid, mate_panel_xid, 0, 0); + + assert_eq!( + state.resources.window(target_xid).unwrap().parent, + mate_panel_xid, + ); + assert!( + state + .resources + .window(target_xid) + .unwrap() + .redirected_backing + .is_some(), + "post-condition: target gained an inherited-redirect backing" + ); +} + +#[test] +fn reparent_with_direct_redirect_keeps_backing() { + // Phase 2 invariant: RedirectWindow(W) is a per-window + // redirect independent of W's parent. Reparenting W must + // NOT touch its backing. + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + + let root_xid = crate::resources::ROOT_WINDOW; + let mate_panel_xid = ResourceId(0x110_0003); + let socket_xid = ResourceId(0x210_0013); + let directly_redirected_xid = ResourceId(0x400_0001); + + state + .composite_redirects + .redirect_window( + directly_redirected_xid, + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: ClientId(14), + }, + ) + .unwrap(); + + seed_window(&mut state, mate_panel_xid, root_xid, 2560, 28); + seed_window(&mut state, socket_xid, mate_panel_xid, 26, 27); + seed_window(&mut state, directly_redirected_xid, root_xid, 50, 50); + seed_redirected_window(&mut state, &mut backend, directly_redirected_xid); + + let backing_before = state + .resources + .window(directly_redirected_xid) + .unwrap() + .redirected_backing + .as_ref() + .map(|b| b.host_pixmap); + assert!(backing_before.is_some()); + + dispatch_reparent_window( + &mut state, + &mut backend, + directly_redirected_xid, + socket_xid, + 0, + 0, + ); + + let backing_after = state + .resources + .window(directly_redirected_xid) + .unwrap() + .redirected_backing + .as_ref() + .map(|b| b.host_pixmap); + assert_eq!( + backing_before, backing_after, + "RedirectWindow(W) survives reparent" + ); +} + +// Window-storage step 4: a redirect backing follows viewability (Xorg +// compRealizeWindow / compUnrealizeWindow → compCheckRedirect); the +// redirect itself survives until Unredirect or destruction. + +fn storage_req( + state: &mut ServerState, + backend: &mut crate::backend::recording::RecordingBackend, + opcode: u8, + data: u8, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(14), + SequenceNumber(1), + RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + None, + ) + .expect("process_request must succeed"); +} + +fn storage_redirect( + state: &mut ServerState, + backend: &mut crate::backend::recording::RecordingBackend, + minor: u8, + window: ResourceId, +) { + let mut body = window.0.to_le_bytes().to_vec(); + body.extend_from_slice(&[1, 0, 0, 0]); // Manual + storage_req(state, backend, 144, minor, &body); +} + +fn storage_window_req( + state: &mut ServerState, + backend: &mut crate::backend::recording::RecordingBackend, + opcode: u8, + window: ResourceId, +) { + storage_req(state, backend, opcode, 0, &window.0.to_le_bytes()); +} + +fn drain_calls( + backend: &crate::backend::recording::RecordingBackend, +) -> Vec { + std::mem::take(&mut *backend.calls.lock().unwrap()) +} + +const MAP_WINDOW: u8 = 8; +const MAP_SUBWINDOWS: u8 = 9; +const UNMAP_WINDOW: u8 = 10; +const UNMAP_SUBWINDOWS: u8 = 11; + +fn backing_of(state: &ServerState, window: ResourceId) -> Option { + state + .resources + .window(window) + .and_then(|w| w.redirected_backing.as_ref()) + .map(|b| b.host_pixmap.as_raw()) +} + +fn storage_host(window: ResourceId) -> u32 { + 0x8000_0000 | window.0 +} + +fn released(calls: &[crate::backend::recording::RecordedCall], backing: u32) -> bool { + calls.iter().any(|c| { + matches!(c, crate::backend::recording::RecordedCall::ReleaseRedirectedBacking(b) if *b == backing) + }) +} + +fn allocations_for(calls: &[crate::backend::recording::RecordedCall], window: ResourceId) -> usize { + calls + .iter() + .filter(|c| { + matches!(c, crate::backend::recording::RecordedCall::AllocateRedirectedBacking { host_window, .. } if *host_window == storage_host(window)) + }) + .count() +} + +fn participation_restored( + calls: &[crate::backend::recording::RecordedCall], + window: ResourceId, +) -> bool { + calls.iter().any(|c| { + matches!(c, crate::backend::recording::RecordedCall::SetWindowSceneParticipation { host_window, participating: true } if *host_window == storage_host(window)) + }) +} + +fn last_participation( + calls: &[crate::backend::recording::RecordedCall], + window: ResourceId, +) -> Option { + calls.iter().rev().find_map(|c| match c { + crate::backend::recording::RecordedCall::SetWindowSceneParticipation { + host_window, + participating, + } if *host_window == storage_host(window) => Some(*participating), + _ => None, + }) +} + +/// A mapped top-level `W`, Manual-redirected through the dispatcher. +fn storage_redirected_top_level() -> ( + ServerState, + crate::backend::recording::RecordingBackend, + ResourceId, + u32, +) { + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + let window = ResourceId(0x0600_0001); + seed_window(&mut state, window, crate::resources::ROOT_WINDOW, 64, 48); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); + storage_redirect(&mut state, &mut backend, 1, window); + let backing = backing_of(&state, window).expect("viewable redirected window has a backing"); + (state, backend, window, backing) +} + +#[test] +fn unmap_of_redirected_window_frees_backing_keeps_redirect_and_exclusion() { + let (mut state, mut backend, window, backing) = storage_redirected_top_level(); + drain_calls(&backend); + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); + let calls = drain_calls(&backend); + assert!( + released(&calls, backing), + "unmap releases the backing; calls={calls:#?}" + ); + assert_eq!(backing_of(&state, window), None); + assert!( + state.composite_redirects.window_mode(window).is_some(), + "redirect record kept" + ); + assert!( + !participation_restored(&calls, window), + "window stays out of the scene" + ); +} + +#[test] +fn remap_of_redirected_window_allocates_a_fresh_backing() { + let (mut state, mut backend, window, backing) = storage_redirected_top_level(); + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); + drain_calls(&backend); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); + let calls = drain_calls(&backend); + assert_eq!(allocations_for(&calls, window), 1); + let fresh = backing_of(&state, window).expect("remap re-creates the backing"); + assert_ne!(fresh, backing); + assert_eq!( + last_participation(&calls, window), + Some(false), + "Manual stays excluded" + ); +} + +#[test] +fn redirect_of_unviewable_window_allocates_at_map() { + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + let window = ResourceId(0x0600_0001); + seed_window(&mut state, window, crate::resources::ROOT_WINDOW, 64, 48); + storage_redirect(&mut state, &mut backend, 1, window); + assert_eq!( + allocations_for(&drain_calls(&backend), window), + 0, + "Xorg: not realized, no pixmap" + ); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); + assert_eq!(allocations_for(&drain_calls(&backend), window), 1); + assert!(backing_of(&state, window).is_some()); +} + +#[test] +fn ancestor_unmap_frees_redirected_descendant_backing_and_remap_restores_it() { + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + let frame = ResourceId(0x0600_0010); + let window = ResourceId(0x0600_0011); + seed_window(&mut state, frame, crate::resources::ROOT_WINDOW, 64, 48); + seed_window(&mut state, window, frame, 32, 24); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); + storage_redirect(&mut state, &mut backend, 1, window); + let backing = backing_of(&state, window).expect("backing"); + drain_calls(&backend); + + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, frame); + let calls = drain_calls(&backend); + assert!(released(&calls, backing)); + assert_eq!(backing_of(&state, window), None); + assert!(state.composite_redirects.window_mode(window).is_some()); + assert!(!participation_restored(&calls, window)); + + storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); + let calls = drain_calls(&backend); + assert_eq!( + allocations_for(&calls, window), + 1, + "descendant realized with its ancestor" + ); + assert_ne!(backing_of(&state, window), Some(backing)); + assert!(backing_of(&state, window).is_some()); + assert_eq!(last_participation(&calls, window), Some(false)); +} + +#[test] +fn redirect_subwindows_children_follow_viewability() { + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + let parent = ResourceId(0x0600_0020); + let shown = ResourceId(0x0600_0021); + let hidden = ResourceId(0x0600_0022); + seed_window(&mut state, parent, crate::resources::ROOT_WINDOW, 64, 48); + seed_window(&mut state, shown, parent, 16, 16); + seed_window(&mut state, hidden, parent, 16, 16); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, parent); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, shown); + storage_redirect(&mut state, &mut backend, 2, parent); // RedirectSubwindows + let shown_backing = backing_of(&state, shown).expect("viewable child redirected"); + assert_eq!( + backing_of(&state, hidden), + None, + "unmapped child has no backing" + ); + assert_eq!( + backing_of(&state, parent), + None, + "the parent itself is not redirected" + ); + + storage_window_req(&mut state, &mut backend, UNMAP_SUBWINDOWS, parent); + let calls = drain_calls(&backend); + assert!(released(&calls, shown_backing)); + assert_eq!(backing_of(&state, shown), None); + assert!(state.composite_redirects.subwindows_mode(parent).is_some()); + assert!(!participation_restored(&calls, shown)); + + storage_window_req(&mut state, &mut backend, MAP_SUBWINDOWS, parent); + let calls = drain_calls(&backend); + assert_eq!(allocations_for(&calls, shown), 1); + assert_eq!(allocations_for(&calls, hidden), 1); + assert_eq!(last_participation(&calls, shown), Some(false)); + assert_eq!(last_participation(&calls, hidden), Some(false)); + + let (a, b) = ( + backing_of(&state, shown).unwrap(), + backing_of(&state, hidden).unwrap(), + ); + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, parent); + let calls = drain_calls(&backend); + assert!( + released(&calls, a) && released(&calls, b), + "ancestor unmap frees every child" + ); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, parent); + let calls = drain_calls(&backend); + assert_eq!(allocations_for(&calls, shown), 1); + assert_eq!(allocations_for(&calls, hidden), 1); +} + +#[test] +fn unredirect_window_still_tears_down_and_restores_participation() { + let (mut state, mut backend, window, backing) = storage_redirected_top_level(); + drain_calls(&backend); + storage_redirect(&mut state, &mut backend, 3, window); // UnredirectWindow + let calls = drain_calls(&backend); + assert!(released(&calls, backing)); + assert_eq!(backing_of(&state, window), None); + assert!(state.composite_redirects.window_mode(window).is_none()); + assert_eq!(last_participation(&calls, window), Some(true)); + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); + assert_eq!( + allocations_for(&drain_calls(&backend), window), + 0, + "no redirect, no backing" + ); +} + +#[test] +fn unredirect_of_hidden_mapped_window_restores_participation_without_backing() { + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + let frame = ResourceId(0x0600_0030); + let window = ResourceId(0x0600_0031); + seed_window(&mut state, frame, crate::resources::ROOT_WINDOW, 64, 48); + seed_window(&mut state, window, frame, 32, 24); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, window); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); + storage_redirect(&mut state, &mut backend, 1, window); + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, frame); + drain_calls(&backend); + storage_redirect(&mut state, &mut backend, 3, window); + let calls = drain_calls(&backend); + assert_eq!( + last_participation(&calls, window), + Some(true), + "mapped window rejoins the scene" + ); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, frame); + assert_eq!(allocations_for(&drain_calls(&backend), window), 0); +} + +#[test] +fn destroy_of_redirected_window_still_releases_backing_and_record() { + let (mut state, mut backend, window, backing) = storage_redirected_top_level(); + drain_calls(&backend); + storage_window_req(&mut state, &mut backend, 4, window); // DestroyWindow + let calls = drain_calls(&backend); + assert!(released(&calls, backing)); + assert!(state.composite_redirects.window_mode(window).is_none()); +} + +#[test] +fn destroy_of_unmapped_redirected_window_drops_the_record() { + let (mut state, mut backend, window, _backing) = storage_redirected_top_level(); + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); + storage_window_req(&mut state, &mut backend, 4, window); + assert!(state.composite_redirects.window_mode(window).is_none()); +} + +#[test] +fn reparent_under_unmapped_parent_frees_backing_keeps_redirect() { + let (mut state, mut backend, window, backing) = storage_redirected_top_level(); + let hidden_parent = ResourceId(0x0600_0040); + seed_window( + &mut state, + hidden_parent, + crate::resources::ROOT_WINDOW, + 64, + 48, + ); + drain_calls(&backend); + dispatch_reparent_window(&mut state, &mut backend, window, hidden_parent, 0, 0); + assert!(released(&drain_calls(&backend), backing)); + assert_eq!(backing_of(&state, window), None); + assert!(state.composite_redirects.window_mode(window).is_some()); + storage_window_req(&mut state, &mut backend, MAP_WINDOW, hidden_parent); + assert_eq!(allocations_for(&drain_calls(&backend), window), 1); +} + +#[test] +fn unmap_severs_named_pixmaps_from_the_window() { + let (mut state, mut backend, window, backing) = storage_redirected_top_level(); + let named = ResourceId(0x0600_0050); + if let Some(w) = state.resources.window_mut(window) { + w.composite_named_pixmaps + .push(crate::resources::NamedCompositePixmap { + client_pixmap: named, + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(backing), + width: 64, + height: 48, + }); + } + storage_window_req(&mut state, &mut backend, UNMAP_WINDOW, window); + assert!( + state + .resources + .window(window) + .unwrap() + .composite_named_pixmaps + .is_empty() + ); + assert_eq!( + render_picture_damage_drawable(&state, named), + named, + "no longer the window's" + ); +} + +#[test] +fn reparent_between_redirected_parents_with_different_modes_flips_mode() { + // Phase 2: when both old_parent and new_parent have + // RedirectSubwindows but with different modes (Manual ↔ + // Automatic), the production reconciliation calls + // flip_redirect_target_mode. That helper preserves the + // backing handle (X Composite spec: old named pixmaps remain + // allocated until FreePixmap; only redirectDraw flips) and + // updates the window's own scene_participating flag per the + // new mode (Manual ⇒ false, Automatic ⇒ true). + let mut state = make_test_state(); + let mut backend = crate::backend::recording::RecordingBackend::new().with_redirect_activation(); + + let root_xid = crate::resources::ROOT_WINDOW; + let parent_manual_xid = ResourceId(0x500_0001); + let parent_automatic_xid = ResourceId(0x500_0002); + let target_xid = ResourceId(0x500_0010); + + state + .composite_redirects + .redirect_subwindows( + parent_manual_xid, + state.resources.children(parent_manual_xid), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: ClientId(14), + }, + ) + .unwrap(); + state + .composite_redirects + .redirect_subwindows( + parent_automatic_xid, + state.resources.children(parent_automatic_xid), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Automatic, + owner: ClientId(14), + }, + ) + .unwrap(); + + seed_window(&mut state, parent_manual_xid, root_xid, 100, 100); + seed_window(&mut state, parent_automatic_xid, root_xid, 100, 100); + // target is initially a child of parent_manual_xid → inherits + // Manual redirect → has a backing allocated, and its own + // scene_participating is false (Manual semantics). + seed_window(&mut state, target_xid, parent_manual_xid, 50, 50); + seed_redirected_window(&mut state, &mut backend, target_xid); + + let backing_before = state + .resources + .window(target_xid) + .unwrap() + .redirected_backing + .as_ref() + .map(|b| b.host_pixmap); + assert!( + backing_before.is_some(), + "pre: target has Manual-inherited backing" + ); + + // Reparent to the Automatic parent. + dispatch_reparent_window( + &mut state, + &mut backend, + target_xid, + parent_automatic_xid, + 0, + 0, + ); + + let backing_after = state + .resources + .window(target_xid) + .unwrap() + .redirected_backing + .as_ref() + .map(|b| b.host_pixmap); + assert_eq!( + backing_before, backing_after, + "mode-flip across redirected parents preserves the backing handle (X Composite spec)" + ); + + // Mode flip side effect: scene_participating flag on the + // window itself follows the new parent's mode. The flip is + // visible in the RecordingBackend's call log — look for a + // SetWindowSceneParticipation(_, true) for target's host xid + // (Automatic ⇒ participating=true; pre-reparent it was + // false under Manual). + let calls = backend.calls.lock().expect("calls poisoned"); + let saw_participation_true = calls.iter().any(|c| { + matches!( + c, + crate::backend::recording::RecordedCall::SetWindowSceneParticipation { + participating: true, + .. + } + ) + }); + assert!( + saw_participation_true, + "expected SetWindowSceneParticipation(_, true) after Manual → Automatic flip; \ + got {:?}", + *calls, + ); +} + +// ---------------- inhibitBGPaint ---------------- + +const INHIBIT_APP: u32 = 1; +const INHIBIT_COMP: u32 = 2; +const INHIBIT_W: u32 = 0x0010_0001; + +/// Root's subwindows Manual-redirected by `INHIBIT_COMP`, which holds a +/// NonEmpty Damage on root; `INHIBIT_W` (100x100 at 0,0, client +/// `INHIBIT_APP`) mapped under it; the app selects Expose on root. +fn manual_root_fixture() -> ( + ServerState, + RecordingBackend, + std::os::unix::net::UnixStream, + std::os::unix::net::UnixStream, +) { + use crate::server::DamageObject; + use yserver_protocol::x11::damage as x11damage; + let mut state = ServerState::new(); + let app = install_client(&mut state, INHIBIT_APP); + let comp = install_client(&mut state, INHIBIT_COMP); + let mut backend = RecordingBackend::new().with_redirect_activation(); + state.resources.window_mut(ROOT_WINDOW).unwrap().host_xid = + crate::backend::WindowHandle::from_raw(backend.window_id()); + create_root_child(&mut state, INHIBIT_W); + state + .resources + .window_mut(ResourceId(INHIBIT_W)) + .unwrap() + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + INHIBIT_W | 0x0040_0000, + )); + let _ = state.resources.map_window(ResourceId(INHIBIT_W)); + state + .clients + .get_mut(&INHIBIT_APP) + .unwrap() + .event_masks + .insert(ROOT_WINDOW, 0x0000_8000); + dispatch_composite_window_update( + &mut state, + &mut backend, + ClientId(INHIBIT_COMP), + 2, + ROOT_WINDOW.0, + 1, + ); + state.damage_objects.insert( + 0x0020_0001, + DamageObject { + owner: ClientId(INHIBIT_COMP), + drawable: ROOT_WINDOW, + level: x11damage::report_level::NON_EMPTY, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + backend.calls.lock().unwrap().clear(); + (state, backend, app, comp) +} + +fn root_fills(state: &ServerState, backend: &RecordingBackend) -> Vec<(i16, i16, u16, u16)> { + let root = state + .resources + .host_drawable_target(ROOT_WINDOW) + .expect("root has a host target") + .host_xid(); + backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::FillRectangle { + host_xid, + x, + y, + width, + height, + .. + } if *host_xid == root => Some((*x, *y, *width, *height)), + _ => None, + }) + .collect() +} + +fn root_exposes(peer: &mut std::os::unix::net::UnixStream) -> Vec<(u16, u16, u16, u16, u16)> { + let u16_at = |e: &[u8], at: usize| u16::from_le_bytes([e[at], e[at + 1]]); + read_all_available(peer) + .chunks_exact(32) + .filter(|e| e[0] & 0x7f == 12 && e[4..8] == ROOT_WINDOW.0.to_le_bytes()) + .map(|e| { + ( + u16_at(e, 8), + u16_at(e, 10), + u16_at(e, 12), + u16_at(e, 14), + u16_at(e, 16), + ) + }) + .collect() +} + +fn damage_event_count(peer: &mut std::os::unix::net::UnixStream) -> usize { + read_all_available(peer) + .chunks_exact(32) + .filter(|e| e[0] & 0x7f == crate::nested::DAMAGE_FIRST_EVENT) + .count() +} + +fn root_size(state: &ServerState) -> (u16, u16) { + let root = state.resources.window(ROOT_WINDOW).unwrap(); + (root.width, root.height) +} + +/// A window the compositor unredirected (fullscreen) clips root again, so +/// unmapping it exposes root. `miWindowExposures` still sends the Expose, +/// but `miPaintWindow` returns on `inhibitBGPaint` before painting +/// (`mi/miexpose.c:387-389`, `:435-436`): no paint, no damage. +#[test] +fn unmap_exposing_an_inhibited_root_paints_nothing_but_still_exposes() { + let (mut state, mut backend, mut app, mut comp) = manual_root_fixture(); + dispatch_composite_window_update( + &mut state, + &mut backend, + ClientId(INHIBIT_COMP), + 3, + INHIBIT_W, + 1, + ); + assert_eq!( + state.composite_redirects.window_mode(ResourceId(INHIBIT_W)), + None + ); + let _ = read_all_available(&mut comp); + let _ = read_all_available(&mut app); + backend.calls.lock().unwrap().clear(); + + handle_unmap_window( + &mut state, + &mut backend, + None, + ClientId(INHIBIT_APP), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 10, + minor: 0, + }, + &INHIBIT_W.to_le_bytes(), + ) + .expect("handle_unmap_window"); + + assert_eq!(root_fills(&state, &backend), []); + assert_eq!(damage_event_count(&mut comp), 0); + assert_eq!(root_exposes(&mut app), [(0, 0, 100, 100, 0)]); +} + +/// `compFreeClientSubwindows` clears `inhibitBGPaint` and calls +/// `ClearToBackground(pWin, 0, 0, 0, 0, TRUE)` before unredirecting the +/// children (`composite/compalloc.c:436-455`), so root's clip list still +/// treats them as transparent (`mi/mivaltree.c:171`): the whole root is +/// painted and exposed in one rect (`mi/miwindow.c:63-117`). +fn assert_whole_root_cleared_and_exposed( + state: &ServerState, + backend: &RecordingBackend, + app: &mut std::os::unix::net::UnixStream, +) { + let (width, height) = root_size(state); + assert_eq!(root_fills(state, backend), [(0, 0, width, height)]); + assert_eq!(root_exposes(app), [(0, 0, width, height, 0)]); +} + +#[test] +fn unredirect_subwindows_clears_and_exposes_the_whole_root() { + let (mut state, mut backend, mut app, _comp) = manual_root_fixture(); + let _ = read_all_available(&mut app); + dispatch_composite_window_update( + &mut state, + &mut backend, + ClientId(INHIBIT_COMP), + 4, + ROOT_WINDOW.0, + 1, + ); + assert!(state.composite_redirects.is_empty()); + assert_whole_root_cleared_and_exposed(&state, &backend, &mut app); +} + +#[test] +fn compositor_disconnect_clears_and_exposes_the_whole_root() { + let (mut state, mut backend, mut app, _comp) = manual_root_fixture(); + let _ = read_all_available(&mut app); + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(INHIBIT_COMP), + ); + assert!(state.composite_redirects.is_empty()); + assert_whole_root_cleared_and_exposed(&state, &backend, &mut app); +} + +/// With the overlay up, root's clip list is empty when the redirect goes; +/// the overlay's teardown then exposes root through `DeleteWindow`'s +/// `UnmapWindow` (`dix/window.c:2856-2866`), now uninhibited, so root is +/// painted wherever the unredirected `W` does not cover it. +#[test] +fn compositor_disconnect_with_overlay_repaints_root_when_the_overlay_goes() { + let (mut state, mut backend, mut app, _comp) = manual_root_fixture(); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(INHIBIT_COMP), + 2, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &ROOT_WINDOW.0.to_le_bytes(), + ); + assert!(backend.cow_materialized); + let _ = read_all_available(&mut app); + backend.calls.lock().unwrap().clear(); + + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(INHIBIT_COMP), + ); + + assert!(!backend.cow_materialized); + let (width, height) = root_size(&state); + let painted: u32 = root_fills(&state, &backend) + .iter() + .map(|(_, _, w, h)| u32::from(*w) * u32::from(*h)) + .sum(); + assert_eq!(painted, u32::from(width) * u32::from(height) - 100 * 100); + let exposed: u32 = root_exposes(&mut app) + .iter() + .map(|(_, _, w, h, _)| u32::from(*w) * u32::from(*h)) + .sum(); + assert_eq!(exposed, painted); +} + +/// `ProcClearToBackground` → `miClearToBackground` → `miPaintWindow`, +/// which returns on `inhibitBGPaint` (`dix/dispatch.c:1711`, +/// `mi/miwindow.c:113-116`, `mi/miexpose.c:435-436`). +#[test] +fn clear_area_on_an_inhibited_root_paints_nothing() { + let (mut state, mut backend, _app, mut comp) = manual_root_fixture(); + let _ = read_all_available(&mut comp); + let body = [ + ROOT_WINDOW.0.to_le_bytes().as_slice(), + &[0, 0, 0, 0, 0, 0, 0, 0], + ] + .concat(); + crate::core_loop::process_request::drawing::handle_clear_area( + &mut state, + &mut backend, + None, + ClientId(INHIBIT_APP), + SequenceNumber(2), + RequestHeader { + opcode: 61, + data: 0, + length_units: 4, + }, + &body, + ) + .expect("handle_clear_area"); + assert_eq!(root_fills(&state, &backend), []); + assert_eq!(damage_event_count(&mut comp), 0); +} + +/// `miResizeWindow` on a redirected W (mi/miwindow.c:342-620, +/// composite/compalloc.c:670-712, composite/compwindow.c:489-528): the +/// pixmap is reallocated first, W's content copied from OLD, then the +/// gravity-moved children carried from OLD, and only then is OLD freed. +#[test] +fn resize_call_order_matches_xorg() { + use crate::backend::recording::RecordedCall; + const W: u32 = 0x0010_0071; + const W_HOST: u32 = 0x0040_0071; + const C: u32 = 0x0010_0072; + const C_HOST: u32 = 0x0040_0072; + const OLD: u32 = 0x0050_0071; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for (xid, parent, x, y, size, bw, gravity) in [ + (W, crate::resources::ROOT_WINDOW, 0, 0, 100, 0, None), + (C, ResourceId(W), 60, 60, 30, 3, Some(9u8)), // SouthEast + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent, + x, + y, + width: size, + height: size, + border_width: bw, + class: 1, + visual: crate::resources::ROOT_VISUAL, + win_gravity: gravity, + ..Default::default() + }, + ); + } + for (xid, host) in [(W, W_HOST), (C, C_HOST)] { + let w = state.resources.window_mut(ResourceId(xid)).expect("window"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(host)); + w.map_state = MapState::Viewable; + } + state + .resources + .window_mut(ResourceId(W)) + .expect("W") + .redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD), + width: 100, + height: 100, + depth: 24, + }); + + let mut body = Vec::new(); + body.extend_from_slice(&W.to_le_bytes()); + body.extend_from_slice(&0x000Cu16.to_le_bytes()); // width | height + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&200u32.to_le_bytes()); + body.extend_from_slice(&200u32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 12, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("ConfigureWindow"); + + let calls = backend.calls(); + let pos = |f: &dyn Fn(&RecordedCall) -> bool| calls.iter().position(f); + let cfg = pos( + &|c| matches!(c, RecordedCall::ConfigureSubwindow { host_xid, .. } if *host_xid == W_HOST), + ) + .expect("configure W"); + let realloc = + pos(&|c| matches!(c, RecordedCall::ReallocateRedirectedBacking { old, .. } if *old == OLD)) + .expect("reallocate"); + let copy = + pos(&|c| matches!(c, RecordedCall::CopyArea { src_host_xid, .. } if *src_host_xid == OLD)) + .expect("content copy from OLD"); + let carry = pos(&|c| { + matches!(c, RecordedCall::MoveSubwindowsForGravity { moves, carry_from } + if *carry_from == Some(OLD) && moves == &vec![(C_HOST, 160, 160)]) + }) + .expect("gravity carry from OLD"); + let drop = pos(&|c| matches!(c, RecordedCall::DropBackingStorage(x) if *x == OLD)) + .expect("OLD dropped"); + assert!( + cfg < realloc && realloc < copy && copy < carry && carry < drop, + "configure < realloc < copy < carry < drop: {calls:?}" + ); +} + +/// A failed reallocation leaves W on OLD: its record still names OLD, +/// the rotate retain is dropped again, and nothing copies from OLD. +#[test] +fn a_failed_reallocation_keeps_the_old_backing() { + use crate::backend::recording::RecordedCall; + let (mut state, mut backend, old_backing) = redirected_window_fixture(100, 50, 0); + backend.reallocate_fails = true; + let old = rotate_redirected_backing_on_resize( + &mut state, + &mut backend, + None, + ResourceId(ROTATE_WINDOW_XID), + 100, + 75, + false, + 0, + ); + assert_eq!(old, None); + let backing = state + .resources + .window(ResourceId(ROTATE_WINDOW_XID)) + .and_then(|w| w.redirected_backing) + .expect("still redirected"); + assert_eq!(backing.host_pixmap.as_raw(), old_backing); + let calls = backend.calls(); + assert!( + calls.contains(&RecordedCall::DropBackingStorage(old_backing)), + "{calls:?}" + ); + assert!( + !calls + .iter() + .any(|c| matches!(c, RecordedCall::CopyArea { .. })), + "{calls:?}" + ); +} + +/// C: a grow reveals the rest of a bordered child's ring. Xorg paints it +/// with `PW_BORDER` and reports it on W (`80,80 58x58` covers it). +#[test] +fn a_grow_paints_and_damages_a_childs_revealed_border() { + use crate::{backend::recording::RecordedCall, server::DamageObject}; + use yserver_protocol::x11::xfixes::RegionRect; + const W: u32 = 0x0010_0081; + const W_HOST: u32 = 0x0040_0081; + const C: u32 = 0x0010_0082; + const C_HOST: u32 = 0x0040_0082; + const OLD: u32 = 0x0050_0081; + const DMG: u32 = 0x0080_0081; + let r = |x, y, width, height| RegionRect { + x, + y, + width, + height, + }; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for (xid, parent, x, y, size, bw) in [ + (W, crate::resources::ROOT_WINDOW, 300, 300, 100, 0), + (C, ResourceId(W), 80, 80, 50, 4), + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent, + x, + y, + width: size, + height: size, + border_width: bw, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + for (xid, host) in [(W, W_HOST), (C, C_HOST)] { + let w = state.resources.window_mut(ResourceId(xid)).expect("window"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(host)); + w.map_state = MapState::Viewable; + } + state + .composite_redirects + .redirect_window( + ResourceId(W), + crate::server::RedirectRecord { + owner: ClientId(1), + mode: crate::server::CompositeRedirectMode::Manual, + }, + ) + .unwrap(); + state + .resources + .window_mut(ResourceId(W)) + .expect("W") + .redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(OLD), + width: 100, + height: 100, + depth: 24, + }); + state.damage_objects.insert( + DMG, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(W), + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::new(); + body.extend_from_slice(&W.to_le_bytes()); + body.extend_from_slice(&0x000Cu16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&200u32.to_le_bytes()); + body.extend_from_slice(&200u32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 12, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("ConfigureWindow"); + + let ring = vec![ + r(16, -4, 38, 4), + r(50, 0, 4, 16), + r(-4, 16, 4, 34), + r(50, 16, 4, 34), + r(-4, 50, 58, 4), + ]; + let calls = backend.calls(); + assert!( + calls.contains(&RecordedCall::PaintWindowBorderRects { + host_xid: C_HOST, + rects: ring.clone(), + }), + "{calls:?}" + ); + let in_w = crate::core_loop::clip_list::translate(ring, 84, 84); + let damaged = &state.damage_objects[&DMG].rects; + assert!( + crate::core_loop::clip_list::subtract(&in_w, damaged).is_empty(), + "W's damage {damaged:?} must cover C's revealed ring" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/core_misc.rs b/crates/yserver-core/src/core_loop/process_request/tests/core_misc.rs new file mode 100644 index 000000000..a682a43d6 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/core_misc.rs @@ -0,0 +1,2552 @@ +use super::*; +use crate::core_loop::process_request::misc::{advertised_extension_names, extension_query_reply}; + +fn named_color_body(name: &[u8]) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&0x2000_0001u32.to_le_bytes()); // cmap + body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0, 0]); // pad + body.extend_from_slice(name); + body +} + +fn free_colors_body(cmap: u32, plane_mask: u32, pixels: &[u32]) -> Vec { + let mut body = Vec::with_capacity(8 + pixels.len() * 4); + body.extend_from_slice(&cmap.to_le_bytes()); + body.extend_from_slice(&plane_mask.to_le_bytes()); + for pixel in pixels { + body.extend_from_slice(&pixel.to_le_bytes()); + } + body +} + +fn dispatch_free_colors(cmap: u32, plane_mask: u32, pixels: &[u32]) -> Vec { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = free_colors_body(cmap, plane_mask, pixels); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(0x1234), + RequestHeader { + opcode: 88, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + assert!( + matches!(outcome, RequestOutcome::Handled), + "unexpected outcome: {outcome:?}" + ); + read_all_available(&mut peer) +} + +fn assert_free_colors_error(error: &[u8], code: u8, bad_value: u32) { + assert_eq!(error.len(), 32, "one fixed-size X11 error"); + assert_eq!(error[0], 0, "Error"); + assert_eq!(error[1], code); + assert_eq!(&error[2..4], &0x1234u16.to_le_bytes()); + assert_eq!(&error[4..8], &bad_value.to_le_bytes()); + assert_eq!(error[10], 88, "major opcode"); +} + +#[test] +fn free_colors_is_dispatched_as_a_successful_core_request() { + let output = dispatch_free_colors( + crate::resources::ROOT_COLORMAP.0, + 0, + &[0x00aa_bbcc, 0x0011_2233], + ); + assert!(output.is_empty(), "successful FreeColors is a void request"); +} + +#[test] +fn free_colors_accepts_valid_nonzero_plane_mask() { + let output = dispatch_free_colors( + crate::resources::ROOT_COLORMAP.0, + 0x0000_000f, + &[0x0011_2230], + ); + assert!(output.is_empty()); +} + +#[test] +fn free_colors_empty_pixel_list_ignores_outside_plane_mask() { + let output = dispatch_free_colors(crate::resources::ROOT_COLORMAP.0, 0xff00_0000, &[]); + assert!(output.is_empty()); +} + +#[test] +fn free_colors_argb_visual_accepts_alpha_bits() { + let output = dispatch_free_colors( + crate::resources::ARGB_COLORMAP.0, + 0x0f00_0000, + &[0xf011_2233], + ); + assert!(output.is_empty()); +} + +#[test] +fn free_colors_outside_plane_mask_returns_bad_value() { + let error = dispatch_free_colors( + crate::resources::ROOT_COLORMAP.0, + 0xff00_0000, + &[0x0011_2233], + ); + assert_free_colors_error(&error, x11::error::BAD_VALUE, 0xff11_2233); +} + +#[test] +fn free_colors_outside_pixel_bits_return_bad_value() { + let error = dispatch_free_colors(crate::resources::ROOT_COLORMAP.0, 0, &[0x8011_2233]); + assert_free_colors_error(&error, x11::error::BAD_VALUE, 0x8011_2233); +} + +#[test] +fn free_colors_unknown_colormap_returns_bad_colormap() { + let error = dispatch_free_colors(0xdead_beef, 0, &[0]); + assert_free_colors_error(&error, x11::error::BAD_COLORMAP, 0xdead_beef); +} + +#[test] +fn alloc_named_color_unknown_name_returns_bad_name() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = named_color_body(b"definitelynotacolor"); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 85, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); + assert_eq!(bytes[1], x11::error::BAD_NAME, "code"); + assert_eq!(bytes[10], 85, "major opcode"); +} + +#[test] +fn lookup_color_unknown_name_returns_bad_name() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = named_color_body(b"definitelynotacolor"); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 92, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); + assert_eq!(bytes[1], x11::error::BAD_NAME, "code"); + assert_eq!(bytes[10], 92, "major opcode"); +} + +#[test] +fn x_resource_query_clients_lists_connected_clients() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let _peer2 = install_client(&mut state, 2); + { + let c = state.clients.get_mut(&1).unwrap(); + c.resource_id_base = 0x0040_0000; + c.resource_id_mask = 0x001f_ffff; + } + { + let c = state.clients.get_mut(&2).unwrap(); + c.resource_id_base = 0x0080_0000; + c.resource_id_mask = 0x001f_ffff; + } + let mut backend = RecordingBackend::new(); + // X-Resource major op 149, QueryClients minor 1. + let header = RequestHeader { + opcode: 149, + data: 1, + length_units: 1, + }; + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[], + None, + ) + .expect("process_request"); + let bytes = read_all_available(&mut peer); + // 32-byte header + 2 clients × 8 bytes. + assert_eq!(bytes.len(), 48, "two clients listed: {bytes:02x?}"); + assert_eq!(&bytes[8..12], &2u32.to_le_bytes(), "num_clients"); + // Sorted by client id: client 1 then client 2. + assert_eq!(&bytes[32..36], &0x0040_0000u32.to_le_bytes(), "c1 base"); + assert_eq!(&bytes[36..40], &0x001f_ffffu32.to_le_bytes(), "c1 mask"); + assert_eq!(&bytes[40..44], &0x0080_0000u32.to_le_bytes(), "c2 base"); + assert_eq!(&bytes[44..48], &0x001f_ffffu32.to_le_bytes(), "c2 mask"); +} + +#[test] +fn x_resource_query_client_resources_counts_by_type() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + { + let c = state.clients.get_mut(&1).unwrap(); + c.resource_id_base = 0x0040_0000; + c.resource_id_mask = 0x001f_ffff; + } + // Client 1 owns 2 GCs + 1 font. + state + .resources + .seed_gc_for_test(ClientId(1), ResourceId(0x0040_0001)); + state + .resources + .seed_gc_for_test(ClientId(1), ResourceId(0x0040_0002)); + state + .resources + .seed_font_for_test(ClientId(1), ResourceId(0x0040_0003)); + + let mut backend = RecordingBackend::new(); + // QueryClientResources (minor 2), xid = the client's resource base. + let xid = 0x0040_0000u32; + let header = RequestHeader { + opcode: 149, + data: 2, + length_units: 2, + }; + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &xid.to_le_bytes(), + None, + ) + .expect("process_request"); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "got {bytes:02x?}"); + let num_types = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize; + assert_eq!( + bytes.len(), + 32 + num_types * 8, + "reply size matches num_types" + ); + // Resolve each returned type atom back to its name — proves the + // canonical strings, not just the counts. + let mut found = std::collections::HashMap::new(); + for i in 0..num_types { + let off = 32 + i * 8; + let atom = u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap()); + let count = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()); + let name = state + .atoms + .name(x11::AtomId(atom)) + .unwrap_or("?") + .to_string(); + found.insert(name, count); + } + assert_eq!(found.get("GC"), Some(&2), "GC count; found={found:?}"); + assert_eq!(found.get("FONT"), Some(&1), "FONT count; found={found:?}"); + assert!( + !found.contains_key("WINDOW"), + "zero-count types omitted; found={found:?}" + ); +} + +#[test] +fn x_resource_query_client_pixmap_bytes_reports_padded_storage() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let _peer2 = install_client(&mut state, 2); + state.clients.get_mut(&1).unwrap().resource_id_base = 0x0040_0000; + state.clients.get_mut(&1).unwrap().resource_id_mask = 0x001f_ffff; + state.clients.get_mut(&2).unwrap().resource_id_base = 0x0080_0000; + state.clients.get_mut(&2).unwrap().resource_id_mask = 0x001f_ffff; + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: ResourceId(0x0040_0001), + drawable: ROOT_WINDOW, + width: 33, + height: 2, + depth: 1, + }, + ); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: ResourceId(0x0040_0002), + drawable: ROOT_WINDOW, + width: 3, + height: 2, + depth: 24, + }, + ); + state.resources.create_pixmap( + ClientId(2), + CreatePixmapRequest { + pixmap: ResourceId(0x0080_0001), + drawable: ROOT_WINDOW, + width: 100, + height: 100, + depth: 32, + }, + ); + let mut backend = RecordingBackend::new(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(7), + RequestHeader { + opcode: 149, + data: 3, + length_units: 2, + }, + &0x0040_0000u32.to_le_bytes(), + None, + ) + .expect("QueryClientPixmapBytes"); + + let reply = read_all_available(&mut peer); + assert_eq!(reply.len(), 32); + // depth-1: 33 bits -> 8-byte padded row * 2 = 16. + // depth-24: 3 pixels * 4 bytes * 2 = 24. Total = 40. + assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), 40); + assert_eq!(u32::from_le_bytes(reply[12..16].try_into().unwrap()), 0); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(8), + RequestHeader { + opcode: 149, + data: 3, + length_units: 2, + }, + &0x00f0_0000u32.to_le_bytes(), + None, + ) + .expect("reject unknown client range"); + let error = read_all_available(&mut peer); + assert_eq!(error[1], x11::error::BAD_VALUE); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + 0x00f0_0000 + ); +} + +#[test] +fn x_resource_query_client_ids_omits_pid_for_nonlocal_client() { + use yserver_protocol::x11::x_resource as x11xres; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // A TCP peer carries no credentials. + state.clients.get_mut(&1).unwrap().peer.cred = None; + let mut backend = RecordingBackend::new(); + let mut body = 1u32.to_le_bytes().to_vec(); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&x11xres::LOCAL_CLIENT_PID_MASK.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 149, + data: x11xres::QUERY_CLIENT_IDS, + length_units: 4, + }, + &body, + None, + ) + .unwrap(); + let reply = read_all_available(&mut peer); + assert_eq!( + u32::from_le_bytes(reply[8..12].try_into().unwrap()), + 0, + "a client without peer credentials has no LocalClientPID" + ); + assert_eq!(reply.len(), 32); +} + +#[test] +fn x_resource_query_client_ids_reports_xid_and_pid_identities() { + use yserver_protocol::x11::x_resource as x11xres; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let _peer2 = install_client(&mut state, 2); + state.clients.get_mut(&1).unwrap().resource_id_base = 0x0040_0000; + state.clients.get_mut(&1).unwrap().resource_id_mask = 0x001f_ffff; + state.clients.get_mut(&2).unwrap().resource_id_base = 0x0080_0000; + state.clients.get_mut(&2).unwrap().resource_id_mask = 0x001f_ffff; + let mut backend = RecordingBackend::new(); + let query = |mask: u32| { + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&1u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // all clients + body.extend_from_slice(&mask.to_le_bytes()); + body + }; + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(9), + RequestHeader { + opcode: 149, + data: x11xres::QUERY_CLIENT_IDS, + length_units: 4, + }, + &query(x11xres::CLIENT_XID_MASK), + None, + ) + .expect("QueryClientIds XIDs"); + let reply = read_all_available(&mut peer); + assert_eq!(reply.len(), 56); + assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), 2); + assert_eq!( + u32::from_le_bytes(reply[32..36].try_into().unwrap()), + 0x0040_0000 + ); + assert_eq!(u32::from_le_bytes(reply[36..40].try_into().unwrap()), 1); + assert_eq!(u32::from_le_bytes(reply[40..44].try_into().unwrap()), 0); + assert_eq!( + u32::from_le_bytes(reply[44..48].try_into().unwrap()), + 0x0080_0000 + ); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(10), + RequestHeader { + opcode: 149, + data: x11xres::QUERY_CLIENT_IDS, + length_units: 4, + }, + &query(x11xres::LOCAL_CLIENT_PID_MASK), + None, + ) + .expect("QueryClientIds PID-only"); + // A PID-only spec suppresses the XID identity and yields one + // LocalClientPID entry per client. Sizes derived from Xorg's encoder + // (Xext/xres.c `ConstructClientIdValue`): a pid entry is the 12-byte + // header plus one value word, `rep.length = 4` counted in BYTES, and + // `num_ids` counts ENTRIES. Two clients => 2*16 = 32 body bytes, so + // reply length = 32/4 = 8 and the whole reply is 64 bytes. + let pids = read_all_available(&mut peer); + assert_eq!(pids.len(), 64); + assert_eq!(u32::from_le_bytes(pids[4..8].try_into().unwrap()), 8); + assert_eq!(u32::from_le_bytes(pids[8..12].try_into().unwrap()), 2); + // The fixture gives both test clients this process's pid; the + // OS call itself is tested in `peer.rs`. + let self_pid = std::process::id(); + for (i, base) in [0x0040_0000u32, 0x0080_0000].into_iter().enumerate() { + let at = 32 + i * 16; + assert_eq!( + u32::from_le_bytes(pids[at..at + 4].try_into().unwrap()), + base, + "entry {i} client", + ); + assert_eq!( + u32::from_le_bytes(pids[at + 4..at + 8].try_into().unwrap()), + x11xres::LOCAL_CLIENT_PID_MASK, + "entry {i} mask", + ); + assert_eq!( + u32::from_le_bytes(pids[at + 8..at + 12].try_into().unwrap()), + 4, + "entry {i} length is in bytes", + ); + assert_eq!( + u32::from_le_bytes(pids[at + 12..at + 16].try_into().unwrap()), + self_pid, + "entry {i} pid", + ); + } +} + +#[test] +fn no_operation_returns_handled() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(7), + RequestHeader { + opcode: 127, + data: 0, + length_units: 1, + }, + &[], + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); +} + +#[test] +fn get_input_focus_writes_reply_through_client_io() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 43, + data: 0, + length_units: 1, + }, + &[], + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); + + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + // Reply opcode is 1 (Reply), sequence in bytes 2..4 little-endian. + assert_eq!(buf[0], 1); + assert_eq!(u16::from_le_bytes([buf[2], buf[3]]), 3); +} + +/// Regression (codex review #1): a grab/ungrab focus transition +/// whose grab window is ALREADY the focus (from == to) must still +/// emit FocusOut+FocusIn(NotifyNonlinear, NotifyGrab) on that +/// window. Xorg DoFocusEvents only short-circuits same-window +/// moves for NON-grab modes (dix/enterleave.c:1557); pre-fix +/// yserver dropped these whenever the grab window held the focus. +#[test] +fn same_window_grab_focus_emits_nonlinear_pair() { + use yserver_protocol::x11::CreateWindowRequest; + + const CLIENT: u32 = 71; + const WIN: u32 = 0x0370_0006; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .clients + .get_mut(&CLIENT) + .unwrap() + .event_masks + .insert(ResourceId(WIN), FOCUS_CHANGE_MASK); + state.core_focus.raw = WIN; + + // GrabKeyboard on WIN while WIN is already the focus → mode 1. + emit_core_focus_transition(&mut state, WIN, WIN, 1); + + let bytes = read_all_available(&mut peer); + assert!( + bytes.len() >= 64, + "expected FocusOut + FocusIn (got {} bytes)", + bytes.len() + ); + assert_eq!(bytes[0], 10, "first event FocusOut"); + assert_eq!(bytes[1], 3, "FocusOut detail NotifyNonlinear"); + assert_eq!(bytes[8], 1, "FocusOut mode NotifyGrab"); + assert_eq!(bytes[32], 9, "second event FocusIn"); + assert_eq!(bytes[33], 3, "FocusIn detail NotifyNonlinear"); + assert_eq!(bytes[40], 1, "FocusIn mode NotifyGrab"); +} + +/// GH #59 regression: a core SetInputFocus issued WHILE a keyboard +/// grab is active must report the focus transition as +/// NotifyWhileGrabbed (mode 3), not NotifyNormal (0) — Xorg +/// dix/events.c:4923. bspwm focuses a newly-mapped window while +/// sxhkd's synchronous passive key grab is still active; emitting +/// NotifyNormal there made GLFW/kitty believe it had genuinely taken +/// focus mid-grab and then ignore every typed key (the KeyPress +/// events still routed correctly to its window). Mirrors the gate +/// already present in `revert_core_focus_from`. +#[test] +fn set_input_focus_during_keyboard_grab_is_notify_while_grabbed() { + use crate::server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}; + use yserver_protocol::x11::CreateWindowRequest; + + const CLIENT: u32 = 71; + const WIN_A: u32 = 0x0071_0001; // currently focused + const WIN_B: u32 = 0x0071_0002; // focus target + + let make = |state: &mut ServerState, win: u32| { + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + }; + + // mode 3 (NotifyWhileGrabbed) when a keyboard grab is active, + // mode 0 (NotifyNormal) otherwise — run both in one test. + for (grab_active, want_mode) in [(true, 3u8), (false, 0u8)] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + make(&mut state, WIN_A); + make(&mut state, WIN_B); + assert!( + state + .resources + .map_window(ResourceId(WIN_B)) + .mapping_changed + ); + { + let c = state.clients.get_mut(&CLIENT).unwrap(); + c.event_masks.insert(ResourceId(WIN_A), FOCUS_CHANGE_MASK); + c.event_masks.insert(ResourceId(WIN_B), FOCUS_CHANGE_MASK); + } + state.core_focus.raw = WIN_A; + if grab_active { + state.active_keyboard_grab = Some(ActiveKeyboardGrab { + owner: ClientId(CLIENT), + grab_window: ROOT_WINDOW, + owner_events: false, + source: ActiveKeyboardGrabSource::PassiveKey { keycode: 36 }, + via_xi2: false, + xi2_mask: 0, + }); + } + + let header = yserver_protocol::x11::RequestHeader { + opcode: 42, + data: 2, // RevertToParent + length_units: 3, + }; + let mut body = Vec::new(); + body.extend_from_slice(&WIN_B.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime + handle_set_input_focus( + &mut state, + ClientId(CLIENT), + SequenceNumber(1), + header, + &body, + ) + .expect("set input focus"); + + let bytes = read_all_available(&mut peer); + assert!( + bytes.len() >= 32, + "expected focus events (grab_active={grab_active}), got {} bytes", + bytes.len() + ); + // First event is the FocusOut on WIN_A; mode is byte 8. + assert_eq!(bytes[0] & 0x7f, 10, "first event must be FocusOut"); + assert_eq!( + bytes[8], want_mode, + "SetInputFocus with grab_active={grab_active} must emit mode {want_mode}" + ); + } +} + +#[test] +fn focus_move_to_child_uses_inferior_detail_for_parent_focus_out() { + use yserver_protocol::x11::CreateWindowRequest; + + const CLIENT: u32 = 52; + const TOP: u32 = 0x0350_0006; + const CHILD: u32 = 0x0350_0007; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(TOP), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD), + parent: ResourceId(TOP), + x: 10, + y: 10, + width: 100, + height: 40, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let client = state.clients.get_mut(&CLIENT).expect("client"); + client + .event_masks + .insert(ResourceId(TOP), FOCUS_CHANGE_MASK); + client + .event_masks + .insert(ResourceId(CHILD), FOCUS_CHANGE_MASK); + client + .xi2_masks + .insert((ResourceId(TOP), 3), (1 << 9) | (1 << 10)); + client + .xi2_masks + .insert((ResourceId(CHILD), 3), (1 << 9) | (1 << 10)); + + state.core_focus = crate::server::CoreFocus { + raw: TOP, + revert_to: 0, + time: 0, + }; + emit_core_focus_transition(&mut state, TOP, CHILD, 0); + state.core_focus.raw = CHILD; + let bytes = read_all_available(&mut peer); + + assert_eq!(bytes.len(), 216, "expected core + XI2 focus out/in"); + // Xorg DoFocusEvents: the core sequence first, then the XI2 one. + let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); + let half = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]); + assert_eq!(bytes[0], 10, "first event should be core FocusOut"); + assert_eq!(bytes[1], 2, "parent FocusOut should be NotifyInferior"); + assert_eq!(word(4), TOP); + assert_eq!(bytes[32], 9, "second event should be core FocusIn"); + assert_eq!(bytes[33], 0, "child FocusIn should be NotifyAncestor"); + assert_eq!(word(36), CHILD); + assert_eq!(bytes[64], 35, "third event should be XI2 GenericEvent"); + assert_eq!(half(72), 10, "XI2 FocusOut evtype"); + assert_eq!(bytes[83], 2, "XI2 parent FocusOut should be NotifyInferior"); + assert_eq!(word(88), TOP); + assert_eq!(bytes[140], 35, "fourth event should be XI2 GenericEvent"); + assert_eq!(half(148), 9, "XI2 FocusIn evtype"); + assert_eq!(bytes[159], 0, "XI2 child FocusIn should be NotifyAncestor"); + assert_eq!(word(164), CHILD); + assert_eq!( + state.core_focus.raw, CHILD, + "keyboard focus should track child" + ); +} + +#[test] +fn window_host_xid_prefers_resolved_host_mapping() { + use crate::backend::WindowHandle; + use yserver_protocol::x11::CreateWindowRequest; + + const CLIENT: u32 = 55; + const WIN: u32 = 0x0360_0008; + const HOST: u32 = 0x0400_1234; + + let mut state = ServerState::new(); + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 64, + height: 64, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(WIN)) + .unwrap() + .host_xid = WindowHandle::from_raw(HOST); + + assert_eq!(window_host_xid(&state, ResourceId(WIN)), HOST); +} + +#[test] +fn grab_server_tracks_owner_until_owner_ungrabs() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 36, + data: 0, + length_units: 1, + }, + &[], + None, + ) + .unwrap(); + assert_eq!(state.server_grab_owner, Some(ClientId(1))); + + // A direct non-owner call cannot steal or release the grab. In the + // real loop these requests are parked before dispatch. + handle_grab_server(&mut state, ClientId(2), SequenceNumber(3)).unwrap(); + handle_ungrab_server(&mut state, ClientId(2), SequenceNumber(4)).unwrap(); + assert_eq!(state.server_grab_owner, Some(ClientId(1))); + + handle_ungrab_server(&mut state, ClientId(1), SequenceNumber(5)).unwrap(); + assert_eq!(state.server_grab_owner, None); +} + +#[test] +fn get_motion_events_filters_and_translates_history() { + let request = |window: ResourceId, start: u32, stop: u32| { + let mut body = vec![0u8; 12]; + body[0..4].copy_from_slice(&window.0.to_le_bytes()); + body[4..8].copy_from_slice(&start.to_le_bytes()); + body[8..12].copy_from_slice(&stop.to_le_bytes()); + body + }; + + let mut state = ServerState::new(); + state.start_instant = std::time::Instant::now() - std::time::Duration::from_secs(1); + state.pointer_motion_history.extend([ + crate::server::PointerMotionRecord { + time: 500, + root_x: 100, + root_y: 50, + }, + crate::server::PointerMotionRecord { + time: 550, + root_x: 900, + root_y: 50, + }, + ]); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(8), + RequestHeader { + opcode: 39, + data: 0, + length_units: 4, + }, + &request(ROOT_WINDOW, 400, 600), + None, + ) + .unwrap(); + let mut reply = [0u8; 40]; + peer.read_exact(&mut reply).unwrap(); + assert_eq!(reply[0], 1); + assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), 1); + assert_eq!(u32::from_le_bytes(reply[32..36].try_into().unwrap()), 500); + assert_eq!(i16::from_le_bytes(reply[36..38].try_into().unwrap()), 100); + assert_eq!(i16::from_le_bytes(reply[38..40].try_into().unwrap()), 50); + + let missing = ResourceId(0x00ff_1234); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(9), + RequestHeader { + opcode: 39, + data: 0, + length_units: 4, + }, + &request(missing, 400, 600), + None, + ) + .unwrap(); + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[1], x11::error::BAD_WINDOW); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + missing.0 + ); + assert_eq!(error[10], 39); +} + +#[test] +fn xtest_compare_cursor_uses_window_and_current_cursor_state() { + const CURSOR_A: ResourceId = ResourceId(0x0010_1000); + const CURSOR_B: ResourceId = ResourceId(0x0010_1001); + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.resources.create_cursor(ClientId(1), CURSOR_A); + state.resources.create_cursor(ClientId(1), CURSOR_B); + state.resources.window_mut(ROOT_WINDOW).unwrap().cursor = Some(CURSOR_A); + let mut backend = RecordingBackend::new(); + let request = |cursor: ResourceId| { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&cursor.0.to_le_bytes()); + body + }; + let header = RequestHeader { + opcode: 146, + data: yserver_protocol::x11::xtest::COMPARE_CURSOR, + length_units: 3, + }; + + for (sequence, cursor, expected) in [ + (1, CURSOR_A, true), + (2, CURSOR_B, false), + (3, ResourceId(1), true), // XTestCurrentCursor + ] { + handle_xtest_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(sequence), + header, + &request(cursor), + ) + .unwrap(); + let reply = read_all_available(&mut peer); + assert_eq!(reply[0], 1); + assert_eq!(reply[1], u8::from(expected)); + } + + let missing = ResourceId(0x0010_dead); + handle_xtest_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(4), + header, + &request(missing), + ) + .unwrap(); + let error = read_all_available(&mut peer); + assert_eq!(error[1], x11::error::BAD_CURSOR); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + missing.0 + ); +} + +#[test] +fn recolor_cursor_rejects_unknown_cursor() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let missing = ResourceId(0x00cc_1234); + let mut body = vec![0u8; 16]; + body[0..4].copy_from_slice(&missing.0.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(10), + RequestHeader { + opcode: 96, + data: 0, + length_units: 5, + }, + &body, + None, + ) + .unwrap(); + + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[1], x11::error::BAD_CURSOR); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + missing.0 + ); + assert_eq!(error[10], 96); +} + +#[test] +fn recolor_cursor_forwards_colors_to_backend() { + const CURSOR: u32 = 0x0010_1234; + const HOST_CURSOR: u32 = 0x00ab_cdef; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state + .resources + .create_cursor(ClientId(1), ResourceId(CURSOR)); + state.resources.set_cursor_host_xid( + ResourceId(CURSOR), + crate::backend::CursorHandle::from_raw_panicking(HOST_CURSOR), + ); + let mut backend = RecordingBackend::new(); + let fore: (u16, u16, u16) = (0x1122, 0x3344, 0x5566); + let back: (u16, u16, u16) = (0x7788, 0x99aa, 0xbbcc); + let mut body = vec![0u8; 16]; + body[0..4].copy_from_slice(&CURSOR.to_le_bytes()); + for (offset, value) in [fore.0, fore.1, fore.2, back.0, back.1, back.2] + .into_iter() + .enumerate() + { + let start = 4 + offset * 2; + body[start..start + 2].copy_from_slice(&value.to_le_bytes()); + } + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(11), + RequestHeader { + opcode: 96, + data: 0, + length_units: 5, + }, + &body, + None, + ) + .unwrap(); + + assert_eq!( + backend.calls.lock().unwrap().as_slice(), + [RecordedCall::RecolorCursor { + host_xid: HOST_CURSOR, + fore, + back, + }] + ); +} + +// ---- host access control: ChangeHosts / ListHosts / SetAccessControl ---- + +/// Run one core request from `client` and return what it wrote. +fn host_request( + state: &mut ServerState, + client: u32, + peer: &mut UnixStream, + sequence: u16, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + let mut backend = RecordingBackend::new(); + process_request( + state, + &mut backend, + ClientId(client), + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("request through core dispatcher"); + read_all_available(peer) +} + +/// ChangeHosts body after the header: `family, pad, length, address, pad`. +fn change_hosts_body(family: u8, addr: &[u8]) -> Vec { + let mut body = vec![family, 0]; + body.extend_from_slice(&u16::try_from(addr.len()).unwrap().to_le_bytes()); + body.extend_from_slice(addr); + body.resize(body.len().next_multiple_of(4), 0); + body +} + +fn change_hosts( + state: &mut ServerState, + peer: &mut UnixStream, + mode: u8, + family: u8, + addr: &[u8], +) -> Vec { + host_request( + state, + 1, + peer, + 20, + 109, + mode, + &change_hosts_body(family, addr), + ) +} + +fn list_hosts(state: &mut ServerState, client: u32, peer: &mut UnixStream) -> Vec { + host_request(state, client, peer, 0x0a0b, 110, 0, &[]) +} + +/// `(code, bad value, major opcode)`. +type HostError = (u8, u32, u8); + +/// The one error in `wire`. +fn host_error(wire: &[u8]) -> HostError { + assert_eq!(wire.len(), 32, "one error: {wire:?}"); + ( + read_error(wire), + u32::from_le_bytes(wire[4..8].try_into().unwrap()), + wire[10], + ) +} + +fn expected_host_error(sequence: u16, code: u8, value: u32, major: u8) -> [u8; 32] { + let mut expected = [0; 32]; + expected[1] = code; + expected[2..4].copy_from_slice(&sequence.to_le_bytes()); + expected[4..8].copy_from_slice(&value.to_le_bytes()); + expected[10] = major; + expected +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct RecordedServerCheck { + client: ClientId, + mode: crate::access::AccessMode, + request: Option, + peer: Option, + admission: Option, +} + +struct RecordingServerPolicy { + decision: crate::access::Decision, + calls: Arc>>, +} + +impl crate::access::AccessPolicy for RecordingServerPolicy { + fn server( + &self, + ctx: &crate::access::AccessContext<'_>, + client: ClientId, + mode: crate::access::AccessMode, + ) -> crate::access::Decision { + self.calls.lock().unwrap().push(RecordedServerCheck { + client, + mode, + request: ctx.request(), + peer: ctx.peer(client).copied(), + admission: ctx.admission(client).cloned(), + }); + self.decision + } +} + +struct RevocableServerPolicy(Arc); + +impl crate::access::AccessPolicy for RevocableServerPolicy { + fn server( + &self, + _ctx: &crate::access::AccessContext<'_>, + _client: ClientId, + _mode: crate::access::AccessMode, + ) -> crate::access::Decision { + if self.0.load(std::sync::atomic::Ordering::SeqCst) { + crate::access::Decision::Deny(crate::access::DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }) + } else { + crate::access::Decision::Allow + } + } +} + +/// `enabled = 1`, no hosts: what a fresh Xorg reports without `-ac` +/// (`dix/dispatch.c:3270-3304`, `os/access.c:956-962`). +const EMPTY_LIST_HOSTS_LE: [u8; 32] = [ + 1, 1, 0x0b, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, +]; + +#[test] +fn server_hook_denies_each_host_access_request() { + // Mutation: ignore a handler's policy denial; the exact error packet and unchanged state must fail. + let requests: [(u8, u8, Vec); 3] = [ + (110, 0, Vec::new()), + (109, 0, change_hosts_body(252, &[])), + (111, 0, Vec::new()), + ]; + + for (opcode, data, body) in requests { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: crate::access::Decision::Deny(crate::access::DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::new(Mutex::new(Vec::new())), + })); + + let sequence = 0x4567; + let wire = host_request(&mut state, 1, &mut peer, sequence, opcode, data, &body); + assert_eq!( + wire, + expected_host_error(sequence, x11::error::BAD_VALUE, 0x55, opcode), + "opcode {opcode} must report the policy's complete error packet" + ); + + state.host_access.policies.clear(); + assert_eq!( + list_hosts(&mut state, 1, &mut peer), + EMPTY_LIST_HOSTS_LE, + "opcode {opcode} must leave hosts and access mode unchanged" + ); + } +} + +#[test] +fn server_hook_asks_with_client_mode_and_context() { + // Mutation: pass READ for ChangeHosts; its recorded MANAGE mode must fail. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let expected_peer = state.clients[&1].peer; + let expected_admission = state.clients[&1].admission; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: crate::access::Decision::Allow, + calls: Arc::clone(&calls), + })); + + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); + assert!(change_hosts(&mut state, &mut peer, 0, 252, &[]).is_empty()); + assert!(host_request(&mut state, 1, &mut peer, 21, 111, 0, &[]).is_empty()); + + assert_eq!( + *calls.lock().unwrap(), + [ + RecordedServerCheck { + client: ClientId(1), + mode: crate::access::AccessMode::READ, + request: Some(crate::access::RequestOpcodes { + major: 110, + minor: 0, + }), + peer: Some(expected_peer), + admission: Some(expected_admission), + }, + RecordedServerCheck { + client: ClientId(1), + mode: crate::access::AccessMode::MANAGE, + request: Some(crate::access::RequestOpcodes { + major: 109, + minor: 0, + }), + peer: Some(expected_peer), + admission: Some(expected_admission), + }, + RecordedServerCheck { + client: ClientId(1), + mode: crate::access::AccessMode::MANAGE, + request: Some(crate::access::RequestOpcodes { + major: 111, + minor: 0, + }), + peer: Some(expected_peer), + admission: Some(expected_admission), + }, + ] + ); +} + +#[test] +fn invalid_mode_answers_before_the_hook_and_the_hook_before_locality() { + // Mutation: move the hook before mode validation or after the locality check; both boundaries fail. + let deny = crate::access::Decision::Deny(crate::access::DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }); + let requests = [(109, change_hosts_body(252, &[])), (111, Vec::new())]; + + for (opcode, body) in requests { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: deny, + calls: Arc::clone(&calls), + })); + + let invalid_mode = host_request(&mut state, 1, &mut peer, 20, opcode, 2, &body); + assert_eq!( + invalid_mode, + expected_host_error(20, x11::error::BAD_VALUE, 2, opcode) + ); + assert!(calls.lock().unwrap().is_empty()); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).unwrap().is_local = false; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: crate::access::Decision::Allow, + calls: Arc::clone(&calls), + })); + + let allowed_non_local = host_request(&mut state, 1, &mut peer, 20, opcode, 0, &body); + assert_eq!( + allowed_non_local, + expected_host_error(20, x11::error::BAD_ACCESS, 0, opcode) + ); + assert_eq!(calls.lock().unwrap().len(), 1); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).unwrap().is_local = false; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: deny, + calls: Arc::clone(&calls), + })); + + let denied_non_local = host_request(&mut state, 1, &mut peer, 20, opcode, 0, &body); + assert_eq!( + denied_non_local, + expected_host_error(20, x11::error::BAD_VALUE, 0x55, opcode) + ); + assert_eq!(calls.lock().unwrap().len(), 1); + } +} + +#[test] +fn several_policies_on_one_request() { + // Mutation: continue after a denial and accept a later Allow; deny-then-allow must stay denied. + let deny = crate::access::Decision::Deny(crate::access::DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }); + let later_deny = crate::access::Decision::Deny(crate::access::DenyError { + code: x11::error::BAD_ACCESS, + value: 0x66, + }); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let allow_calls = Arc::new(Mutex::new(Vec::new())); + let deny_calls = Arc::new(Mutex::new(Vec::new())); + let after_deny_calls = Arc::new(Mutex::new(Vec::new())); + for (decision, calls) in [ + (crate::access::Decision::Allow, Arc::clone(&allow_calls)), + (deny, Arc::clone(&deny_calls)), + (later_deny, Arc::clone(&after_deny_calls)), + ] { + state.install_access_policy(Arc::new(RecordingServerPolicy { decision, calls })); + } + let wire = list_hosts(&mut state, 1, &mut peer); + assert_eq!( + wire, + expected_host_error(0x0a0b, x11::error::BAD_VALUE, 0x55, 110) + ); + assert_eq!(allow_calls.lock().unwrap().len(), 1); + assert_eq!(deny_calls.lock().unwrap().len(), 1); + assert!(after_deny_calls.lock().unwrap().is_empty()); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let deny_calls = Arc::new(Mutex::new(Vec::new())); + let allow_calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: deny, + calls: Arc::clone(&deny_calls), + })); + state.install_access_policy(Arc::new(RecordingServerPolicy { + decision: crate::access::Decision::Allow, + calls: Arc::clone(&allow_calls), + })); + let wire = list_hosts(&mut state, 1, &mut peer); + assert_eq!( + wire, + expected_host_error(0x0a0b, x11::error::BAD_VALUE, 0x55, 110) + ); + assert_eq!(deny_calls.lock().unwrap().len(), 1); + assert!(allow_calls.lock().unwrap().is_empty()); +} + +#[test] +fn revocation_applies_from_the_next_check() { + // Mutation: skip the next ListHosts check after an Allow; revocation must make the second request fail. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let revoked = Arc::new(std::sync::atomic::AtomicBool::new(false)); + state.install_access_policy(Arc::new(RevocableServerPolicy(Arc::clone(&revoked)))); + + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); + revoked.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + list_hosts(&mut state, 1, &mut peer), + expected_host_error(0x0a0b, x11::error::BAD_VALUE, 0x55, 110) + ); +} + +#[test] +fn list_hosts_on_a_fresh_server_is_enabled_and_empty() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); +} + +#[test] +fn change_hosts_inserts_newest_first_and_list_hosts_encodes_them() { + let user = b"localuser\0#1000"; + let group = b"localgroup\0#1000"; + let mut expected_le = vec![1, 1, 0x0b, 0x0a, 10, 0, 0, 0, 2, 0]; + expected_le.extend_from_slice(&[0; 22]); + expected_le.extend_from_slice(&[5, 0, 16, 0]); + expected_le.extend_from_slice(group); + expected_le.extend_from_slice(&[5, 0, 15, 0]); + expected_le.extend_from_slice(user); + expected_le.push(0); + let mut expected_be = vec![1, 1, 0x0a, 0x0b, 0, 0, 0, 10, 0, 2]; + expected_be.extend_from_slice(&[0; 22]); + expected_be.extend_from_slice(&[5, 0, 0, 16]); + expected_be.extend_from_slice(group); + expected_be.extend_from_slice(&[5, 0, 0, 15]); + expected_be.extend_from_slice(user); + expected_be.push(0); + + for (byte_order, expected) in [ + (ClientByteOrder::LittleEndian, expected_le), + (ClientByteOrder::BigEndian, expected_be), + ] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).unwrap().byte_order = byte_order; + assert!(change_hosts(&mut state, &mut peer, 0, 5, user).is_empty()); + assert!(change_hosts(&mut state, &mut peer, 0, 5, group).is_empty()); + assert_eq!( + list_hosts(&mut state, 1, &mut peer), + expected, + "{byte_order:?}" + ); + } +} + +#[test] +fn local_host_entry_is_listed_once_and_deleted() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut one_entry = EMPTY_LIST_HOSTS_LE.to_vec(); + one_entry[4] = 1; // length + one_entry[8] = 1; // nHosts + one_entry.extend_from_slice(&[0xfc, 0, 0, 0]); + assert!(change_hosts(&mut state, &mut peer, 0, 252, &[]).is_empty()); + assert_eq!(list_hosts(&mut state, 1, &mut peer), one_entry); + assert!(change_hosts(&mut state, &mut peer, 0, 252, &[]).is_empty()); + assert_eq!(list_hosts(&mut state, 1, &mut peer), one_entry); + assert!(change_hosts(&mut state, &mut peer, 1, 252, &[]).is_empty()); + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); +} + +#[test] +fn host_requests_report_xorg_errors_and_change_nothing() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let unknown_user = b"localuser\0nosuchuser_305"; + let cases: [(u8, u8, &[u8], HostError); 6] = [ + (0, 5, b"foo\0bar", (x11::error::BAD_VALUE, 7, 109)), + ( + 0, + 5, + unknown_user, + ( + x11::error::BAD_VALUE, + u32::try_from(unknown_user.len()).unwrap(), + 109, + ), + ), + (0, 1, &[1, 2, 3, 4], (x11::error::BAD_VALUE, 4, 109)), + (0, 7, &[1, 2, 3, 4], (x11::error::BAD_VALUE, 7, 109)), + (0, 6, &[1, 2, 3, 4], (x11::error::BAD_VALUE, 4, 109)), + (2, 0, &[127, 0, 0, 1], (x11::error::BAD_VALUE, 2, 109)), + ]; + for (mode, family, addr, expected) in cases { + let wire = change_hosts(&mut state, &mut peer, mode, family, addr); + assert_eq!(host_error(&wire), expected, "mode {mode} family {family}"); + } + let wire = host_request(&mut state, 1, &mut peer, 21, 111, 2, &[]); + assert_eq!(host_error(&wire), (x11::error::BAD_VALUE, 2, 111)); + + // ListHosts with one extra word. + let mut backend = RecordingBackend::new(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(22), + RequestHeader { + opcode: 110, + data: 0, + length_units: 2, + }, + &[0; 4], + None, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(read_error(&wire), x11::error::BAD_LENGTH); + assert_eq!(wire[10], 110); + + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); +} + +#[test] +fn a_non_local_client_may_list_but_not_change() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).unwrap().is_local = false; + let wire = change_hosts(&mut state, &mut peer, 0, 252, &[]); + assert_eq!(host_error(&wire), (x11::error::BAD_ACCESS, 0, 109)); + let wire = host_request(&mut state, 1, &mut peer, 21, 111, 0, &[]); + assert_eq!(host_error(&wire), (x11::error::BAD_ACCESS, 0, 111)); + // The mode is checked before access. + let wire = change_hosts(&mut state, &mut peer, 2, 252, &[]); + assert_eq!(host_error(&wire), (x11::error::BAD_VALUE, 2, 109)); + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); +} + +#[test] +fn set_access_control_sets_the_enabled_flag() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + assert!(host_request(&mut state, 1, &mut peer, 21, 111, 0, &[]).is_empty()); + assert_eq!(list_hosts(&mut state, 1, &mut peer)[1], 0); + assert!(host_request(&mut state, 1, &mut peer, 21, 111, 1, &[]).is_empty()); + assert_eq!(list_hosts(&mut state, 1, &mut peer)[1], 1); +} + +#[test] +fn deleting_an_absent_entry_is_success() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + assert!(change_hosts(&mut state, &mut peer, 1, 0, &[192, 0, 2, 1]).is_empty()); + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); +} + +#[test] +fn narrowing_access_leaves_connected_clients_alone() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut other = install_client(&mut state, 2); + assert!(change_hosts(&mut state, &mut peer, 0, 5, b"localuser\0#4242").is_empty()); + assert!(change_hosts(&mut state, &mut peer, 1, 5, b"localuser\0#4242").is_empty()); + assert!(host_request(&mut state, 1, &mut peer, 21, 111, 1, &[]).is_empty()); + assert!(state.clients.contains_key(&1) && state.clients.contains_key(&2)); + assert_eq!(list_hosts(&mut state, 1, &mut peer), EMPTY_LIST_HOSTS_LE); + assert_eq!(list_hosts(&mut state, 2, &mut other), EMPTY_LIST_HOSTS_LE); +} + +#[test] +fn unknown_major_opcodes_return_bad_request() { + // Xorg's ProcVector routes reserved core opcodes 120-126 and + // unregistered extension slots to ProcBadRequest. Opcode 127 remains + // NoOperation and the registered extension slots are matched above. + for opcode in [120, 126, 255] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(0x1234), + RequestHeader { + opcode, + data: 0, + length_units: 1, + }, + &[], + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); + + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[0], 0, "wire packet must be an X11 error"); + assert_eq!(error[1], x11::error::BAD_REQUEST); + assert_eq!(u16::from_le_bytes([error[2], error[3]]), 0x1234); + assert_eq!( + error[10], opcode, + "error must identify the unknown major opcode" + ); + assert_eq!(u16::from_le_bytes([error[8], error[9]]), 0); + } +} + +#[test] +fn no_operation_remains_a_successful_noop() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(7), + RequestHeader { + opcode: 127, + data: 0, + length_units: 1, + }, + &[], + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); + + peer.set_nonblocking(true).unwrap(); + let mut byte = [0u8; 1]; + assert_eq!( + peer.read(&mut byte).unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); +} + +#[test] +fn unknown_extension_minors_return_bad_request() { + // Each locally-dispatched extension below has an Xorg dispatcher that + // returns core BadRequest when the minor is outside its request table. + // GLX is intentionally absent: its dispatcher uses GLXBadRequest and + // has separate coverage for that extension-specific error. + let extensions = [ + (128, "RANDR"), + (130, "MIT-SHM"), + (133, "RENDER"), + (134, "DPMS"), + (135, "BIG-REQUESTS"), + (136, "XKEYBOARD"), + (137, "XInputExtension"), + (138, "Generic Event Extension"), + (140, "XFIXES"), + (141, "SHAPE"), + (142, "SYNC"), + (143, "DAMAGE"), + (144, "Composite"), + (145, "Present"), + (146, "XTEST"), + (147, "DRI3"), + (149, "X-Resource"), + (150, "MIT-SCREEN-SAVER"), + (151, "XINERAMA"), + (152, "XC-MISC"), + (153, "XFree86-VidModeExtension"), + (154, "RECORD"), + ]; + + for (opcode, name) in extensions { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(0x4321), + RequestHeader { + opcode, + data: u8::MAX, + length_units: 1, + }, + &[], + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled), "{name}"); + + let mut error = [0u8; 32]; + peer.read_exact(&mut error) + .unwrap_or_else(|e| panic!("{name}: missing error: {e}")); + assert_eq!(error[0], 0, "{name}: packet must be an X11 error"); + assert_eq!(error[1], x11::error::BAD_REQUEST, "{name}"); + assert_eq!( + u16::from_le_bytes([error[2], error[3]]), + 0x4321, + "{name}: sequence" + ); + assert_eq!( + u16::from_le_bytes([error[8], error[9]]), + u16::from(u8::MAX), + "{name}: minor opcode" + ); + assert_eq!(error[10], opcode, "{name}: major opcode"); + } +} + +/// A `SendEvent` with an empty `event_mask` is addressed to the +/// client that *created* the destination window (X11 SendEvent +/// semantics). That is the XEmbed input-forwarding contract: a +/// systray manager (cinnamon) forwards the synthetic core +/// ButtonPress of a user click on the tray icon to the embedded +/// client, which also holds an XI2 selection on the window; dropping +/// it left pamac's tray icon unclickable (HW air 2026-06-22). +#[test] +fn send_event_empty_mask_delivers_synthetic_button_to_owner_despite_xi2_selection() { + use std::io::Read; + + const SENDER: u32 = 1; // cinnamon + const OWNER: u32 = 2; // pamac + const WIN: u32 = 0x0020_0001; // pamac's embedded icon window + + let mut state = ServerState::new(); + let _sender_peer = install_client(&mut state, SENDER); + let mut owner_peer = install_client(&mut state, OWNER); + + // Window created by (owned by) the pamac client. + state.resources.create_window( + yserver_protocol::x11::ClientId(OWNER), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 24, + height: 24, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + // pamac (GTK3) selects XI2 ButtonPress (bit 4) on its own window — + // exactly what makes the guard fire. + state + .clients + .get_mut(&OWNER) + .unwrap() + .xi2_masks + .insert((ResourceId(WIN), 1), 1 << 4); + + // SendEvent: destination=WIN, event_mask=0, template = core + // ButtonPress (type 4). + let mut body = Vec::with_capacity(40); + body.extend_from_slice(&WIN.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // empty event-mask + let mut tmpl = [0u8; 32]; + tmpl[0] = 4; // ButtonPress + body.extend_from_slice(&tmpl); + let header = yserver_protocol::x11::RequestHeader { + opcode: 25, + data: 0, // propagate = false + length_units: 11, + }; + handle_send_event( + &mut state, + &mut RecordingBackend::new(), + ClientId(SENDER), + SequenceNumber(1), + header, + &body, + ) + .expect("SendEvent"); + + owner_peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 256]; + loop { + match owner_peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + // The owner must receive the synthetic ButtonPress (type 4 with + // the sent-event bit 0x80 set → 0x84). + assert!( + !wire.is_empty() && wire[0] == 0x84, + "owner must receive the XEmbed-forwarded ButtonPress; got {} bytes: {:?}", + wire.len(), + &wire[..wire.len().min(40)], + ); +} + +/// Windows for the `SendEvent` tests: W (owned by `owner`, child of the +/// root) and its child C, neither mapped, so the pointer sprite is the +/// root. +fn send_event_tree(state: &mut ServerState, owner: u32, w: u32, c: u32) { + for (id, parent) in [(w, ROOT_WINDOW.0), (c, w)] { + state.resources.create_window( + yserver_protocol::x11::ClientId(owner), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(id), + parent: ResourceId(parent), + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } +} + +fn send_event_body(destination: u32, mask: u32, event_type: u8) -> Vec { + let mut body = Vec::with_capacity(40); + body.extend_from_slice(&destination.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); + let mut tmpl = [0u8; 32]; + tmpl[0] = event_type; + body.extend_from_slice(&tmpl); + body +} + +fn run_send_event(state: &mut ServerState, sender: u32, propagate: u8, body: &[u8]) { + let header = yserver_protocol::x11::RequestHeader { + opcode: 25, + data: propagate, + length_units: 11, + }; + handle_send_event( + state, + &mut RecordingBackend::new(), + ClientId(sender), + SequenceNumber(1), + header, + body, + ) + .expect("SendEvent"); +} + +fn drain_wire(peer: &mut UnixStream) -> Vec { + use std::io::Read; + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 256]; + while let Ok(n) = peer.read(&mut tmp) { + if n == 0 { + break; + } + wire.extend_from_slice(&tmp[..n]); + } + wire +} + +/// The first byte of each 32-byte packet on the wire. +fn wire_types(wire: &[u8]) -> Vec { + wire.chunks(32).map(|p| p[0]).collect() +} + +/// #212: a synthetic core Motion/Press/Release reaches the client whose +/// CORE mask matches even when it also selected the XI2 form of the +/// event on the window (master or all-devices) and on the root. Xorg +/// `GetClientsForDelivery` (`dix/events.c:2241`) takes the core +/// `OtherClients` for a core type; XI2 masks never enter. Measured: +/// goldens/sendevent-xi2.txt, the "XI2 AllMasterDevices" steps. +#[test] +fn send_event_core_mask_delivers_despite_xi2_selection() { + const SENDER: u32 = 1; + const OWNER: u32 = 2; + const W: u32 = 0x0020_0001; + const C: u32 = 0x0020_0002; + let mut state = ServerState::new(); + let mut sender_peer = install_client(&mut state, SENDER); + let mut owner_peer = install_client(&mut state, OWNER); + send_event_tree(&mut state, OWNER, W, C); + let owner = state.clients.get_mut(&OWNER).unwrap(); + owner.event_masks.insert(ResourceId(W), 0x4C); // ButtonPress|Release|PointerMotion + owner.xi2_masks.insert((ResourceId(W), 1), 0x70); // XI_ButtonPress|Release|Motion + owner.xi2_masks.insert((ROOT_WINDOW, 0), 0x70); + for (event_type, mask) in [(6u8, 0x40u32), (4, 0x0C), (5, 0x0C)] { + run_send_event(&mut state, SENDER, 0, &send_event_body(W, mask, event_type)); + } + assert_eq!( + wire_types(&drain_wire(&mut owner_peer)), + vec![0x86, 0x84, 0x85] + ); + assert!(drain_wire(&mut sender_peer).is_empty()); +} + +/// Propagation (Xorg `ProcSendEvent`, `dix/events.c:5622-5636`): no +/// selector on C, so propagate=True carries the event to W; False stops +/// at C; C's do-not-propagate mask strips its bits, and an empty +/// remainder ends the walk. Measured: goldens/sendevent-xi2.txt. +#[test] +fn send_event_propagates_by_core_masks_and_do_not_propagate() { + const SENDER: u32 = 1; + const OWNER: u32 = 2; + const W: u32 = 0x0020_0001; + const C: u32 = 0x0020_0002; + let mut state = ServerState::new(); + let _sender_peer = install_client(&mut state, SENDER); + let mut owner_peer = install_client(&mut state, OWNER); + send_event_tree(&mut state, OWNER, W, C); + let owner = state.clients.get_mut(&OWNER).unwrap(); + owner.event_masks.insert(ResourceId(W), 0x0C); // ButtonPress|ButtonRelease + owner.xi2_masks.insert((ResourceId(W), 1), 0x70); + + run_send_event(&mut state, SENDER, 0, &send_event_body(C, 0x04, 4)); + assert!( + drain_wire(&mut owner_peer).is_empty(), + "propagate False stops at C" + ); + + run_send_event(&mut state, SENDER, 1, &send_event_body(C, 0x04, 4)); + assert_eq!(wire_types(&drain_wire(&mut owner_peer)), vec![0x84]); + + state + .resources + .window_mut(ResourceId(C)) + .unwrap() + .do_not_propagate_mask = 0x04; + run_send_event(&mut state, SENDER, 1, &send_event_body(C, 0x04, 4)); + assert!( + drain_wire(&mut owner_peer).is_empty(), + "DNP strips the only bit" + ); + // ButtonPress|ButtonRelease minus DNP ButtonPress still matches W. + run_send_event(&mut state, SENDER, 1, &send_event_body(C, 0x0C, 4)); + assert_eq!(wire_types(&drain_wire(&mut owner_peer)), vec![0x84]); +} + +/// InputFocus (`dix/events.c:5594-5611`): with the pointer outside the +/// focus window the walk starts AND ends at the focus window, so W's +/// selection is never reached from focus C; focus W gets it. Focus None +/// delivers nothing and raises no error. Measured: +/// goldens/sendevent-xi2.txt, the "focus" steps. +#[test] +fn send_event_input_focus_stops_at_the_focus_window() { + const SENDER: u32 = 1; + const OWNER: u32 = 2; + const W: u32 = 0x0020_0001; + const C: u32 = 0x0020_0002; + let mut state = ServerState::new(); + let mut sender_peer = install_client(&mut state, SENDER); + let mut owner_peer = install_client(&mut state, OWNER); + send_event_tree(&mut state, OWNER, W, C); + state + .clients + .get_mut(&OWNER) + .unwrap() + .event_masks + .insert(ResourceId(W), 0x01); // KeyPress + + state.core_focus.raw = C; + run_send_event(&mut state, SENDER, 1, &send_event_body(1, 0x01, 2)); + assert!( + drain_wire(&mut owner_peer).is_empty(), + "walk ends at focus C" + ); + + state.core_focus.raw = W; + run_send_event(&mut state, SENDER, 1, &send_event_body(1, 0x01, 2)); + assert_eq!(wire_types(&drain_wire(&mut owner_peer)), vec![0x82]); + + state.core_focus.raw = 0; + run_send_event(&mut state, SENDER, 1, &send_event_body(1, 0x01, 2)); + assert!(drain_wire(&mut owner_peer).is_empty()); + assert!( + drain_wire(&mut sender_peer).is_empty(), + "focus None is not an error" + ); +} + +/// `ProcSendEvent` errors (`dix/events.c:5563-5619`), each measured on +/// Xorg (goldens/sendevent-xi2.txt): an unknown destination is +/// BadWindow; event types outside 2..=34 and 64.. (GenericEvent too), +/// a ClientMessage format other than 8/16/32, and mask bits above +/// `AllEventMasks` are BadValue carrying the offending value. +#[test] +fn send_event_rejects_like_xorg() { + const SENDER: u32 = 1; + const OWNER: u32 = 2; + const W: u32 = 0x0020_0001; + const C: u32 = 0x0020_0002; + let mut state = ServerState::new(); + let mut sender_peer = install_client(&mut state, SENDER); + let mut owner_peer = install_client(&mut state, OWNER); + send_event_tree(&mut state, OWNER, W, C); + let mut client_message = send_event_body(W, 0, 33); + client_message[9] = 7; + let cases: [(Vec, u8, u32); 6] = [ + (send_event_body(0x7fff_fff0, 0, 4), 3, 0x7fff_fff0), + (send_event_body(W, 0x0200_0000, 4), 2, 0x0200_0000), + (send_event_body(W, 0, 1), 2, 1), + (send_event_body(W, 0, 35), 2, 35), + (send_event_body(W, 0, 40), 2, 40), + (client_message, 2, 7), + ]; + for (body, code, value) in cases { + run_send_event(&mut state, SENDER, 0, &body); + let wire = drain_wire(&mut sender_peer); + assert_eq!(wire.len(), 32, "one error for {body:?}"); + assert_eq!((wire[0], wire[1]), (0, code)); + assert_eq!( + u32::from_le_bytes([wire[4], wire[5], wire[6], wire[7]]), + value + ); + } + assert!(drain_wire(&mut owner_peer).is_empty()); +} + +fn assert_window_removal_releases_pointer_grab(opcode: u8) { + use crate::server::ActivePointerGrab; + + const OWNER: u32 = 1; + let grab_window = ResourceId(0x0010_0001); + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let _peer = install_client(&mut state, OWNER); + + state.resources.create_window( + ClientId(OWNER), + CreateWindowRequest { + depth: 24, + window: grab_window, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(grab_window); + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(OWNER), + grab_window, + event_mask: 0xFFFF, + cursor: ResourceId(0), + time: 0, + owner_events: true, + via_xi2: true, + implicit: false, + passive: false, + xi2_mask: u64::MAX, + }); + + process_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(1), + RequestHeader { + opcode, + data: 0, + length_units: 2, + }, + &grab_window.0.to_le_bytes(), + None, + ) + .expect("window removal request"); + + assert!( + state.active_pointer_grab.is_none(), + "opcode {opcode} must deactivate a grab held on the removed window", + ); +} + +/// Destroying a grab window deactivates the grab, matching Xorg's +/// DeleteWindowFromAnyEvents teardown. +#[test] +fn destroying_a_grab_window_releases_the_pointer_grab() { + assert_window_removal_releases_pointer_grab(4); +} + +/// An unmapped grab window is no longer viewable and cannot retain an +/// active grab. +#[test] +fn unmapping_a_grab_window_releases_the_pointer_grab() { + assert_window_removal_releases_pointer_grab(10); +} + +/// Per X11 spec (Xorg `dix/enterleave.c:606` → +/// `CoreEnterLeaveEvents` → `CoreEnterNotifies` → +/// `DeliverEventsToWindow`): grab-activation crossing events +/// flow through the normal event-delivery path, which filters +/// by the client's per-window event-mask selection. xts's +/// `GrabPointer` test opens a fresh connection, creates a +/// grab window WITHOUT selecting `EnterWindowMask` (0x10), and +/// expects the next thing on the wire after sending GrabPointer +/// to be the reply (opcode 1). Pre-fix yserver's +/// `emit_core_grab_activation_crossings` fanned `EnterNotify` +/// (event type 7) unconditionally to the grabber via +/// `fanout_event_to_clients(&[client_id], …)` regardless of +/// mask, so the event landed on the wire BEFORE the reply +/// and the test reported `wanted REPLY - X_GrabPointer , got +/// EVENT - EnterNotify` (xts Xproto run 2026-05-31-11:13:07: +/// 1 FAIL on `GrabPointer` + 1 FAIL on `GrabKeyboard` + 8 +/// UNRESOLVED on `AllowEvents` / `ChangeActivePointerGrab`). +/// Marco / GTK3 popups still receive the crossings because +/// they select `EnterWindowMask` on their popup windows. +#[test] +fn grab_pointer_skips_synthesised_crossing_when_mask_unselected() { + const CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x100_0007; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + // Create the grab window WITHOUT EnterWindowMask selected + // (mirrors xts's fresh CreateWindow). + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + + // GrabPointer body: window(4) event-mask(2) pointer-mode(1) + // keyboard-mode(1) confine-to(4) cursor(4) time(4) = 20. + // event-mask=0, modes async, confine_to=None, cursor=None, + // time=CurrentTime. + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&GRAB_WIN.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); // event-mask + body.push(0); // pointer-mode async + body.push(0); // keyboard-mode async + body.extend_from_slice(&0u32.to_le_bytes()); // confine-to None + body.extend_from_slice(&0u32.to_le_bytes()); // cursor None + body.extend_from_slice(&0u32.to_le_bytes()); // time CurrentTime + + handle_grab_pointer( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(11), + RequestHeader { + opcode: 26, + data: 0, // owner_events false + length_units: 6, + }, + &body, + ) + .expect("handle_grab_pointer"); + + peer.set_nonblocking(true).unwrap(); + let mut tmp = [0u8; 1024]; + let mut wire = Vec::new(); + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + // First 32-byte chunk must be the reply (opcode 1), NOT an + // EnterNotify (event type 7). + assert!( + wire.len() >= 32, + "GrabPointer must produce at least the reply on the wire", + ); + assert_ne!( + wire[0] & 0x7f, + 7, + "Pre-fix: EnterNotify (type 7) landed on the wire before \ + the GrabPointer reply because crossings were unconditionally \ + fanned to the grabber regardless of EnterWindowMask. xts \ + reports this as `wanted REPLY - X_GrabPointer , got EVENT - \ + EnterNotify` and marks dependent tests UNRESOLVED.", + ); + assert_eq!( + wire[0], 1, + "GrabPointer must put the reply (opcode 1) first on the wire \ + when the grabber has not selected EnterWindowMask", + ); + // No EnterNotify anywhere — the grabber didn't select it. + let enter_notifies = wire.chunks_exact(32).filter(|c| c[0] & 0x7f == 7).count(); + assert_eq!( + enter_notifies, 0, + "EnterNotify must not be delivered to a grabber that didn't \ + select EnterWindowMask on the grab window", + ); +} + +/// Positive companion to the test above: when the grabber HAS +/// selected `EnterWindowMask` on the grab window (the +/// marco / GTK3 popup-menu pattern), the synthesised crossing +/// must still fire. The grab fix is "respect the event-mask +/// filter", not "drop crossings entirely". +#[test] +fn grab_pointer_emits_crossing_when_grabber_selected_enter_mask() { + const CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x100_0008; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + // marco/GTK3 popup pattern: the pointer is over the panel (the + // root here), NOT over the popup being grabbed — grab + // activation must emit Enter(NotifyGrab) on the popup for + // GTK3's hover machinery. (With the pointer already inside the + // grab window Xorg emits nothing: DoEnterLeaveEvents from==to.) + state.pointer_root = (500, 500); + state + .clients + .get_mut(&CLIENT_ID) + .unwrap() + .event_masks + .insert(ResourceId(GRAB_WIN), 0x10); + + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&GRAB_WIN.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.push(0); + body.push(0); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + + handle_grab_pointer( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(13), + RequestHeader { + opcode: 26, + data: 0, + length_units: 6, + }, + &body, + ) + .expect("handle_grab_pointer"); + + peer.set_nonblocking(true).unwrap(); + let mut tmp = [0u8; 1024]; + let mut wire = Vec::new(); + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + let enter_notifies = wire.chunks_exact(32).filter(|c| c[0] & 0x7f == 7).count(); + assert!( + enter_notifies >= 1, + "EnterNotify must still fire to a grabber that selected \ + EnterWindowMask (marco/GTK3 popup-menu pattern)", + ); +} + +/// Symmetric to the activation test: xts case 116 +/// (`pUngrabPointer-1.(A)`) opens a connection with NO event +/// mask selected, grabs+ungrabs, and verifies the server +/// sends NOTHING. Pre-fix `emit_core_grab_deactivation_crossing` +/// fanned `LeaveNotify` unconditionally to the ungrabber; the +/// test reported `wanted NOTHING, got EVENT - LeaveNotify`. +/// Mirror fix: the deactivation crossing must respect +/// `LeaveWindowMask` (0x20) on the prior grab window. +#[test] +fn ungrab_pointer_skips_synthesised_leave_when_mask_unselected() { + const CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x100_0009; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + + // Seed an active grab so handle_ungrab_pointer has + // something to deactivate (mirrors xts's GrabPointer → + // UngrabPointer sequence). + state.active_pointer_grab = Some(crate::server::ActivePointerGrab { + owner: ClientId(CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + event_mask: 0, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + + handle_ungrab_pointer( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(17), + &[0u8; 4], + ) + .expect("handle_ungrab_pointer"); + + peer.set_nonblocking(true).unwrap(); + let mut tmp = [0u8; 1024]; + let mut wire = Vec::new(); + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + let leave_notifies = wire.chunks_exact(32).filter(|c| c[0] & 0x7f == 8).count(); + assert_eq!( + leave_notifies, 0, + "UngrabPointer from a client that did not select \ + LeaveWindowMask must not produce a LeaveNotify on the \ + wire (xts case 116 / `pUngrabPointer-1.(A)`)", + ); + assert!( + wire.is_empty(), + "UngrabPointer with no event mask selected must produce \ + NOTHING on the wire; got {} bytes: {:?}", + wire.len(), + &wire[..wire.len().min(64)], + ); +} + +// NOTE: the 3rd argument is the SEQUENCE number, not a client id — +// every request in these tests comes from ClientId(1). +fn send_xcmisc( + state: &mut ServerState, + backend: &mut RecordingBackend, + seq: u16, + minor: u8, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(1), + SequenceNumber(seq), + RequestHeader { + opcode: 152, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("process_request"); +} + +#[test] +fn xcmisc_get_version_replies_1_1() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // GetVersion body: client major(2), minor(2) — values ignored. + let body = [0u8, 0, 0, 0]; + send_xcmisc(&mut state, &mut backend, 1, 0, &body); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "fixed 32-byte reply, got {bytes:02x?}"); + assert_eq!(bytes[0], 1, "X_Reply"); + assert_eq!(&bytes[2..4], &1u16.to_le_bytes(), "sequence"); + assert_eq!(&bytes[8..10], &1u16.to_le_bytes(), "major=1"); + assert_eq!(&bytes[10..12], &1u16.to_le_bytes(), "minor=1"); +} + +#[test] +fn xcmisc_bad_length_and_unknown_minor() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // GetVersion with wrong body size → BadLength. + send_xcmisc(&mut state, &mut backend, 1, 0, &[0u8; 8]); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32); + assert_eq!(bytes[1], x11::error::BAD_LENGTH); + assert_eq!(bytes[10], 152, "major opcode"); + assert_eq!(&bytes[8..10], &0u16.to_le_bytes(), "minor 0 echoed"); + // Unknown minor 3 → BadRequest (Xorg dispatcher default). + send_xcmisc(&mut state, &mut backend, 2, 3, &[]); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32); + assert_eq!(bytes[1], x11::error::BAD_REQUEST); + assert_eq!(&bytes[8..10], &3u16.to_le_bytes(), "minor 3 echoed"); +} + +#[test] +fn xcmisc_advertised_in_query_and_list_extensions() { + // QueryExtension "XC-MISC" → present with major 152; covered via + // extension_query_reply + advertised_extension_names directly + // (cheaper than wire round-trips; they are what the handlers use). + let mut backend = RecordingBackend::new(); + let reply = extension_query_reply("XC-MISC", &mut backend); + assert_eq!(reply, Some((152, 0, 0))); + assert!(advertised_extension_names(&mut backend).contains(&"XC-MISC")); +} + +#[test] +fn xcmisc_get_xid_range_skips_used_ids() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Give the test client a realistic base/mask (install_client + // defaults to base=0, mask=u32::MAX). + { + let c = state.clients.get_mut(&1).unwrap(); + c.resource_id_base = 0x0010_0000; + c.resource_id_mask = 0x000F_FFFF; + } + // Occupy the low end of the range. + for i in 0..4u32 { + state + .resources + .create_cursor(ClientId(1), ResourceId(0x0010_0000 + i)); + } + send_xcmisc(&mut state, &mut backend, 1, 1, &[]); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[0], 1); + let start = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); + let count = u32::from_le_bytes(bytes[12..16].try_into().unwrap()); + assert_eq!(start, 0x0010_0004, "range starts after the used prefix"); + assert_eq!(count, 0x000F_FFFF - 4 + 1); + // Wrong length → BadLength. + send_xcmisc(&mut state, &mut backend, 2, 1, &[0u8; 4]); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_LENGTH); +} + +#[test] +fn xcmisc_get_xid_list_returns_free_ids() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + { + let c = state.clients.get_mut(&1).unwrap(); + c.resource_id_base = 0x0010_0000; + c.resource_id_mask = 0x000F_FFFF; + } + // Occupy ids 0,2 in the range; ask for 4 ids. + state + .resources + .create_cursor(ClientId(1), ResourceId(0x0010_0000)); + state + .resources + .create_cursor(ClientId(1), ResourceId(0x0010_0002)); + send_xcmisc(&mut state, &mut backend, 1, 2, &4u32.to_le_bytes()); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32 + 16, "32 header + 4 ids"); + let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); + assert_eq!(count, 4); + let length = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); + assert_eq!(length, 4, "reply length in words = id count"); + let ids: Vec = bytes[32..] + .chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap())) + .collect(); + assert_eq!( + ids, + vec![0x0010_0001, 0x0010_0003, 0x0010_0004, 0x0010_0005], + "skips occupied 0x...0 and 0x...2" + ); + // Huge count is clamped to the RANGE size, not allocated. Shrink + // the client's range first so the reply stays ~1 KiB — a 1M-id + // reply would block the test's unread socketpair (write_or_buffer + // does a synchronous write; OUTBOUND_CAP would trip the + // disconnect path). + state.clients.get_mut(&1).unwrap().resource_id_mask = 0xFF; + send_xcmisc(&mut state, &mut backend, 2, 2, &u32::MAX.to_le_bytes()); + let bytes = read_all_available(&mut peer); + let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); + assert_eq!(count, 0x100 - 2, "256-id range minus 2 occupied"); + // BadLength on wrong size. + send_xcmisc(&mut state, &mut backend, 3, 2, &[]); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_LENGTH); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/damage_ext.rs b/crates/yserver-core/src/core_loop/process_request/tests/damage_ext.rs new file mode 100644 index 000000000..c970e805c --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/damage_ext.rs @@ -0,0 +1,2046 @@ +use super::*; +use crate::resources::COMPOSITE_OVERLAY_WINDOW; + +/// Manual-mode redirect removes W from the normal scene and keeps +/// B as an off-screen compositor source. B must not become a scene +/// participant, or the scene path can double-present redirected +/// client content behind/above the compositor's output surface. +#[test] +fn manual_redirect_keeps_window_out_of_scene() { + use crate::backend::recording::RecordedCall; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Install a top-level child of root (the soon-to-be-Manual- + // redirected window). Use real CreateWindow flow so the + // resource record carries width/height/depth that + // `activate_redirect_backing_for` snapshots. + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + // Viewable: Xorg allocates a redirect backing only for a realized window. + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + state + .composite_redirects + .redirect_window( + ResourceId(WINDOW_XID), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: yserver_protocol::x11::ClientId(1), + }, + ) + .unwrap(); + + activate_redirect_backing_for( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + crate::server::CompositeRedirectMode::Manual, + BackingDamage::Allocation, + ); + + // Window participation: Manual → false (the external + // compositor owns the window's presentation). The paired + // assertion that B *is* scene-participating lives in + // `manual_redirect_marks_backing_scene_participating_so_paints_emit_damage`. + let calls = backend.calls(); + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::SetWindowSceneParticipation { + host_window, + participating: false, + } if *host_window == HOST_XID + )), + "expected SetWindowSceneParticipation(W, false) for Manual mode; got {calls:?}", + ); + // Positive control for the COW guard + // (`activate_redirect_on_cow_is_never_applied`): a NORMAL window + // DOES receive a redirect backing. This proves the COW guard is + // overlay-window-specific, not a blanket disable of + // `activate_redirect_backing_for`. + assert!( + state + .resources + .window(ResourceId(WINDOW_XID)) + .expect("window exists") + .redirected_backing + .is_some(), + "a normal window must receive a redirect backing", + ); +} + +/// Xorg `compCheckRedirect` (`composite/compwindow.c:156-170`) forces +/// `should = FALSE` for `pWin == cs->pOverlayWin`: the overlay window +/// is NEVER actually redirected, regardless of trigger. Since Phase 2 +/// made the COW a real child of root, a compositor's +/// `CompositeRedirectSubwindows(root, Manual)` (mutter / cinnamon-mutter +/// all issue it) drives `activate_redirect_backing_for` once per root +/// child — including the COW. Without the guard the COW gets a Manual +/// backing + `scene_participating=false`, and the Phase 3 Manual-skip +/// drops the whole composited desktop from scanout (blank desktop, +/// observed bee/cinnamon-mutter 2026-06-09). The COW must keep its +/// `redirected_backing` empty and its scene participation untouched. +#[test] +fn activate_redirect_on_cow_is_never_applied() { + use crate::backend::recording::RecordedCall; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Materialize the COW exactly as the `GetOverlayWindow` 0->1 + // claim does (host xid == COMPOSITE_OVERLAY_WINDOW.0 for the + // RecordingBackend / v2 path, per the dispatch handler). + let cow_host = crate::backend::WindowHandle::from_raw_panicking(COMPOSITE_OVERLAY_WINDOW.0); + state.resources.materialize_cow_resource(cow_host); + + // This is the call `RedirectSubwindows(root, Manual)`'s child + // loop makes for every child of root — the COW included. + activate_redirect_backing_for( + &mut state, + &mut backend, + None, + COMPOSITE_OVERLAY_WINDOW, + crate::server::CompositeRedirectMode::Manual, + BackingDamage::Allocation, + ); + + let cow = state + .resources + .window(COMPOSITE_OVERLAY_WINDOW) + .expect("COW exists"); + assert!( + cow.redirected_backing.is_none(), + "COW must never receive a redirect backing \ + (compCheckRedirect: should=FALSE for pOverlayWin)", + ); + // And no scene-participation flip was recorded for the COW host — + // the Phase 3 Manual-skip is driven off this flag. + let calls = backend.calls(); + assert!( + !calls.iter().any(|c| matches!( + c, + RecordedCall::SetWindowSceneParticipation { host_window, .. } + if *host_window == COMPOSITE_OVERLAY_WINDOW.0 + )), + "COW scene participation must not be flipped by redirect activation; got {calls:?}", + ); +} + +/// Manual-redirected backing must have scene_participating=true so +/// the v2 scene's damage harvest sees paints into it. +/// +/// Post-`6ffd370` the scene walk emits the Manual-redirected window +/// at its own coords but samples storage from the backing via +/// `redirected_target` indirection. `store.damage()` is gated on +/// the *target's* `scene_participating` — if the backing is marked +/// non-participating, every paint into it silently drops its scene +/// damage. Buffer-age clipped compose then never repaints the +/// affected region, and the BO retains whatever was in it the last +/// time it was flipped. Symptom: window content invisible except +/// where cursor damage happens to overlap the window's rect. +#[test] +fn manual_redirect_marks_backing_scene_participating_so_paints_emit_damage() { + use crate::backend::recording::RecordedCall; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + // Viewable: Xorg allocates a redirect backing only for a realized window. + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + state + .composite_redirects + .redirect_window( + ResourceId(WINDOW_XID), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: yserver_protocol::x11::ClientId(1), + }, + ) + .unwrap(); + + activate_redirect_backing_for( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + crate::server::CompositeRedirectMode::Manual, + BackingDamage::Allocation, + ); + + let calls = backend.calls(); + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::SetBackingSceneParticipation { + participating: true, + .. + } + )), + "expected SetBackingSceneParticipation(B, true) for Manual mode so the \ + scene's redirected_target damage-peek sees paints; got {calls:?}", + ); +} + +/// Redirecting an already-mapped window must emit one initial full +/// DamageNotify wakeup so a compositor that subscribes after map +/// can pull the seeded backing into the COW immediately. Without +/// this, the backing contains the correct pixels but the COW keeps +/// showing the root/background until some unrelated later event +/// (click, move, resize) dirties the window. +#[test] +fn activate_redirect_on_mapped_window_emits_initial_damage() { + use crate::server::{DamageObject, RedirectRecord}; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0010; + const HOST_XID: u32 = 0x0040_0010; + const DAMAGE_XID: u32 = 0x0010_0011; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + state + .composite_redirects + .redirect_window( + ResourceId(WINDOW_XID), + RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: yserver_protocol::x11::ClientId(CLIENT_ID), + }, + ) + .unwrap(); + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(CLIENT_ID), + drawable: ResourceId(WINDOW_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + activate_redirect_backing_for( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + crate::server::CompositeRedirectMode::Manual, + BackingDamage::Allocation, + ); + + let damage = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object after redirect activation"); + assert!( + !damage.rects.is_empty(), + "redirect activation on an already-mapped window must emit an initial \ + full damage wakeup so compositors pull the seeded backing immediately", + ); +} + +/// A compositor subscribes to DAMAGE on the `NameWindowPixmap` +/// pixmap, not the original window. That pixmap must receive the +/// same initial seed as a plain viewable window, otherwise the +/// first composite after redirect can stay blank until some later +/// client paint lands. +#[test] +fn damage_create_on_named_pixmap_alias_seeds_initial_damage() { + use yserver_protocol::x11::damage as x11damage; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0012; + const HOST_WINDOW_XID: u32 = 0x0040_0012; + const PIXMAP_XID: u32 = 0x0020_0012; + const DAMAGE_ID: u32 = 0x0080_0012; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + HOST_WINDOW_XID, + )); + w.map_state = crate::resources::MapState::Viewable; + } + activate_redirect_backing_for( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + crate::server::CompositeRedirectMode::Manual, + BackingDamage::Allocation, + ); + let host_pixmap = state + .resources + .window(ResourceId(WINDOW_XID)) + .and_then(|w| w.redirected_backing.as_ref()) + .map(|b| b.host_pixmap) + .expect("redirected backing"); + state.resources.create_pixmap( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 100, + height: 50, + depth: 24, + }, + ); + let _ = state + .resources + .set_pixmap_host_xid(ResourceId(PIXMAP_XID), host_pixmap); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.composite_named_pixmaps + .push(crate::resources::NamedCompositePixmap { + client_pixmap: ResourceId(PIXMAP_XID), + host_pixmap, + width: 100, + height: 50, + }); + } + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&DAMAGE_ID.to_le_bytes()); + body.extend_from_slice(&PIXMAP_XID.to_le_bytes()); + body.push(x11damage::report_level::NON_EMPTY); + body.extend_from_slice(&[0, 0, 0]); + + let header = RequestHeader { + opcode: 0, + data: x11damage::CREATE, + length_units: 0, + }; + handle_damage_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("damage create handled"); + + let damage = state + .damage_objects + .get(&DAMAGE_ID) + .expect("damage object created"); + assert!( + !damage.rects.is_empty(), + "creating DAMAGE on a named pixmap alias of a viewable window must seed \ + initial damage so picom sees the current backing immediately", + ); +} + +/// Mapping a Manual-redirected window must not leave it visible +/// in the normal scene. The map path temporarily flips the +/// storage on, then the redirect-mode reapply must force it back +/// off. +#[test] +fn map_window_reapplies_manual_redirect_scene_participation() { + use crate::backend::recording::RecordedCall; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0002; + const HOST_XID: u32 = 0x0040_0002; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + state + .composite_redirects + .redirect_window( + ResourceId(WINDOW_XID), + crate::server::RedirectRecord { + mode: crate::server::CompositeRedirectMode::Manual, + owner: yserver_protocol::x11::ClientId(CLIENT_ID), + }, + ) + .unwrap(); + + activate_redirect_backing_for( + &mut state, + &mut backend, + None, + ResourceId(WINDOW_XID), + crate::server::CompositeRedirectMode::Manual, + BackingDamage::Allocation, + ); + let before = backend.calls().len(); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window"); + + let calls = &backend.calls()[before..]; + assert!( + calls.iter().any(|c| matches!( + c, + RecordedCall::SetWindowSceneParticipation { + host_window, + participating: false, + } if *host_window == HOST_XID + )), + "mapping a Manual-redirected window must reassert scene_participating=false; got {calls:?}", + ); + assert!( + !calls.iter().any(|c| matches!( + c, + RecordedCall::SetWindowSceneParticipation { + host_window, + participating: true, + } if *host_window == HOST_XID + )), + "mapping a Manual-redirected window must not leave it scene_participating=true; got {calls:?}", + ); +} + +/// Audit #11 regression — when a window maps, server-background +/// paint fills the window's storage but no `DamageNotify` fires +/// for the affected region. Compositors that subscribe to +/// `XDamageCreate(window)` (marco-with-compositing, picom) miss +/// the first frame and the window stays invisible on COW until +/// the next paint into it. Symptom: override-redirect popup +/// menus, mate-panel system-tray icons (`nm-applet`) don't show +/// when a compositor is active and v2 routes the visible output +/// through `Present::Pixmap → COW`. +/// +/// Oracle: a `DamageObject` subscribed to a freshly-created +/// window with a background pixel must accumulate damage rects +/// after `handle_map_window` returns (`miWindowExposures` paints +/// the background; a background-None window gets none). +#[test] +fn map_window_emits_damage_on_window_extent() { + use crate::server::DamageObject; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0010; + const HOST_XID: u32 = 0x0040_0010; + const DAMAGE_ID: u32 = 0x0080_0010; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + background_pixel: Some(0x0080_8080), + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + + // Compositor subscribes via `XDamageCreate(window)`. Pin the + // pre-state explicitly: no rects accumulated yet. + state.damage_objects.insert( + DAMAGE_ID, + DamageObject { + owner: ClientId(CLIENT_ID), + drawable: ResourceId(WINDOW_XID), + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window"); + + let damage = state + .damage_objects + .get(&DAMAGE_ID) + .expect("damage_object survived map"); + assert!( + !damage.rects.is_empty(), + "MapWindow must fire damage on the window's extent so a \ + subscribed compositor repaints the new region into its \ + offscreen — pre-fix this is empty and the compositor \ + never sees the newly-mapped popup / tray icon / window", + ); +} + +#[test] +fn map_window_seeds_damage_for_newly_viewable_descendant() { + use crate::server::DamageObject; + + const CLIENT_ID: u32 = 1; + const PARENT_XID: u32 = 0x0010_0012; + const PARENT_HOST_XID: u32 = 0x0040_0012; + const CHILD_XID: u32 = 0x0010_0013; + const CHILD_HOST_XID: u32 = 0x0040_0013; + const CHILD_DAMAGE_ID: u32 = 0x0080_0013; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(PARENT_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 400, + height: 300, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_XID), + parent: ResourceId(PARENT_XID), + x: 20, + y: 30, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + background_pixel: Some(0x0080_8080), + ..Default::default() + }, + ); + { + let parent = state + .resources + .window_mut(ResourceId(PARENT_XID)) + .expect("parent installed"); + parent.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + PARENT_HOST_XID, + )); + parent.map_state = crate::resources::MapState::Unmapped; + } + { + let child = state + .resources + .window_mut(ResourceId(CHILD_XID)) + .expect("child installed"); + child.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + CHILD_HOST_XID, + )); + child.map_state = crate::resources::MapState::Unviewable; + } + + state.damage_objects.insert( + CHILD_DAMAGE_ID, + DamageObject { + owner: ClientId(CLIENT_ID), + drawable: ResourceId(CHILD_XID), + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&PARENT_XID.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window"); + + let child_damage = state + .damage_objects + .get(&CHILD_DAMAGE_ID) + .expect("child damage object survives"); + assert!( + !child_damage.rects.is_empty(), + "mapping a parent must seed damage for descendants promoted from \ + Unviewable to Viewable; otherwise compositors miss the child's \ + first visible frame" + ); +} + +/// A NonEmpty damage that already fired and was never subtracted stays +/// non-empty across the map: Xorg reports NonEmpty only on the empty → +/// non-empty transition (`DamageReportDamage`, `miext/damage/damage.c`), +/// as the issue-#248 probe measures for the mapped window itself +/// (`b/pixel`, `map2`: no DamageNotify). +#[test] +fn map_window_does_not_rereport_held_nonempty_damage_for_newly_viewable_descendant() { + use crate::{nested::DAMAGE_FIRST_EVENT, server::DamageObject}; + use std::io::Read; + use yserver_protocol::x11::{damage as x11damage, xfixes::RegionRect}; + + const CLIENT_ID: u32 = 1; + const PARENT_XID: u32 = 0x0010_0022; + const PARENT_HOST_XID: u32 = 0x0040_0022; + const CHILD_XID: u32 = 0x0010_0023; + const CHILD_HOST_XID: u32 = 0x0040_0023; + const CHILD_DAMAGE_ID: u32 = 0x0080_0023; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(PARENT_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 400, + height: 300, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_XID), + parent: ResourceId(PARENT_XID), + x: 20, + y: 30, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let parent = state + .resources + .window_mut(ResourceId(PARENT_XID)) + .expect("parent installed"); + parent.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + PARENT_HOST_XID, + )); + parent.map_state = crate::resources::MapState::Unmapped; + } + { + let child = state + .resources + .window_mut(ResourceId(CHILD_XID)) + .expect("child installed"); + child.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + CHILD_HOST_XID, + )); + child.map_state = crate::resources::MapState::Unviewable; + } + + state.damage_objects.insert( + CHILD_DAMAGE_ID, + DamageObject { + owner: ClientId(CLIENT_ID), + drawable: ResourceId(CHILD_XID), + level: x11damage::report_level::NON_EMPTY, + rects: vec![RegionRect { + x: 0, + y: 0, + width: 200, + height: 80, + }], + pending_notify_fired: true, + last_reported_geometry: Some(x11damage::Rectangle { + x: 20, + y: 30, + width: 200, + height: 80, + }), + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&PARENT_XID.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window"); + + peer.set_nonblocking(true).expect("set nonblocking"); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + + assert!( + !all.chunks_exact(32).any(|evt| evt[0] == DAMAGE_FIRST_EVENT), + "a held NON_EMPTY damage must not re-report when its drawable becomes viewable" + ); +} + +#[test] +fn damage_subtract_flushes_coalesced_paint_before_consuming_damage() { + use yserver_protocol::x11::{damage, xfixes::RegionRect}; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let rects = vec![RegionRect { + x: 10, + y: 20, + width: 30, + height: 40, + }]; + // NonEmpty damage has already notified the compositor; later paints + // accumulate without another notification/submission boundary. + state.damage_objects.insert( + 0x100, + crate::server::DamageObject { + owner: ClientId(1), + drawable: ROOT_WINDOW, + level: damage::report_level::NON_EMPTY, + rects: rects.clone(), + pending_notify_fired: true, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + let body: Vec = [0x100_u32, 0, 0x200] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 143, + data: damage::SUBTRACT, + length_units: 4, + }, + &body, + None, + ) + .expect("Subtract"); + + assert_eq!(state.xfixes_regions[&0x200].rects(), rects); + assert!(state.damage_objects[&0x100].rects.is_empty()); + assert_eq!( + backend.calls(), + vec![RecordedCall::FlushBeforeDamageNotify], + "Subtract must submit paint even when there is no new DamageNotify" + ); +} + +#[test] +fn fetch_region_flushes_paint_before_exposing_damage_rectangles() { + use yserver_protocol::x11::xfixes; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.xfixes_client_major.insert(1, 5); + let mut backend = RecordingBackend::new(); + state.xfixes_regions.insert( + 0x200, + crate::server::XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::from_rects(&[xfixes::RegionRect { + x: 10, + y: 20, + width: 30, + height: 40, + }]), + }, + ); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: xfixes::FETCH_REGION, + length_units: 2, + }, + &0x200_u32.to_le_bytes(), + None, + ) + .expect("FetchRegion"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 40); + assert_eq!(bytes[0], 1, "reply, not an error"); + assert_eq!(&bytes[32..], &[10, 0, 20, 0, 30, 0, 40, 0]); + assert_eq!( + backend.calls(), + vec![RecordedCall::FlushBeforeDamageNotify], + "FetchRegion must submit paint before publishing its damage region" + ); +} + +#[test] +fn damage_create_on_viewable_window_seeds_full_damage() { + use yserver_protocol::x11::{RequestHeader, damage as x11damage}; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0100; + const HOST_XID: u32 = 0x0040_0100; + const DAMAGE_ID: u32 = 0x0080_0100; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + + state.resources.create_window( + ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 11, + y: 22, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + w.map_state = crate::resources::MapState::Viewable; + } + let mut body = Vec::new(); + body.extend_from_slice(&DAMAGE_ID.to_le_bytes()); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body.push(x11damage::report_level::NON_EMPTY); + body.extend_from_slice(&[0, 0, 0]); + + let header = RequestHeader { + opcode: 0, + data: x11damage::CREATE, + length_units: 0, + }; + handle_damage_request( + &mut state, + &mut RecordingBackend::new(), + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("damage create handled"); + + let damage = state + .damage_objects + .get(&DAMAGE_ID) + .expect("damage object created"); + assert!( + !damage.rects.is_empty(), + "creating DAMAGE on an already-viewable window must seed initial \ + damage so the subscriber does not miss the current visible frame" + ); +} + +fn dispatch_damage_subtract( + state: &mut ServerState, + backend: &mut RecordingBackend, + damage_id: u32, + repair: u32, + parts: u32, +) { + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&damage_id.to_le_bytes()); + body.extend_from_slice(&repair.to_le_bytes()); + body.extend_from_slice(&parts.to_le_bytes()); + process_request( + state, + backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 143, // DAMAGE major + data: yserver_protocol::x11::damage::SUBTRACT, + length_units: 4, + }, + &body, + None, + ) + .unwrap(); +} + +#[test] +fn damage_subtract_with_no_repair_returns_old_damage_in_parts_and_clears() { + use crate::server::{DamageObject, XFixesRegion}; + use yserver_protocol::x11::xfixes::RegionRect; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let damaged_rect = RegionRect { + x: 10, + y: 20, + width: 30, + height: 40, + }; + state.damage_objects.insert( + 0x20, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(0x100), + level: 0, + rects: vec![damaged_rect], + pending_notify_fired: true, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + // Pre-create the parts region so the handler writes into it. + state.xfixes_regions.insert( + 0x21, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + + dispatch_damage_subtract(&mut state, &mut backend, 0x20, 0, 0x21); + + // Per X11 DAMAGE spec: repair==None → parts gets old damage, + // damage is cleared. + let parts = state + .xfixes_regions + .get(&0x21) + .expect("parts region must exist"); + assert_eq!( + parts.rects(), + vec![damaged_rect], + "with repair=None, parts must receive the entire old damage region; \ + pre-fix this returns Vec::new() and starves compositors of a real clip" + ); + let damage = state.damage_objects.get(&0x20).unwrap(); + assert!( + damage.rects.is_empty(), + "with repair=None, damage must be fully cleared" + ); + assert!( + !damage.pending_notify_fired, + "Subtract is the cycle boundary — pending_notify_fired must reset" + ); +} + +/// A writer does not take ownership of an existing DAMAGE parts region. +/// Mutation: assigning Subtract's parts region to the writer makes the +/// owner's post-disconnect FetchRegion reply disappear. +#[test] +fn damage_subtract_parts_keeps_existing_region_owner() { + use crate::server::DamageObject; + use yserver_protocol::x11::{RequestHeader, damage as x11damage, xfixes}; + + const OWNER: u32 = 1; + const WRITER: u32 = 2; + const DAMAGE_ID: u32 = 0x0080_0020; + const PARTS_ID: u32 = 0x0080_0021; + let damaged_rect = xfixes::RegionRect { + x: 10, + y: 20, + width: 30, + height: 40, + }; + + let mut state = ServerState::new(); + let mut owner_peer = install_client(&mut state, OWNER); + let _writer_peer = install_client(&mut state, WRITER); + state.xfixes_client_major.insert(OWNER, 5); + let mut backend = RecordingBackend::new(); + + // Owner creates the existing parts region through the request path. + let mut create_body = PARTS_ID.to_le_bytes().to_vec(); + create_body.extend_from_slice(&0_i16.to_le_bytes()); + create_body.extend_from_slice(&0_i16.to_le_bytes()); + create_body.extend_from_slice(&1_u16.to_le_bytes()); + create_body.extend_from_slice(&1_u16.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: xfixes::CREATE_REGION, + length_units: 4, + }, + &create_body, + None, + ) + .expect("CreateRegion"); + + state.damage_objects.insert( + DAMAGE_ID, + DamageObject { + owner: ClientId(OWNER), + drawable: ROOT_WINDOW, + level: x11damage::report_level::RAW_RECTANGLES, + rects: vec![damaged_rect], + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + let mut subtract_body = Vec::with_capacity(12); + subtract_body.extend_from_slice(&DAMAGE_ID.to_le_bytes()); + subtract_body.extend_from_slice(&0_u32.to_le_bytes()); + subtract_body.extend_from_slice(&PARTS_ID.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(WRITER), + SequenceNumber(1), + RequestHeader { + opcode: 143, + data: x11damage::SUBTRACT, + length_units: 4, + }, + &subtract_body, + None, + ) + .expect("Subtract"); + + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(WRITER), + ); + + process_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(2), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: xfixes::FETCH_REGION, + length_units: 2, + }, + &PARTS_ID.to_le_bytes(), + None, + ) + .expect("FetchRegion"); + let reply = read_all_available(&mut owner_peer); + assert_eq!(reply.len(), 40, "FetchRegion returns the parts rectangle"); + assert_eq!(reply[0], 1, "the owner's parts region survives disconnect"); + assert_eq!( + &reply[32..40], + &[10, 0, 20, 0, 30, 0, 40, 0], + "Subtract copied the damage rectangles into the owner's parts region", + ); +} + +#[test] +fn damage_subtract_with_no_repair_canonicalizes_parts_region() { + use crate::server::{DamageObject, XFixesRegion}; + use yserver_protocol::x11::xfixes::RegionRect; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + state.damage_objects.insert( + 0x40, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(0x100), + level: 0, + rects: vec![ + RegionRect { + x: 0, + y: 0, + width: 10, + height: 10, + }, + RegionRect { + x: 10, + y: 0, + width: 10, + height: 10, + }, + RegionRect { + x: 0, + y: 0, + width: 20, + height: 10, + }, + ], + pending_notify_fired: true, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + state.xfixes_regions.insert( + 0x41, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + + dispatch_damage_subtract(&mut state, &mut backend, 0x40, 0, 0x41); + + let parts = state + .xfixes_regions + .get(&0x41) + .expect("parts region must exist"); + assert_eq!( + parts.rects(), + vec![RegionRect { + x: 0, + y: 0, + width: 20, + height: 10, + }], + "with repair=None, parts must be canonicalized before they are handed to the client" + ); +} + +#[test] +fn damage_subtract_with_repair_returns_intersection_and_subtracts_from_damage() { + use crate::server::{DamageObject, XFixesRegion}; + use yserver_protocol::x11::xfixes::RegionRect; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + // Damage: 100x100 at origin. + state.damage_objects.insert( + 0x30, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(0x100), + level: 0, + rects: vec![RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }], + pending_notify_fired: true, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + // Repair: right-half strip 50x100 at (50, 0). MUST remain + // unchanged by Subtract — it's an input filter, not an output. + let repair_rect = RegionRect { + x: 50, + y: 0, + width: 50, + height: 100, + }; + state.xfixes_regions.insert( + 0x31, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::from_rects(&[repair_rect]), + }, + ); + state.xfixes_regions.insert( + 0x32, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + + dispatch_damage_subtract(&mut state, &mut backend, 0x30, 0x31, 0x32); + + // parts = damage ∩ repair → right half 50x100 at (50, 0). + let parts = &state.xfixes_regions.get(&0x32).unwrap().rects(); + let parts_area: u64 = parts + .iter() + .map(|r| u64::from(r.width) * u64::from(r.height)) + .sum(); + assert_eq!( + parts_area, + 50 * 100, + "parts must cover the intersection (5000 px²); got {parts:?}" + ); + for r in parts { + assert!( + r.x >= 50, + "parts rect {r:?} extends outside the repair filter" + ); + } + + // damage = damage − repair → left half 50x100 at (0, 0). + let damage = &state.damage_objects.get(&0x30).unwrap().rects; + let damage_area: u64 = damage + .iter() + .map(|r| u64::from(r.width) * u64::from(r.height)) + .sum(); + assert_eq!( + damage_area, + 50 * 100, + "damage must retain the un-repaired left half (5000 px²); got {damage:?}" + ); + for r in damage { + assert!( + r.x + i16::try_from(r.width).unwrap_or(i16::MAX) <= 50, + "damage rect {r:?} extends into the repaired region" + ); + } + + // repair region MUST NOT have been overwritten — pre-fix this + // stomped repair with `damage.rects.clone()`. + let repair_now = &state.xfixes_regions.get(&0x31).unwrap().rects(); + assert_eq!( + repair_now, + &vec![repair_rect], + "Subtract must treat the repair region as read-only input; \ + pre-fix this overwrote it with the damage rects" + ); +} + +#[test] +fn damage_subtract_with_remaining_nonempty_damage_rereports_immediately() { + use crate::server::{DamageObject, XFixesRegion}; + use yserver_protocol::x11::{CreateWindowRequest, damage as x11damage, xfixes::RegionRect}; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let _peer = install_client(&mut state, 1); + + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(0x100), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(0x100)); + + state.damage_objects.insert( + 0x40, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(0x100), + level: x11damage::report_level::NON_EMPTY, + rects: vec![RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }], + pending_notify_fired: true, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + state.xfixes_regions.insert( + 0x41, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::from_rects(&[RegionRect { + x: 50, + y: 0, + width: 50, + height: 100, + }]), + }, + ); + state.xfixes_regions.insert( + 0x42, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + + dispatch_damage_subtract(&mut state, &mut backend, 0x40, 0x41, 0x42); + + let damage = state.damage_objects.get(&0x40).expect("damage object"); + assert!( + !damage.rects.is_empty(), + "repair only covered part of the damage; some damage must remain" + ); + assert!( + damage.pending_notify_fired, + "Xorg immediately re-reports remaining non-empty damage after Subtract; \ + pre-fix yserver left fired=false and waited for unrelated future drawing" + ); +} + +/// X11 Composite + DAMAGE interaction: a configure that changes a +/// redirected window's screen-space presentation must emit a +/// `DamageNotify` to the compositor's damage subscription on that +/// window. Xorg behaviour (compositor.c) — without this event, +/// marco/picom/etc. never mark the moved window dirty and their +/// SetPictureClipRectangles excludes the window's region, so +/// composites against the redirected backing no-op or partially +/// blend, producing the "CC disappears on drag / muddy bands on +/// caja-redraw" symptom we measured against a Xephyr (Xorg-family) +/// reference run: yserver emitted 0 DamageNotify events to marco; +/// Xephyr emitted 776. +/// +/// Reproduce minimally: install marco client, create a top-level +/// window with a damage object owned by marco, set the window +/// `redirected_backing` (Manual-redirect activated state), then +/// send a move-only ConfigureWindow. Read marco's socket and +/// look for the DamageNotify event (event opcode 94 = DAMAGE +/// first_event + 0). +#[test] +fn configure_window_on_redirected_window_emits_damage_to_subscriber() { + use crate::{ + resources::{ROOT_WINDOW, RedirectedBacking}, + server::{CompositeRedirectMode, DamageObject, RedirectRecord}, + }; + use std::io::Read; + use yserver_protocol::x11::CreateWindowRequest; + const MARCO: u32 = 14; + const FRAME_XID: u32 = 0x0010_0001; + const DAMAGE_XID: u32 = 0x0010_0002; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, MARCO); + + // Frame W under root. + state.resources.create_window( + ClientId(MARCO), + CreateWindowRequest { + depth: 24, + window: ResourceId(FRAME_XID), + parent: ROOT_WINDOW, + x: 100, + y: 100, + width: 997, + height: 652, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(FRAME_XID)); + state + .composite_redirects + .redirect_window( + ResourceId(FRAME_XID), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(MARCO), + }, + ) + .unwrap(); + // Mark the frame as redirected (Manual-redirect activated + // state). `host_pixmap` value is opaque to the damage path. + if let Some(w) = state.resources.window_mut(ResourceId(FRAME_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0xDEAD_BEEF); + w.redirected_backing = Some(RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw(0xC0DE).unwrap(), + width: 997, + height: 652, + depth: 24, + }); + } + // Damage subscription on the frame, owned by marco, NonEmpty + // level (0x03) so any change fires. + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(MARCO), + drawable: ResourceId(FRAME_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + // ConfigureWindow body: window(4) + value_mask(2) + pad(2) + + // x(4 as i16) + y(4 as i16). value_mask = 0x03 = CWX | CWY. + // Move from (100, 100) to (250, 300). + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&FRAME_XID.to_le_bytes()); + body.extend_from_slice(&0x0003u16.to_le_bytes()); // value_mask + body.extend_from_slice(&[0u8; 2]); // pad + body.extend_from_slice(&250i32.to_le_bytes()); // x + body.extend_from_slice(&300i32.to_le_bytes()); // y + process_request( + &mut state, + &mut backend, + ClientId(MARCO), + SequenceNumber(1), + RequestHeader { + opcode: 12, // ConfigureWindow + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + // Drain marco's socket. Look for a DamageNotify event: + // event_code = DAMAGE_FIRST_EVENT + 0. + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let damage_evt: [u8; 32] = all + .chunks_exact(32) + .find(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT) + .map(|s| { + let mut a = [0u8; 32]; + a.copy_from_slice(s); + a + }) + .unwrap_or_else(|| { + panic!( + "ConfigureWindow on a redirected window must emit DamageNotify \ + (event code 94) to the compositor's damage subscriber. \ + Pre-fix yserver emits 0 DamageNotify events vs Xephyr's 776, \ + which leaves marco's compositor unable to mark the moved \ + window dirty. Got {} bytes; first 32: {:02x?}", + all.len(), + all.get(..32.min(all.len())).unwrap_or(&[]), + ) + }); + // Per X11 DAMAGE proto: DamageNotify.geometry encodes the + // damaged drawable's CURRENT root-relative position + extent + // (Xorg damageext.c fills from pDrawable->{x,y,width,height}; + // for windows, x/y are root-relative). marco/picom etc. use + // this to map the damage region into screen space. yserver's + // encoder historically hardcoded {x: 0, y: 0, w, h}, leaving + // marco mapping the damage to the wrong screen rect after + // every move — visible as "top-left bits stay rendered" + // after dragging (marco recomposites at the OLD position + // because the geometry origin points back to (0,0)). + // + // Wire layout: offsets 24..32 hold geometry as + // (x i16, y i16, w u16, h u16) little-endian. The window + // was configured to (250, 300) above. + let geom_x = i16::from_le_bytes([damage_evt[24], damage_evt[25]]); + let geom_y = i16::from_le_bytes([damage_evt[26], damage_evt[27]]); + let geom_w = u16::from_le_bytes([damage_evt[28], damage_evt[29]]); + let geom_h = u16::from_le_bytes([damage_evt[30], damage_evt[31]]); + assert_eq!( + (geom_x, geom_y, geom_w, geom_h), + (250, 300, 997, 652), + "DamageNotify.geometry must encode the window's CURRENT \ + root-relative position + extent; pre-fix this hardcodes \ + (0, 0, w, h) and breaks marco's screen-rect mapping", + ); +} + +/// Effective redirect state includes inherited `RedirectSubwindows` +/// mode, not just a directly populated `window.redirected_backing`. +/// A move-only ConfigureWindow under an inherited redirect still +/// needs to wake the compositor with DamageNotify. +#[test] +fn configure_window_on_inherited_redirect_emits_damage_to_subscriber() { + use crate::{ + resources::ROOT_WINDOW, + server::{CompositeRedirectMode, DamageObject, RedirectRecord}, + }; + use std::io::Read; + use yserver_protocol::x11::CreateWindowRequest; + + const MARCO: u32 = 14; + const CHILD_XID: u32 = 0x0010_0101; + const DAMAGE_XID: u32 = 0x0010_0102; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, MARCO); + + state + .composite_redirects + .redirect_subwindows( + ROOT_WINDOW, + state.resources.children(ROOT_WINDOW), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(MARCO), + }, + ) + .unwrap(); + + state.resources.create_window( + ClientId(MARCO), + CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_XID), + parent: ROOT_WINDOW, + x: 100, + y: 100, + width: 545, + height: 204, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .composite_redirects + .redirect_new_subwindow(ROOT_WINDOW, ResourceId(CHILD_XID)); + let _ = state.resources.map_window(ResourceId(CHILD_XID)); + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(MARCO), + drawable: ResourceId(CHILD_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&CHILD_XID.to_le_bytes()); + body.extend_from_slice(&0x0003u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&250i32.to_le_bytes()); + body.extend_from_slice(&300i32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(MARCO), + SequenceNumber(1), + RequestHeader { + opcode: 12, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + + assert!( + all.chunks_exact(32) + .any(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT), + "move-only ConfigureWindow under inherited RedirectSubwindows \ + must emit DamageNotify even when redirected_backing is not \ + directly populated on the child window", + ); +} + +#[test] +fn configure_window_move_on_unmapped_redirected_window_emits_no_damage() { + // i3 floating-drag smear repro: i3 creates a "floatingcon" + // frame as a root child, sizes/moves it during the drag, but + // NEVER maps it. Root is composite-redirected (fastcompmgr), + // so the child inherits the redirect. A move/resize + // ConfigureWindow on this UNMAPPED window must NOT emit + // DamageNotify — Xorg damages only realized/viewable windows on + // configure. Without the map-state gate, fastcompmgr receives + // damage for the unmapped floatingcon, NameWindowPixmaps it, and + // composites its stale backing at the drag position → the trail. + use crate::{ + resources::ROOT_WINDOW, + server::{CompositeRedirectMode, DamageObject, RedirectRecord}, + }; + use std::io::Read; + use yserver_protocol::x11::CreateWindowRequest; + + const FASTCOMPMGR: u32 = 14; + const FLOATINGCON_XID: u32 = 0x0010_0101; + const DAMAGE_XID: u32 = 0x0010_0102; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, FASTCOMPMGR); + + state + .composite_redirects + .redirect_subwindows( + ROOT_WINDOW, + state.resources.children(ROOT_WINDOW), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(FASTCOMPMGR), + }, + ) + .unwrap(); + + state.resources.create_window( + ClientId(FASTCOMPMGR), + CreateWindowRequest { + depth: 24, + window: ResourceId(FLOATINGCON_XID), + parent: ROOT_WINDOW, + x: 100, + y: 100, + width: 545, + height: 204, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + // NOTE: deliberately NOT calling map_window — the floatingcon + // stays Unmapped for its whole life. + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(FASTCOMPMGR), + drawable: ResourceId(FLOATINGCON_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + // ConfigureWindow move: value-mask x|y (0x0003), new (250, 300). + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&FLOATINGCON_XID.to_le_bytes()); + body.extend_from_slice(&0x0003u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&250i32.to_le_bytes()); + body.extend_from_slice(&300i32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(FASTCOMPMGR), + SequenceNumber(1), + RequestHeader { + opcode: 12, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + + assert!( + !all.chunks_exact(32) + .any(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT), + "move ConfigureWindow on an UNMAPPED redirected window must \ + NOT emit DamageNotify (i3 floatingcon smear); Xorg damages \ + only realized windows on configure", + ); +} + +#[test] +fn configure_window_stack_only_on_redirected_window_does_not_emit_damage() { + use crate::{ + resources::{ROOT_WINDOW, RedirectedBacking}, + server::{CompositeRedirectMode, DamageObject, RedirectRecord}, + }; + use std::io::Read; + use yserver_protocol::x11::CreateWindowRequest; + + const MARCO: u32 = 14; + const FRAME_XID: u32 = 0x0010_0201; + const SIBLING_XID: u32 = 0x0010_0202; + const DAMAGE_XID: u32 = 0x0010_0203; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, MARCO); + + for xid in [FRAME_XID, SIBLING_XID] { + state.resources.create_window( + ClientId(MARCO), + CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 5120, + height: 1440, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(xid)); + state + .composite_redirects + .redirect_window( + ResourceId(xid), + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(MARCO), + }, + ) + .unwrap(); + if let Some(w) = state.resources.window_mut(ResourceId(xid)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0xD000_0000 | xid); + w.redirected_backing = Some(RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw(0xC000_0000 | xid).unwrap(), + width: 5120, + height: 1440, + depth: 24, + }); + } + } + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(MARCO), + drawable: ResourceId(FRAME_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + // value_mask = 0x60 = CWSibling | CWStackMode, no geometry bits. + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&FRAME_XID.to_le_bytes()); + body.extend_from_slice(&0x0060u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&SIBLING_XID.to_le_bytes()); + body.push(1); // Below + body.extend_from_slice(&[0u8; 3]); + process_request( + &mut state, + &mut backend, + ClientId(MARCO), + SequenceNumber(1), + RequestHeader { + opcode: 12, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + + assert!( + !all.chunks_exact(32) + .any(|evt| evt[0] == crate::nested::DAMAGE_FIRST_EVENT), + "stack-only ConfigureWindow on a redirected window must not emit synthetic \ + DamageNotify; that turns restacks into bogus full-window damage", + ); +} + +/// A child's drawable origin in its parent is `x + bw` (`dix/window.c`, +/// `drawable.x = parent.x + x + bw`), so damage on a bordered child reaches +/// the parent shifted by its border too (Xorg: `84,84 10x10`). +#[test] +fn a_bordered_childs_damage_reaches_the_parent_at_its_content_origin() { + use crate::server::DamageObject; + const W: u32 = 0x0010_0031; + const C: u32 = 0x0010_0032; + const W_DAMAGE: u32 = 0x0080_0031; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + for (xid, parent, x, y, w, h, bw) in [ + (W, ROOT_WINDOW, 0, 0, 200, 200, 0), + (C, ResourceId(W), 80, 80, 50, 50, 4), + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent, + x, + y, + width: w, + height: h, + border_width: bw, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let win = state.resources.window_mut(ResourceId(xid)).expect("window"); + win.map_state = crate::resources::MapState::Viewable; + } + state.damage_objects.insert( + W_DAMAGE, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(W), + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + crate::core_loop::damage_fanout::accumulate_damage_region_to_state( + &mut state, + ResourceId(C), + &[xfixes::RegionRect { + x: 0, + y: 0, + width: 10, + height: 10, + }], + ); + let got: Vec<(i16, i16, u16, u16)> = state.damage_objects[&W_DAMAGE] + .rects + .iter() + .map(|r| (r.x, r.y, r.width, r.height)) + .collect(); + assert_eq!(got, vec![(84, 84, 10, 10)]); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/drawing.rs b/crates/yserver-core/src/core_loop/process_request/tests/drawing.rs new file mode 100644 index 000000000..e9a4595ee --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/drawing.rs @@ -0,0 +1,1807 @@ +use super::*; +use crate::core_loop::process_request::drawing::{ + copy_area_effective_dst_rects, copy_area_source_split, xybitmap_to_target_zpixmap, + xybitmap_to_zpixmap, +}; + +#[test] +fn xybitmap_to_zpixmap_preserves_lsb_first_bits_without_left_pad() { + let src = [ + 0b0000_1101u8, + 0, + 0, + 0, // row 0: 1 0 1 1 + 0b0000_0010u8, + 0, + 0, + 0, // row 1: 0 1 0 0 + ]; + let out = xybitmap_to_zpixmap(&src, 4, 2, 0).expect("convert"); + assert_eq!(out, src); +} + +#[test] +fn xybitmap_to_zpixmap_strips_left_pad_bits() { + let src = [ + 0b0011_0100u8, + 0, + 0, + 0, // left_pad=2, payload bits => 1 0 1 1 + ]; + let out = xybitmap_to_zpixmap(&src, 4, 1, 2).expect("convert"); + assert_eq!(out, vec![0b0000_1101u8, 0, 0, 0]); +} + +#[test] +fn xybitmap_to_target_zpixmap_expands_bits_with_fg_bg_at_depth_24() { + let src = [ + 0b0000_0101u8, + 0, + 0, + 0, // row: 1 0 1 + ]; + let out = + xybitmap_to_target_zpixmap(&src, 3, 1, 0, 24, 0x0000_00ff, 0x0000_ff00).expect("convert"); + assert_eq!(out.len(), 12); + assert_eq!(&out[0..4], &0x0000_00ffu32.to_le_bytes()); + assert_eq!(&out[4..8], &0x0000_ff00u32.to_le_bytes()); + assert_eq!(&out[8..12], &0x0000_00ffu32.to_le_bytes()); +} + +#[test] +fn xybitmap_to_target_zpixmap_expands_bits_with_fg_bg_at_depth_4() { + let src = [ + 0b0000_0110u8, + 0, + 0, + 0, // row: 0 1 1 + ]; + let out = xybitmap_to_target_zpixmap(&src, 3, 1, 0, 4, 0x0d, 0x02).expect("convert"); + assert_eq!(out, vec![0xd2, 0x0d, 0, 0]); +} + +#[test] +fn poly_fill_rectangle_unknown_drawable_returns_bad_drawable() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(0x2000), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + let body = poly_fill_rectangle_body(0xdead_beef, 0x2000); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 70, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + + let bytes = read_all_available(&mut peer); + assert!( + bytes.len() >= 32, + "expected 32-byte error reply, got {} bytes: {:02x?}", + bytes.len(), + bytes + ); + let buf = &bytes[..32]; + assert_eq!(buf[1], x11::error::BAD_DRAWABLE); + assert_eq!(buf[10], 70); +} + +#[test] +fn query_font_invalid_fontable_returns_bad_font() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // QueryFont (op 47) body = FONTABLE(4). 0xdeadbeef is unregistered. + let body = 0xdead_beefu32.to_le_bytes(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 47, + data: 0, + length_units: 2, + }, + &body, + None, + ) + .expect("process_request"); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); + assert_eq!(bytes[1], x11::error::BAD_FONT, "code"); + assert_eq!(bytes[10], 47, "major opcode"); + assert_eq!(&bytes[4..8], &0xdead_beefu32.to_le_bytes(), "bad font id"); +} + +fn run_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + opcode: u8, + seq: u16, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(1), + SequenceNumber(seq), + RequestHeader { + opcode, + data: 0, + length_units: u32::try_from(body.len() / 4 + 1).unwrap(), + }, + body, + None, + ) + .expect("process_request"); +} + +/// Xorg: a GC created without GCFont holds the server default font +/// (`dix/gc.c:507`), so QueryFont on its GContext answers with that font +/// (`dixLookupFontable`) instead of BadFont. +#[test] +fn query_font_on_a_fontless_gc_answers_with_the_default_font() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + crate::core_loop::process_request::install_default_font(&mut state, &mut backend) + .expect("default font"); + // CreateGC(gc, drawable, value-mask = foreground | background). + let gc = 0x0010_0001u32; + let mut body = Vec::new(); + for word in [gc, crate::resources::ROOT_WINDOW.0, 0xc, 0, 0x00ff_ffff] { + body.extend_from_slice(&word.to_le_bytes()); + } + run_request(&mut state, &mut backend, 55, 1, &body); + run_request(&mut state, &mut backend, 47, 2, &gc.to_le_bytes()); + let via_gc = read_all_available(&mut peer); + run_request( + &mut state, + &mut backend, + 47, + 3, + &crate::resources::DEFAULT_FONT.0.to_le_bytes(), + ); + let via_font = read_all_available(&mut peer); + assert_eq!(via_gc[0], 1, "a reply, not an error: {via_gc:02x?}"); + assert_eq!(via_gc[4..], via_font[4..], "same font as the default"); + assert!( + u16::from_le_bytes([via_gc[46], via_gc[47]]) > 0, + "the default font carries properties" + ); +} + +#[test] +fn query_text_extents_invalid_fontable_returns_bad_font() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // QueryTextExtents (op 48) body = FONTABLE(4) + STRING16 (zero chars). + let body = 0xdead_beefu32.to_le_bytes(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 48, + data: 0, + length_units: 2, + }, + &body, + None, + ) + .expect("process_request"); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); + assert_eq!(bytes[1], x11::error::BAD_FONT, "code"); + assert_eq!(bytes[10], 48, "major opcode"); + assert_eq!( + &bytes[4..8], + &0xdead_beefu32.to_le_bytes(), + "bad fontable id" + ); +} + +#[test] +fn poly_fill_rectangle_input_only_returns_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 0, + window: ResourceId(0x1100), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 10, + height: 10, + border_width: 0, + class: 2, + visual: ResourceId(0), + ..Default::default() + }, + ); + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(0x2000), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + let body = poly_fill_rectangle_body(0x1100, 0x2000); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 70, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + + let bytes = read_all_available(&mut peer); + assert!( + bytes.len() >= 32, + "expected 32-byte error reply, got {} bytes: {:02x?}", + bytes.len(), + bytes + ); + let buf = &bytes[..32]; + assert_eq!(buf[1], x11::error::BAD_MATCH); + assert_eq!(buf[10], 70); +} + +#[test] +fn poly_fill_rectangle_depth_mismatch_returns_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: ResourceId(0x1200), + drawable: ROOT_WINDOW, + width: 4, + height: 4, + depth: 1, + }, + ); + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(0x2000), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + let body = poly_fill_rectangle_body(0x1200, 0x2000); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 70, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + + let bytes = read_all_available(&mut peer); + assert!( + bytes.len() >= 32, + "expected 32-byte error reply, got {} bytes: {:02x?}", + bytes.len(), + bytes + ); + let buf = &bytes[..32]; + assert_eq!(buf[1], x11::error::BAD_MATCH); + assert_eq!(buf[10], 70); +} + +/// X11 §CopyArea source-availability split: requested source +/// rect vs source drawable bounds → (clamped copy, missing +/// dst-coord rects for GraphicsExpose). +#[test] +fn copy_area_source_split_right_half_missing() { + let mut state = ServerState::new(); + // 100×100 pixmap as the source. + state.resources.create_pixmap( + ClientId(1), + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(0x700), + drawable: crate::resources::ROOT_WINDOW, + width: 100, + height: 100, + }, + ); + // Copy 100 wide from x=50 → right 50 missing. + let (avail, missing) = copy_area_source_split(&state, ResourceId(0x700), 50, 0, 0, 0, 100, 100); + assert_eq!(avail, Some((50, 0, 0, 0, 50, 100)), "clamped copy"); + assert_eq!( + missing, + vec![(50, 0, 50, 100)], + "missing right half in DST coords (xts XCopyArea-4 expects x=50 w=50)" + ); + // Fully in-bounds → NoExposure (empty missing list). + let (avail, missing) = copy_area_source_split(&state, ResourceId(0x700), 0, 0, 10, 10, 80, 80); + assert_eq!(avail, Some((0, 0, 10, 10, 80, 80))); + assert!(missing.is_empty(), "fully available → NoExposure"); + // Fully out of bounds → no copy, whole rect exposed. + let (avail, missing) = copy_area_source_split(&state, ResourceId(0x700), 200, 0, 5, 5, 30, 30); + assert!(avail.is_none()); + assert_eq!(missing, vec![(5, 5, 30, 30)]); +} + +/// Stage 4d follow-up (codex review 2026-05-18): when ClipByChildren +/// (or any other clipping) fully covers the destination so no pixels +/// are actually copied, the X11 spec still requires the server to +/// emit a GraphicsExpose / NoExposure event for clients with +/// `graphics-exposures=True`. Pre-fix the early-return-on-empty +/// path silently swallowed this event; clients waiting on it +/// (xterm, gtk2 backing-store users) would hang. +#[test] +fn copy_area_fully_clipped_still_emits_graphics_expose_event() { + use std::io::Read; + use yserver_protocol::x11::{CreateGcRequest, CreateWindowRequest}; + + const FRAME_XID: u32 = 0x0010_0001; + const FRAME_HOST: u32 = 0x0040_0001; + const FRAME_BACKING_HOST: u32 = 0x0050_0001; + const CHILD_XID: u32 = 0x0010_0002; + const CHILD_HOST: u32 = 0x0040_0002; + const SRC_PIXMAP_XID: u32 = 0x0010_0010; + const SRC_PIXMAP_HOST: u32 = 0x0040_0010; + const GC_XID: u32 = 0x0010_0020; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // Make the peer-read non-blocking so an absent event doesn't + // hang the test. + peer.set_nonblocking(true).expect("nonblocking"); + let mut backend = RecordingBackend::new(); + + // Frame 100×100 entirely covered by child window 100×100 at + // (0, 0). Any CopyArea(dst=frame, 0,0 100x100) gets fully + // clipped by the child. + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(FRAME_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(FRAME_XID)) + .expect("frame"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(FRAME_HOST)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(FRAME_BACKING_HOST), + width: 100, + height: 100, + depth: 24, + }); + w.map_state = crate::resources::MapState::Viewable; + } + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_XID), + parent: ResourceId(FRAME_XID), + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(CHILD_XID)) + .expect("child"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(CHILD_HOST)); + w.map_state = crate::resources::MapState::Viewable; + } + state.resources.create_pixmap( + ClientId(1), + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(SRC_PIXMAP_XID), + drawable: ROOT_WINDOW, + width: 100, + height: 100, + depth: 24, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(SRC_PIXMAP_XID), + crate::backend::PixmapHandle::from_raw_for_test(SRC_PIXMAP_HOST), + ); + // GC with graphics_exposures = True (the spec default; without + // explicit override the GC inherits that default). + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(GC_XID), + drawable: ResourceId(FRAME_XID), + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: Some(true), + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&SRC_PIXMAP_XID.to_le_bytes()); + body.extend_from_slice(&FRAME_XID.to_le_bytes()); + body.extend_from_slice(&GC_XID.to_le_bytes()); + body.extend_from_slice(&0_i16.to_le_bytes()); + body.extend_from_slice(&0_i16.to_le_bytes()); + body.extend_from_slice(&0_i16.to_le_bytes()); + body.extend_from_slice(&0_i16.to_le_bytes()); + body.extend_from_slice(&100_u16.to_le_bytes()); + body.extend_from_slice(&100_u16.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 62, + data: 0, + length_units: 7, + }, + &body, + None, + ) + .expect("dispatch CopyArea"); + + // No backend.copy_area should have fired (fully clipped). + let copy_calls = backend + .calls() + .into_iter() + .filter(|c| matches!(c, crate::backend::recording::RecordedCall::CopyArea { .. })) + .count(); + assert_eq!( + copy_calls, 0, + "fully-clipped CopyArea must NOT call backend.copy_area", + ); + + // The graphics-exposures contract still fires for a fully + // dst-clipped copy — but as NoExposure: the SOURCE was fully + // available (GraphicsExpose only describes missing source + // regions; dst-side child clipping doesn't expose anything). + let mut buf = [0u8; 64]; + let n = peer.read(&mut buf).unwrap_or(0); + assert!( + n >= 32, + "expected a 32-byte NoExposure event even for a \ + fully-clipped CopyArea (codex review 2026-05-18); got \ + {n} bytes", + ); + assert_eq!( + buf[0], 14, + "first byte must be NoExposure (event type 14) — source \ + fully available", + ); +} + +// ---- Unviewable CopyArea/CopyPlane sources (Xorg micopy.c / miexpose.c) ---- + +const UV_FRAME: u32 = 0x0010_0101; +const UV_CHILD: u32 = 0x0010_0102; +const UV_LONE: u32 = 0x0010_0103; +const UV_SHOWN: u32 = 0x0010_0104; +const UV_PIXMAP: u32 = 0x0010_0110; +const UV_DST_PIXMAP: u32 = 0x0010_0111; +const UV_GC: u32 = 0x0010_0120; +const UV_GC_NOEXP: u32 = 0x0010_0121; + +fn uv_gc_request(gc: u32, graphics_exposures: bool) -> yserver_protocol::x11::CreateGcRequest { + yserver_protocol::x11::CreateGcRequest { + gc: ResourceId(gc), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: Some(graphics_exposures), + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + } +} + +fn uv_window( + state: &mut ServerState, + xid: u32, + parent: ResourceId, + map_state: crate::resources::MapState, +) { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let w = state.resources.window_mut(ResourceId(xid)).expect("window"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + xid | 0x0040_0000, + )); + w.map_state = map_state; +} + +fn uv_pixmap(state: &mut ServerState, xid: u32) { + state.resources.create_pixmap( + ClientId(1), + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(xid), + drawable: ROOT_WINDOW, + width: 100, + height: 100, + depth: 24, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(xid), + crate::backend::PixmapHandle::from_raw_for_test(xid | 0x0040_0000), + ); +} + +/// Unmapped frame with a mapped (so Unviewable) child, a lone unmapped +/// window, a viewable window, two pixmaps and GCs with exposures on/off. +fn uv_fixture() -> (ServerState, UnixStream) { + use crate::resources::MapState; + let mut state = ServerState::new(); + let peer = install_client(&mut state, 1); + uv_window(&mut state, UV_FRAME, ROOT_WINDOW, MapState::Unmapped); + uv_window( + &mut state, + UV_CHILD, + ResourceId(UV_FRAME), + MapState::Unviewable, + ); + uv_window(&mut state, UV_LONE, ROOT_WINDOW, MapState::Unmapped); + uv_window(&mut state, UV_SHOWN, ROOT_WINDOW, MapState::Viewable); + uv_pixmap(&mut state, UV_PIXMAP); + uv_pixmap(&mut state, UV_DST_PIXMAP); + state + .resources + .create_gc(ClientId(1), uv_gc_request(UV_GC, true)); + state + .resources + .create_gc(ClientId(1), uv_gc_request(UV_GC_NOEXP, false)); + (state, peer) +} + +#[allow(clippy::too_many_arguments)] +fn uv_copy( + state: &mut ServerState, + backend: &mut RecordingBackend, + opcode: u8, + src: u32, + dst: u32, + gc: u32, + src_xy: (i16, i16), + dst_xy: (i16, i16), + size: (u16, u16), +) { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&src.to_le_bytes()); + body.extend_from_slice(&dst.to_le_bytes()); + body.extend_from_slice(&gc.to_le_bytes()); + body.extend_from_slice(&src_xy.0.to_le_bytes()); + body.extend_from_slice(&src_xy.1.to_le_bytes()); + body.extend_from_slice(&dst_xy.0.to_le_bytes()); + body.extend_from_slice(&dst_xy.1.to_le_bytes()); + body.extend_from_slice(&size.0.to_le_bytes()); + body.extend_from_slice(&size.1.to_le_bytes()); + if opcode == 63 { + body.extend_from_slice(&1u32.to_le_bytes()); + } + process_request( + state, + backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("dispatch copy"); +} + +fn uv_copy_calls(backend: &RecordingBackend) -> usize { + use crate::backend::recording::RecordedCall; + backend + .calls() + .into_iter() + .filter(|c| { + matches!( + c, + RecordedCall::CopyArea { .. } | RecordedCall::CopyPlane { .. } + ) + }) + .count() +} + +/// Decoded (type, drawable, x, y, w, h, count, major) per 32-byte event. +type UvEvent = (u8, u32, u16, u16, u16, u16, u16, u8); + +fn uv_events(bytes: &[u8]) -> Vec { + bytes + .chunks_exact(32) + .map(|e| { + let u16_at = |i: usize| u16::from_le_bytes([e[i], e[i + 1]]); + let drawable = u32::from_le_bytes([e[4], e[5], e[6], e[7]]); + if e[0] == 13 { + ( + 13, + drawable, + u16_at(8), + u16_at(10), + u16_at(12), + u16_at(14), + u16_at(18), + e[20], + ) + } else { + (e[0], drawable, 0, 0, 0, 0, 0, e[10]) + } + }) + .collect() +} + +/// `miHandleExposures` (`mi/miexpose.c:120-305`) as measured by +/// tools/vng-scenarios/expose-probe.c: a client window C (190x100) +/// with a child V (100,10 80x120). A scroll whose source runs past +/// C's bottom lands its missing rows outside C: NoExpose. A source +/// under V is hidden under ClipByChildren, not under IncludeInferiors. +#[test] +fn copy_area_exposes_what_the_source_hides_inside_the_destination_clip() { + use crate::resources::MapState; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let (c, v) = (0x0010_0130u32, 0x0010_0131u32); + uv_window(&mut state, c, ROOT_WINDOW, MapState::Viewable); + uv_window(&mut state, v, ResourceId(c), MapState::Viewable); + for (id, x, y, w, h) in [(c, 5, 20, 190, 100), (v, 100, 10, 80, 120)] { + let win = state.resources.window_mut(ResourceId(id)).unwrap(); + (win.x, win.y, win.width, win.height) = (x, y, w, h); + } + state + .resources + .create_gc(ClientId(1), uv_gc_request(UV_GC, true)); + let mut inferiors = uv_gc_request(UV_GC_NOEXP, true); + inferiors.subwindow_mode = Some(1); + state.resources.create_gc(ClientId(1), inferiors); + let mut copy = |state: &mut ServerState, gc, src: (i16, i16), dst: (i16, i16), size| { + uv_copy(state, &mut backend, 62, c, c, gc, src, dst, size); + uv_events(&read_all_available(&mut peer)) + }; + assert_eq!( + copy(&mut state, UV_GC, (0, 0), (0, 40), (100, 200)), + vec![(14, c, 0, 0, 0, 0, 0, 62)], + "NoExpose" + ); + assert_eq!( + copy(&mut state, UV_GC, (90, 20), (10, 20), (40, 40)), + vec![(13, c, 20, 20, 30, 40, 0, 62)] + ); + assert_eq!( + copy(&mut state, UV_GC_NOEXP, (90, 20), (10, 20), (40, 40)), + vec![(14, c, 0, 0, 0, 0, 0, 62)], + "IncludeInferiors: V's pixels are the source's" + ); +} + +/// Xorg: an unrealized source window has an empty clipList +/// (mivaltree.c:691-696, miwindow.c:741-744, window.c:892), so miDoCopy +/// copies nothing and miHandleExposures exposes the whole rect. +#[test] +fn copy_area_from_unviewable_window_exposes_whole_dest_rect() { + for (opcode, src) in [ + (62u8, UV_LONE), + (62, UV_CHILD), + (63, UV_LONE), + (63, UV_CHILD), + ] { + let (mut state, mut peer) = uv_fixture(); + let mut backend = RecordingBackend::new(); + uv_copy( + &mut state, + &mut backend, + opcode, + src, + UV_DST_PIXMAP, + UV_GC, + (10, 20), + (5, 7), + (30, 40), + ); + assert_eq!( + uv_copy_calls(&backend), + 0, + "op {opcode} src 0x{src:x}: nothing copied" + ); + assert_eq!( + uv_events(&read_all_available(&mut peer)), + vec![(13, UV_DST_PIXMAP, 5, 7, 30, 40, 0, opcode)], + "op {opcode} src 0x{src:x}: one GraphicsExpose for the dest rect, no NoExpose", + ); + } +} + +#[test] +fn copy_area_from_unviewable_window_without_exposures_sends_nothing() { + for opcode in [62u8, 63] { + let (mut state, mut peer) = uv_fixture(); + let mut backend = RecordingBackend::new(); + uv_copy( + &mut state, + &mut backend, + opcode, + UV_CHILD, + UV_DST_PIXMAP, + UV_GC_NOEXP, + (0, 0), + (0, 0), + (30, 40), + ); + assert_eq!(uv_copy_calls(&backend), 0); + assert!( + read_all_available(&mut peer).is_empty(), + "op {opcode}: no events" + ); + } +} + +/// A pixmap or viewable window source is unchanged: copied, NoExpose. +#[test] +fn copy_area_from_pixmap_or_viewable_window_still_copies_with_no_expose() { + for opcode in [62u8, 63] { + for src in [UV_PIXMAP, UV_SHOWN] { + let (mut state, mut peer) = uv_fixture(); + let mut backend = RecordingBackend::new(); + uv_copy( + &mut state, + &mut backend, + opcode, + src, + UV_DST_PIXMAP, + UV_GC, + (10, 20), + (5, 7), + (30, 40), + ); + assert_eq!(uv_copy_calls(&backend), 1, "op {opcode} src 0x{src:x}"); + assert_eq!( + uv_events(&read_all_available(&mut peer)), + vec![(14, UV_DST_PIXMAP, 0, 0, 0, 0, 0, opcode)], + "op {opcode} src 0x{src:x}: NoExpose", + ); + } + } +} + +/// Xorg miDoCopy returns NULL for an unrealized destination before any +/// copy or exposure (micopy.c:157-160), so the requestor gets NoExpose +/// even when the source is unavailable. +#[test] +fn copy_area_to_unviewable_window_copies_nothing_and_sends_no_expose() { + for opcode in [62u8, 63] { + for (src, src_xy) in [(UV_PIXMAP, (0, 0)), (UV_PIXMAP, (90, 0)), (UV_LONE, (0, 0))] { + let (mut state, mut peer) = uv_fixture(); + let mut backend = RecordingBackend::new(); + uv_copy( + &mut state, + &mut backend, + opcode, + src, + UV_CHILD, + UV_GC, + src_xy, + (0, 0), + (30, 40), + ); + assert_eq!(uv_copy_calls(&backend), 0, "op {opcode} src 0x{src:x}"); + assert!( + !backend.calls().iter().any(|c| matches!( + c, + crate::backend::recording::RecordedCall::PaintWindowBackgroundRect { .. } + )), + "op {opcode} src 0x{src:x}: no background paint", + ); + assert_eq!( + uv_events(&read_all_available(&mut peer)), + vec![(14, UV_CHILD, 0, 0, 0, 0, 0, opcode)], + "op {opcode} src 0x{src:x} at {src_xy:?}: NoExpose", + ); + } + } +} + +/// Drawing to an unmapped window records no damage (Xorg damage.c:197). +#[test] +fn poly_fill_on_unmapped_window_records_no_damage() { + use crate::server::DamageObject; + const DAMAGE_XID: u32 = 0x0010_0130; + for (window, expect_damage) in [(UV_LONE, false), (UV_CHILD, false), (UV_SHOWN, true)] { + let (mut state, _peer) = uv_fixture(); + let mut backend = RecordingBackend::new(); + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(window), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + let body = poly_fill_rectangle_body(window, UV_GC); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 70, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("PolyFillRectangle"); + let dmg = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object"); + assert_eq!( + !dmg.rects.is_empty() || dmg.pending_notify_fired, + expect_damage, + "window 0x{window:x}: rects={:?} fired={}", + dmg.rects, + dmg.pending_notify_fired, + ); + } +} + +/// Stage 4d Manual-redirect CopyArea ClipByChildren fix. +/// +/// Scenario (matches marco's failing #6886 / #7450 CopyArea on +/// the MATE Control Center frame): +/// - Frame window 997×652 at root, mapped, with a redirected +/// backing pixmap allocated. +/// - CC client window 975×600 reparented under the frame at +/// (11, 41), mapped. +/// - X11 CopyArea(src=decoration_pixmap, dst=frame_window, +/// gc=default) 997×652. +/// +/// Pre-fix: dispatch resolves `dst` to the backing pixmap and +/// hands the backend a single full-extent copy, which clobbers +/// the area where CC's content lives in the backing. +/// +/// Spec-correct (Xorg `mi/midispcur.c` + the X11 GC +/// `subwindow-mode` default): under `ClipByChildren`, subtract +/// every mapped child's geometry before copying. Result is the +/// four border strips (top/bottom/left/right of CC). +#[test] +fn copy_area_into_window_with_mapped_child_excludes_child_area() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreateGcRequest, CreateWindowRequest}; + + const FRAME_XID: u32 = 0x0010_0001; + const FRAME_HOST: u32 = 0x0040_0001; + const FRAME_BACKING_HOST: u32 = 0x0050_0001; + const CHILD_XID: u32 = 0x0010_0002; + const CHILD_HOST: u32 = 0x0040_0002; + const SRC_PIXMAP_XID: u32 = 0x0010_0010; + const SRC_PIXMAP_HOST: u32 = 0x0040_0010; + const GC_XID: u32 = 0x0010_0020; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Frame: top-level under root, viewable, redirected (backing + // present). Mirrors the post-Reparent + post-Map + post- + // activate_redirect_backing state. + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(FRAME_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 997, + height: 652, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(FRAME_XID)) + .expect("frame"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(FRAME_HOST)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(FRAME_BACKING_HOST), + width: 997, + height: 652, + depth: 24, + }); + w.map_state = crate::resources::MapState::Viewable; + } + // CC: child of frame, viewable, at (11, 41) sized 975×600. + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_XID), + parent: ResourceId(FRAME_XID), + x: 11, + y: 41, + width: 975, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(CHILD_XID)) + .expect("child"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(CHILD_HOST)); + w.map_state = crate::resources::MapState::Viewable; + } + // Source pixmap (depth-24, same depth as frame). + state.resources.create_pixmap( + ClientId(1), + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(SRC_PIXMAP_XID), + drawable: ROOT_WINDOW, + width: 997, + height: 652, + depth: 24, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(SRC_PIXMAP_XID), + crate::backend::PixmapHandle::from_raw_for_test(SRC_PIXMAP_HOST), + ); + // GC for client 1. Every value-mask field is None → defaults + // apply, including subwindow-mode = ClipByChildren. + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(GC_XID), + drawable: ResourceId(FRAME_XID), + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + // Build CopyArea body: src(4) dst(4) gc(4) src_x(2) src_y(2) + // dst_x(2) dst_y(2) width(2) height(2). + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&SRC_PIXMAP_XID.to_le_bytes()); + body.extend_from_slice(&FRAME_XID.to_le_bytes()); + body.extend_from_slice(&GC_XID.to_le_bytes()); + body.extend_from_slice(&0_i16.to_le_bytes()); // src_x + body.extend_from_slice(&0_i16.to_le_bytes()); // src_y + body.extend_from_slice(&0_i16.to_le_bytes()); // dst_x + body.extend_from_slice(&0_i16.to_le_bytes()); // dst_y + body.extend_from_slice(&997_u16.to_le_bytes()); // width + body.extend_from_slice(&652_u16.to_le_bytes()); // height + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 62, // CopyArea major opcode + data: 0, + length_units: 7, // 1 header + 6 body words = 7 (4-byte units) + }, + &body, + None, + ) + .expect("dispatch CopyArea"); + + let copy_calls: Vec<_> = backend + .calls() + .into_iter() + .filter_map(|c| match c { + RecordedCall::CopyArea { + src_host_xid, + dst_host_xid, + src_x, + src_y, + dst_x, + dst_y, + width, + height, + } => Some(( + src_host_xid, + dst_host_xid, + src_x, + src_y, + dst_x, + dst_y, + width, + height, + )), + _ => None, + }) + .collect(); + + // Pre-fix: a single 997×652 CopyArea covering CC's area. + // Post-fix: four border strips that miss the (11, 41, 975, 600) + // child rect entirely. + assert_eq!( + copy_calls.len(), + 4, + "expected 4 border strips for ClipByChildren around the \ + mapped child; pre-fix this is 1 (the full-extent copy \ + that clobbers CC's area in the backing); got {copy_calls:?}", + ); + + // No copy may overlap the child rect (11, 41, 975, 600). + let child = (11_i32, 41_i32, 11_i32 + 975, 41_i32 + 600); + for (_, dst_host, _, _, dx, dy, w, h) in ©_calls { + let r = ( + i32::from(*dx), + i32::from(*dy), + i32::from(*dx) + i32::from(*w), + i32::from(*dy) + i32::from(*h), + ); + let overlaps = r.0 < child.2 && r.2 > child.0 && r.1 < child.3 && r.3 > child.1; + assert!( + !overlaps, + "copy strip ({dx},{dy} {w}x{h}) overlaps the child rect (11,41 975x600); \ + ClipByChildren must exclude mapped children", + ); + // Preserve window identity for backend border translation. + assert_eq!( + *dst_host, FRAME_HOST, + "ClipByChildren strips stay in window-local coordinates", + ); + } +} + +/// InputOnly children do not contribute visible pixels and must +/// not be subtracted by ClipByChildren. +#[test] +fn copy_area_clip_by_children_ignores_input_only_child() { + use crate::resources::{MapState, WindowClass}; + use yserver_protocol::x11::{CreateWindowRequest, ResourceId}; + + let mut state = ServerState::new(); + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(0x0020_0001), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 0, + window: ResourceId(0x0020_0002), + parent: ResourceId(0x0020_0001), + x: 10, + y: 10, + width: 20, + height: 20, + border_width: 0, + class: 2, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let child = state + .resources + .window_mut(ResourceId(0x0020_0002)) + .expect("child"); + child.map_state = MapState::Viewable; + assert_eq!(child.class, WindowClass::InputOnly); + } + + let rect = yserver_protocol::x11::CopyAreaRequest { + src: ResourceId(0x1), + dst: ResourceId(0x0020_0001), + gc: ResourceId(0x1), + src_x: 0, + src_y: 0, + dst_x: 0, + dst_y: 0, + width: 100, + height: 80, + }; + let draw_state = crate::backend::DrawState { + subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, + ..Default::default() + }; + + let got = copy_area_effective_dst_rects(&state, ResourceId(0x0020_0001), &draw_state, &rect); + assert_eq!(got.len(), 1); + assert_eq!(got[0].x, 0); + assert_eq!(got[0].y, 0); + assert_eq!(got[0].width, 100); + assert_eq!(got[0].height, 80); +} + +/// A bounding-shaped child takes only its shape out of its parent +/// under ClipByChildren (Xorg subtracts its `borderSize`, +/// `dix/window.c:1747-1770`). xfce4-settings-manager's socket S at +/// (8,8) 730x531 is shaped to the 450 rows of its viewport, and the +/// manager repaints its button bar under S's rect but outside its +/// shape with `CopyArea(8,464 730x36)`; measured on Xorg 21.1 by +/// tools/vng-scenarios/xembed-scroll-probe.c, the bar is drawn. +#[test] +fn copy_area_clip_by_children_takes_out_only_a_shaped_childs_shape() { + use crate::resources::MapState; + use yserver_protocol::x11::{CreateWindowRequest, ResourceId, shape as x11shape}; + + let mut state = ServerState::new(); + let (c, s) = (ResourceId(0x0020_0101), ResourceId(0x0020_0102)); + for (window, parent, x, y, width, height) in + [(c, ROOT_WINDOW, 0, 0, 746, 500), (s, c, 8, 8, 730, 531)] + { + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + CreateWindowRequest { + depth: 24, + window, + parent, + x, + y, + width, + height, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + state.resources.window_mut(s).expect("socket").map_state = MapState::Viewable; + crate::nested::set_shape_rects( + &mut state, + s, + x11shape::KIND_BOUNDING, + vec![yserver_protocol::x11::xfixes::RegionRect { + x: 0, + y: 0, + width: 730, + height: 450, + }], + ); + let request = yserver_protocol::x11::CopyAreaRequest { + src: ResourceId(0x1), + dst: c, + gc: ResourceId(0x1), + src_x: 0, + src_y: 0, + dst_x: 8, + dst_y: 464, + width: 730, + height: 36, + }; + let draw_state = crate::backend::DrawState { + subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, + ..Default::default() + }; + let got = copy_area_effective_dst_rects(&state, c, &draw_state, &request); + assert_eq!(got.len(), 1); + assert_eq!( + (got[0].x, got[0].y, got[0].width, got[0].height), + (8, 464, 730, 36) + ); +} + +/// MANUALLY-redirected children must not be subtracted by +/// ClipByChildren. They don't claim the parent's pixmap real +/// estate — the redirecting compositor (which may be the +/// parent's own client) puts the children's pixels there +/// itself via subsequent ops. Subtracting them strips the +/// compositor's own composite-target rect to empty. +/// +/// Live trigger: mate-panel notification-area-applet, which +/// calls `RedirectWindow(socket, Manual)` on each tray slot and +/// then `CopyArea` from each embedded applet's redirected +/// pixmap into its own visible top-level. Pre-fix every such +/// CopyArea is "fully clipped, no backend call" because the +/// manually-redirected socket children fully overlap the +/// destination — so the tray icons never make it into the +/// notification-area-applet's own backing, and mate-compositor +/// (which reads that backing via NameWindowPixmap) shows the +/// panel without icons. +#[test] +fn copy_area_clip_by_children_ignores_manually_redirected_child() { + use crate::{ + resources::{MapState, WindowClass}, + server::{CompositeRedirectMode, RedirectRecord}, + }; + use yserver_protocol::x11::{ClientId, CreateWindowRequest, ResourceId}; + + let mut state = ServerState::new(); + let parent_xid = ResourceId(0x0021_0003); + let child_xid = ResourceId(0x0021_0013); + + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: parent_xid, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: child_xid, + parent: parent_xid, + x: 0, + y: 0, + width: 100, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let child = state.resources.window_mut(child_xid).expect("child"); + child.map_state = MapState::Viewable; + assert_eq!(child.class, WindowClass::InputOutput); + } + // RedirectWindow(child, Manual). Key shape is + // `(window, subwindows=false)` for per-window + // RedirectWindow (vs `(parent, true)` for the inherited + // RedirectSubwindows form). + state + .composite_redirects + .redirect_window( + child_xid, + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); + + let rect = yserver_protocol::x11::CopyAreaRequest { + src: ResourceId(0x1), + dst: parent_xid, + gc: ResourceId(0x1), + src_x: 0, + src_y: 0, + dst_x: 0, + dst_y: 0, + width: 100, + height: 80, + }; + let draw_state = crate::backend::DrawState { + subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, + ..Default::default() + }; + + let got = copy_area_effective_dst_rects(&state, parent_xid, &draw_state, &rect); + assert_eq!( + got.len(), + 1, + "manual-redirected child must not be subtracted; got {got:?}" + ); + assert_eq!(got[0].x, 0); + assert_eq!(got[0].y, 0); + assert_eq!(got[0].width, 100); + assert_eq!(got[0].height, 80); +} + +/// Regression guard: an AUTOMATIC-redirected child *must* +/// still be subtracted by ClipByChildren. With Automatic +/// redirect the X server auto-composites the child's backing +/// into the parent's pixmap; the parent's own paint then +/// clipping out the child's area is the correct shape (the +/// child's pixels arrive via the auto-composite, not via the +/// parent's paint). The manual-only exception above must not +/// loosen this case. +#[test] +fn copy_area_clip_by_children_still_subtracts_automatic_redirected_child() { + use crate::{ + resources::{MapState, WindowClass}, + server::{CompositeRedirectMode, RedirectRecord}, + }; + use yserver_protocol::x11::{ClientId, CreateWindowRequest, ResourceId}; + + let mut state = ServerState::new(); + let parent_xid = ResourceId(0x0022_0001); + let child_xid = ResourceId(0x0022_0002); + + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: parent_xid, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: child_xid, + parent: parent_xid, + x: 10, + y: 10, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let child = state.resources.window_mut(child_xid).expect("child"); + child.map_state = MapState::Viewable; + assert_eq!(child.class, WindowClass::InputOutput); + } + state + .composite_redirects + .redirect_window( + child_xid, + RedirectRecord { + mode: CompositeRedirectMode::Automatic, + owner: ClientId(1), + }, + ) + .unwrap(); + + let rect = yserver_protocol::x11::CopyAreaRequest { + src: ResourceId(0x1), + dst: parent_xid, + gc: ResourceId(0x1), + src_x: 0, + src_y: 0, + dst_x: 0, + dst_y: 0, + width: 100, + height: 80, + }; + let draw_state = crate::backend::DrawState { + subwindow_mode: crate::backend::SubwindowMode::ClipByChildren, + ..Default::default() + }; + + let got = copy_area_effective_dst_rects(&state, parent_xid, &draw_state, &rect); + // Automatic-redirected child is still subtracted, so we + // expect the original 100×80 rect to be split into four + // border strips around the (10,10 50x50) child rect. + assert!( + got.len() >= 2, + "automatic-redirected child must still be subtracted; expected > 1 \ + strip, got {got:?}" + ); + let child = (10_i32, 10_i32, 60_i32, 60_i32); + for r in &got { + let rr = ( + i32::from(r.x), + i32::from(r.y), + i32::from(r.x) + i32::from(r.width), + i32::from(r.y) + i32::from(r.height), + ); + let overlaps = rr.0 < child.2 && rr.2 > child.0 && rr.1 < child.3 && rr.3 > child.1; + assert!( + !overlaps, + "strip ({},{} {}x{}) overlaps automatic-redirected child (10,10 50x50)", + r.x, r.y, r.width, r.height, + ); + } +} + +// ── Redirected-backing geometry, D: draws name the window, not its backing ── + +const RD_WIN: u32 = 0x0020_0001; +const RD_WIN_HOST: u32 = 0x0040_0001; +const RD_BACKING_HOST: u32 = 0x0040_0002; +const RD_PIXMAP: u32 = 0x0020_0003; +const RD_PIXMAP_HOST: u32 = 0x0040_0003; +const RD_GC: u32 = 0x0020_0004; + +/// A viewable, bordered, redirected top-level plus a depth-24 pixmap and a GC. +fn redirected_draw_fixture() -> (ServerState, UnixStream) { + let mut state = ServerState::new(); + let peer = install_client(&mut state, 1); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(RD_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 4, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(RD_WIN)) + .expect("window"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(RD_WIN_HOST)); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(RD_BACKING_HOST), + width: 108, + height: 108, + depth: 24, + }); + w.map_state = crate::resources::MapState::Viewable; + } + state.resources.create_pixmap( + ClientId(1), + yserver_protocol::x11::CreatePixmapRequest { + pixmap: ResourceId(RD_PIXMAP), + drawable: ROOT_WINDOW, + width: 10, + height: 10, + depth: 24, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(RD_PIXMAP), + crate::backend::PixmapHandle::from_raw_for_test(RD_PIXMAP_HOST), + ); + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(RD_GC), + drawable: ResourceId(RD_WIN), + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: Some(false), + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + (state, peer) +} + +fn run_draw(state: &mut ServerState, opcode: u8, data: u8, body: &[u8]) -> Vec { + let mut backend = RecordingBackend::new(); + process_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("process_request"); + backend.calls() +} + +/// Xorg draws a redirected window at its content origin inside the pixmap +/// (`__fbPixOffXWin`, fb/fb.h:445); only the window xid carries that offset +/// and ClipByChildren to the backend. +#[test] +fn poly_fill_rect_on_a_redirected_window_names_the_window() { + let (mut state, _peer) = redirected_draw_fixture(); + let calls = run_draw(&mut state, 70, 0, &poly_fill_rectangle_body(RD_WIN, RD_GC)); + let hosts: Vec = calls + .iter() + .filter_map(|c| match c { + RecordedCall::PolyFillRectangle { host_xid } => Some(*host_xid), + _ => None, + }) + .collect(); + assert_eq!(hosts, vec![RD_WIN_HOST], "{calls:?}"); +} + +#[test] +fn put_image_on_a_redirected_window_names_the_window() { + let (mut state, _peer) = redirected_draw_fixture(); + let mut body = Vec::new(); + body.extend_from_slice(&RD_WIN.to_le_bytes()); + body.extend_from_slice(&RD_GC.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + body.push(0); // left pad + body.push(24); // depth + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(&0x0000_00ffu32.to_le_bytes()); + // format ZPixmap (2) rides in the header data byte. + let calls = run_draw(&mut state, 72, 2, &body); + let hosts: Vec = calls + .iter() + .filter_map(|c| match c { + RecordedCall::PutImage { host_xid, .. } => Some(*host_xid), + _ => None, + }) + .collect(); + assert_eq!(hosts, vec![RD_WIN_HOST], "{calls:?}"); +} + +#[test] +fn copy_plane_onto_a_redirected_window_names_the_window() { + let (mut state, _peer) = redirected_draw_fixture(); + let mut body = Vec::new(); + body.extend_from_slice(&RD_PIXMAP.to_le_bytes()); + body.extend_from_slice(&RD_WIN.to_le_bytes()); + body.extend_from_slice(&RD_GC.to_le_bytes()); + for v in [0i16, 0, 0, 0] { + body.extend_from_slice(&v.to_le_bytes()); + } + body.extend_from_slice(&10u16.to_le_bytes()); + body.extend_from_slice(&10u16.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + let calls = run_draw(&mut state, 63, 0, &body); + let dsts: Vec = calls + .iter() + .filter_map(|c| match c { + RecordedCall::CopyPlane { dst_host_xid, .. } => Some(*dst_host_xid), + _ => None, + }) + .collect(); + assert_eq!(dsts, vec![RD_WIN_HOST], "{calls:?}"); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/dri3_shm.rs b/crates/yserver-core/src/core_loop/process_request/tests/dri3_shm.rs new file mode 100644 index 000000000..d3bc69dbd --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/dri3_shm.rs @@ -0,0 +1,1516 @@ +use super::*; +use crate::core_loop::process_request::{ + misc::{advertised_extension_names, extension_query_reply}, + xshm::{extract_shm_zpixmap_region, handle_mit_shm_put_image}, +}; + +#[test] +fn remote_clients_are_rejected_before_dri3_and_mit_shm_handlers() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").is_local = false; + let mut backend = RecordingBackend::new(); + + for (sequence, minor) in (0u8..=11).enumerate() { + #[allow(clippy::cast_possible_truncation)] + let sequence = sequence as u16 + 1; + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode: 147, + data: minor, + length_units: 1, + }, + &[], + None, + ) + .expect("dispatch"); + let reply = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(reply.len(), 32); + assert_eq!(reply[0], 0); + assert_eq!(reply[1], x11::error::BAD_MATCH); + assert_eq!( + u16::from_le_bytes(reply[8..10].try_into().unwrap()), + u16::from(minor) + ); + assert_eq!(reply[10], 147); + } + + for (sequence, minor) in (1u8..=7).enumerate() { + #[allow(clippy::cast_possible_truncation)] + let sequence = sequence as u16 + 20; + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode: 130, + data: minor, + length_units: 1, + }, + &[], + None, + ) + .expect("dispatch"); + let reply = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(reply.len(), 32); + assert_eq!(reply[0], 0); + assert_eq!(reply[1], x11::error::BAD_REQUEST); + assert_eq!( + u16::from_le_bytes(reply[8..10].try_into().unwrap()), + u16::from(minor) + ); + assert_eq!(reply[10], 130); + } +} + +#[test] +fn remote_mit_shm_query_version_remains_reachable() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").is_local = false; + let mut backend = RecordingBackend::new(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 130, + data: 0, + length_units: 1, + }, + &[], + None, + ) + .expect("ShmQueryVersion dispatch"); + let reply = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(reply[0], 1, "ShmQueryVersion must not be locality-gated"); +} + +#[test] +fn local_clients_reach_dri3_and_mit_shm_handlers() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: yserver_protocol::x11::dri3::QUERY_VERSION, + length_units: 3, + }, + &[1, 0, 0, 0, 4, 0, 0, 0], + None, + ) + .expect("DRI3::QueryVersion dispatch"); + let reply = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(reply[0], 1, "local DRI3 request reaches its handler"); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 130, + data: yserver_protocol::x11::mit_shm::ATTACH, + length_units: 1, + }, + &[], + None, + ) + .expect("MIT-SHM Attach dispatch"); + let reply = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(reply[0], 0, "malformed local request reaches the handler"); + assert_eq!(reply[1], x11::error::BAD_LENGTH); +} + +#[test] +fn remote_client_can_query_present() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").is_local = false; + let mut backend = RecordingBackend::new(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::QUERY_VERSION, + length_units: 1, + }, + &[], + None, + ) + .expect("Present::QueryVersion dispatch"); + let reply = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(reply[0], 1, "Present must not be locality-gated"); +} + +#[test] +fn locality_gated_extensions_remain_advertised() { + let mut backend = syncobj_cap_backend(); + let names = advertised_extension_names(&mut backend); + + for name in ["MIT-SHM", "DRI3", "XFree86-VidModeExtension"] { + assert!( + extension_query_reply(name, &mut backend).is_some(), + "{name} must be advertised before its per-client locality gate" + ); + assert!( + names.contains(&name), + "{name} must remain in ListExtensions" + ); + } +} + +#[test] +fn fd_reply_refuses_a_client_without_fd_passing() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let client = state.clients.get_mut(&1).expect("test client"); + client.fd_passing = false; + let file = std::fs::File::open("/dev/null").expect("open null device"); + + let error = send_reply_with_fd(client, &[1; 32], std::os::fd::AsRawFd::as_raw_fd(&file)) + .expect_err("non-FD-capable clients must reject descriptor replies"); + assert_eq!(error.kind(), io::ErrorKind::Unsupported); +} + +#[test] +fn dri3_hidden_when_caps_unsupported() { + // Default RecordingBackend returns Dri3Caps::unsupported() + // (version (0, 0)), so DRI3 must not appear in QueryExtension / + // ListExtensions output. KmsBackend overrides + // dri3_capabilities() and the Phase 4.2 vng smoke covers the + // advertised path. + let mut backend = RecordingBackend::new(); + assert!(extension_query_reply("DRI3", &mut backend).is_none()); + let names = advertised_extension_names(&mut backend); + assert!( + !names.contains(&"DRI3"), + "DRI3 should be hidden when caps unsupported, got: {names:?}" + ); +} + +#[test] +fn glx_follows_backend_availability() { + let mut backend = RecordingBackend::new(); + assert!(extension_query_reply("GLX", &mut backend).is_some()); + assert!(advertised_extension_names(&mut backend).contains(&"GLX")); + + backend.glx_available = false; + assert!(extension_query_reply("GLX", &mut backend).is_none()); + let names = advertised_extension_names(&mut backend); + assert!( + !names.contains(&"GLX"), + "GLX must be hidden, got: {names:?}" + ); +} + +/// Build an ImportSyncobj request body: syncobj(4) + drawable(4), fd via +/// SCM_RIGHTS (attached_fd). +fn import_syncobj_body(syncobj: u32, drawable: u32) -> Vec { + let mut body = vec![0u8; 8]; + body[0..4].copy_from_slice(&syncobj.to_le_bytes()); + body[4..8].copy_from_slice(&drawable.to_le_bytes()); + body +} + +/// RecordingBackend with a DRI3 1.4 / `syncobj: true` surface so the +/// IMPORT_SYNCOBJ / FREE_SYNCOBJ handlers pass their `caps.syncobj` gate. +/// Kept as a per-test opt-in: the DEFAULT backend must stay +/// `Dri3Caps::unsupported()` for the existing +/// `dri3_hidden_when_caps_unsupported` test (process_request.rs:37076). +fn syncobj_cap_backend() -> RecordingBackend { + let mut backend = RecordingBackend::new(); + backend.dri3_caps = crate::backend::Dri3Caps { + version: (1, 4), + modifiers: false, + fence_fd: false, + syncobj: true, + }; + backend +} + +#[test] +fn import_syncobj_in_use_xid_is_bad_id_choice() { + use yserver_protocol::x11::{CreatePixmapRequest, ResourceId}; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + + // install_client (process_request.rs:29047) gives every test client + // base=0/mask=u32::MAX — "every xid is in range" — so the + // xid_out_of_client_range half of the LEGAL_NEW_RESOURCE gate is + // unreachable in this fixture. Exercise the OTHER half: name a + // pixmap with the xid, then ImportSyncobj with the same xid -> + // resources.xid_in_use fires. + const XID: u32 = 0x0040_0001; + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(XID), + drawable: ROOT_WINDOW, + width: 1, + height: 1, + }, + ); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 10, // IMPORT_SYNCOBJ + length_units: 3, + }, + // drawable=0 is fine here: the xid check (Xorg LEGAL_NEW_RESOURCE) + // fires before the drawable check. + &import_syncobj_body(XID, 0), + None, // no SCM_RIGHTS fd + ) + .unwrap(); + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_ID_CHOICE, + "an in-use xid must be rejected as BadIDChoice (Xorg LEGAL_NEW_RESOURCE)", + ); +} + +#[test] +fn import_syncobj_bad_drawable_is_bad_drawable() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + + // A legal syncobj xid (never used, so no xid_in_use) naming a drawable + // that does not exist -> the Xorg drawable check (dixLookupDrawable) + // must fire with BadDrawable. It runs AFTER the xid check and BEFORE + // the fd check. + const SYNCOBJ: u32 = 0x0010_0001; + const MISSING_DRAWABLE: u32 = 0x0050_0001; + assert!( + state + .resources + .window(ResourceId(MISSING_DRAWABLE)) + .is_none() + && state + .resources + .pixmap(ResourceId(MISSING_DRAWABLE)) + .is_none(), + "fixture: MISSING_DRAWABLE must not exist" + ); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 10, // IMPORT_SYNCOBJ + length_units: 3, + }, + &import_syncobj_body(SYNCOBJ, MISSING_DRAWABLE), + None, // no SCM_RIGHTS fd + ) + .unwrap(); + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_DRAWABLE, + "ImportSyncobj naming a nonexistent drawable must be BadDrawable", + ); + // The bad drawable must abort the request: nothing imported. + assert!(!backend.dri3_syncobj_owners.contains_key(&SYNCOBJ)); +} + +#[test] +fn import_syncobj_missing_fd_is_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 10, // IMPORT_SYNCOBJ + length_units: 3, + }, + // legal xid; install_client is range-permissive. drawable=ROOT_WINDOW + // (0x100) exists in the default ResourceTable, so the request passes + // the xid + drawable checks and lands on the fd check (Xorg: + // ReadFdFromClient < 0 -> BadValue). + &import_syncobj_body(0x0010_0001, ROOT_WINDOW.0), + None, // no fd attached + ) + .unwrap(); + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_VALUE, + "ImportSyncobj without an fd must be BadValue (Xorg ReadFdFromClient)", + ); +} + +#[test] +fn free_syncobj_unknown_is_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&0x0040_9999u32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 11, // FREE_SYNCOBJ + length_units: 2, + }, + &body, + None, + ) + .unwrap(); + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_VALUE, + "FreeSyncobj of an unknown xid must be BadValue", + ); +} + +#[test] +fn free_syncobj_of_another_client_is_bad_access() { + let mut state = ServerState::new(); + let _peer_a = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + let mut backend = syncobj_cap_backend(); + + // Client A imports 0x0010_0001 (a legal xid for client 1 — the + // handler now validates range). drawable=ROOT_WINDOW exists, so the + // request passes the xid + drawable checks. RecordingBackend ignores + // the fd's payload, only ownership is recorded. + let fd = std::fs::File::open("/dev/null") + .expect("open /dev/null") + .into(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 10, + length_units: 3, + }, + &import_syncobj_body(0x0010_0001, ROOT_WINDOW.0), + Some(fd), + ) + .unwrap(); + + // Client B frees A's syncobj. FreeSyncobj has no range check (it is + // not a new-resource request), so B can name A's xid — the ownership + // check is what must reject it. Xorg's dixLookupResourceByType with + // DixWriteAccess maps a foreign owner to BadAccess. + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&0x0010_0001u32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 11, + length_units: 2, + }, + &body, + None, + ) + .unwrap(); + peer_b.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer_b.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_ACCESS, + "FreeSyncobj of another client's syncobj must be BadAccess", + ); + + // A still owns it (ImportSyncobj is a void request — nothing to read + // on A's socket; the ownership assertion is the whole check). + assert!(backend.dri3_syncobj_owners.contains_key(&0x0010_0001)); +} + +#[test] +fn import_syncobj_duplicate_xid_is_bad_id_choice() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + + const XID: u32 = 0x0010_0001; + let fd1: std::os::fd::OwnedFd = std::fs::File::open("/dev/null") + .expect("open /dev/null") + .into(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 10, // IMPORT_SYNCOBJ + length_units: 3, + }, + &import_syncobj_body(XID, ROOT_WINDOW.0), + Some(fd1), + ) + .unwrap(); + + // Re-import of the SAME xid is rejected by the core X resource + // registry before the backend is touched, matching Xorg's + // LEGAL_NEW_RESOURCE gate. + let fd2: std::os::fd::OwnedFd = std::fs::File::open("/dev/null") + .expect("open /dev/null") + .into(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 147, + data: 10, // IMPORT_SYNCOBJ + length_units: 3, + }, + &import_syncobj_body(XID, ROOT_WINDOW.0), + Some(fd2), + ) + .unwrap(); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_ID_CHOICE, + "re-importing a live syncobj XID must be BadIDChoice", + ); +} + +#[test] +fn live_syncobj_xid_cannot_be_reused_for_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = syncobj_cap_backend(); + const XID: u32 = 0x0010_0001; + + let fd: std::os::fd::OwnedFd = std::fs::File::open("/dev/null") + .expect("open /dev/null") + .into(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data: 10, + length_units: 3, + }, + &import_syncobj_body(XID, ROOT_WINDOW.0), + Some(fd), + ) + .unwrap(); + assert!(state.resources.xid_in_use(ResourceId(XID))); + + let mut body = vec![0u8; 12]; + body[0..4].copy_from_slice(&XID.to_le_bytes()); + body[4..8].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body[8..10].copy_from_slice(&1u16.to_le_bytes()); + body[10..12].copy_from_slice(&1u16.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 53, // CreatePixmap + data: 24, + length_units: 4, + }, + &body, + None, + ) + .unwrap(); + + peer.set_nonblocking(true).unwrap(); + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(read_error(&error), x11::error::BAD_ID_CHOICE); +} + +#[test] +fn kill_client_by_retained_syncobj_xid_destroys_zombie_resources() { + const SYNCOBJ: u32 = 0x0070_0094; + let mut state = ServerState::new(); + let _killer_peer = install_client(&mut state, 1); + let _owner_peer = install_client(&mut state, 7); + let mut backend = RecordingBackend::new(); + state.close_down_modes.insert(7, 1); // RetainPermanent + assert!( + state + .resources + .register_dri3_syncobj(ResourceId(SYNCOBJ), ClientId(7)) + ); + backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(7)); + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(7)); + assert_eq!(state.zombie_clients.get(&7), Some(&1)); + + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 113, // KillClient + data: 0, + length_units: 2, + }, + &SYNCOBJ.to_le_bytes(), + None, + ) + .unwrap(); + + assert!(matches!(outcome, RequestOutcome::Handled)); + assert!(!state.resources.xid_in_use(ResourceId(SYNCOBJ))); + assert!(!backend.dri3_syncobj_owners.contains_key(&SYNCOBJ)); + assert!(!state.zombie_clients.contains_key(&7)); +} + +#[test] +fn kill_client_all_temporary_destroys_retained_syncobj() { + const SYNCOBJ: u32 = 0x0070_0095; + let mut state = ServerState::new(); + let _killer_peer = install_client(&mut state, 1); + let _owner_peer = install_client(&mut state, 7); + let mut backend = RecordingBackend::new(); + state.close_down_modes.insert(7, 2); // RetainTemporary + assert!( + state + .resources + .register_dri3_syncobj(ResourceId(SYNCOBJ), ClientId(7)) + ); + backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(7)); + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(7)); + assert_eq!(state.zombie_clients.get(&7), Some(&2)); + + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 113, // KillClient + data: 0, + length_units: 2, + }, + &0u32.to_le_bytes(), // AllTemporary + None, + ) + .unwrap(); + + assert!(matches!(outcome, RequestOutcome::Handled)); + assert!(!state.resources.xid_in_use(ResourceId(SYNCOBJ))); + assert!(!backend.dri3_syncobj_owners.contains_key(&SYNCOBJ)); + assert!(!state.zombie_clients.contains_key(&7)); +} + +#[test] +fn dri3_get_supported_modifiers_default_window_subset_screen() { + // Default Backend::dri3_supported_modifiers returns + // ([LINEAR], [LINEAR]); the window list must always be a + // subset of the screen list per design §3.2. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = vec![0u8; 8]; + body[0..4].copy_from_slice(&0xCAFEu32.to_le_bytes()); // window + body[4] = 24; + body[5] = 32; + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(11), + RequestHeader { + opcode: 147, + data: 6, // GET_SUPPORTED_MODIFIERS + length_units: 3, + }, + &body, + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); + peer.set_nonblocking(true).unwrap(); + // Reply: 32-byte header + 8*nwin + 8*nscr; nwin=nscr=1. + let mut buf = [0u8; 48]; + peer.read_exact(&mut buf).expect("reply bytes delivered"); + assert_eq!(buf[0], 1, "expected Reply, got opcode {}", buf[0]); + let nwin = u32::from_le_bytes(buf[8..12].try_into().unwrap()); + let nscr = u32::from_le_bytes(buf[12..16].try_into().unwrap()); + assert!(nwin <= nscr, "window-list must be subset: {nwin} > {nscr}"); + assert_eq!(nwin, 1); + assert_eq!(nscr, 1); + let m_win = u64::from_le_bytes(buf[32..40].try_into().unwrap()); + let m_scr = u64::from_le_bytes(buf[40..48].try_into().unwrap()); + assert_eq!(m_win, 0); // LINEAR + assert_eq!(m_scr, 0); +} + +#[test] +fn dri3_pixmap_from_buffers_rejects_multi_plane() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // 60-byte body with num_buffers=2 (multi-plane). Phase 4.2 + // accepts only num_buffers==1; everything else returns + // BadAlloc per design "single-plane RGB only" scope. + let mut body = vec![0u8; 60]; + body[0..4].copy_from_slice(&0xAAAA_AAAAu32.to_le_bytes()); // pixmap xid + body[4..8].copy_from_slice(&0xBBBB_BBBBu32.to_le_bytes()); // window xid + body[8] = 2; // num_buffers + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(5), + RequestHeader { + opcode: 147, + data: 7, // PIXMAP_FROM_BUFFERS + length_units: 16, + }, + &body, + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error bytes delivered"); + assert_eq!(buf[0], 0, "expected Error, got opcode {}", buf[0]); + assert_eq!(buf[1], 11, "expected BadAlloc (11), got {}", buf[1]); +} + +#[test] +fn dri3_open_emits_bad_alloc_when_backend_unsupported() { + // RecordingBackend's default Backend::dri3_open returns Err + // (DRI3 unsupported). The dispatcher must convert that to a + // BadAlloc error event, not a successful reply. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = vec![0u8; 8]; + body[0..4].copy_from_slice(&0xCAFEu32.to_le_bytes()); // drawable + body[4..8].copy_from_slice(&0u32.to_le_bytes()); // provider + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 147, + data: 1, // OPEN + length_units: 3, + }, + &body, + None, + ) + .unwrap(); + assert!(matches!(outcome, RequestOutcome::Handled)); + // Read 32 bytes from the peer end of the client's UnixStream: + // X errors are 32-byte fixed-size messages with opcode 0 in + // byte 0 and the error code in byte 1. + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("error bytes delivered to peer"); + assert_eq!(buf[0], 0, "expected Error (opcode 0), got {}", buf[0]); + assert_eq!(buf[1], 11, "expected BadAlloc (11), got {}", buf[1]); +} + +// ---------------- extract_shm_zpixmap_region ---------------- +// +// The protocol-level byte-extraction for MIT-SHM PutImage. Until +// 2026-05-15 the handler ignored `total_width` / `src_x` / +// `src_y` and read a tightly-packed `src_width × src_height × +// bpp` block at `offset`. That happens to be correct when the +// client sets `total == src` and `src_xy == 0` (the common +// case), but reads garbage when the client uploads a sub-region +// of a larger shm image. xfdesktop's thumbnail upload pattern +// and any cairo-padded surface trigger the latter, which +// manifests as horizontal-band corruption around the thumbnail. + +#[test] +fn mit_shm_put_image_honors_gc_clip_rectangles() { + const CLIENT: u32 = 1; + const PIXMAP: u32 = 0x0020_0001; + const GC: u32 = 0x0020_0002; + const SHMSEG: u32 = 0x0020_0003; + const HOST_PIXMAP: u32 = 0x0040_0001; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + state.resources.create_pixmap( + ClientId(CLIENT), + x11::CreatePixmapRequest { + depth: 32, + pixmap: ResourceId(PIXMAP), + drawable: ROOT_WINDOW, + width: 4, + height: 4, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP), + crate::backend::PixmapHandle::from_raw(HOST_PIXMAP).expect("non-zero host pixmap"), + )); + state.resources.create_gc( + ClientId(CLIENT), + CreateGcRequest { + gc: ResourceId(GC), + drawable: ResourceId(PIXMAP), + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + let clip = x11::ClipRectangles { + ordering: 0, + x_origin: 0, + y_origin: 0, + rectangles: [ + 0i16.to_le_bytes(), + 1i16.to_le_bytes(), + 4u16.to_le_bytes(), + 1u16.to_le_bytes(), + ] + .concat(), + }; + state.resources.set_clip_rectangles( + ClientId(CLIENT), + x11::SetClipRectanglesRequest { + gc: ResourceId(GC), + clip: clip.clone(), + }, + ); + + let fd = std::os::fd::IntoRawFd::into_raw_fd( + crate::anon_shm::create_anon_shm(c"mit-shm-put-image-test") + .expect("create_anon_shm failed"), + ); + assert_eq!(unsafe { libc::ftruncate(fd, 64) }, 0, "ftruncate failed"); + let mut segment = crate::server::MitShmSegment::from_fd(ClientId(CLIENT), fd, false) + .expect("map test SHM segment"); + segment + .as_mut_slice() + .expect("writable SHM segment") + .fill(0xff); + state.mit_shm_segments.insert(SHMSEG, segment); + + handle_mit_shm_put_image( + &mut state, + &mut backend, + None, + ClientId(CLIENT), + SequenceNumber(1), + yserver_protocol::x11::mit_shm::PutImageRequest { + drawable: PIXMAP, + gc: GC, + total_width: 4, + total_height: 4, + src_x: 0, + src_y: 0, + src_width: 4, + src_height: 4, + dst_x: 0, + dst_y: 0, + depth: 32, + format: 2, + send_event: false, + shmseg: SHMSEG, + offset: 0, + }, + ) + .expect("MIT-SHM PutImage succeeds"); + + assert!(backend.calls.lock().expect("calls lock").contains( + &crate::backend::recording::RecordedCall::ApplyClipState( + crate::backend::ClipState::Rectangles { + origin: (0, 0), + rects: clip, + }, + ), + )); +} + +fn d32_pixel(b: u8, g: u8, r: u8, a: u8) -> [u8; 4] { + // Wire byte order for a depth-32 ZPixmap is [B, G, R, A] — + // see the comment in `try_vk_put_image`. + [b, g, r, a] +} + +#[test] +fn extract_d32_tight_packing_returns_input() { + // total == src, src_xy == 0 → output is exactly the input. + let mut bytes = Vec::new(); + for y in 0..4u8 { + for x in 0..4u8 { + bytes.extend_from_slice(&d32_pixel(x, y, x ^ y, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 0, 4, 4, 32) + .expect("tight extraction succeeds"); + assert_eq!(out, bytes); +} + +/// 2026-05-28 perf-cliff fix: full-frame extracts MUST return +/// `Cow::Borrowed` (no allocation, no memcpy). On cinnamon the +/// hot-path PutImage of the 28MB compositor stage was spending +/// 8-10ms in the legacy per-row Vec::extend_from_slice loop. +/// Borrowing the SHM slice directly drops it to a bounds-check. +/// Tested both depth=24 and depth=32 at the boundary (full frame, +/// no offset, row_bytes == src_stride) and against a partial / +/// padded case that MUST still allocate. +#[test] +fn extract_full_frame_d32_returns_borrowed_slice() { + // 8×4 full-frame extract, depth 32 → row_bytes == src_stride. + let mut bytes = Vec::new(); + for y in 0..4u8 { + for x in 0..8u8 { + bytes.extend_from_slice(&d32_pixel(x, y, x ^ y, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 8, 4, 0, 0, 8, 4, 32) + .expect("full-frame d32 extraction succeeds"); + assert!( + matches!(out, std::borrow::Cow::Borrowed(_)), + "full-frame extract must zero-copy (Cow::Borrowed)", + ); + assert_eq!(out.as_ref(), bytes.as_slice()); +} + +#[test] +fn extract_full_frame_d24_returns_borrowed_slice() { + // 8×4 full-frame, depth 24 (4 bytes per pixel — same as d32). + let mut bytes = Vec::new(); + for y in 0..4u8 { + for x in 0..8u8 { + bytes.extend_from_slice(&d32_pixel(x, y, x ^ y, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 8, 4, 0, 0, 8, 4, 24) + .expect("full-frame d24 extraction succeeds"); + assert!( + matches!(out, std::borrow::Cow::Borrowed(_)), + "full-frame d24 extract must zero-copy (Cow::Borrowed)", + ); + assert_eq!(out.as_ref(), bytes.as_slice()); +} + +#[test] +fn extract_partial_region_returns_owned_vec() { + // Same data but ask for a sub-region — the borrow fast path + // MUST NOT trigger. + let mut bytes = Vec::new(); + for y in 0..8u8 { + for x in 0..8u8 { + bytes.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 8, 8, 2, 2, 4, 4, 32) + .expect("partial extraction succeeds"); + assert!( + matches!(out, std::borrow::Cow::Owned(_)), + "partial extract must allocate (Cow::Owned)", + ); +} + +#[test] +fn extract_d8_padded_full_frame_does_not_borrow() { + // Depth-8 with src_width=5 → src_stride=8 (pad-to-32-bit). + // row_bytes (5) < src_stride (8) — the borrow fast path's + // `row_bytes == src_stride` precondition excludes this so + // the slow padding path runs. + let bytes: Vec = (0..16).map(|i| i as u8).collect(); + let out = extract_shm_zpixmap_region(&bytes, 0, 5, 2, 0, 0, 5, 2, 8) + .expect("padded d8 extraction succeeds"); + assert!( + matches!(out, std::borrow::Cow::Owned(_)), + "padded full-frame d8 must NOT borrow (per-row padding required)", + ); +} + +#[test] +fn extract_d32_subregion_of_larger_buffer() { + // 8×8 total, take 4×4 at (2, 2). The handler must read row 2 + // bytes 8..24, row 3 bytes 8..24, etc. — NOT 64 contiguous + // bytes from offset 0, which is what the pre-fix handler + // did. + let mut bytes = Vec::new(); + for y in 0..8u8 { + for x in 0..8u8 { + bytes.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 8, 8, 2, 2, 4, 4, 32) + .expect("subregion extraction succeeds"); + // Output must be the (2,2)..(6,6) tile, tightly packed. + let mut want = Vec::new(); + for y in 2..6u8 { + for x in 2..6u8 { + want.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); + } + } + assert_eq!(out, want); +} + +#[test] +fn extract_d32_total_wider_than_src() { + // 16×4 total, take 4×4 at (0, 0). Each src row must skip the + // unused 12 trailing pixels of the total row. + let mut bytes = Vec::new(); + for y in 0..4u8 { + for x in 0..16u8 { + bytes.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 16, 4, 0, 0, 4, 4, 32) + .expect("wide-total extraction succeeds"); + let mut want = Vec::new(); + for y in 0..4u8 { + for x in 0..4u8 { + want.extend_from_slice(&d32_pixel(x, y, 0, 0xFF)); + } + } + assert_eq!(out, want); +} + +#[test] +fn extract_honors_offset() { + // Image starts partway into the shm segment. + let mut bytes = vec![0xAAu8; 16]; + for y in 0..2u8 { + for x in 0..2u8 { + bytes.extend_from_slice(&d32_pixel(x, y, 0xFF, 0xFF)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 16, 2, 2, 0, 0, 2, 2, 32) + .expect("offset extraction succeeds"); + assert_eq!(out, &bytes[16..]); +} + +#[test] +fn extract_d8_padding_total_wider_than_src() { + // 6-wide total → 8 bytes/row (padded to 32-bit). Take a 5×2 + // tile. Output stride is `((5 + 3) & ~3) = 8` bytes/row so + // we get 16 bytes; first 5 are image data, next 3 are pad. + let bytes: Vec = (0..16).map(|i| i as u8).collect(); + let out = + extract_shm_zpixmap_region(&bytes, 0, 6, 2, 0, 0, 5, 2, 8).expect("d8 extraction succeeds"); + assert_eq!(out.len(), 16); + // Row 0 image bytes: 0..5 of the input; row 0 trailing pad: zero. + assert_eq!(&out[..5], &bytes[..5]); + assert_eq!(&out[5..8], &[0, 0, 0]); + // Row 1 image bytes: 8..13 of the input. + assert_eq!(&out[8..13], &bytes[8..13]); + assert_eq!(&out[13..16], &[0, 0, 0]); +} + +#[test] +fn extract_d8_src_x_offset() { + // 8-wide total → 8 bytes/row. Take a 4×1 tile at src_x=2. + let bytes: Vec = (0..8).map(|i| i as u8).collect(); + let out = extract_shm_zpixmap_region(&bytes, 0, 8, 1, 2, 0, 4, 1, 8) + .expect("d8 src_x extraction succeeds"); + // src_width=4 → src_stride=4 (already 32-bit aligned). Output is bytes 2..6. + assert_eq!(out, vec![2u8, 3, 4, 5]); +} + +#[test] +fn extract_rejects_region_outside_total() { + let bytes = vec![0u8; 64]; + // src_x + src_width > total_width + assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 2, 0, 4, 4, 32).is_none()); + // src_y + src_height > total_height + assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 2, 4, 4, 32).is_none()); +} + +#[test] +fn extract_rejects_negative_src_xy() { + let bytes = vec![0u8; 64]; + assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, -1, 0, 4, 4, 32).is_none()); + assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, -1, 4, 4, 32).is_none()); +} + +#[test] +fn extract_rejects_offset_beyond_buffer() { + let bytes = vec![0u8; 16]; + // 4×4 d32 = 64 bytes; only 16 available. + assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 0, 4, 4, 32).is_none()); +} + +#[test] +fn extract_rejects_unsupported_depth() { + let bytes = vec![0u8; 64]; + assert!(extract_shm_zpixmap_region(&bytes, 0, 4, 4, 0, 0, 4, 4, 16).is_none()); +} + +#[test] +fn extract_d24_treats_padding_byte_as_image_data() { + // d24 on the wire is 4 bytes per pixel like d32; the 4th + // byte is undefined but transmitted. Extraction must copy + // all 4 bytes — the put_image backend stamps 0xFF later. + let mut bytes = Vec::new(); + for y in 0..2u8 { + for x in 0..2u8 { + bytes.extend_from_slice(&d32_pixel(x, y, 0xCC, 0x77)); + } + } + let out = extract_shm_zpixmap_region(&bytes, 0, 2, 2, 0, 0, 2, 2, 24) + .expect("d24 extraction succeeds"); + assert_eq!(out, bytes); +} + +/// DRI3::BufferFromPixmap: when the backend's `dri3_export_pixmap` +/// returns Err (e.g. no exportable backing, Vulkan unavailable, or +/// any promotion failure), the dispatcher must emit `BadPixmap` +/// (error code 4) — matching Xorg `dri3/dri3_request.c:277`. +/// Previously this emitted `BadAlloc` (11). +#[test] +fn buffer_from_pixmap_export_failure_returns_bad_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // RecordingBackend does not override dri3_export_pixmap, so the + // default trait implementation returns Err("DRI3 export unsupported + // on this backend") — exactly the failure case we're testing. + let mut backend = RecordingBackend::new(); + + // Register a pixmap in the resource table with a valid host_xid so + // the handler reaches the dri3_export_pixmap call (not the + // BadDrawable path). + let pixmap_xid: u32 = 0x1000; + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap_xid), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + }, + ); + assert!( + state.resources.set_pixmap_host_xid( + ResourceId(pixmap_xid), + crate::backend::PixmapHandle::from_raw(0xdead_cafe).unwrap(), + ), + "set_pixmap_host_xid must succeed" + ); + + // BufferFromPixmap body: 4-byte pixmap XID (little-endian). + let body = pixmap_xid.to_le_bytes().to_vec(); + + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(7), + RequestHeader { + opcode: 147, // DRI3_MAJOR_OPCODE + data: 3, // BUFFER_FROM_PIXMAP + length_units: 2, + }, + &body, + None, + ) + .expect("process_request should not hard-error"); + + assert!( + matches!(outcome, RequestOutcome::Handled), + "expected Handled, got {outcome:?}" + ); + + // Read the 32-byte X error packet from the peer socket. + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("BadPixmap error packet must be delivered to client"); + assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); + assert_eq!( + buf[1], + x11::error::BAD_PIXMAP, + "expected BadPixmap ({}), got {}", + x11::error::BAD_PIXMAP, + buf[1] + ); +} + +/// DRI3::BuffersFromPixmap (op 8): like op 3, a backend export +/// failure must emit `BadPixmap` (the modifier-aware multi-plane +/// reply shares op 3's error contract). The default RecordingBackend +/// returns Err from `dri3_export_pixmap_buffers`. +#[test] +fn buffers_from_pixmap_export_failure_returns_bad_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let pixmap_xid: u32 = 0x1000; + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap_xid), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(pixmap_xid), + crate::backend::PixmapHandle::from_raw(0xdead_cafe).unwrap(), + )); + + let body = pixmap_xid.to_le_bytes().to_vec(); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(7), + RequestHeader { + opcode: 147, // DRI3_MAJOR_OPCODE + data: 8, // BUFFERS_FROM_PIXMAP + length_units: 2, + }, + &body, + None, + ) + .expect("process_request should not hard-error"); + + assert!( + matches!(outcome, RequestOutcome::Handled), + "expected Handled, got {outcome:?}" + ); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("BadPixmap error packet must be delivered to client"); + assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); + assert_eq!( + buf[1], + x11::error::BAD_PIXMAP, + "expected BadPixmap ({}), got {}", + x11::error::BAD_PIXMAP, + buf[1] + ); +} + +/// A renderer without SYNC_FD semaphores (`fence_fd: false`, lavapipe) still +/// takes FenceFromFD: Mesa's X11 swapchain shares an xshmfence per buffer +/// through it and waits on it, which Xorg accepts on every screen +/// (`miSyncShmFenceFromFD`). Refused (BadImplementation), every present +/// waited for ever. FDFromFence, which exports a SYNC_FD, stays refused, +/// and an AwaitFence on the client's untriggered fence parks the client +/// rather than waiting on the core thread. +#[test] +fn fence_from_fd_takes_an_xshmfence_without_sync_fd_semaphores() { + use yserver_protocol::x11::sync as s; + const FENCE: u32 = 0x0040_0002; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.dri3_caps = crate::backend::Dri3Caps { + version: (1, 2), + modifiers: false, + fence_fd: false, + syncobj: false, + }; + let (fd, _other) = std::os::unix::net::UnixStream::pair().unwrap(); + let mut body = vec![0u8; 12]; + body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body[4..8].copy_from_slice(&FENCE.to_le_bytes()); + let request = |state: &mut ServerState, + backend: &mut RecordingBackend, + opcode: u8, + data: u8, + body: &[u8], + fd: Option| { + process_request( + state, + backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + fd, + ) + .unwrap() + }; + request(&mut state, &mut backend, 147, 4, &body, Some(fd.into())); + peer.set_nonblocking(true).unwrap(); + assert!( + read_all_available(&mut peer).is_empty(), + "FenceFromFD answered without an error" + ); + assert!(state.sync_fences.contains_key(&FENCE), "the fence exists"); + + request(&mut state, &mut backend, 147, 5, &FENCE.to_le_bytes(), None); + let refused = read_all_available(&mut peer); + assert_eq!(read_error(&refused[..32]), x11::error::BAD_IMPLEMENTATION); + + // AwaitFence (SYNC 142, minor 19) on the untriggered fence returns at + // once, the client parked until the fence triggers. + let outcome = request( + &mut state, + &mut backend, + 142, + s::AWAIT_FENCE, + &FENCE.to_le_bytes(), + None, + ); + assert!(matches!(outcome, RequestOutcome::Handled)); + assert!( + read_all_available(&mut peer).is_empty(), + "no reply, no error" + ); +} + +/// FenceFromFD checks as Xorg's `proc_dri3_fence_from_fd`: an ID outside +/// the client's range or already in use (another client's fence) is +/// BadIDChoice, a missing drawable BadDrawable, a missing fd BadValue, +/// and a fd the backend can't take BadValue with no fence made +/// (`miSyncShmCreateFenceFromFd`). None of them touches the fence that +/// was there, and a destroyed fence's ID can be taken again. +#[test] +fn fence_from_fd_checks_ids_drawable_and_fd_as_xorg() { + const FENCE: u32 = 0x0040_0002; + const OTHER: u32 = 0x0080_0002; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut peer2 = install_client(&mut state, 2); + { + let c2 = state.clients.get_mut(&2).unwrap(); + c2.resource_id_base = 0x0080_0000; + c2.resource_id_mask = 0x001f_ffff; + } + let mut backend = RecordingBackend::new(); + let body = |drawable: u32, fence: u32| { + let mut body = vec![0u8; 12]; + body[0..4].copy_from_slice(&drawable.to_le_bytes()); + body[4..8].copy_from_slice(&fence.to_le_bytes()); + body + }; + let fd = || -> Option { + let (fd, _other) = std::os::unix::net::UnixStream::pair().unwrap(); + Some(fd.into()) + }; + let request = |state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + data: u8, + body: &[u8], + fd: Option| { + process_request( + state, + backend, + ClientId(client), + SequenceNumber(1), + RequestHeader { + opcode: 147, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + fd, + ) + .unwrap() + }; + let error = |peer: &mut std::os::unix::net::UnixStream| { + let buf = read_all_available(peer); + assert_eq!(buf.len(), 32, "one error: {buf:02x?}"); + ( + read_error(&buf), + u32::from_le_bytes(buf[4..8].try_into().unwrap()), + ) + }; + + // Client 1 makes FENCE; client 2 can't take it (in use), nor an ID + // outside its own range. + request( + &mut state, + &mut backend, + 1, + 4, + &body(ROOT_WINDOW.0, FENCE), + fd(), + ); + assert!(read_all_available(&mut peer).is_empty()); + assert_eq!(state.sync_fences[&FENCE].owner, ClientId(1)); + request( + &mut state, + &mut backend, + 2, + 4, + &body(ROOT_WINDOW.0, FENCE), + fd(), + ); + assert_eq!(error(&mut peer2), (x11::error::BAD_ID_CHOICE, FENCE)); + assert_eq!( + state.sync_fences[&FENCE].owner, + ClientId(1), + "not overwritten" + ); + request( + &mut state, + &mut backend, + 2, + 4, + &body(ROOT_WINDOW.0, 0x0040_0003), + fd(), + ); + assert_eq!(error(&mut peer2), (x11::error::BAD_ID_CHOICE, 0x0040_0003)); + + // A drawable that doesn't exist, then no fd, then a fd the backend + // can't take: each an error, and no fence. + request( + &mut state, + &mut backend, + 2, + 4, + &body(0x0099_0000, OTHER), + fd(), + ); + assert_eq!(error(&mut peer2), (x11::error::BAD_DRAWABLE, 0x0099_0000)); + request( + &mut state, + &mut backend, + 2, + 4, + &body(ROOT_WINDOW.0, OTHER), + None, + ); + assert_eq!(error(&mut peer2).0, x11::error::BAD_VALUE); + backend.refuse_fence_fds = true; + request( + &mut state, + &mut backend, + 2, + 4, + &body(ROOT_WINDOW.0, OTHER), + fd(), + ); + assert_eq!(error(&mut peer2).0, x11::error::BAD_VALUE); + assert!( + !state.sync_fences.contains_key(&OTHER), + "no server-only fence" + ); + backend.refuse_fence_fds = false; + request( + &mut state, + &mut backend, + 2, + 4, + &body(ROOT_WINDOW.0, OTHER), + fd(), + ); + assert!(read_all_available(&mut peer2).is_empty()); + assert_eq!(state.sync_fences[&OTHER].owner, ClientId(2)); + + // SYNC DestroyFence (142, minor 17) frees FENCE; client 1 takes it again. + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 142, + data: yserver_protocol::x11::sync::DESTROY_FENCE, + length_units: 2, + }, + &FENCE.to_le_bytes(), + None, + ) + .unwrap(); + assert!(!state.sync_fences.contains_key(&FENCE)); + request( + &mut state, + &mut backend, + 1, + 4, + &body(ROOT_WINDOW.0, FENCE), + fd(), + ); + assert!(read_all_available(&mut peer).is_empty()); + assert!(state.sync_fences.contains_key(&FENCE)); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/expose_probe.rs b/crates/yserver-core/src/core_loop/process_request/tests/expose_probe.rs new file mode 100644 index 000000000..dd6495844 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/expose_probe.rs @@ -0,0 +1,779 @@ +//! Request-level replays of `tools/expose-order-probe.c`: one client drives +//! the requests and watches the events, printed the probe's way so each +//! expectation is a line of the Xorg log. + +use super::*; + +const EXPOSURE_AND_SUBSTRUCTURE: u32 = 0x0000_8000 | 0x0008_0000; +const DAMAGE_MAJOR: u8 = 143; +const COMPOSITE_MAJOR: u8 = 144; +const DAMAGE_RAW: u8 = 0; +const DAMAGE_NON_EMPTY: u8 = 3; + +/// A recorded fill: x, y, width, height. +pub(super) type Fill = (i16, i16, u16, u16); + +/// Background of a probe window. +#[derive(Clone, Copy)] +pub(super) enum Bg { + None, + ParentRelative, + Pixel(u32), +} + +pub(super) struct Probe { + pub(super) state: ServerState, + pub(super) backend: RecordingBackend, + peer: UnixStream, + names: Vec<(u32, &'static str)>, + damages: Vec<(u32, bool)>, + next_xid: u32, + sequence: u16, +} + +impl Probe { + /// The probe's observer: SubstructureNotify on root. + pub(super) fn new() -> Self { + let mut state = ServerState::new(); + let peer = install_client(&mut state, 1); + let mut probe = Self { + state, + backend: RecordingBackend::new(), + peer, + names: vec![(ROOT_WINDOW.0, "root")], + damages: Vec::new(), + next_xid: 0x0020_0001, + sequence: 0, + }; + probe.backend.redirect_activation_supported = true; + probe.select(ROOT_WINDOW.0, 0x0008_0000); + probe + } + + /// ChangeWindowAttributes(event-mask). + pub(super) fn select(&mut self, window: u32, mask: u32) { + let mut body = window.to_le_bytes().to_vec(); + body.extend_from_slice(&0x0800u32.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); + self.request(2, 0, &body); + } + + pub(super) fn request(&mut self, opcode: u8, data: u8, body: &[u8]) { + self.try_request(opcode, data, body) + .expect("request through core dispatcher"); + } + + pub(super) fn try_request( + &mut self, + opcode: u8, + data: u8, + body: &[u8], + ) -> io::Result { + self.sequence = self.sequence.wrapping_add(1); + process_request( + &mut self.state, + &mut self.backend, + ClientId(1), + SequenceNumber(self.sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + None, + ) + } + + fn xid(&mut self) -> u32 { + let id = self.next_xid; + self.next_xid += 1; + id + } + + /// The probe's `mk`: an override-redirect `InputOutput` child selecting + /// Exposure and SubstructureNotify. + pub(super) fn create( + &mut self, + name: &'static str, + parent: u32, + geometry: (i16, i16, u16, u16), + bg: Bg, + ) -> u32 { + let id = self.xid(); + let (x, y, w, h) = geometry; + let mut body = Vec::new(); + for word in [id, parent] { + body.extend_from_slice(&word.to_le_bytes()); + } + for half in [ + x.to_le_bytes(), + y.to_le_bytes(), + w.to_le_bytes(), + h.to_le_bytes(), + ] { + body.extend_from_slice(&half); + } + body.extend_from_slice(&0u16.to_le_bytes()); // border + body.extend_from_slice(&1u16.to_le_bytes()); // InputOutput + body.extend_from_slice(&0u32.to_le_bytes()); // CopyFromParent visual + let (mask, first) = match bg { + Bg::None => (0x0001u32, 0u32), + Bg::ParentRelative => (0x0001, 1), + Bg::Pixel(p) => (0x0002, p), + }; + body.extend_from_slice(&(mask | 0x0200 | 0x0800).to_le_bytes()); + for word in [first, 1, EXPOSURE_AND_SUBSTRUCTURE] { + body.extend_from_slice(&word.to_le_bytes()); + } + self.request(1, 0, &body); + self.names.push((id, name)); + id + } + + pub(super) fn map(&mut self, window: u32) { + self.request(8, 0, &window.to_le_bytes()); + } + + pub(super) fn map_subwindows(&mut self, window: u32) { + self.request(9, 0, &window.to_le_bytes()); + } + + /// COMPOSITE `RedirectSubwindows(window, Manual)`. + pub(super) fn redirect_subwindows(&mut self, window: u32) { + let mut body = window.to_le_bytes().to_vec(); + body.extend_from_slice(&[1, 0, 0, 0]); + self.request(COMPOSITE_MAJOR, 2, &body); + } + + /// COMPOSITE `UnredirectSubwindows(window, Manual)`. + pub(super) fn unredirect_subwindows(&mut self, window: u32) { + let mut body = window.to_le_bytes().to_vec(); + body.extend_from_slice(&[1, 0, 0, 0]); + self.request(COMPOSITE_MAJOR, 4, &body); + } + + /// COMPOSITE `GetOverlayWindow(root)` (minor 7) or `ReleaseOverlayWindow` (8). + pub(super) fn overlay(&mut self, minor: u8) { + self.request(COMPOSITE_MAJOR, minor, &ROOT_WINDOW.0.to_le_bytes()); + } + + /// How `window`'s background was painted on realize: `Some(true)` with + /// its storage or, deferred, after a redirect backing was allocated; + /// `Some(false)` never; `None` when not realized. + pub(super) fn realized_painted(&self, window: u32) -> Option { + let host = self + .state + .resources + .window(ResourceId(window))? + .host_xid? + .as_raw(); + let calls = self.backend.calls.lock().unwrap(); + let (mut realized, mut deferred, mut backing) = (None, false, false); + for call in calls.iter() { + match call { + RecordedCall::RealizeWindowStorage(x) if *x == host => realized = Some(true), + RecordedCall::RealizeWindowStorageUnpainted(x) if *x == host => { + realized = Some(false); + } + RecordedCall::RealizeWindowStorageDeferred(x) if *x == host => { + (realized, deferred, backing) = (Some(false), true, false); + } + RecordedCall::AllocateRedirectedBacking { .. } => backing = true, + RecordedCall::PaintWindowBackgroundRect { host_xid, .. } + if *host_xid == host && deferred && backing => + { + realized = Some(true); + } + _ => {} + } + } + realized + } + + pub(super) fn reparent(&mut self, window: u32, parent: u32, x: i16, y: i16) { + let mut body = Vec::new(); + for word in [window, parent] { + body.extend_from_slice(&word.to_le_bytes()); + } + body.extend_from_slice(&x.to_le_bytes()); + body.extend_from_slice(&y.to_le_bytes()); + self.request(7, 0, &body); + } + + pub(super) fn clear(&mut self, window: u32, rect: (i16, i16, u16, u16)) { + self.try_clear(window, rect) + .expect("request through core dispatcher"); + } + + pub(super) fn try_clear( + &mut self, + window: u32, + rect: (i16, i16, u16, u16), + ) -> io::Result { + let mut body = window.to_le_bytes().to_vec(); + for half in [ + rect.0.to_le_bytes(), + rect.1.to_le_bytes(), + rect.2.to_le_bytes(), + rect.3.to_le_bytes(), + ] { + body.extend_from_slice(&half); + } + self.try_request(61, 1, &body) + } + + /// The probe's `watch_damage` at one level: `raw` RawRectangles, else NonEmpty. + pub(super) fn watch_damage(&mut self, drawable: u32, raw: bool) { + let id = self.xid(); + let mut body = Vec::new(); + for word in [id, drawable] { + body.extend_from_slice(&word.to_le_bytes()); + } + body.push(if raw { DAMAGE_RAW } else { DAMAGE_NON_EMPTY }); + body.extend_from_slice(&[0, 0, 0]); + self.request(DAMAGE_MAJOR, 1, &body); + self.damages.push((id, raw)); + } + + /// The fills recorded on `window`'s storage since the last call. + pub(super) fn take_fills(&mut self, window: u32) -> Vec { + let host = self + .state + .resources + .window(ResourceId(window)) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()); + let calls = std::mem::take(&mut *self.backend.calls.lock().unwrap()); + calls + .iter() + .filter_map(|call| match call { + RecordedCall::FillRectangle { + host_xid, + x, + y, + width, + height, + .. + } if Some(*host_xid) == host => Some((*x, *y, *width, *height)), + _ => None, + }) + .collect() + } + + fn nm(&self, id: u32) -> &'static str { + self.names + .iter() + .rev() + .find(|(x, _)| *x == id) + .map_or("?", |(_, n)| n) + } + + /// The events since the last step, formatted like the probe's line; + /// NonEmpty damage is then subtracted as the probe does. + pub(super) fn step(&mut self) -> String { + let bytes = read_all_available(&mut self.peer); + let mut out = String::new(); + let u16_at = |e: &[u8], at: usize| u16::from_le_bytes([e[at], e[at + 1]]); + for e in bytes.chunks_exact(32) { + let line = match e[0] & 0x7f { + 12 => format!( + " Expose({} {},{} {}x{} c{})", + self.nm(le_u32(e, 4)), + u16_at(e, 8), + u16_at(e, 10), + u16_at(e, 12), + u16_at(e, 14), + u16_at(e, 16) + ), + 19 => format!(" Map({}@{})", self.nm(le_u32(e, 8)), self.nm(le_u32(e, 4))), + 18 => format!( + " Unmap({}@{})", + self.nm(le_u32(e, 8)), + self.nm(le_u32(e, 4)) + ), + 21 => format!( + " Reparent({}@{} ->{} {},{})", + self.nm(le_u32(e, 8)), + self.nm(le_u32(e, 4)), + self.nm(le_u32(e, 12)), + u16_at(e, 16) as i16, + u16_at(e, 18) as i16 + ), + c if c == crate::nested::DAMAGE_FIRST_EVENT => { + let damage = le_u32(e, 8); + let raw = self + .damages + .iter() + .find(|(d, _)| *d == damage) + .map(|(_, r)| *r); + format!( + " Dmg{}({} {},{} {}x{})", + match raw { + Some(true) => "R", + Some(false) => "N", + None => "?", + }, + self.nm(le_u32(e, 4)), + u16_at(e, 16) as i16, + u16_at(e, 18) as i16, + u16_at(e, 20), + u16_at(e, 22) + ) + } + 0 => format!(" Error({})", e[1]), + _ => continue, + }; + out.push_str(&line); + } + let non_empty: Vec = self + .damages + .iter() + .filter(|(_, raw)| !raw) + .map(|(d, _)| *d) + .collect(); + for d in non_empty { + let mut body = d.to_le_bytes().to_vec(); + body.extend_from_slice(&[0; 8]); + self.request(DAMAGE_MAJOR, 3, &body); + } + let _ = read_all_available(&mut self.peer); + out.trim_start().to_string() + } +} + +/// Case 4 of the probe: ClearArea on `V`, whose bottom-right `S` covers; +/// each step's events and the fills on `V`. +fn clear_area_case(v_bg: Bg, raw: bool) -> Vec<(String, Vec)> { + let mut p = Probe::new(); + let t = p.create("T", ROOT_WINDOW.0, (50, 50, 400, 300), Bg::Pixel(0x40_4040)); + let v = p.create("V", t, (20, 20, 200, 150), v_bg); + p.create("S", t, (120, 95, 150, 100), Bg::Pixel(0x00_ff00)); + p.map_subwindows(t); + p.map(t); + p.watch_damage(t, raw); + let _ = p.step(); + let _ = p.take_fills(v); + [ + (0, 0, 0, 0), + (0, 0, 60, 50), + (40, 30, 120, 80), + (120, 90, 50, 40), + (150, 0, 50, 150), + ] + .into_iter() + .map(|r| { + p.clear(v, r); + (p.step(), p.take_fills(v)) + }) + .collect() +} + +/// `miClearToBackground` clips the rect to the clip list, paints and +/// exposes per clip-list box (`mi/miwindow.c:84-112`, `mi/miexpose.c:365`). +fn events(case: Vec<(String, Vec)>) -> Vec { + case.into_iter().map(|(e, _)| e).collect() +} + +#[test] +fn clear_area_exposes_and_damages_only_the_clip_list() { + assert_eq!( + events(clear_area_case(Bg::Pixel(0x80_8080), true)), + [ + "DmgR(T 20,20 200x75) DmgR(T 20,95 100x75) Expose(V 0,0 200x75 c1) Expose(V 0,75 100x75 c0)", + "DmgR(T 20,20 60x50) Expose(V 0,0 60x50 c0)", + "DmgR(T 60,50 120x45) DmgR(T 60,95 60x35) Expose(V 40,30 120x45 c1) Expose(V 40,75 60x35 c0)", + "", + "DmgR(T 170,20 50x75) Expose(V 150,0 50x75 c0)", + ] + ); + assert_eq!( + events(clear_area_case(Bg::Pixel(0x80_8080), false)), + [ + "DmgN(T 0,0 400x300) Expose(V 0,0 200x75 c1) Expose(V 0,75 100x75 c0)", + "DmgN(T 0,0 400x300) Expose(V 0,0 60x50 c0)", + "DmgN(T 0,0 400x300) Expose(V 40,30 120x45 c1) Expose(V 40,75 60x35 c0)", + "", + "DmgN(T 0,0 400x300) Expose(V 150,0 50x75 c0)", + ] + ); + assert_eq!( + events(clear_area_case(Bg::None, true)), + [ + "Expose(V 0,0 200x75 c1) Expose(V 0,75 100x75 c0)", + "Expose(V 0,0 60x50 c0)", + "Expose(V 40,30 120x45 c1) Expose(V 40,75 60x35 c0)", + "", + "Expose(V 150,0 50x75 c0)", + ] + ); +} + +/// A failed fill fails the ClearArea and damages nothing it did not paint. +#[test] +fn clear_area_fill_failure_propagates_without_damage() { + let mut p = Probe::new(); + let t = p.create("T", ROOT_WINDOW.0, (50, 50, 400, 300), Bg::Pixel(0x40_4040)); + let v = p.create("V", t, (20, 20, 200, 150), Bg::Pixel(0x80_8080)); + p.map(v); + p.map(t); + p.watch_damage(t, true); + let _ = p.step(); + p.backend.fail_fill_rectangle = true; + assert!(p.try_clear(v, (0, 0, 0, 0)).is_err()); + assert_eq!(p.step(), ""); +} + +/// `miPaintWindow` fills only the clipped region (`mi/miwindow.c:110-116`). +#[test] +fn clear_area_paints_only_the_clip_list() { + let fills: Vec<_> = clear_area_case(Bg::Pixel(0x80_8080), true) + .into_iter() + .map(|(_, f)| f) + .collect(); + assert_eq!( + fills, + [ + vec![(0, 0, 200, 75), (0, 75, 100, 75)], + vec![(0, 0, 60, 50)], + vec![(40, 30, 120, 45), (40, 75, 60, 35)], + vec![], + vec![(150, 0, 50, 75)], + ] + ); + assert!( + clear_area_case(Bg::None, true) + .iter() + .all(|(_, f)| f.is_empty()) + ); +} + +/// Case 2 of the probe in comp mode: ParentRelative or pixel `K` (with +/// ParentRelative `G`) under `P`, whose subwindows a Manual redirect holds; +/// root's are redirected too. The map steps' events, and whether P, K, G +/// were realized with their background paint. +fn manual_parent_case( + k_bg: Bg, + map_parent_last: bool, + raw: bool, +) -> (Vec, [Option; 3]) { + let mut p = Probe::new(); + p.redirect_subwindows(ROOT_WINDOW.0); + let pw = p.create("P", ROOT_WINDOW.0, (50, 50, 300, 200), Bg::Pixel(0x80_8080)); + let k = p.create("K", pw, (20, 20, 120, 100), k_bg); + let g = p.create("G", k, (10, 10, 50, 40), Bg::ParentRelative); + p.map(g); + p.redirect_subwindows(pw); + p.watch_damage(pw, raw); + p.watch_damage(k, raw); + let _ = p.step(); + let order = if map_parent_last { [k, pw] } else { [pw, k] }; + let lines = order + .into_iter() + .map(|w| { + p.map(w); + p.step() + }) + .collect(); + (lines, [pw, k, g].map(|w| p.realized_painted(w))) +} + +/// `compRedirectSubwindows` sets `inhibitBGPaint` on P (`composite/compalloc.c:404-411`) +/// and `miPaintWindow` follows K's ParentRelative chain to it (`mi/miexpose.c:425-436`): +/// neither is painted nor damaged. K draws into its own pixmap, so its paint +/// never damages P. +#[test] +fn manual_redirect_parent_inhibits_parent_relative_children() { + const K_EXPOSES: &str = "Expose(K 0,0 120x10 c3) Expose(K 0,10 10x40 c2) \ + Expose(K 60,10 60x40 c1) Expose(K 0,50 120x50 c0)"; + let unpainted = [Some(false), Some(false), Some(false)]; + assert_eq!( + manual_parent_case(Bg::ParentRelative, false, true), + ( + vec![ + "Map(P@root) Expose(P 0,0 300x200 c0)".to_string(), + format!("Map(K@P) {K_EXPOSES} Expose(G 0,0 50x40 c0)"), + ], + unpainted + ) + ); + assert_eq!( + manual_parent_case(Bg::ParentRelative, true, true), + ( + vec![ + "Map(K@P)".to_string(), + format!("Map(P@root) Expose(P 0,0 300x200 c0) {K_EXPOSES} Expose(G 0,0 50x40 c0)"), + ], + unpainted + ) + ); + let k_raw = "DmgR(K 0,0 120x10) DmgR(K 0,10 10x40) DmgR(K 60,10 60x40) DmgR(K 0,50 120x50)"; + let painted_k = [Some(false), Some(true), Some(true)]; + assert_eq!( + manual_parent_case(Bg::Pixel(0x20_50a0), false, true), + ( + vec![ + "Map(P@root) Expose(P 0,0 300x200 c0)".to_string(), + format!("Map(K@P) {k_raw} {K_EXPOSES} DmgR(K 10,10 50x40) Expose(G 0,0 50x40 c0)"), + ], + painted_k + ) + ); + assert_eq!( + manual_parent_case(Bg::Pixel(0x20_50a0), true, true).0[1], + format!( + "Map(P@root) Expose(P 0,0 300x200 c0) {k_raw} {K_EXPOSES} DmgR(K 10,10 50x40) \ + Expose(G 0,0 50x40 c0)" + ) + ); + assert_eq!( + manual_parent_case(Bg::Pixel(0x20_50a0), false, false).0[1], + format!("Map(K@P) DmgN(K 0,0 120x100) {K_EXPOSES} Expose(G 0,0 50x40 c0)") + ); + assert_eq!( + manual_parent_case(Bg::Pixel(0x20_50a0), true, false).0[1], + format!( + "Map(P@root) Expose(P 0,0 300x200 c0) DmgN(K 0,0 120x100) {K_EXPOSES} \ + Expose(G 0,0 50x40 c0)" + ) + ); +} + +/// Case 3 of the probe in comp mode: W1 (with child W1c) and W2 mapped under +/// the overlay, then ReleaseOverlayWindow and UnredirectSubwindows(root) in +/// either order. The unredirect step's events, root's size. +fn overlay_release_case(bg: Bg, release_first: bool) -> (String, (u16, u16)) { + let mut p = Probe::new(); + p.redirect_subwindows(ROOT_WINDOW.0); + p.select(ROOT_WINDOW.0, EXPOSURE_AND_SUBSTRUCTURE); + p.overlay(7); + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW.0; + p.names.push((cow, "COW")); + p.select(cow, EXPOSURE_AND_SUBSTRUCTURE); + let w1 = p.create("W1", ROOT_WINDOW.0, (50, 50, 200, 150), bg); + let w2 = p.create("W2", ROOT_WINDOW.0, (150, 100, 200, 150), bg); + let w1c = p.create("W1c", w1, (10, 10, 60, 40), bg); + p.map(w1c); + for w in [w1, w2] { + p.watch_damage(w, false); + p.watch_damage(w, true); + } + p.map(w1); + p.map(w2); + let _ = p.step(); + if release_first { + p.overlay(8); + let _ = p.step(); + } + p.unredirect_subwindows(ROOT_WINDOW.0); + let line = p.step(); + let root = p.state.resources.window(ROOT_WINDOW).unwrap(); + (line, (root.width, root.height)) +} + +/// `compFreeClientSubwindows` unredirects the children bottom-most first +/// (`composite/compalloc.c:450`), each `compRestoreWindow` copying its old +/// backing back with IncludeInferiors (`:232-256`): DAMAGE over the window +/// while the ones above are still redirected, nothing under the overlay. +#[test] +fn unredirect_after_overlay_release_damages_the_restored_windows() { + for bg in [Bg::None, Bg::Pixel(0x80_8080)] { + let (line, (w, h)) = overlay_release_case(bg, true); + assert_eq!( + line, + format!( + "Expose(root 0,0 {w}x{h} c0) DmgN(W1 0,0 200x150) DmgR(W1 0,0 200x150) \ + DmgN(W2 0,0 200x150) DmgR(W2 0,0 200x150)" + ) + ); + assert_eq!(overlay_release_case(bg, false).0, ""); + } +} + +/// Case 1a of the probe: MapSubwindows on T with A, B (over A) and C. +fn map_subwindows_case(child_bg: Bg) -> String { + let mut p = Probe::new(); + let t = p.create("T", ROOT_WINDOW.0, (50, 50, 300, 200), Bg::None); + p.create("A", t, (10, 10, 80, 80), child_bg); + p.create("B", t, (60, 60, 80, 80), child_bg); + p.create("C", t, (190, 10, 80, 80), child_bg); + p.watch_damage(t, true); + p.map(t); + let _ = p.step(); + p.map_subwindows(t); + p.step() +} + +/// `MapSubwindows` delivers MapNotify from firstChild down (`dix/window.c:2739`); +/// the exposures follow, top-most first. +#[test] +fn map_subwindows_notifies_top_most_first() { + const EXPOSES: &str = "Expose(C 0,0 80x80 c0) Expose(B 0,0 80x80 c0) \ + Expose(A 0,0 80x50 c1) Expose(A 0,50 50x30 c0)"; + assert_eq!( + map_subwindows_case(Bg::None), + format!("Map(C@T) Map(B@T) Map(A@T) {EXPOSES}") + ); + assert_eq!( + map_subwindows_case(Bg::Pixel(0x80_8080)), + "Map(C@T) Map(B@T) Map(A@T) DmgR(T 190,10 80x80) Expose(C 0,0 80x80 c0) \ + DmgR(T 60,60 80x80) Expose(B 0,0 80x80 c0) DmgR(T 10,10 80x50) DmgR(T 10,60 50x30) \ + Expose(A 0,0 80x50 c1) Expose(A 0,50 50x30 c0)" + ); +} + +/// Case 1b of the probe with both damage levels on P and R, NonEmpty then +/// RawRectangles each, as the probe creates them. +fn reparent_case(comp: bool) -> Vec { + let mut p = Probe::new(); + if comp { + p.redirect_subwindows(ROOT_WINDOW.0); + } + let bg = Bg::Pixel(0x80_8080); + let pw = p.create("P", ROOT_WINDOW.0, (50, 50, 300, 200), bg); + let r = p.create("R", ROOT_WINDOW.0, (400, 60, 120, 100), bg); + let k = p.create("Rk", r, (10, 10, 50, 40), bg); + p.map(k); + for w in [pw, r] { + p.watch_damage(w, false); + p.watch_damage(w, true); + } + let _ = p.step(); + p.map(pw); + p.map(r); + let mut lines = vec![p.step()]; + p.reparent(r, pw, 20, 30); + lines.push(p.step()); + p.reparent(r, ROOT_WINDOW.0, 400, 60); + lines.push(p.step()); + lines +} + +/// Xorg reports each damage object in its pixmap's list order: new objects +/// are prepended (`miext/damage/damage.c:1482`), and a window given a pixmap, +/// by compositing or a reparent, moves its own to the head oldest first +/// (`damageSetWindowPixmap`, `:1547-1575`). Each reports its whole part of +/// the op before the next (`damageRegionProcessPending`, `:285-300`). +#[test] +fn damage_notifies_follow_the_damage_list_order() { + const R_EXPOSES: &str = "Expose(R 0,0 120x10 c3) Expose(R 0,10 10x40 c2) \ + Expose(R 60,10 60x40 c1) Expose(R 0,50 120x50 c0)"; + const R_RAW: &str = + "DmgR(R 0,0 120x10) DmgR(R 0,10 10x40) DmgR(R 60,10 60x40) DmgR(R 0,50 120x50)"; + const P_RAW: &str = + "DmgR(P 20,30 120x10) DmgR(P 20,40 10x40) DmgR(P 80,40 60x40) DmgR(P 20,80 120x50)"; + const INTO: &str = "Unmap(R@root) Reparent(R@root ->P 20,30) Reparent(R@P ->P 20,30) Map(R@P)"; + const OUT: &str = "Reparent(R@P ->root 400,60) Reparent(R@root ->root 400,60) Map(R@root)"; + const RK: &str = "DmgR(R 10,10 50x40) Expose(Rk 0,0 50x40 c0)"; + assert_eq!( + reparent_case(false), + [ + format!( + "Map(P@root) DmgR(P 0,0 300x200) DmgN(P 0,0 300x200) Expose(P 0,0 300x200 c0) \ + Map(R@root) {R_RAW} DmgN(R 0,0 120x100) {R_EXPOSES} {RK}" + ), + format!( + "{INTO} DmgN(R 0,0 120x100) {R_RAW} {P_RAW} DmgN(P 0,0 300x200) {R_EXPOSES} \ + DmgR(R 10,10 50x40) DmgR(P 30,40 50x40) Expose(Rk 0,0 50x40 c0)" + ), + format!( + "Unmap(R@P) DmgR(P 20,30 120x100) DmgN(P 0,0 300x200) Expose(P 20,30 120x100 c0) \ + {OUT} DmgN(R 0,0 120x100) {R_RAW} {R_EXPOSES} {RK}" + ), + ] + ); + assert_eq!( + reparent_case(true), + [ + format!( + "Map(P@root) DmgN(P 0,0 300x200) DmgR(P 0,0 300x200) Expose(P 0,0 300x200 c0) \ + Map(R@root) DmgN(R 0,0 120x100) {R_RAW} {R_EXPOSES} {RK}" + ), + format!( + "{INTO} DmgN(R 0,0 120x100) {R_RAW} DmgN(P 0,0 300x200) {P_RAW} {R_EXPOSES} \ + DmgR(R 10,10 50x40) DmgR(P 30,40 50x40) Expose(Rk 0,0 50x40 c0)" + ), + format!( + "Unmap(R@P) DmgN(P 0,0 300x200) DmgR(P 20,30 120x100) Expose(P 20,30 120x100 c0) \ + {OUT} DmgN(R 0,0 120x100) {R_RAW} {R_EXPOSES} {RK}" + ), + ] + ); +} + +/// A window whose background waits for the backing its map allocates is +/// painted, once the backing exists, where its map exposures paint: its +/// content less its viewable InputOutput children's border boxes +/// (ClipByChildren). Painted whole, it covered a bordered child in the +/// backing they share, border included, and a child's own deferred paint is +/// its background alone. An InputOnly child draws nothing and leaves no hole. +#[test] +fn a_deferred_background_leaves_the_childrens_area_alone() { + let mut p = Probe::new(); + p.redirect_subwindows(ROOT_WINDOW.0); + let w = p.create("W", ROOT_WINDOW.0, (0, 0, 178, 178), Bg::Pixel(0xFF_FFFF)); + let c = p.create("C", w, (10, 10, 50, 50), Bg::Pixel(0xFF_FFFF)); + // ConfigureWindow(C, CWBorderWidth = 4): its border box is (10, 10) to + // (68, 68). + let mut body = c.to_le_bytes().to_vec(); + body.extend_from_slice(&0x0010u16.to_le_bytes()); + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(&4u32.to_le_bytes()); + p.request(12, 0, &body); + // An InputOnly child over the background's bottom right. + let mut body = Vec::new(); + for word in [0x0010_7777_u32, w] { + body.extend_from_slice(&word.to_le_bytes()); + } + for half in [120i16, 120, 40, 40] { + body.extend_from_slice(&half.to_le_bytes()); + } + body.extend_from_slice(&0u16.to_le_bytes()); // border + body.extend_from_slice(&2u16.to_le_bytes()); // InputOnly + body.extend_from_slice(&0u32.to_le_bytes()); // CopyFromParent visual + body.extend_from_slice(&0u32.to_le_bytes()); // no attributes + p.request(1, 0, &body); + p.map(c); + p.map(0x0010_7777); + p.map(w); + let host = p + .state + .resources + .window(ResourceId(w)) + .and_then(|w| w.host_xid) + .expect("W's host") + .as_raw(); + let rects: Vec<(i16, i16, u16, u16)> = p + .backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::PaintWindowBackgroundRect { + host_xid, + x, + y, + width, + height, + } if *host_xid == host => Some((*x, *y, *width, *height)), + _ => None, + }) + .collect(); + assert!(!rects.is_empty(), "W's background is painted"); + let overlaps_child = |&(x, y, w, h): &(i16, i16, u16, u16)| { + let (x, y, w, h) = (i32::from(x), i32::from(y), i32::from(w), i32::from(h)); + x < 68 && x + w > 10 && y < 68 && y + h > 10 + }; + assert!( + !rects.iter().any(overlaps_child), + "nothing of W's paint covers C or its border: {rects:?}" + ); + let area: u32 = rects + .iter() + .map(|&(_, _, w, h)| u32::from(w) * u32::from(h)) + .sum(); + assert_eq!( + area, + 178 * 178 - 58 * 58, + "all of W but C's border box, the InputOnly child's area included: {rects:?}" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs b/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs new file mode 100644 index 000000000..98241ff0f --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs @@ -0,0 +1,1028 @@ +use super::*; +use crate::access::{ + AccessContext, AccessMode, AccessPolicy, Decision, DenyError, RequestOpcodes, ResourceTarget, +}; +use std::sync::atomic::{AtomicBool, Ordering}; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(super) enum ExtensionHook { + Access, + Dispatch, + Resource, + Property, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(super) struct RecordedExtensionCheck { + pub(super) hook: ExtensionHook, + pub(super) client: ClientId, + pub(super) extension: String, + pub(super) request: Option, + pub(super) peer: Option, + pub(super) admission: Option, + pub(super) target: Option, + pub(super) property: Option<(ResourceId, AtomId)>, + pub(super) mode: Option, + pub(super) owner: Option, +} + +pub(super) struct RecordingExtensionPolicy { + pub(super) decision: Decision, + pub(super) calls: Arc>>, +} + +impl RecordingExtensionPolicy { + fn check( + &self, + hook: ExtensionHook, + ctx: &AccessContext<'_>, + client: ClientId, + extension: &str, + target: Option, + property: Option<(ResourceId, AtomId)>, + mode: Option, + ) -> Decision { + self.calls.lock().unwrap().push(RecordedExtensionCheck { + hook, + client, + extension: extension.to_owned(), + request: ctx.request(), + peer: ctx.peer(client).copied(), + admission: ctx.admission(client).cloned(), + owner: target.and_then(|target| ctx.owner(target.id, target.kind)), + target, + property, + mode, + }); + self.decision + } +} + +impl AccessPolicy for RecordingExtensionPolicy { + fn extension_access( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + extension: &str, + ) -> Decision { + self.check( + ExtensionHook::Access, + ctx, + client, + extension, + None, + None, + None, + ) + } + + fn extension_dispatch( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + extension: &str, + ) -> Decision { + self.check( + ExtensionHook::Dispatch, + ctx, + client, + extension, + None, + None, + None, + ) + } + + fn resource( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.check( + ExtensionHook::Resource, + ctx, + client, + "", + Some(*target), + None, + Some(mode), + ) + } + + fn property( + &self, + ctx: &AccessContext<'_>, + client: ClientId, + window: ResourceId, + property: AtomId, + mode: AccessMode, + ) -> Decision { + self.check( + ExtensionHook::Property, + ctx, + client, + "", + None, + Some((window, property)), + Some(mode), + ) + } +} + +struct NameSetDenier(HashSet); + +impl AccessPolicy for NameSetDenier { + fn extension_access( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + extension: &str, + ) -> Decision { + if self.0.contains(extension) { + Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }) + } else { + Decision::Allow + } + } +} + +struct RevocableExtensionPolicy(Arc); + +impl RevocableExtensionPolicy { + fn decision(&self) -> Decision { + if self.0.load(Ordering::SeqCst) { + Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }) + } else { + Decision::Allow + } + } +} + +impl AccessPolicy for RevocableExtensionPolicy { + fn extension_access( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _extension: &str, + ) -> Decision { + self.decision() + } + + fn extension_dispatch( + &self, + _ctx: &AccessContext<'_>, + _client: ClientId, + _extension: &str, + ) -> Decision { + self.decision() + } +} + +fn name_denier(names: &[&str]) -> NameSetDenier { + NameSetDenier(names.iter().map(|name| (*name).to_owned()).collect()) +} + +fn query_extension_body(name: &str) -> Vec { + let name = name.as_bytes(); + let mut body = Vec::with_capacity(4 + name.len().div_ceil(4) * 4); + body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(name); + body.resize(body.len().div_ceil(4) * 4, 0); + body +} + +fn dispatch_extension_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client_id: ClientId, + sequence: u16, + opcode: u8, + minor: u8, + body: &[u8], +) { + process_request( + state, + backend, + client_id, + SequenceNumber(sequence), + RequestHeader { + opcode, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + None, + ) + .expect("process_request"); +} + +fn query_extension( + state: &mut ServerState, + backend: &mut RecordingBackend, + sequence: u16, + name: &str, +) -> Vec { + let mut peer = install_client(state, 1); + let body = query_extension_body(name); + dispatch_extension_request(state, backend, ClientId(1), sequence, 98, 0, &body); + read_all_available(&mut peer) +} + +fn list_extensions(state: &mut ServerState, backend: &mut RecordingBackend) -> Vec { + let mut peer = install_client(state, 1); + dispatch_extension_request(state, backend, ClientId(1), 1, 99, 0, &[]); + read_all_available(&mut peer) +} + +fn names_from_list_reply(reply: &[u8]) -> Vec { + assert_eq!(reply.first(), Some(&1), "ListExtensions must reply"); + let name_count = usize::from(reply[1]); + let extra_units = u32::from_le_bytes(reply[4..8].try_into().unwrap()) as usize; + assert_eq!(reply.len(), 32 + extra_units * 4, "reply length field"); + + let encoded_names = &reply[32..]; + let mut names = Vec::with_capacity(name_count); + let mut offset = 0; + for _ in 0..name_count { + let length = usize::from(encoded_names[offset]); + offset += 1; + names.push(String::from_utf8(encoded_names[offset..offset + length].to_vec()).unwrap()); + offset += length; + } + assert_eq!(encoded_names.len(), offset.div_ceil(4) * 4); + assert!(encoded_names[offset..].iter().all(|byte| *byte == 0)); + names +} + +fn absent_query_reply(reply: &[u8]) { + assert_eq!(reply.len(), 32); + assert_eq!(reply[0], 1, "reply, not error"); + assert_eq!( + &reply[8..12], + &[0, 0, 0, 0], + "absent extensions have zero presence, opcode, event, and error fields" + ); +} + +fn dispatch_error(reply: &[u8], sequence: u16, minor: u16, major: u8) { + assert_eq!(reply.len(), 32, "one X error packet"); + assert_eq!(reply[0], 0, "error packet"); + assert_eq!(reply[1], x11::error::BAD_REQUEST, "BadRequest"); + assert_eq!(&reply[2..4], &sequence.to_le_bytes(), "sequence"); + assert_eq!(&reply[4..8], &[0, 0, 0, 0], "error value"); + assert_eq!(&reply[8..10], &minor.to_le_bytes(), "minor opcode"); + assert_eq!(reply[10], major, "major opcode"); +} + +fn request_reply_without_policy(opcode: u8, minor: u8, body: &[u8]) -> Vec { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + opcode, + minor, + body, + ); + read_all_available(&mut peer) +} + +#[test] +fn query_extension_denied_answers_like_an_unknown_name() { + // Mutation: drop the access check; XFIXES becomes present and differs from the unknown-name reply. + let mut unknown_state = ServerState::new(); + let mut unknown_backend = RecordingBackend::new(); + let unknown = query_extension( + &mut unknown_state, + &mut unknown_backend, + 0x1234, + "NO-SUCH-EXTENSION", + ); + + let mut denied_state = ServerState::new(); + denied_state.install_access_policy(Arc::new(name_denier(&["XFIXES"]))); + let mut denied_backend = RecordingBackend::new(); + let denied = query_extension(&mut denied_state, &mut denied_backend, 0x1234, "XFIXES"); + + absent_query_reply(&unknown); + absent_query_reply(&denied); + assert_eq!( + denied, unknown, + "denied and unknown extensions are indistinguishable" + ); +} + +#[test] +fn list_extensions_leaves_out_denied_names() { + // Mutation: ignore the access decision; the denied names remain in the list. + let mut baseline_state = ServerState::new(); + let mut baseline_backend = RecordingBackend::new(); + let baseline = list_extensions(&mut baseline_state, &mut baseline_backend); + let baseline_names = names_from_list_reply(&baseline); + assert!(baseline_names.iter().any(|name| name == "XFIXES")); + assert!(baseline_names.iter().any(|name| name == "SHAPE")); + let expected: Vec<_> = baseline_names + .iter() + .filter(|name| name.as_str() != "XFIXES" && name.as_str() != "SHAPE") + .cloned() + .collect(); + + let mut denied_state = ServerState::new(); + denied_state.install_access_policy(Arc::new(name_denier(&["XFIXES", "SHAPE"]))); + let mut denied_backend = RecordingBackend::new(); + let denied = list_extensions(&mut denied_state, &mut denied_backend); + assert_eq!(names_from_list_reply(&denied), expected); + assert_eq!(usize::from(denied[1]), expected.len()); + assert_eq!( + denied.len(), + 32 + u32::from_le_bytes(denied[4..8].try_into().unwrap()) as usize * 4 + ); + + let mut all_denied_state = ServerState::new(); + all_denied_state.install_access_policy(Arc::new(name_denier( + &baseline_names + .iter() + .map(String::as_str) + .collect::>(), + ))); + let mut all_denied_backend = RecordingBackend::new(); + let all_denied = list_extensions(&mut all_denied_state, &mut all_denied_backend); + assert_eq!(all_denied[0], 1); + assert_eq!(all_denied[1], 0); + assert_eq!(&all_denied[4..8], &[0, 0, 0, 0]); + assert_eq!(all_denied.len(), 32); + assert!(names_from_list_reply(&all_denied).is_empty()); +} + +#[test] +fn extension_access_asks_once_per_available_extension() { + // Mutation: ask before availability is checked; unavailable RENDER is then recorded. + let mut baseline_state = ServerState::new(); + let mut baseline_backend = RecordingBackend::new(); + let advertised = + names_from_list_reply(&list_extensions(&mut baseline_state, &mut baseline_backend)); + assert!(advertised.iter().any(|name| name == "SYNC")); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let expected_peer = state.clients[&1].peer; + let expected_admission = state.clients[&1].admission; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + let mut backend = RecordingBackend::new(); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 10, + 98, + 0, + &query_extension_body("SYNC"), + ); + let _ = read_all_available(&mut peer); + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 11, 99, 0, &[]); + let _ = read_all_available(&mut peer); + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 12, + 98, + 0, + &query_extension_body("RENDER"), + ); + let _ = read_all_available(&mut peer); + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 13, + 98, + 0, + &query_extension_body("xfixes"), + ); + let _ = read_all_available(&mut peer); + + let mut expected = vec![RecordedExtensionCheck { + hook: ExtensionHook::Access, + client: ClientId(1), + extension: "SYNC".to_owned(), + request: Some(RequestOpcodes { + major: 98, + minor: 0, + }), + peer: Some(expected_peer), + admission: Some(expected_admission), + target: None, + property: None, + mode: None, + owner: None, + }]; + expected.extend(advertised.iter().map(|name| RecordedExtensionCheck { + hook: ExtensionHook::Access, + client: ClientId(1), + extension: name.clone(), + request: Some(RequestOpcodes { + major: 99, + minor: 0, + }), + peer: Some(expected_peer), + admission: Some(expected_admission), + target: None, + property: None, + mode: None, + owner: None, + })); + assert_eq!(*calls.lock().unwrap(), expected); +} + +#[test] +fn extension_access_allow_keeps_bytes() { + // Mutation: use the denial reply path after an Allow; every query and the list reply changes. + let mut baseline_state = ServerState::new(); + let mut baseline_backend = RecordingBackend::new(); + let baseline_list = list_extensions(&mut baseline_state, &mut baseline_backend); + let advertised = names_from_list_reply(&baseline_list); + + let mut allow_state = ServerState::new(); + allow_state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::new(Mutex::new(Vec::new())), + })); + let mut allow_backend = RecordingBackend::new(); + assert_eq!( + list_extensions(&mut allow_state, &mut allow_backend), + baseline_list + ); + + for (index, name) in advertised.iter().enumerate() { + let sequence = u16::try_from(index + 2).unwrap(); + let mut baseline_state = ServerState::new(); + let mut baseline_backend = RecordingBackend::new(); + let baseline = query_extension(&mut baseline_state, &mut baseline_backend, sequence, name); + + let mut allow_state = ServerState::new(); + allow_state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::new(Mutex::new(Vec::new())), + })); + let mut allow_backend = RecordingBackend::new(); + let allowed = query_extension(&mut allow_state, &mut allow_backend, sequence, name); + assert_eq!(allowed, baseline, "QueryExtension({name}) wire reply"); + } +} + +#[test] +fn extension_access_first_denial_wins() { + // Mutation: keep asking after a denial; the later policy records a call. + let deny = Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }); + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let allow_calls = Arc::new(Mutex::new(Vec::new())); + let deny_calls = Arc::new(Mutex::new(Vec::new())); + let after_deny_calls = Arc::new(Mutex::new(Vec::new())); + for (decision, calls) in [ + (Decision::Allow, Arc::clone(&allow_calls)), + (deny, Arc::clone(&deny_calls)), + (Decision::Allow, Arc::clone(&after_deny_calls)), + ] { + state.install_access_policy(Arc::new(RecordingExtensionPolicy { decision, calls })); + } + let mut backend = RecordingBackend::new(); + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + 98, + 0, + &query_extension_body("XFIXES"), + ); + let reply = read_all_available(&mut peer); + absent_query_reply(&reply); + assert_eq!(allow_calls.lock().unwrap().len(), 1); + assert_eq!(deny_calls.lock().unwrap().len(), 1); + assert!(after_deny_calls.lock().unwrap().is_empty()); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let deny_calls = Arc::new(Mutex::new(Vec::new())); + let allow_calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: deny, + calls: Arc::clone(&deny_calls), + })); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&allow_calls), + })); + let mut backend = RecordingBackend::new(); + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + 98, + 0, + &query_extension_body("XFIXES"), + ); + absent_query_reply(&read_all_available(&mut peer)); + assert_eq!(deny_calls.lock().unwrap().len(), 1); + assert!(allow_calls.lock().unwrap().is_empty()); +} + +#[test] +fn extension_access_revocation_applies_to_the_next_request() { + // Mutation: reuse the prior Allow for the next request; revocation must make that reply absent. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let revoked = Arc::new(AtomicBool::new(false)); + state.install_access_policy(Arc::new(RevocableExtensionPolicy(Arc::clone(&revoked)))); + let mut backend = RecordingBackend::new(); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + 98, + 0, + &query_extension_body("XFIXES"), + ); + let allowed = read_all_available(&mut peer); + assert_eq!(allowed[0], 1); + assert_eq!(allowed[8], 1); + + revoked.store(true, Ordering::SeqCst); + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 2, + 98, + 0, + &query_extension_body("XFIXES"), + ); + absent_query_reply(&read_all_available(&mut peer)); +} + +#[test] +fn extension_access_denial_does_not_deny_dispatch() { + // Mutation: apply the discovery denial to extension dispatch; QueryVersion must still reply. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.install_access_policy(Arc::new(name_denier(&["XFIXES"]))); + let mut backend = RecordingBackend::new(); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + 98, + 0, + &query_extension_body("XFIXES"), + ); + absent_query_reply(&read_all_available(&mut peer)); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 2, + 140, + 0, + &[5, 0, 0, 0, 0, 0, 0, 0], + ); + let version = read_all_available(&mut peer); + assert_eq!(version.len(), 32); + assert_eq!(version[0], 1, "XFIXES QueryVersion reply"); + assert_eq!(version[1], 0, "successful version reply"); + assert_eq!(u32::from_le_bytes(version[8..12].try_into().unwrap()), 5); + assert_eq!(u32::from_le_bytes(version[12..16].try_into().unwrap()), 0); +} + +#[test] +fn every_extension_dispatch_denial_answers_bad_request() { + // Value 0 is deliberate, not Xorg parity: Xorg sends the stale client->errorValue here. + // Mutation: return the policy's DenyError; the packet must still be BadRequest with value 0. + for extension in crate::nested::EXTENSIONS { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::clone(&calls), + })); + let mut backend = RecordingBackend::new(); + let body = [0u8; 8]; + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 0x1234, + extension.major_opcode, + 0, + &body, + ); + + dispatch_error( + &read_all_available(&mut peer), + 0x1234, + 0, + extension.major_opcode, + ); + assert!( + backend.calls().is_empty(), + "{} handler must not run", + extension.name + ); + assert_eq!( + *calls.lock().unwrap(), + [RecordedExtensionCheck { + hook: ExtensionHook::Dispatch, + client: ClientId(1), + extension: extension.name.to_owned(), + request: Some(RequestOpcodes { + major: extension.major_opcode, + minor: 0, + }), + peer: Some(state.clients[&1].peer), + admission: Some(state.clients[&1].admission), + target: None, + property: None, + mode: None, + owner: None, + }], + "one dispatch check for {}", + extension.name, + ); + if extension.name == "BIG-REQUESTS" { + assert!(!state.clients[&1].big_requests_enabled); + } + } +} + +#[test] +fn extension_dispatch_preserves_nonzero_minor_in_check_and_error() { + // Mutations: hard-code minor 0 in RequestOpcodes or in the denial error; each assertion must fail. + let major = crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.name == "XFIXES") + .unwrap() + .major_opcode; + let calls = Arc::new(Mutex::new(Vec::new())); + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::clone(&calls), + })); + let mut backend = RecordingBackend::new(); + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 9, major, 1, &[0; 8]); + + dispatch_error(&read_all_available(&mut peer), 9, 1, major); + assert_eq!( + *calls.lock().unwrap(), + [RecordedExtensionCheck { + hook: ExtensionHook::Dispatch, + client: ClientId(1), + extension: "XFIXES".to_owned(), + request: Some(RequestOpcodes { major, minor: 1 }), + peer: Some(state.clients[&1].peer), + admission: Some(state.clients[&1].admission), + target: None, + property: None, + mode: None, + owner: None, + }], + ); +} + +#[test] +fn denied_big_requests_enable_releases_the_reader() { + // Mutation: return BadRequest without sending IgnoreBigRequests; the reader-control assertion fails. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let (control_tx, control_rx) = crossbeam_channel::unbounded(); + state.clients.get_mut(&1).unwrap().reader_control = Some(control_tx); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::new(Mutex::new(Vec::new())), + })); + let mut backend = RecordingBackend::new(); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 7, + crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.name == "BIG-REQUESTS") + .unwrap() + .major_opcode, + 0, + &[0; 8], + ); + + dispatch_error(&read_all_available(&mut peer), 7, 0, 135); + assert!(!state.clients[&1].big_requests_enabled); + assert!(matches!( + control_rx.try_recv(), + Ok(crate::server::ReaderControl::IgnoreBigRequests) + )); + assert!(control_rx.try_recv().is_err(), "one release signal only"); +} + +#[test] +fn extension_dispatch_asks_with_client_name_and_opcodes() { + // Mutation: filter dispatch by discovery availability; unadvertised RENDER must still be checked. + let version_body = [5, 0, 0, 0, 0, 0, 0, 0]; + let xfixes_major = crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.name == "XFIXES") + .unwrap() + .major_opcode; + let render_major = crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.name == "RENDER") + .unwrap() + .major_opcode; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&calls), + })); + let mut backend = RecordingBackend::new(); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + xfixes_major, + 0, + &version_body, + ); + let xfixes_reply = read_all_available(&mut peer); + assert_eq!( + xfixes_reply, + request_reply_without_policy(xfixes_major, 0, &version_body) + ); + + dispatch_extension_request( + &mut state, + &mut backend, + ClientId(1), + 1, + render_major, + 0, + &version_body, + ); + let render_reply = read_all_available(&mut peer); + assert_eq!( + render_reply, + request_reply_without_policy(render_major, 0, &version_body) + ); + + for opcode in [43, 200] { + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 1, opcode, 0, &[]); + assert_eq!( + read_all_available(&mut peer), + request_reply_without_policy(opcode, 0, &[]), + "opcode {opcode} keeps its no-policy bytes", + ); + } + assert_eq!( + *calls.lock().unwrap(), + [ + RecordedExtensionCheck { + hook: ExtensionHook::Dispatch, + client: ClientId(1), + extension: "XFIXES".to_owned(), + request: Some(RequestOpcodes { + major: xfixes_major, + minor: 0, + }), + peer: Some(state.clients[&1].peer), + admission: Some(state.clients[&1].admission), + target: None, + property: None, + mode: None, + owner: None, + }, + RecordedExtensionCheck { + hook: ExtensionHook::Dispatch, + client: ClientId(1), + extension: "RENDER".to_owned(), + request: Some(RequestOpcodes { + major: render_major, + minor: 0, + }), + peer: Some(state.clients[&1].peer), + admission: Some(state.clients[&1].admission), + target: None, + property: None, + mode: None, + owner: None, + }, + ] + ); +} + +#[test] +fn transport_gate_and_max_length_answer_before_the_dispatch_check() { + // Mutation: move the dispatch check above the locality gate; DRI3 must keep BadMatch and make no policy call. + let dri3_major = crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.name == "DRI3") + .unwrap() + .major_opcode; + let dri3_body = [0u8; 8]; + + let mut baseline_state = ServerState::new(); + let mut baseline_peer = install_client(&mut baseline_state, 1); + baseline_state.clients.get_mut(&1).unwrap().is_local = false; + baseline_state.clients.get_mut(&1).unwrap().fd_passing = false; + dispatch_extension_request( + &mut baseline_state, + &mut RecordingBackend::new(), + ClientId(1), + 1, + dri3_major, + 0, + &dri3_body, + ); + let baseline_gate = read_all_available(&mut baseline_peer); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).unwrap().is_local = false; + state.clients.get_mut(&1).unwrap().fd_passing = false; + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::clone(&calls), + })); + dispatch_extension_request( + &mut state, + &mut RecordingBackend::new(), + ClientId(1), + 1, + dri3_major, + 0, + &dri3_body, + ); + let gate = read_all_available(&mut peer); + assert_eq!(gate, baseline_gate); + assert_eq!(gate[1], x11::error::BAD_MATCH); + assert!(calls.lock().unwrap().is_empty()); + + let mut baseline_state = ServerState::new(); + let mut baseline_peer = install_client(&mut baseline_state, 1); + let mut baseline_backend = RecordingBackend::new(); + process_request( + &mut baseline_state, + &mut baseline_backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: dri3_major, + data: 0, + length_units: 65_536, + }, + &dri3_body, + None, + ) + .unwrap(); + let baseline_length = read_all_available(&mut baseline_peer); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }), + calls: Arc::clone(&calls), + })); + process_request( + &mut state, + &mut RecordingBackend::new(), + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: dri3_major, + data: 0, + length_units: 65_536, + }, + &dri3_body, + None, + ) + .unwrap(); + let length = read_all_available(&mut peer); + assert_eq!(length, baseline_length); + assert_eq!(length[1], x11::error::BAD_LENGTH); + assert!(calls.lock().unwrap().is_empty()); +} + +#[test] +fn extension_dispatch_first_denial_wins_and_revocation_applies() { + // Mutations: let a later Allow override Deny, or reuse a prior Allow after revocation; each request must re-check. + let deny = Decision::Deny(DenyError { + code: x11::error::BAD_VALUE, + value: 0x55, + }); + let major = crate::nested::EXTENSIONS + .iter() + .find(|extension| extension.name == "XFIXES") + .unwrap() + .major_opcode; + let body = [5, 0, 0, 0, 0, 0, 0, 0]; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let first_calls = Arc::new(Mutex::new(Vec::new())); + let deny_calls = Arc::new(Mutex::new(Vec::new())); + let after_deny_calls = Arc::new(Mutex::new(Vec::new())); + for (decision, calls) in [ + (Decision::Allow, Arc::clone(&first_calls)), + (deny, Arc::clone(&deny_calls)), + (Decision::Allow, Arc::clone(&after_deny_calls)), + ] { + state.install_access_policy(Arc::new(RecordingExtensionPolicy { decision, calls })); + } + let mut backend = RecordingBackend::new(); + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 1, major, 0, &body); + dispatch_error(&read_all_available(&mut peer), 1, 0, major); + assert_eq!(first_calls.lock().unwrap().len(), 1); + assert_eq!(deny_calls.lock().unwrap().len(), 1); + assert!(after_deny_calls.lock().unwrap().is_empty()); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let deny_calls = Arc::new(Mutex::new(Vec::new())); + let allow_calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: deny, + calls: Arc::clone(&deny_calls), + })); + state.install_access_policy(Arc::new(RecordingExtensionPolicy { + decision: Decision::Allow, + calls: Arc::clone(&allow_calls), + })); + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 1, major, 0, &body); + dispatch_error(&read_all_available(&mut peer), 1, 0, major); + assert_eq!(deny_calls.lock().unwrap().len(), 1); + assert!(allow_calls.lock().unwrap().is_empty()); + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let revoked = Arc::new(AtomicBool::new(false)); + state.install_access_policy(Arc::new(RevocableExtensionPolicy(Arc::clone(&revoked)))); + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 1, major, 0, &body); + assert_eq!( + read_all_available(&mut peer)[0], + 1, + "first request is allowed" + ); + revoked.store(true, Ordering::SeqCst); + dispatch_extension_request(&mut state, &mut backend, ClientId(1), 2, major, 0, &body); + dispatch_error(&read_all_available(&mut peer), 2, 0, major); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/fonts.rs b/crates/yserver-core/src/core_loop/process_request/tests/fonts.rs new file mode 100644 index 000000000..67b7503d0 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/fonts.rs @@ -0,0 +1,284 @@ +//! Core font lifetime as in Xorg: `CloseFont` frees the id +//! (`dix/dispatch.c:1319`), the font lives while a GC holds it +//! (`pFont->refcnt`, `dix/dixfonts.c:462`; `dix/gc.c:290`, `:697`, `:771`). + +use super::*; +use crate::{ + backend::recording::RecordedCall, + resources::{DEFAULT_FONT, ROOT_WINDOW}, +}; + +const F: u32 = 0x0010_0010; +const G: u32 = 0x0010_0011; +const GC1: u32 = 0x0010_0001; +const GC2: u32 = 0x0010_0002; + +struct Fx { + state: ServerState, + backend: RecordingBackend, + peers: Vec, + seq: u16, +} + +impl Fx { + fn new() -> Self { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + crate::core_loop::process_request::install_default_font(&mut state, &mut backend) + .expect("default font"); + let peers = vec![install_client(&mut state, 1), install_client(&mut state, 2)]; + Self { + state, + backend, + peers, + seq: 0, + } + } + + fn req_as(&mut self, client: u32, opcode: u8, words: &[u32]) -> Vec { + let body: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + self.raw_as(client, opcode, &body) + } + + fn raw_as(&mut self, client: u32, opcode: u8, body: &[u8]) -> Vec { + self.seq += 1; + process_request( + &mut self.state, + &mut self.backend, + ClientId(client), + SequenceNumber(self.seq), + RequestHeader { + opcode, + data: 0, + length_units: u32::try_from(body.len() / 4 + 1).unwrap(), + }, + body, + None, + ) + .expect("process_request"); + let i = usize::try_from(client - 1).unwrap(); + read_all_available(&mut self.peers[i]) + } + + fn req(&mut self, opcode: u8, words: &[u32]) -> Vec { + self.req_as(1, opcode, words) + } + + fn open_font_as(&mut self, client: u32, fid: u32, name: &str) { + let mut body = fid.to_le_bytes().to_vec(); + body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(name.as_bytes()); + body.resize(body.len().next_multiple_of(4), 0); + assert!(self.raw_as(client, 45, &body).is_empty(), "OpenFont failed"); + } + + fn open_font(&mut self, fid: u32, name: &str) { + self.open_font_as(1, fid, name); + } + + /// CreateGC on the root with GCFont = `font`, or no values at all. + fn create_gc_as(&mut self, client: u32, gc: u32, font: Option) -> Vec { + match font { + Some(font) => self.req_as(client, 55, &[gc, ROOT_WINDOW.0, 0x4000, font]), + None => self.req_as(client, 55, &[gc, ROOT_WINDOW.0, 0]), + } + } + + fn host(&self, fid: u32) -> u32 { + self.state + .resources + .font(ResourceId(fid)) + .expect("open font") + .host_xid + .as_raw() + } + + fn gc_host(&self, gc: u32) -> Option { + self.state + .resources + .resolve_draw_state(ResourceId(gc)) + .and_then(|s| s.font) + .map(|f| f.as_raw()) + } + + fn closes(&self, host: u32) -> usize { + self.backend + .calls() + .iter() + .filter(|c| matches!(c, RecordedCall::CloseFont(x) if *x == host)) + .count() + } + + fn query_font(&mut self, fontable: u32) -> Vec { + self.req(47, &[fontable]) + } +} + +fn assert_bad_font(bytes: &[u8], id: u32, opcode: u8) { + assert!(bytes.len() >= 32, "expected an error, got {bytes:02x?}"); + assert_eq!((bytes[0], bytes[1]), (0, x11::error::BAD_FONT), "BadFont"); + assert_eq!(&bytes[4..8], &id.to_le_bytes(), "bad value"); + assert_eq!(bytes[10], opcode, "major opcode"); +} + +/// A QueryFont reply with its sequence number masked. +fn font_reply(mut bytes: Vec) -> Vec { + assert_eq!( + bytes.first(), + Some(&1), + "a reply, not an error: {bytes:02x?}" + ); + bytes[2..4].fill(0); + bytes +} + +/// `ProcCloseFont` looks the id up as RT_FONT: an unknown id and a GContext +/// are both BadFont with the id as value. +#[test] +fn close_font_of_a_non_font_id_is_bad_font() { + let mut fx = Fx::new(); + assert_bad_font(&fx.req(46, &[0xdead_beef]), 0xdead_beef, 46); + assert!(fx.create_gc_as(1, GC1, None).is_empty()); + assert_bad_font(&fx.req(46, &[GC1]), GC1, 46); +} + +/// The id is freed: closing it again is BadFont, and it can name a new font. +#[test] +fn close_font_frees_the_id() { + let mut fx = Fx::new(); + fx.open_font(F, "fixed"); + assert!(fx.req(46, &[F]).is_empty()); + assert_bad_font(&fx.req(46, &[F]), F, 46); + assert_bad_font(&fx.query_font(F), F, 47); + fx.open_font(F, "cursor"); +} + +/// A GC keeps its font after `CloseFont`: it still draws with it, QueryFont +/// on the GContext still answers, and the font goes with the last GC. +#[test] +fn a_gc_keeps_its_font_after_close_font() { + let mut fx = Fx::new(); + let baseline = fx.state.resources.live_font_count(); + fx.open_font(F, "cursor"); + let host = fx.host(F); + let before = font_reply(fx.query_font(F)); + assert!(fx.create_gc_as(1, GC1, Some(F)).is_empty()); + assert!(fx.req(46, &[F]).is_empty()); + assert_eq!(fx.closes(host), 0, "closed while a GC holds it"); + assert_eq!(fx.gc_host(GC1), Some(host)); + assert_eq!(font_reply(fx.query_font(GC1)), before); + assert!(fx.req(60, &[GC1]).is_empty()); + assert_eq!(fx.closes(host), 1, "the last GC releases the font"); + assert_eq!(fx.state.resources.live_font_count(), baseline); +} + +/// After `CloseFont` + `OpenFont` of another font under the same id, the old +/// GC still has the old font and a new GC gets the new one. +#[test] +fn a_reused_font_id_does_not_retarget_an_old_gc() { + let mut fx = Fx::new(); + fx.open_font(F, "cursor"); + let old_host = fx.host(F); + let old = font_reply(fx.query_font(F)); + assert!(fx.create_gc_as(1, GC1, Some(F)).is_empty()); + assert!(fx.req(46, &[F]).is_empty()); + fx.open_font(F, "fixed"); + let new_host = fx.host(F); + let new = font_reply(fx.query_font(F)); + assert_ne!(old, new, "the two fonts must differ to prove anything"); + assert!(fx.create_gc_as(1, GC2, Some(F)).is_empty()); + assert_eq!(fx.gc_host(GC1), Some(old_host)); + assert_eq!(fx.gc_host(GC2), Some(new_host)); + assert_eq!(font_reply(fx.query_font(GC1)), old); + assert_eq!(font_reply(fx.query_font(GC2)), new); +} + +/// CopyGC takes a reference, ChangeGC and a PolyText font item drop the +/// old one; the font goes when the last of them lets go. +#[test] +fn copy_change_and_poly_text_move_font_references() { + let mut fx = Fx::new(); + fx.open_font(F, "cursor"); + fx.open_font(G, "fixed"); + let host = fx.host(F); + assert!(fx.create_gc_as(1, GC1, Some(F)).is_empty()); + assert!(fx.create_gc_as(1, GC2, None).is_empty()); + assert!(fx.req(57, &[GC1, GC2, 0x4000]).is_empty(), "CopyGC"); + assert!(fx.req(46, &[F]).is_empty()); + assert!(fx.req(56, &[GC1, 0x4000, G]).is_empty(), "ChangeGC"); + assert_eq!(fx.closes(host), 0, "GC2 still holds it"); + assert_eq!(fx.gc_host(GC2), Some(host)); + // PolyText8 on GC2 with one font item, G. + let mut body: Vec = [ROOT_WINDOW.0, GC2] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + body.extend_from_slice(&[0, 0, 10, 0, 255]); + body.extend_from_slice(&G.to_be_bytes()); + body.resize(body.len().next_multiple_of(4), 0); + assert!(fx.raw_as(1, 74, &body).is_empty(), "PolyText8"); + assert_eq!(fx.gc_host(GC2), Some(fx.host(G))); + assert_eq!(fx.closes(host), 1); +} + +/// `ChangeGCXIDs` resolves GCFont before changing anything: BadFont, and +/// CreateGC makes no GC. +#[test] +fn create_and_change_gc_with_an_unknown_font_are_bad_font() { + let mut fx = Fx::new(); + assert_bad_font(&fx.create_gc_as(1, GC1, Some(F)), F, 55); + assert!(fx.state.resources.gc(ResourceId(GC1)).is_none()); + assert!(fx.create_gc_as(1, GC1, None).is_empty()); + // GCForeground | GCFont. + assert_bad_font(&fx.req(56, &[GC1, 0x4004, 0x00ab_cdef, F]), F, 56); + assert_eq!(fx.state.resources.gc_foreground(ResourceId(GC1)), 0); +} + +/// The default font's id can be closed like any other (Xorg's is a plain +/// server-client resource); new GCs still get the font. +#[test] +fn close_font_of_the_default_font_frees_only_its_id() { + let mut fx = Fx::new(); + let host = fx.host(DEFAULT_FONT.0); + assert!(fx.create_gc_as(1, GC1, None).is_empty()); + assert!(fx.req(46, &[DEFAULT_FONT.0]).is_empty()); + assert_bad_font(&fx.query_font(DEFAULT_FONT.0), DEFAULT_FONT.0, 47); + assert_bad_font(&fx.req(46, &[DEFAULT_FONT.0]), DEFAULT_FONT.0, 46); + assert!(fx.create_gc_as(1, GC2, None).is_empty()); + assert_eq!(fx.gc_host(GC1), Some(host)); + assert_eq!(fx.gc_host(GC2), Some(host)); + font_reply(fx.query_font(GC2)); + assert_eq!(fx.closes(host), 0); +} + +/// Disconnects free GCs and font ids in either order; a font another +/// client's GC holds survives its opener, and each font closes once. +#[test] +fn disconnect_releases_fonts_in_either_order() { + for opener_first in [true, false] { + let mut fx = Fx::new(); + let baseline = fx.state.resources.live_font_count(); + fx.open_font_as(1, F, "cursor"); + let host = fx.host(F); + assert!(fx.create_gc_as(1, GC1, Some(F)).is_empty()); + assert!(fx.create_gc_as(2, GC2, Some(F)).is_empty()); + let (first, second) = if opener_first { (1, 2) } else { (2, 1) }; + crate::core_loop::process_disconnect::process_disconnect( + &mut fx.state, + &mut fx.backend, + ClientId(first), + ); + assert_eq!(fx.closes(host), 0, "client {second} still holds it"); + if opener_first { + assert_eq!(fx.gc_host(GC2), Some(host)); + } + crate::core_loop::process_disconnect::process_disconnect( + &mut fx.state, + &mut fx.backend, + ClientId(second), + ); + assert_eq!(fx.closes(host), 1, "opener_first={opener_first}"); + assert_eq!(fx.state.resources.live_font_count(), baseline); + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/gc_pixmap.rs b/crates/yserver-core/src/core_loop/process_request/tests/gc_pixmap.rs new file mode 100644 index 000000000..6bb97f81f --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/gc_pixmap.rs @@ -0,0 +1,1076 @@ +use super::*; + +#[test] +fn poly_fill_rectangle_unknown_gc_returns_bad_gc() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let body = poly_fill_rectangle_body(ROOT_WINDOW.0, 0xdead_beef); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 70, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + + let bytes = read_all_available(&mut peer); + assert!( + bytes.len() >= 32, + "expected 32-byte error reply, got {} bytes: {:02x?}", + bytes.len(), + bytes + ); + let buf = &bytes[..32]; + assert_eq!(buf[1], x11::error::BAD_GC); + assert_eq!(buf[10], 70); +} + +/// Decode a 32-byte X11 error at the wire offsets fixed by the core +/// protocol encoding (`Errors`): 0 = 0, 1 = code, 2..4 = sequence, +/// 4..8 = bad resource id / value, 8..10 = minor opcode, 10 = major +/// opcode. Asserted as raw bytes on purpose — running the reply back +/// through our own decoder would pass even if encoder and decoder +/// were wrong together. +fn assert_x11_error_bytes( + bytes: &[u8], + code: u8, + bad_value: u32, + minor: u16, + major: u8, + sequence: u16, + what: &str, +) { + assert_eq!( + bytes.len(), + 32, + "{what}: expected exactly one 32-byte error, got {:02x?}", + bytes + ); + assert_eq!(bytes[0], 0, "{what}: byte 0 marks a packet as an error"); + assert_eq!(bytes[1], code, "{what}: error code"); + assert_eq!( + u16::from_le_bytes([bytes[2], bytes[3]]), + sequence, + "{what}: sequence number" + ); + assert_eq!( + u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), + bad_value, + "{what}: bad resource id must be the XID exactly as sent" + ); + assert_eq!( + u16::from_le_bytes([bytes[8], bytes[9]]), + minor, + "{what}: minor opcode" + ); + assert_eq!(bytes[10], major, "{what}: major opcode"); +} + +/// Drive one four-byte resource-release request (FreePixmap / FreeGC / +/// FreeCursor: `xResourceReq`, 2 units total) through the real +/// dispatch table and return whatever the client was sent. +fn run_free_resource_request( + state: &mut ServerState, + peer: &mut UnixStream, + opcode: u8, + xid: u32, + sequence: u16, +) -> Vec { + let mut backend = RecordingBackend::new(); + let body = xid.to_le_bytes().to_vec(); + process_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode, + data: 0, + length_units: 2, + }, + &body, + None, + ) + .expect("process_request"); + read_all_available(peer) +} + +/// #143. picom's `x_prepare_for_sleep` (picom `src/x.c:1194`) fires a +/// deliberately invalid `FreePixmap(drawable=None)` as a sync barrier +/// and *expects* `BadPixmap`: XCB only completes a checked **void** +/// request once it reads a packet with a higher sequence number, and +/// for a void request that packet is the error. Xorg answers every one +/// of these (measured: 419 requests -> 419 `BadPixmap`); we answered +/// none of 538, so picom's checked `ChangeWindowAttributes` batch never +/// completed and its window import stalled ~10s instead of ~120ms. +#[test] +fn free_pixmap_none_returns_bad_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let bytes = run_free_resource_request(&mut state, &mut peer, 54, 0, 0x0067); + + assert_x11_error_bytes( + &bytes, + x11::error::BAD_PIXMAP, + 0, + 0, + 54, + 0x0067, + "FreePixmap(None)", + ); +} + +#[test] +fn free_pixmap_unknown_xid_returns_bad_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let bytes = run_free_resource_request(&mut state, &mut peer, 54, 0x00de_ad00, 7); + + assert_x11_error_bytes( + &bytes, + x11::error::BAD_PIXMAP, + 0x00de_ad00, + 0, + 54, + 7, + "FreePixmap(unknown)", + ); +} + +/// The error path must not swallow the ordinary one: a pixmap the +/// server knows is freed silently, as Xorg's `Success` return does. +#[test] +fn free_pixmap_known_xid_reports_no_error() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(0x3100), + drawable: ROOT_WINDOW, + width: 8, + height: 8, + }, + ); + + let bytes = run_free_resource_request(&mut state, &mut peer, 54, 0x3100, 8); + + assert!( + bytes.is_empty(), + "FreePixmap(known) must be silent, got {bytes:02x?}" + ); + assert!(state.resources.pixmap(ResourceId(0x3100)).is_none()); +} + +/// Xorg `ProcFreeGC` -> `dixLookupGC` -> `X11_RESTYPE_GC.errorValue` +/// = `BadGC` (`../xserver/dix/resource.c:454`). +#[test] +fn free_gc_none_returns_bad_gc() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let bytes = run_free_resource_request(&mut state, &mut peer, 60, 0, 0x0068); + + assert_x11_error_bytes(&bytes, x11::error::BAD_GC, 0, 0, 60, 0x0068, "FreeGC(None)"); +} + +#[test] +fn free_gc_unknown_xid_returns_bad_gc() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let bytes = run_free_resource_request(&mut state, &mut peer, 60, 0x00be_ef00, 9); + + assert_x11_error_bytes( + &bytes, + x11::error::BAD_GC, + 0x00be_ef00, + 0, + 60, + 9, + "FreeGC(unknown)", + ); +} + +#[test] +fn free_gc_known_xid_reports_no_error() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state + .resources + .seed_gc_for_test(ClientId(1), ResourceId(0x2100)); + + let bytes = run_free_resource_request(&mut state, &mut peer, 60, 0x2100, 10); + + assert!( + bytes.is_empty(), + "FreeGC(known) must be silent, got {bytes:02x?}" + ); + assert!(state.resources.gc(ResourceId(0x2100)).is_none()); +} + +/// Xorg `ProcFreeCursor` -> `X11_RESTYPE_CURSOR.errorValue` = +/// `BadCursor` (`../xserver/dix/resource.c:466`). +#[test] +fn free_cursor_none_returns_bad_cursor() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let bytes = run_free_resource_request(&mut state, &mut peer, 95, 0, 0x0069); + + assert_x11_error_bytes( + &bytes, + x11::error::BAD_CURSOR, + 0, + 0, + 95, + 0x0069, + "FreeCursor(None)", + ); +} + +#[test] +fn free_cursor_unknown_xid_returns_bad_cursor() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let bytes = run_free_resource_request(&mut state, &mut peer, 95, 0x00c0_ff00, 11); + + assert_x11_error_bytes( + &bytes, + x11::error::BAD_CURSOR, + 0x00c0_ff00, + 0, + 95, + 11, + "FreeCursor(unknown)", + ); +} + +#[test] +fn free_cursor_known_xid_reports_no_error() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state + .resources + .create_cursor(ClientId(1), ResourceId(0x4100)); + + let bytes = run_free_resource_request(&mut state, &mut peer, 95, 0x4100, 12); + + assert!( + bytes.is_empty(), + "FreeCursor(known) must be silent, got {bytes:02x?}" + ); + assert!(!state.resources.cursor_exists(ResourceId(0x4100))); +} + +#[test] +fn free_pixmap_retains_host_pixmap_while_gc_clip_mask_still_references_it() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 1, + pixmap: ResourceId(0x3000), + drawable: ROOT_WINDOW, + width: 8, + height: 8, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(0x3000), + crate::backend::PixmapHandle::from_raw(0xcafe).unwrap(), + )); + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(0x2000), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: Some(Some(ResourceId(0x3000))), + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(0x3000), + ) + .expect("free pixmap"); + + let calls = backend.calls.lock().expect("calls"); + assert!( + !calls + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(0xcafe))), + "host pixmap must stay alive while retained by GC clip mask" + ); +} + +/// #196 fixture: client 1 owns GC 0x2100 and depth-24 tile / depth-1 +/// stipple / depth-1 clip pixmaps, host xids 0xd001..=0xd003. +fn gc_with_freed_pixmaps(state: &mut ServerState, mask: u32, values: &[u32]) { + for (i, depth) in [24u8, 1, 1].into_iter().enumerate() { + let pixmap = ResourceId(0x3100 + i as u32); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth, + pixmap, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + pixmap, + crate::backend::PixmapHandle::from_raw(0xd001 + i as u32).unwrap(), + )); + } + create_plain_gc(state, ResourceId(0x2100)); + change_gc(state, &mut RecordingBackend::new(), 0x2100, mask, values); +} + +fn create_plain_gc(state: &mut ServerState, gc: ResourceId) { + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc, + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); +} + +fn change_gc( + state: &mut ServerState, + backend: &mut RecordingBackend, + gc: u32, + mask: u32, + values: &[u32], +) { + let mut body = gc.to_le_bytes().to_vec(); + body.extend(mask.to_le_bytes()); + for v in values { + body.extend(v.to_le_bytes()); + } + handle_change_gc( + state, + backend, + None, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 56, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + ) + .expect("change gc"); +} + +fn free_pixmaps(state: &mut ServerState, backend: &mut RecordingBackend, ids: &[u32]) { + for &id in ids { + handle_free_pixmap( + state, + backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(id), + ) + .expect("free pixmap"); + } +} + +const GC_TILE: u32 = 0x0000_0400; +const GC_STIPPLE: u32 = 0x0000_0800; +const GC_CLIP_MASK: u32 = 0x0008_0000; + +/// #196: a GC's tile / stipple / clip-mask ref dies when ChangeGC replaces +/// it (Xorg `dix/gc.c:256`/`:273` DestroyPixmap the old tile / stipple; +/// `mi/migc.c:68` drops a clip mask as soon as it is a region). Once the +/// client has freed the pixmap, that was the last reference: the host +/// storage must go, exactly once. It leaked for the session. +#[test] +fn change_gc_releases_a_freed_pixmap_it_replaces() { + for (mask, host) in [ + (GC_TILE, 0xd001), + (GC_STIPPLE, 0xd002), + (GC_CLIP_MASK, 0xd003), + ] { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let pixmap = 0x3100 + (host - 0xd001); + gc_with_freed_pixmaps(&mut state, mask, &[pixmap]); + free_pixmaps(&mut state, &mut backend, &[pixmap]); + assert_eq!( + host_frees(&backend), + Vec::::new(), + "mask {mask:#x}: GC still holds it" + ); + // Tile can't be None: replace it with another pixmap; the rest clear. + let replacement = if mask == GC_TILE { 0x3102 } else { 0 }; + change_gc(&mut state, &mut backend, 0x2100, mask, &[replacement]); + assert_eq!(host_frees(&backend), vec![host], "mask {mask:#x}"); + change_gc(&mut state, &mut backend, 0x2100, mask, &[replacement]); + assert_eq!( + host_frees(&backend), + vec![host], + "mask {mask:#x}: exactly once" + ); + } +} + +/// The positive control: a displaced pixmap the client still owns stays. +#[test] +fn change_gc_keeps_a_replaced_pixmap_the_client_still_owns() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + gc_with_freed_pixmaps(&mut state, GC_TILE | GC_STIPPLE, &[0x3100, 0x3101]); + change_gc( + &mut state, + &mut backend, + 0x2100, + GC_TILE | GC_STIPPLE, + &[0x3102, 0x3102], + ); + assert_eq!(host_frees(&backend), Vec::::new()); + free_pixmaps(&mut state, &mut backend, &[0x3100, 0x3101]); + assert_eq!( + host_frees(&backend), + vec![0xd001, 0xd002], + "unreferenced: freed at FreePixmap" + ); +} + +#[test] +fn set_clip_rectangles_releases_a_freed_clip_mask() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + gc_with_freed_pixmaps(&mut state, GC_CLIP_MASK, &[0x3102]); + free_pixmaps(&mut state, &mut backend, &[0x3102]); + let mut body = 0x2100u32.to_le_bytes().to_vec(); + body.extend([0u8; 4]); // clip x/y origin + body.extend([0u8, 0, 0, 0, 8, 0, 8, 0]); // one rectangle + handle_set_clip_rectangles( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 59, + data: 0, + length_units: 5, + }, + &body, + ) + .expect("set clip rectangles"); + assert_eq!(host_frees(&backend), vec![0xd003]); +} + +/// XFixesSetGCClipRegion replaces the clip mask like SetClipRectangles +/// (`xfixes/region.c` `ProcXFixesSetGCClipRegion` -> `ChangeClip`), for +/// region None and for a real region alike: a clip mask the client freed +/// is released then, exactly once. +#[test] +fn xfixes_set_gc_clip_region_releases_a_freed_clip_mask() { + use yserver_protocol::x11::xfixes as x11xfixes; + for region in [0u32, 0x4100] { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + gc_with_freed_pixmaps(&mut state, GC_CLIP_MASK, &[0x3102]); + free_pixmaps(&mut state, &mut backend, &[0x3102]); + assert_eq!(host_frees(&backend), Vec::::new()); + let mut xfixes = |state: &mut ServerState, minor: u8, body: Vec| { + let header = RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }; + handle_xfixes_request( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("XFIXES request"); + }; + if region != 0 { + let mut body = region.to_le_bytes().to_vec(); + body.extend([0u8, 0, 0, 0, 8, 0, 8, 0]); + xfixes(&mut state, x11xfixes::CREATE_REGION, body); + } + let mut body = 0x2100u32.to_le_bytes().to_vec(); + body.extend(region.to_le_bytes()); + body.extend([0u8; 4]); // clip x/y origin + xfixes(&mut state, x11xfixes::SET_GC_CLIP_REGION, body.clone()); + xfixes(&mut state, x11xfixes::SET_GC_CLIP_REGION, body); + assert_eq!( + host_frees(&backend), + vec![0xd003], + "region {region:#x}: released once" + ); + } +} + +/// Xorg `CopyGC` drops dst's old tile / stipple (`dix/gc.c:673`/`:685`); +/// one the source GC also holds survives. +#[test] +fn copy_gc_releases_freed_pixmaps_it_overwrites() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + gc_with_freed_pixmaps(&mut state, GC_TILE | GC_STIPPLE, &[0x3100, 0x3101]); + create_plain_gc(&mut state, ResourceId(0x2101)); + change_gc( + &mut state, + &mut backend, + 0x2101, + GC_TILE | GC_STIPPLE, + &[0x3100, 0x3102], + ); + free_pixmaps(&mut state, &mut backend, &[0x3100, 0x3101, 0x3102]); + assert_eq!( + host_frees(&backend), + Vec::::new(), + "both GCs hold them" + ); + let mut body = 0x2101u32.to_le_bytes().to_vec(); + body.extend(0x2100u32.to_le_bytes()); + body.extend((GC_TILE | GC_STIPPLE).to_le_bytes()); + handle_copy_gc( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 57, + minor: 0, + }, + &body, + ) + .expect("copy gc"); + // 0x2100 now holds tile 0xd001 + stipple 0xd003; its old stipple 0xd002 went. + assert_eq!(host_frees(&backend), vec![0xd002]); +} + +/// Xorg `FreeGC` drops the tile / stipple / clip (`dix/gc.c:776-781`). +#[test] +fn free_gc_releases_the_freed_pixmaps_it_held() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + gc_with_freed_pixmaps( + &mut state, + GC_TILE | GC_STIPPLE | GC_CLIP_MASK, + &[0x3100, 0x3101, 0x3102], + ); + free_pixmaps(&mut state, &mut backend, &[0x3100, 0x3101]); + handle_free_gc( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 60, + minor: 0, + }, + &0x2100u32.to_le_bytes(), + ) + .expect("free gc"); + assert_eq!( + host_frees(&backend), + vec![0xd001, 0xd002], + "0x3102 is still the client's" + ); +} + +/// #133: `FreePixmap` has to respect a window's BORDER reference the same +/// way it respects a background one. `XCreatePixmap` → +/// `XSetWindowBorderPixmap` → `XFreePixmap` is ordinary client code, and +/// X11 keeps the storage alive because the window still names it (Xorg +/// refcounts `pWin->border.pixmap`). `handle_free_pixmap` consulted only +/// the background and GC references, so it freed the host handle +/// underneath a ring that was still sampling it — found by auditing this +/// case against `change_window_attributes`'s release path, which does gate +/// on all three. +#[test] +fn free_pixmap_retains_host_pixmap_while_a_window_border_still_references_it() { + const HOST_TILE: u32 = 0x9999_0007; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0011); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + let tile = ResourceId(0x0080_1307); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: tile, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + depth: 24, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + tile, + crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"), + )); + + run_border_request( + &mut state, + 2, + 0, + &border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]), + ); + assert_no_error(&read_all_available(&mut peer), "CWA border-pixmap"); + // Not vacuous: the reference must actually be recorded, or the + // retention below would hold for the wrong reason. + assert!( + state.resources.host_xid_referenced_by_window_border( + crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero") + ), + "the window must hold the tile as its border before FreePixmap" + ); + + let mut backend = RecordingBackend::new(); + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(tile.0), + ) + .expect("free pixmap"); + + assert!( + !backend + .calls() + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))), + "host pixmap must stay alive while a window still borders with it" + ); +} + +/// The cross-reference case the CWA release path calls out: nothing stops +/// a client naming one pixmap as a background on window A and a border on +/// window B. The order here is deliberate — the background reference is +/// dropped FIRST, so the `FreePixmap` in the middle is suppressed by the +/// BORDER check alone and the step is not vacuous. The final release is +/// the positive control: once nothing holds the tile the host handle must +/// actually be freed, so a test that can never observe a free would fail. +#[test] +fn a_host_pixmap_shared_as_background_and_border_frees_only_when_both_let_go() { + const HOST_TILE: u32 = 0x9999_0008; + let host = crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"); + const CWA_BACK_PIXMAP: u32 = 0x0001; + let freed = |calls: &[RecordedCall]| { + calls + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))) + }; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let bg_win = ResourceId(0x0080_0021); + let border_win = ResourceId(0x0080_0022); + seed_window(&mut state, bg_win, ROOT_WINDOW, 10, 10); + seed_window(&mut state, border_win, ROOT_WINDOW, 10, 10); + let tile = ResourceId(0x0080_1308); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: tile, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + depth: 24, + }, + ); + assert!(state.resources.set_pixmap_host_xid(tile, host)); + + run_border_request( + &mut state, + 2, + 0, + &border_cwa_body(bg_win.0, CWA_BACK_PIXMAP, &[tile.0]), + ); + run_border_request( + &mut state, + 2, + 0, + &border_cwa_body(border_win.0, CWA_BORDER_PIXMAP, &[tile.0]), + ); + assert_no_error(&read_all_available(&mut peer), "CWA shared tile"); + assert!( + state.resources.host_xid_referenced_by_window_bg(host), + "window A must hold the tile as its background" + ); + assert!( + state.resources.host_xid_referenced_by_window_border(host), + "window B must hold the tile as its border" + ); + + // 1. Drop A's background. B's border and the client's own ownership + // both still hold the tile. + let calls = run_border_request_recording( + &mut state, + 2, + 0, + &border_cwa_body(bg_win.0, CWA_BACK_PIXMAP, &[0]), + ); + assert!( + !state.resources.host_xid_referenced_by_window_bg(host), + "window A must no longer hold the tile as its background" + ); + assert!( + !freed(&calls), + "replacing the background must not free storage the other window's \ + border still samples" + ); + + // 2. The client drops the resource id. Only B's border holds the tile + // now, so this step exercises the border check on its own. + let mut backend = RecordingBackend::new(); + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(3), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(tile.0), + ) + .expect("free pixmap"); + assert!( + !freed(&backend.calls()), + "FreePixmap must respect a border-only reference" + ); + + // 3. Positive control: B swaps to a solid border, nothing holds the + // tile and the client no longer owns it, so it must be released. + let calls = run_border_request_recording( + &mut state, + 2, + 0, + &border_cwa_body(border_win.0, CWA_BORDER_PIXEL, &[0x0000_00ff]), + ); + assert!( + freed(&calls), + "the fully orphaned host tile must be released, or this test could \ + never observe a free at all" + ); +} + +/// #133: the mirror image of the retention above. A tile kept alive past +/// its `FreePixmap` by a window's border must be RELEASED when that window +/// dies — otherwise nothing is left to notice it: no resource owns it and +/// no window references it. `destroy_window_subtree` collected only +/// background pixmaps, so this leaked the host storage for the rest of the +/// session. +#[test] +fn destroying_a_window_releases_the_border_tile_it_was_keeping_alive() { + const HOST_TILE: u32 = 0x9999_0009; + let host = crate::backend::PixmapHandle::from_raw(HOST_TILE).expect("non-zero"); + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0031); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + let tile = ResourceId(0x0080_1309); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: tile, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + depth: 24, + }, + ); + assert!(state.resources.set_pixmap_host_xid(tile, host)); + run_border_request( + &mut state, + 2, + 0, + &border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]), + ); + assert_no_error(&read_all_available(&mut peer), "CWA border-pixmap"); + + // The client drops the id; the border reference retains the storage. + let mut backend = RecordingBackend::new(); + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(tile.0), + ) + .expect("free pixmap"); + assert!( + !backend + .calls() + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))), + "retained while the border holds it" + ); + assert!( + state.resources.host_xid_still_referenced(host), + "the border must be the only thing keeping it alive now" + ); + + // Destroying the window removes that last reference, so the host + // handle has to go with it. + let mut backend = RecordingBackend::new(); + destroy_window_subtree(&mut state, &mut backend, None, win).expect("destroy"); + assert!( + !state.resources.host_xid_still_referenced(host), + "nothing may reference the tile after the window is destroyed" + ); + assert!( + backend + .calls() + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(HOST_TILE))), + "destroying the window must release the border tile it was keeping alive" + ); +} + +/// #133 minor: one request replacing BOTH attributes, where both named the +/// same tile, hands the same host handle back twice. Freeing it twice is +/// inert on KMS — the store entry is gone by the second call — but it is a +/// broken backend contract, and a recording or host-X11 backend sees the +/// duplicate. +#[test] +fn replacing_a_shared_background_and_border_frees_the_host_tile_once() { + const HOST_OLD: u32 = 0x9999_000a; + const HOST_NEW: u32 = 0x9999_000b; + const CWA_BACK_PIXMAP: u32 = 0x0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0041); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + + let make_tile = |state: &mut ServerState, id: u32, host: u32| { + let pix = ResourceId(id); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: pix, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + depth: 24, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + pix, + crate::backend::PixmapHandle::from_raw(host).expect("non-zero") + )); + pix + }; + let old = make_tile(&mut state, 0x0080_1310, HOST_OLD); + let new = make_tile(&mut state, 0x0080_1311, HOST_NEW); + + // One tile as BOTH the background and the border. + run_border_request( + &mut state, + 2, + 0, + &border_cwa_body(win.0, CWA_BACK_PIXMAP | CWA_BORDER_PIXMAP, &[old.0, old.0]), + ); + assert_no_error(&read_all_available(&mut peer), "CWA shared tile"); + + // The client drops the id, so only the two attributes hold it and the + // replacement below fully orphans it. + let mut backend = RecordingBackend::new(); + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(old.0), + ) + .expect("free pixmap"); + + // Replace both in ONE request: `released.background` and + // `released.border` are the same handle. + let calls = run_border_request_recording( + &mut state, + 2, + 0, + &border_cwa_body(win.0, CWA_BACK_PIXMAP | CWA_BORDER_PIXMAP, &[new.0, new.0]), + ); + let frees = calls + .iter() + .filter(|call| matches!(call, RecordedCall::FreePixmap(HOST_OLD))) + .count(); + assert_eq!( + frees, 1, + "the shared host tile must be freed exactly once, got {frees}" + ); +} + +#[test] +fn free_pixmap_retains_host_pixmap_while_gc_tile_still_references_it() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 1, + pixmap: ResourceId(0x3001), + drawable: ROOT_WINDOW, + width: 8, + height: 8, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(0x3001), + crate::backend::PixmapHandle::from_raw(0xbeef).unwrap(), + )); + state.resources.create_gc( + ClientId(1), + CreateGcRequest { + gc: ResourceId(0x2001), + drawable: ROOT_WINDOW, + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: Some(FillStyle::Tiled.protocol_value()), + fill_rule: None, + tile: Some(ResourceId(0x3001)), + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(0x3001), + ) + .expect("free pixmap"); + + let calls = backend.calls.lock().expect("calls"); + assert!( + !calls + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(0xbeef))), + "host pixmap must stay alive while retained by GC tile" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/glx.rs b/crates/yserver-core/src/core_loop/process_request/tests/glx.rs new file mode 100644 index 000000000..cbfcc6c03 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/glx.rs @@ -0,0 +1,2625 @@ +use super::*; +use crate::{ + access::{ + AccessContext, AccessMode, AccessPolicy, Decision, DenyError, RequestOpcodes, ResourceKind, + ResourceTarget, + }, + core_loop::process_request::glx::{ + drawable_attributes_for, glx_extension_string, glx_fbconfig_depth, glx_fbconfig_visual, + glx_visual_fbconfig, synthesise_glx_fb_configs, synthesise_glx_visual_configs, + }, +}; + +// #96: each visual-backed GLX FBConfig must advertise GLX_PBUFFER_BIT plus +// the three GLX_MAX_PBUFFER_* caps, or Chromium/ANGLE can't allocate its +// offscreen pbuffer surface and falls back to software (no WebGL/Maps 3D). +// The #152 native-pixmap config is deliberately pixmap-only. Property +// counts must stay uniform across configs (GetFBConfigs encodes a single +// num_properties for all of them). +#[test] +fn glx_fb_configs_advertise_pbuffer() { + use yserver_protocol::x11::glx as g; + for tfp in [false, true] { + let configs = synthesise_glx_fb_configs(tfp); + assert!(!configs.is_empty()); + let prop_count = configs[0].len(); + for config in &configs { + assert_eq!(config.len(), prop_count, "non-uniform property count"); + let get = |attr: u32| config.iter().find(|(a, _)| *a == attr).map(|(_, v)| *v); + let drawable = get(g::GLX_DRAWABLE_TYPE).expect("DRAWABLE_TYPE present"); + if drawable == g::GLX_PIXMAP_BIT { + assert_eq!(get(g::GLX_VISUAL_ID), Some(0)); + assert_eq!(get(g::GLX_X_RENDERABLE), Some(0)); + continue; + } + assert_ne!( + drawable & g::GLX_PBUFFER_BIT, + 0, + "config must advertise GLX_PBUFFER_BIT (tfp={tfp})" + ); + let max_w = get(g::GLX_MAX_PBUFFER_WIDTH).expect("MAX_PBUFFER_WIDTH present"); + let max_h = get(g::GLX_MAX_PBUFFER_HEIGHT).expect("MAX_PBUFFER_HEIGHT present"); + assert!(max_w > 0 && max_h > 0, "pbuffer caps must be non-zero"); + assert!(get(g::GLX_MAX_PBUFFER_PIXELS).is_some()); + } + } +} + +#[test] +fn glx_visuals_have_one_unambiguous_double_buffered_config() { + use yserver_protocol::x11::glx as g; + + let visuals = synthesise_glx_visual_configs(); + assert_eq!(visuals.len(), 3); + assert!(visuals.iter().all(|visual| visual.double_buffer)); + + let configs = synthesise_glx_fb_configs(false); + assert_eq!(configs.len(), 4); + let mut visual_ids = HashSet::new(); + for config in configs { + let get = |attr: u32| config.iter().find(|(a, _)| *a == attr).map(|(_, v)| *v); + let visual_id = get(g::GLX_VISUAL_ID).expect("VISUAL_ID present"); + if visual_id == 0 { + assert_eq!(get(g::GLX_DRAWABLE_TYPE), Some(g::GLX_PIXMAP_BIT)); + assert_eq!(get(g::GLX_DOUBLEBUFFER), Some(0)); + } else { + assert!( + visual_ids.insert(visual_id), + "duplicate visual 0x{visual_id:x}" + ); + assert_eq!(get(g::GLX_DOUBLEBUFFER), Some(1)); + } + } + assert_eq!(visual_ids.len(), 3); +} + +// glmark2 2023.01 defaults to stencil=0 and rejects any positive +// stencil count while choosing its default FBConfig. Keep that config on +// a distinct X visual: reusing ROOT_VISUAL would recreate the config / +// visual ambiguity that made Mesa allocate fake front buffers (#96). +#[test] +fn glmark_can_choose_an_opaque_zero_stencil_window_config() { + use yserver_protocol::x11::glx as g; + + let config = synthesise_glx_fb_configs(false) + .into_iter() + .find(|config| { + let get = |attribute| { + config + .iter() + .find(|(key, _)| *key == attribute) + .map(|(_, value)| *value) + }; + get(g::GLX_DRAWABLE_TYPE).is_some_and(|value| value & g::GLX_WINDOW_BIT != 0) + && get(g::GLX_DOUBLEBUFFER) == Some(1) + && get(g::GLX_STENCIL_SIZE) == Some(0) + }) + .expect("a double-buffered stencil-0 window FBConfig for glmark2"); + let get = |attribute| { + config + .iter() + .find(|(key, _)| *key == attribute) + .map(|(_, value)| *value) + }; + assert_ne!(get(g::GLX_VISUAL_ID), Some(crate::resources::ROOT_VISUAL.0)); + assert_ne!(get(g::GLX_VISUAL_ID), Some(crate::resources::ARGB_VISUAL.0)); + assert_eq!( + get(g::GLX_VISUAL_ID), + Some(crate::resources::GLMARK_VISUAL.0) + ); +} + +// QtWebEngine's GLXHelper chooses a native-pixmap config with this exact +// attribute set before it imports a DMA-BUF through DRI3. In particular, +// it requires GLX_DOUBLEBUFFER=false. It must not reuse either real X +// visual: doing so recreates #96, where Mesa paired a single-buffered +// context with a double-buffered window and allocated a fake front buffer. +#[test] +fn qtwebengine_can_choose_an_isolated_single_buffered_pixmap_config() { + use yserver_protocol::x11::glx as g; + + let configs = synthesise_glx_fb_configs(true); + let config = configs + .iter() + .find(|config| { + let get = |attr: u32| { + config + .iter() + .find(|(key, _)| *key == attr) + .map(|(_, value)| *value) + }; + get(g::GLX_RED_SIZE).is_some_and(|value| value >= 8) + && get(g::GLX_GREEN_SIZE).is_some_and(|value| value >= 8) + && get(g::GLX_BLUE_SIZE).is_some_and(|value| value >= 8) + && get(g::GLX_ALPHA_SIZE).is_some_and(|value| value >= 8) + && get(g::GLX_BUFFER_SIZE).is_some_and(|value| value >= 32) + && get(g::GLX_BIND_TO_TEXTURE_RGBA_EXT) == Some(1) + && get(g::GLX_DRAWABLE_TYPE).is_some_and(|value| value & g::GLX_PIXMAP_BIT != 0) + && get(g::GLX_BIND_TO_TEXTURE_TARGETS_EXT) + .is_some_and(|value| value & g::GLX_TEXTURE_2D_BIT_EXT != 0) + && get(g::GLX_DOUBLEBUFFER) == Some(0) + }) + .expect("a QtWebEngine native-pixmap FBConfig"); + let get = |attr: u32| { + config + .iter() + .find(|(key, _)| *key == attr) + .map(|(_, value)| *value) + }; + assert_eq!(get(g::GLX_VISUAL_ID), Some(0)); + assert_eq!(get(g::GLX_DRAWABLE_TYPE), Some(g::GLX_PIXMAP_BIT)); + assert_eq!(get(g::GLX_X_RENDERABLE), Some(0)); +} + +// #96: pbuffer GetGeometry must report the fbconfig's true depth so Mesa's +// loader_dri3 backs it correctly. fbconfig 0x101 maps to ROOT_VISUAL +// (depth 24), while 0x103 maps to ARGB_VISUAL (depth 32). +#[test] +fn glx_fbconfig_depth_tracks_visual() { + assert_eq!(glx_fbconfig_depth(0x101), 24); + assert_eq!(glx_fbconfig_depth(0x103), 32); + // Unknown fbconfig falls back to the depth-24 default. + assert_eq!(glx_fbconfig_depth(0xDEAD), 24); +} + +/// Every GLX visual `GetVisualConfigs` advertises has an FBConfig carrying +/// that visual (Xorg's `pGlxScreen->visuals[i]` *is* a config), and the +/// pairing round-trips. FBConfig IDs and the visual-less FBConfig are +/// not GLX visuals. +#[test] +fn glx_visual_fbconfig_pairs_every_advertised_visual() { + for visual in synthesise_glx_visual_configs() { + let fbconfig = glx_visual_fbconfig(visual.visual_id) + .unwrap_or_else(|| panic!("visual 0x{:x} has no FBConfig", visual.visual_id)); + assert_eq!(glx_fbconfig_visual(fbconfig), visual.visual_id); + } + assert_eq!(glx_visual_fbconfig(0x101), None); + assert_eq!(glx_visual_fbconfig(0x104), None); + assert_eq!(glx_fbconfig_visual(0x104), 0); + assert_eq!(glx_fbconfig_visual(0xDEAD), 0); +} + +#[test] +fn glx_extension_string_includes_tfp_only_when_capable() { + let with = glx_extension_string(true); + let without = glx_extension_string(false); + assert!(with.contains("GLX_EXT_texture_from_pixmap")); + assert!(!without.contains("GLX_EXT_texture_from_pixmap")); + // Base extensions always present. + assert!(with.contains("GLX_ARB_create_context")); + assert!(without.contains("GLX_ARB_create_context")); +} + +/// Xorg writes a space after **every** enabled extension +/// (`glx/extension_string.c:144-145`), so its GLX extension string +/// always ends with `' '` before the NUL. yserver's did not, and +/// `libGLX_nvidia` responds by losing the final token *and* dropping +/// `GLX_ARB_get_proc_address` from the client extension string — which +/// makes libepoxy abort and takes `kwin_x11` down with SIGABRT. +/// +/// Measured 2026-08-07; see +/// `docs/superpowers/specs/2026-08-07-glx-extension-string-terminator-design.md` +/// and `~/yserver-glx-logs/2026-08-07-terminator-evidence/`. +#[test] +fn glx_extension_string_is_space_terminated() { + for tfp_supported in [false, true] { + let s = glx_extension_string(tfp_supported); + assert!( + s.ends_with(' '), + "GLX extension string must end with Xorg's space terminator; \ + tfp_supported={tfp_supported} produced {s:?}" + ); + } +} + +/// Companion to `glx_extension_string_is_space_terminated`: the +/// terminator must not come at the cost of the token list. Green both +/// before and after that fix — this is a guard, not a regression test. +#[test] +fn glx_extension_string_tokens_match_advertised_constants() { + use yserver_protocol::x11::glx as g; + for tfp_supported in [false, true] { + let s = glx_extension_string(tfp_supported); + assert!( + !s.starts_with(' '), + "no leading separator; tfp_supported={tfp_supported} produced {s:?}" + ); + assert!( + !s.contains(" "), + "no doubled separator; tfp_supported={tfp_supported} produced {s:?}" + ); + let mut expected: Vec<&str> = g::SERVER_EXTENSIONS.split_whitespace().collect(); + expected.push(g::SGIX_FBCONFIG_EXTENSION); + if tfp_supported { + expected.push(g::TFP_EXTENSION); + } + let tokens: Vec<&str> = s.split_whitespace().collect(); + assert_eq!( + tokens, expected, + "token list must be the advertised constants, in order; \ + tfp_supported={tfp_supported}" + ); + } +} + +#[test] +fn fbconfigs_emit_bind_to_texture_pairs_in_xorg_order() { + use yserver_protocol::x11::glx as g; + let configs = synthesise_glx_fb_configs(true); + // All configs same length (wire encoder requirement). + let len = configs[0].len(); + assert!(configs.iter().all(|c| c.len() == len)); + + for c in &configs { + // Find the bind-to-texture block; it must appear as a contiguous run in this order. + let idx = c + .iter() + .position(|(k, _)| *k == g::GLX_BIND_TO_TEXTURE_RGB_EXT) + .expect("RGB present"); + let order = [ + g::GLX_BIND_TO_TEXTURE_RGB_EXT, + g::GLX_BIND_TO_TEXTURE_RGBA_EXT, + g::GLX_BIND_TO_MIPMAP_TEXTURE_EXT, + g::GLX_BIND_TO_TEXTURE_TARGETS_EXT, + g::GLX_Y_INVERTED_EXT, + ]; + for (i, key) in order.iter().enumerate() { + assert_eq!(c[idx + i].0, *key, "wrong order at offset {i}"); + } + // Values: + assert_eq!(c[idx + 2].1, 0, "MIPMAP must be 0/false"); + assert_eq!( + c[idx + 3].1, + g::GLX_DONT_CARE, + "BIND_TO_TEXTURE_TARGETS is GLX_DONT_CARE so it matches any \ + client-driver target bitmask (driConfigEqual)" + ); + assert_eq!( + c[idx + 4].1, + g::GLX_DONT_CARE, + "Y_INVERTED in FBConfig is GLX_DONT_CARE" + ); + } + + // Both depths advertise RGB=true RGBA=true, matching radeonsi's + // TFP configs (HW-verified). RGBA=true on depth-24 is correct: + // opaque windows sample as α=1. + let depth24 = configs + .iter() + .find(|c| c.iter().any(|(k, v)| *k == g::GLX_VISUAL_ID && *v == 0x102)) + .unwrap(); + let d24 = depth24 + .iter() + .position(|(k, _)| *k == g::GLX_BIND_TO_TEXTURE_RGB_EXT) + .unwrap(); + assert_eq!(depth24[d24].1, 1); // RGB true + assert_eq!(depth24[d24 + 1].1, 1); // RGBA true on depth-24 (match radeonsi) + + let depth32 = configs + .iter() + .find(|c| c.iter().any(|(k, v)| *k == g::GLX_VISUAL_ID && *v == 0x103)) + .unwrap(); + let d32 = depth32 + .iter() + .position(|(k, _)| *k == g::GLX_BIND_TO_TEXTURE_RGB_EXT) + .unwrap(); + assert_eq!(depth32[d32 + 1].1, 1); // RGBA true on depth-32 +} + +#[test] +fn fbconfigs_omit_bind_to_texture_when_tfp_unsupported() { + use yserver_protocol::x11::glx as g; + let configs = synthesise_glx_fb_configs(false); + assert!( + configs + .iter() + .all(|c| c.iter().all(|(k, _)| *k != g::GLX_BIND_TO_TEXTURE_RGB_EXT)) + ); + // Still equal length across configs. + let len = configs[0].len(); + assert!(configs.iter().all(|c| c.len() == len)); +} + +/// GLX Task 3.4: `glXCreatePixmap` records the X drawable in +/// `glx_drawables`, calls `acquire_glx_pixmap_export` on the backend, +/// and `glXDestroyPixmap` clears the entry and calls +/// `release_glx_pixmap_export`. +#[test] +fn glx_create_pixmap_records_x_drawable_and_destroy_clears_it() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Register an X pixmap in the resource table with a known host_xid. + let x_pixmap_xid: u32 = 0x2000; + let host_xid_raw: u32 = 0xdead_0001; + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(x_pixmap_xid), + drawable: ROOT_WINDOW, + width: 64, + height: 32, + }, + ); + assert!( + state.resources.set_pixmap_host_xid( + ResourceId(x_pixmap_xid), + crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), + ), + "set_pixmap_host_xid must succeed" + ); + + let glx_xid: u32 = 0x4000_0001; + let fbconfig: u32 = 0x101; + + // Build a GLX CREATE_PIXMAP request body: + // [screen(u32)][fbconfig(u32)][x_window(u32)][glx_window(u32)] + let mut create_body = Vec::new(); + create_body.extend_from_slice(&0u32.to_le_bytes()); // screen = 0 + create_body.extend_from_slice(&fbconfig.to_le_bytes()); + create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); + create_body.extend_from_slice(&glx_xid.to_le_bytes()); + + let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, // GLX_MAJOR_OPCODE + data: x11glx::CREATE_PIXMAP, // minor = 22 + length_units, + }, + &create_body, + None, + ) + .expect("process_request CREATE_PIXMAP"); + + // Verify the GlxDrawable was recorded. + let d = state + .glx_drawables + .get(&glx_xid) + .expect("GlxDrawable must be present after CreatePixmap"); + assert_eq!( + d.x_drawable, x_pixmap_xid, + "x_drawable must point to the X pixmap" + ); + assert_eq!(d.fbconfig, fbconfig); + + // Verify acquire was forwarded to the backend. + assert!( + backend + .calls() + .contains(&RecordedCall::AcquireGlxPixmapExport(host_xid_raw)), + "AcquireGlxPixmapExport must be recorded after CreatePixmap" + ); + + // Build a GLX DESTROY_PIXMAP request body: [glx_xid(u32)] + let destroy_body = glx_xid.to_le_bytes().to_vec(); + let length_units = u32::try_from(1 + destroy_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(2), + RequestHeader { + opcode: 148, + data: x11glx::DESTROY_PIXMAP, // minor = 23 + length_units, + }, + &destroy_body, + None, + ) + .expect("process_request DESTROY_PIXMAP"); + + // GlxDrawable must be removed. + assert!( + !state.glx_drawables.contains_key(&glx_xid), + "GlxDrawable must be removed after DestroyPixmap" + ); + + // Verify release was forwarded to the backend. + assert!( + backend + .calls() + .contains(&RecordedCall::ReleaseGlxPixmapExport(host_xid_raw)), + "ReleaseGlxPixmapExport must be recorded after DestroyPixmap" + ); +} + +// ─── GLX 1.0 CreateGLXPixmap / DestroyGLXPixmap, QueryContext, IsDirect ─── +// +// Expected wire behaviour is Xorg's, captured from Xvfb 21.1.24 +// (llvmpipe GLX) with an xcb probe on 2026-09-26. Xvfb's GLX visual 0x21 +// carries FBConfig 0x88; the yserver counterpart used below is +// ROOT_VISUAL 0x102 carrying FBConfig 0x101 (synthesise_glx_fb_configs). +// Error values, minors and the order in which the checks fire are +// Xvfb's, verbatim. + +const GLX_TEST_XID_BASE: u32 = 0x0020_0000; +const GLX_TEST_XID_MASK: u32 = 0x001f_ffff; + +/// A client whose XID range is `0x0020_0000 | 0x001f_ffff`, the range +/// Xvfb handed the capture probe, so `LEGAL_NEW_RESOURCE` is exercised. +fn glx_legacy_fixture() -> (ServerState, RecordingBackend, UnixStream) { + let mut state = ServerState::new(); + let peer = install_client(&mut state, 1); + let client = state.clients.get_mut(&1).expect("test client"); + client.resource_id_base = GLX_TEST_XID_BASE; + client.resource_id_mask = GLX_TEST_XID_MASK; + (state, RecordingBackend::new(), peer) +} + +type RecordedResourceAccess = ( + ResourceTarget, + AccessMode, + Option, + Option, +); + +struct DenyPbufferGeometryPolicy { + calls: Arc>>, +} + +impl AccessPolicy for DenyPbufferGeometryPolicy { + fn resource( + &self, + ctx: &AccessContext<'_>, + _client: ClientId, + target: &ResourceTarget, + mode: AccessMode, + ) -> Decision { + self.calls.lock().unwrap().push(( + *target, + mode, + ctx.request(), + ctx.owner(target.id, target.kind), + )); + if target.kind == ResourceKind::GlxDrawable { + Decision::Deny(DenyError { + code: yserver_protocol::x11::error::BAD_VALUE, + value: 0x55, + }) + } else { + Decision::Allow + } + } +} + +#[test] +fn get_geometry_checks_glx_drawable_without_backing_pixmap() { + // Mutation: check only windows and pixmaps; a pbuffer with no backing pixmap must still be checked as GlxDrawable. + let (mut state, mut backend, mut owner_peer) = glx_legacy_fixture(); + let mut other_peer = install_client(&mut state, 2); + let pbuffer = GLX_TEST_XID_BASE | 0x70; + backend.create_pixmap_fails = true; + use yserver_protocol::x11::glx; + let pbuffer_body = glx_legacy_words(&[ + 0, + 0x101, + pbuffer, + 2, + glx::GLX_PBUFFER_WIDTH, + 64, + glx::GLX_PBUFFER_HEIGHT, + 32, + ]); + assert!( + glx_legacy_send( + &mut state, + &mut backend, + &mut owner_peer, + 1, + glx::CREATE_PBUFFER, + &pbuffer_body, + ) + .is_empty() + ); + assert!(state.glx_drawables.contains_key(&pbuffer)); + assert!(state.resources.pixmap(ResourceId(pbuffer)).is_none()); + let calls = Arc::new(Mutex::new(Vec::new())); + state.install_access_policy(Arc::new(DenyPbufferGeometryPolicy { + calls: Arc::clone(&calls), + })); + let backend_before = backend.calls(); + + process_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(9), + RequestHeader { + opcode: 14, + data: 0, + length_units: 2, + }, + &pbuffer.to_le_bytes(), + None, + ) + .expect("GetGeometry on pbuffer"); + let bytes = read_all_or_buffered(&mut state, 2, &mut other_peer); + let mut expected = vec![0, yserver_protocol::x11::error::BAD_VALUE]; + expected.extend_from_slice(&9u16.to_le_bytes()); + expected.extend_from_slice(&0x55u32.to_le_bytes()); + expected.extend_from_slice(&0u16.to_le_bytes()); + expected.push(14); + expected.extend_from_slice(&[0; 21]); + assert_eq!(bytes, expected, "policy error, with no geometry reply"); + assert_eq!(backend.calls(), backend_before); + assert_eq!( + *calls.lock().unwrap(), + [( + ResourceTarget { + id: ResourceId(pbuffer), + kind: ResourceKind::GlxDrawable, + creation: None, + }, + AccessMode::GET_ATTR, + Some(RequestOpcodes { + major: 14, + minor: 0 + }), + Some(ClientId(1)), + )] + ); + assert!(read_all_available(&mut owner_peer).is_empty()); +} + +fn glx_legacy_x_pixmap(state: &mut ServerState, xid: u32, depth: u8, host: Option) { + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth, + pixmap: ResourceId(xid), + drawable: ROOT_WINDOW, + width: 64, + height: 32, + }, + ); + if let Some(host) = host { + assert!(state.resources.set_pixmap_host_xid( + ResourceId(xid), + crate::backend::PixmapHandle::from_raw(host).expect("non-zero host xid"), + )); + } +} + +fn glx_legacy_words(words: &[u32]) -> Vec { + words.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// Run one request for `client` and return every byte it wrote. +fn glx_legacy_send_major( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + client: u32, + (opcode, minor): (u8, u8), + body: &[u8], +) -> Vec { + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + process_request( + state, + backend, + ClientId(client), + SequenceNumber(7), + RequestHeader { + opcode, + data: minor, + length_units, + }, + body, + None, + ) + .expect("process_request"); + read_all_or_buffered(state, client, peer) +} + +/// Run one GLX request for `client` and return every byte it wrote. +fn glx_legacy_send( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + client: u32, + minor: u8, + body: &[u8], +) -> Vec { + glx_legacy_send_major( + state, + backend, + peer, + client, + (crate::nested::GLX_MAJOR_OPCODE, minor), + body, + ) +} + +/// Assert `bytes` is exactly one X error with this code, bad value and +/// minor opcode on the GLX major opcode. +fn assert_glx_legacy_error(what: &str, bytes: &[u8], code: u8, value: u32, minor: u8) { + assert_eq!(bytes.len(), 32, "{what}: expected exactly one error packet"); + assert_eq!(bytes[0], 0, "{what}: expected an X error"); + assert_eq!(bytes[1], code, "{what}: error code"); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + value, + "{what}: bad value" + ); + assert_eq!( + u16::from_le_bytes([bytes[8], bytes[9]]), + u16::from(minor), + "{what}: minor opcode" + ); + assert_eq!( + bytes[10], + crate::nested::GLX_MAJOR_OPCODE, + "{what}: major opcode" + ); +} + +fn create_glx_pixmap_body(screen: u32, visual: u32, pixmap: u32, glx_pixmap: u32) -> Vec { + glx_legacy_words(&[screen, visual, pixmap, glx_pixmap]) +} + +/// Decode the (attribute, value) pairs of a GetDrawableAttributes / +/// QueryContext reply, checking the header's length and count agree. +fn glx_legacy_reply_pairs(bytes: &[u8]) -> Vec<(u32, u32)> { + assert_eq!(bytes[0], 1, "expected a reply, got {bytes:02x?}"); + let length = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let n = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize; + assert_eq!(length, 2 * n, "reply length must be 2 * n"); + assert_eq!(bytes.len(), 32 + 8 * n, "reply size"); + (0..n) + .map(|i| { + let at = 32 + 8 * i; + ( + u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()), + u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()), + ) + }) + .collect() +} + +/// GLX 1.0 `glXCreateGLXPixmap` (minor 13) used to hit the +/// `GLXBadRenderRequest` catch-all, so Xlib's default handler killed the +/// app. It must create the same GLXPixmap record GLX 1.3 `CreatePixmap` +/// does (config = the visual's FBConfig), hold the export ref, report +/// Xorg's drawable attributes, and `DestroyGLXPixmap` (15) must release +/// the ref — also after the X pixmap was freed first (Xorg bumps the +/// pixmap refcount, glxcmds.c `DoCreateGLXPixmap`). +#[test] +fn glx10_create_glx_pixmap_records_pixmap_and_destroy_releases_it() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::glx as g; + + let (mut state, mut backend, mut peer) = glx_legacy_fixture(); + let pixmap = GLX_TEST_XID_BASE | 0x01; + let glx_pixmap = GLX_TEST_XID_BASE | 0x02; + let host = 0xdead_0001; + glx_legacy_x_pixmap(&mut state, pixmap, 24, Some(host)); + + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::CREATE_GLX_PIXMAP, + &create_glx_pixmap_body(0, crate::resources::ROOT_VISUAL.0, pixmap, glx_pixmap), + ); + assert!( + out.is_empty(), + "CreateGLXPixmap succeeds silently, got {out:02x?}" + ); + let record = state + .glx_drawables + .get(&glx_pixmap) + .expect("GLXPixmap recorded"); + assert_eq!(record.kind, crate::server::GlxDrawableKind::Pixmap); + assert_eq!(record.x_drawable, pixmap); + assert_eq!(record.fbconfig, 0x101, "the visual's FBConfig"); + assert_eq!(record.glx_export_host_xid, Some(host)); + assert!( + backend + .calls() + .contains(&RecordedCall::AcquireGlxPixmapExport(host)) + ); + + // Xvfb: 0x20d4=0 0x801d=64 0x801e=32 0x800c=0 0x20d6=0x20dd + // 0x801f=0 0x8013= 0x8010=GLX_PIXMAP_BIT + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::GET_DRAWABLE_ATTRIBUTES, + &glx_pixmap.to_le_bytes(), + ); + assert_eq!( + glx_legacy_reply_pairs(&out), + vec![ + (g::GLX_Y_INVERTED_EXT, 0), + (g::GLX_WIDTH, 64), + (g::GLX_HEIGHT, 32), + (g::GLX_SCREEN, 0), + (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_RECTANGLE_EXT), + (g::GLX_EVENT_MASK, 0), + (g::GLX_FBCONFIG_ID, 0x101), + (g::GLX_DRAWABLE_TYPE, g::GLX_PIXMAP_BIT), + ] + ); + + // FreePixmap first, then DestroyGLXPixmap: both Success on Xvfb. + let out = glx_legacy_send_major( + &mut state, + &mut backend, + &mut peer, + 1, + (54, 0), + &pixmap.to_le_bytes(), + ); + assert!(out.is_empty(), "FreePixmap: got {out:02x?}"); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::DESTROY_GLX_PIXMAP, + &glx_pixmap.to_le_bytes(), + ); + assert!( + out.is_empty(), + "DestroyGLXPixmap succeeds silently, got {out:02x?}" + ); + assert!(!state.glx_drawables.contains_key(&glx_pixmap)); + assert!( + backend + .calls() + .contains(&RecordedCall::ReleaseGlxPixmapExport(host)) + ); +} + +/// Every CreateGLXPixmap failure Xvfb produced, with its error code, +/// bad value and the precedence between checks: size, then the new +/// XID (`LEGAL_NEW_RESOURCE`), then the screen (GLXVND: BadMatch), then +/// the visual (BadValue), then the pixmap (core BadDrawable, or core +/// BadPixmap for a window). A failed request creates nothing. +#[test] +fn glx10_create_glx_pixmap_errors_match_xorg() { + use yserver_protocol::x11::{error, glx as g}; + + let (mut state, mut backend, mut peer) = glx_legacy_fixture(); + let pixmap = GLX_TEST_XID_BASE | 0x01; + let other_pixmap = GLX_TEST_XID_BASE | 0x03; + let existing_glx = GLX_TEST_XID_BASE | 0x04; + let fresh = GLX_TEST_XID_BASE | 0x05; + let vis = crate::resources::ROOT_VISUAL.0; + glx_legacy_x_pixmap(&mut state, pixmap, 24, None); + glx_legacy_x_pixmap(&mut state, other_pixmap, 32, None); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::CREATE_GLX_PIXMAP, + &create_glx_pixmap_body(0, vis, pixmap, existing_glx), + ); + assert!(out.is_empty()); + + let bad_id = error::BAD_ID_CHOICE; + let unknown = 0x5a_5a5a; + let root = ROOT_WINDOW.0; + let cases: &[(&str, [u32; 4], u8, u32)] = &[ + ( + "glx id in use", + [0, vis, pixmap, existing_glx], + bad_id, + existing_glx, + ), + ( + "glx id = X pixmap", + [0, vis, pixmap, other_pixmap], + bad_id, + other_pixmap, + ), + ( + "glx id out of range", + [0, vis, pixmap, 0x07f0_0001], + bad_id, + 0x07f0_0001, + ), + ("screen 1", [1, vis, pixmap, fresh], error::BAD_MATCH, 1), + ( + "unknown visual", + [0, 0xdead, pixmap, fresh], + error::BAD_VALUE, + 0xdead, + ), + // An FBConfig ID is not a GLX visual (Xvfb: its visual-less + // FBConfig 0x41 → BadValue 0x41). + ( + "visual-less fbconfig id", + [0, 0x104, pixmap, fresh], + error::BAD_VALUE, + 0x104, + ), + ( + "fbconfig id of a visual", + [0, 0x101, pixmap, fresh], + error::BAD_VALUE, + 0x101, + ), + ( + "screen 1 + bad visual", + [1, 0xdead, pixmap, fresh], + error::BAD_MATCH, + 1, + ), + ( + "root window as pixmap", + [0, vis, root, fresh], + error::BAD_PIXMAP, + root, + ), + ( + "unknown pixmap", + [0, vis, unknown, fresh], + error::BAD_DRAWABLE, + unknown, + ), + ( + "bad visual + bad pixmap", + [0, 0xdead, unknown, fresh], + error::BAD_VALUE, + 0xdead, + ), + ( + "bad pixmap + glx id in use", + [0, vis, unknown, existing_glx], + bad_id, + existing_glx, + ), + ]; + for (what, [screen, visual, pix, glx], code, value) in cases { + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::CREATE_GLX_PIXMAP, + &create_glx_pixmap_body(*screen, *visual, *pix, *glx), + ); + assert_glx_legacy_error(what, &out, *code, *value, g::CREATE_GLX_PIXMAP); + } + assert!(!state.glx_drawables.contains_key(&fresh)); + assert!(!state.glx_drawables.contains_key(&other_pixmap)); + assert_eq!(state.glx_drawables.len(), 1); +} + +/// Xorg does not compare the pixmap depth with the visual: Xvfb accepted +/// depth-32, depth-8 and depth-1 pixmaps for its depth-24 visual. +#[test] +fn glx10_create_glx_pixmap_accepts_any_pixmap_depth() { + use yserver_protocol::x11::glx as g; + + let (mut state, mut backend, mut peer) = glx_legacy_fixture(); + for (i, depth) in (0_u32..).zip([32_u8, 8, 1]) { + let pixmap = GLX_TEST_XID_BASE | (0x10 + i); + let glx_pixmap = GLX_TEST_XID_BASE | (0x20 + i); + glx_legacy_x_pixmap(&mut state, pixmap, depth, None); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::CREATE_GLX_PIXMAP, + &create_glx_pixmap_body(0, crate::resources::ROOT_VISUAL.0, pixmap, glx_pixmap), + ); + assert!(out.is_empty(), "depth {depth}: got {out:02x?}"); + assert!(state.glx_drawables.contains_key(&glx_pixmap)); + } +} + +/// DestroyGLXPixmap takes only a live GLX *pixmap*: anything else is +/// `GLXBadPixmap` with the XID as bad value (GLXVND's XID map, then +/// `validGlxDrawable`'s type check). GLX 1.0 and GLX 1.3 pixmaps are the +/// same resource type, so either destroy request frees either. +#[test] +fn glx10_destroy_glx_pixmap_errors_and_cross_version_destroy_match_xorg() { + use yserver_protocol::x11::glx as g; + + let (mut state, mut backend, mut peer) = glx_legacy_fixture(); + let bad_pixmap = crate::nested::GLX_FIRST_ERROR + g::ERROR_GLX_BAD_PIXMAP; + let pixmap = GLX_TEST_XID_BASE | 0x01; + glx_legacy_x_pixmap(&mut state, pixmap, 24, None); + let legacy = GLX_TEST_XID_BASE | 0x02; + let modern = GLX_TEST_XID_BASE | 0x03; + let glx_window = GLX_TEST_XID_BASE | 0x04; + let pbuffer = GLX_TEST_XID_BASE | 0x05; + let vis = crate::resources::ROOT_VISUAL.0; + + let mut send = |state: &mut ServerState, minor: u8, body: &[u8]| { + glx_legacy_send(state, &mut backend, &mut peer, 1, minor, body) + }; + let window_body = glx_legacy_words(&[0, 0x101, ROOT_WINDOW.0, glx_window]); + assert!(send(&mut state, g::CREATE_WINDOW, &window_body).is_empty()); + let pbuffer_body = glx_legacy_words(&[0, 0x101, pbuffer, 0]); + assert!(send(&mut state, g::CREATE_PBUFFER, &pbuffer_body).is_empty()); + + for (what, xid) in [ + ("unknown xid", 0x5a_5a5a), + ("X pixmap", pixmap), + ("GLX window", glx_window), + ("GLX pbuffer", pbuffer), + ] { + let out = send(&mut state, g::DESTROY_GLX_PIXMAP, &xid.to_le_bytes()); + assert_glx_legacy_error(what, &out, bad_pixmap, xid, g::DESTROY_GLX_PIXMAP); + } + assert!(state.glx_drawables.contains_key(&glx_window)); + assert!(state.glx_drawables.contains_key(&pbuffer)); + + // GLX 1.0 pixmap destroyed by GLX 1.3 DestroyPixmap; a second + // destroy through DestroyGLXPixmap is GLXBadPixmap. + let body = create_glx_pixmap_body(0, vis, pixmap, legacy); + assert!(send(&mut state, g::CREATE_GLX_PIXMAP, &body).is_empty()); + assert!(send(&mut state, g::DESTROY_PIXMAP, &legacy.to_le_bytes()).is_empty()); + assert!(!state.glx_drawables.contains_key(&legacy)); + let out = send(&mut state, g::DESTROY_GLX_PIXMAP, &legacy.to_le_bytes()); + assert_glx_legacy_error( + "destroyed twice", + &out, + bad_pixmap, + legacy, + g::DESTROY_GLX_PIXMAP, + ); + + // GLX 1.3 pixmap destroyed by GLX 1.0 DestroyGLXPixmap. + let body = glx_legacy_words(&[0, 0x101, pixmap, modern, 0]); + assert!(send(&mut state, g::CREATE_PIXMAP, &body).is_empty()); + assert!(send(&mut state, g::DESTROY_GLX_PIXMAP, &modern.to_le_bytes()).is_empty()); + assert!(!state.glx_drawables.contains_key(&modern)); +} + +/// CreateGLXPixmap, DestroyGLXPixmap, QueryContext and IsDirect are all +/// `REQUEST_SIZE_MATCH` in Xorg's GLXVND stubs: a short or long request +/// is core `BadLength`, and nothing is created. +#[test] +fn glx10_fixed_size_requests_reject_wrong_length() { + use yserver_protocol::x11::{error, glx as g}; + + let (mut state, mut backend, mut peer) = glx_legacy_fixture(); + let pixmap = GLX_TEST_XID_BASE | 0x01; + glx_legacy_x_pixmap(&mut state, pixmap, 24, None); + let mut long_create = create_glx_pixmap_body( + 0, + crate::resources::ROOT_VISUAL.0, + pixmap, + GLX_TEST_XID_BASE | 0x02, + ); + long_create.extend_from_slice(&[0; 4]); + let short_create = &long_create[..12]; + for (what, minor, body) in [ + ( + "CreateGLXPixmap long", + g::CREATE_GLX_PIXMAP, + long_create.as_slice(), + ), + ("CreateGLXPixmap short", g::CREATE_GLX_PIXMAP, short_create), + ("DestroyGLXPixmap long", g::DESTROY_GLX_PIXMAP, &[0; 8][..]), + ("DestroyGLXPixmap empty", g::DESTROY_GLX_PIXMAP, &[][..]), + ("QueryContext long", g::QUERY_CONTEXT, &[0; 8][..]), + ("QueryContext empty", g::QUERY_CONTEXT, &[][..]), + ("IsDirect long", g::IS_DIRECT, &[0; 8][..]), + ("IsDirect empty", g::IS_DIRECT, &[][..]), + ] { + let out = glx_legacy_send(&mut state, &mut backend, &mut peer, 1, minor, body); + assert_glx_legacy_error(what, &out, error::BAD_LENGTH, 0, minor); + } + assert!(state.glx_drawables.is_empty()); +} + +/// `QueryContext` (GLX_EXT_import_context) answers Xorg's five +/// attributes in Xorg's order (glxcmds.c `DoQueryContext`) for every +/// creation request, to any client, and `GLXBadContext` for an XID that +/// is not a live context. `IsDirect` reports the creation request's +/// `isDirect` and shares the `GLXBadContext` rule. +#[test] +fn glx_query_context_and_is_direct_match_xorg() { + use yserver_protocol::x11::glx as g; + + let (mut state, mut backend, mut peer) = glx_legacy_fixture(); + let mut peer2 = install_client(&mut state, 2); + let bad_context = crate::nested::GLX_FIRST_ERROR + g::ERROR_GLX_BAD_CONTEXT; + let root_visual = crate::resources::ROOT_VISUAL.0; + let ctx1 = GLX_TEST_XID_BASE | 0x11; + let ctx2 = GLX_TEST_XID_BASE | 0x12; + let ctx3 = GLX_TEST_XID_BASE | 0x13; + let ctx4 = GLX_TEST_XID_BASE | 0x14; + let ctx5 = GLX_TEST_XID_BASE | 0x15; + + let creates: [(u8, Vec); 5] = [ + // CreateContext: context visual screen share isDirect + (g::CREATE_CONTEXT, vec![ctx1, root_visual, 0, 0, 1]), + // CreateNewContext (visual-less FBConfig, share ctx1): + // context fbconfig screen renderType share isDirect + ( + g::CREATE_NEW_CONTEXT, + vec![ctx2, 0x104, 0, g::GLX_RGBA_TYPE, ctx1, 1], + ), + // CreateContextAttribsARB (share ctx1, GL 3.0): + // context fbconfig screen share isDirect numAttribs attribs + ( + g::CREATE_CONTEXT_ATTRIBS_ARB, + vec![ctx3, 0x101, 0, ctx1, 1, 2, 0x2091, 3, 0x2092, 0], + ), + // CreateContextAttribsARB with GLX_RENDER_TYPE = GLX_RGBA_TYPE. + ( + g::CREATE_CONTEXT_ATTRIBS_ARB, + vec![ + ctx4, + 0x101, + 0, + 0, + 1, + 1, + g::GLX_RENDER_TYPE, + g::GLX_RGBA_TYPE, + ], + ), + // CreateContext asking for an indirect context (isDirect 0). + (g::CREATE_CONTEXT, vec![ctx5, root_visual, 0, 0, 0]), + ]; + for (minor, words) in &creates { + let body = glx_legacy_words(words); + let out = glx_legacy_send(&mut state, &mut backend, &mut peer, 1, *minor, &body); + assert!(out.is_empty(), "create minor {minor}: got {out:02x?}"); + } + + let expect = |share: u32, visual: u32, fbconfig: u32| { + vec![ + (g::GLX_SHARE_CONTEXT_EXT, share), + (g::GLX_VISUAL_ID, visual), + (g::GLX_SCREEN, 0), + (g::GLX_FBCONFIG_ID, fbconfig), + (g::GLX_RENDER_TYPE, g::GLX_RGBA_TYPE), + ] + }; + for (ctx, share, visual, fbconfig) in [ + // Xvfb: 0x800a=0 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 + (ctx1, 0, root_visual, 0x101), + // Xvfb: 0x800a=ctx1 0x800b=0 0x800c=0 0x8013=0x41 0x8011=0x8014 + (ctx2, ctx1, 0, 0x104), + // Xvfb: 0x800a=ctx1 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 + (ctx3, ctx1, root_visual, 0x101), + // Xvfb: 0x800a=0 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 + (ctx4, 0, root_visual, 0x101), + // Xvfb +iglx: 0x800a=0 0x800b=0x21 0x800c=0 0x8013=0x88 0x8011=0x8014 + (ctx5, 0, root_visual, 0x101), + ] { + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::QUERY_CONTEXT, + &ctx.to_le_bytes(), + ); + assert_eq!( + glx_legacy_reply_pairs(&out), + expect(share, visual, fbconfig), + "QueryContext(0x{ctx:x})" + ); + } + + // Another client may query and IsDirect it: that is what + // import_context is for. + let ctx1_body = ctx1.to_le_bytes(); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer2, + 2, + g::QUERY_CONTEXT, + &ctx1_body, + ); + assert_eq!(glx_legacy_reply_pairs(&out), expect(0, root_visual, 0x101)); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer2, + 2, + g::IS_DIRECT, + &ctx1_body, + ); + assert_eq!(out.len(), 32, "IsDirect reply is 32 bytes"); + assert_eq!(out[0], 1, "IsDirect reply"); + assert_eq!(&out[4..8], &[0; 4], "IsDirect reply length 0"); + assert_eq!(out[8], 1, "IsDirect(ctx1) = True"); + // Xvfb +iglx: IsDirect of a context created with isDirect 0 is 0. + // (Without +iglx Xorg refuses that CreateContext with BadValue.) + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::IS_DIRECT, + &ctx5.to_le_bytes(), + ); + assert_eq!((out.len(), out[0], out[8]), (32, 1, 0), "IsDirect(ctx5)"); + + let pixmap = GLX_TEST_XID_BASE | 0x01; + let glx_pixmap = GLX_TEST_XID_BASE | 0x02; + glx_legacy_x_pixmap(&mut state, pixmap, 24, None); + let body = create_glx_pixmap_body(0, root_visual, pixmap, glx_pixmap); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::CREATE_GLX_PIXMAP, + &body, + ); + assert!(out.is_empty()); + for (what, xid) in [ + ("unknown", 0x5a_5a5a), + ("GLX pixmap", glx_pixmap), + ("None", 0), + ] { + for minor in [g::QUERY_CONTEXT, g::IS_DIRECT] { + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + minor, + &xid.to_le_bytes(), + ); + assert_glx_legacy_error(what, &out, bad_context, xid, minor); + } + } + + let ctx2_body = ctx2.to_le_bytes(); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::DESTROY_CONTEXT, + &ctx2_body, + ); + assert!(out.is_empty()); + let out = glx_legacy_send( + &mut state, + &mut backend, + &mut peer, + 1, + g::QUERY_CONTEXT, + &ctx2_body, + ); + assert_glx_legacy_error( + "destroyed context", + &out, + bad_context, + ctx2, + g::QUERY_CONTEXT, + ); +} + +/// `GetDrawableAttributes` on a GLXPixmap/GLXWindow must report the +/// geometry of the *backing* X drawable. The GLX XID is a fresh +/// client-allocated id with no X resource behind it, so resolving the +/// geometry from the GLX XID itself always missed and fell through to +/// `unwrap_or((0, 0))`. Measured on the wire against `libGLX_nvidia` +/// (2026-08-03): a 64×32 backing drawable was reported as +/// `GLX_WIDTH`/`GLX_HEIGHT` = 0. Xorg reads `pGlxDraw->pDraw->width` / +/// `->height` (glxcmds.c:1891). Against the old logic this test FAILS +/// with 0×0. +#[test] +fn glx_drawable_attributes_report_backing_drawable_geometry() { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + let x_pixmap_xid: u32 = 0x2000; + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(x_pixmap_xid), + drawable: ROOT_WINDOW, + width: 64, + height: 32, + }, + ); + + let glx_xid: u32 = 0x4000_0001; + let fbconfig: u32 = 0x101; + let mut create_body = Vec::new(); + create_body.extend_from_slice(&0u32.to_le_bytes()); // screen = 0 + create_body.extend_from_slice(&fbconfig.to_le_bytes()); + create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); + create_body.extend_from_slice(&glx_xid.to_le_bytes()); + let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: g::CREATE_PIXMAP, + length_units, + }, + &create_body, + None, + ) + .expect("process_request CREATE_PIXMAP"); + + let attribs = drawable_attributes_for(&state, glx_xid); + let get = |key: u32| { + attribs + .iter() + .find(|(k, _)| *k == key) + .map(|(_, v)| *v) + .unwrap_or_else(|| panic!("attribute 0x{key:x} must be present")) + }; + assert_eq!(get(g::GLX_WIDTH), 64, "GLX_WIDTH must track the X pixmap"); + assert_eq!(get(g::GLX_HEIGHT), 32, "GLX_HEIGHT must track the X pixmap"); + assert_eq!( + get(g::GLX_FBCONFIG_ID), + fbconfig, + "a registered GLX drawable must report its real fbconfig" + ); +} + +/// Naked X window (GLX 1.2 pattern, no GLX record): Xorg skips the +/// whole `pGlxDraw` block — `GLX_FBCONFIG_ID` / `GLX_TEXTURE_TARGET_EXT` +/// / `GLX_EVENT_MASK` must be **absent**, not present-and-zero — and +/// still ends with `GLX_DRAWABLE_TYPE = GLX_WINDOW_BIT` +/// (glxcmds.c:1875-1914). Asserts exact set and order. +#[test] +fn glx_drawable_attributes_naked_window_matches_xorg() { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let client_id = ClientId(1); + let window_xid: u32 = 0x2000; + state.resources.create_window( + client_id, + CreateWindowRequest { + depth: 24, + window: ResourceId(window_xid), + parent: ROOT_WINDOW, + width: 64, + height: 32, + ..Default::default() + }, + ); + + let attribs = drawable_attributes_for(&state, window_xid); + assert_eq!( + attribs, + vec![ + (g::GLX_Y_INVERTED_EXT, 0), + (g::GLX_WIDTH, 64), + (g::GLX_HEIGHT, 32), + (g::GLX_SCREEN, 0), + (g::GLX_DRAWABLE_TYPE, g::GLX_WINDOW_BIT), + ], + "naked-window attribute set and order must match glxcmds.c:1889-1914" + ); +} + +/// Registered GLXWindow: the `pGlxDraw` block is present, in Xorg's +/// order (glxcmds.c:1894-1906), with `GLX_STEREO_TREE_EXT = 0` for +/// window-type drawables and `GLX_DRAWABLE_TYPE = GLX_WINDOW_BIT` last. +#[test] +fn glx_drawable_attributes_glx_window_matches_xorg() { + use crate::server::{GlxDrawable, GlxDrawableKind}; + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let client_id = ClientId(1); + let x_window: u32 = 0x2000; + state.resources.create_window( + client_id, + CreateWindowRequest { + depth: 24, + window: ResourceId(x_window), + parent: ROOT_WINDOW, + width: 64, + height: 32, + ..Default::default() + }, + ); + let glx_xid: u32 = 0x4000_0001; + state.glx_drawables.insert( + glx_xid, + GlxDrawable { + owner: client_id, + kind: GlxDrawableKind::Window, + x_drawable: x_window, + fbconfig: 0x101, + width: 0, + height: 0, + event_mask: 0, + glx_export_host_xid: None, + texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, + }, + ); + + let attribs = drawable_attributes_for(&state, glx_xid); + assert_eq!( + attribs, + vec![ + (g::GLX_Y_INVERTED_EXT, 0), + (g::GLX_WIDTH, 64), + (g::GLX_HEIGHT, 32), + (g::GLX_SCREEN, 0), + (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_2D_EXT), + (g::GLX_EVENT_MASK, 0), + (g::GLX_FBCONFIG_ID, 0x101), + (g::GLX_STEREO_TREE_EXT, 0), + (g::GLX_DRAWABLE_TYPE, g::GLX_WINDOW_BIT), + ], + "GLXWindow attribute set and order must match glxcmds.c:1889-1914" + ); +} + +/// Registered GLXPixmap: like GLXWindow but without +/// `GLX_STEREO_TREE_EXT` (window-only) and with +/// `GLX_DRAWABLE_TYPE = GLX_PIXMAP_BIT`. +#[test] +fn glx_drawable_attributes_glx_pixmap_matches_xorg() { + use crate::server::{GlxDrawable, GlxDrawableKind}; + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let client_id = ClientId(1); + let x_pixmap: u32 = 0x2000; + state.resources.create_pixmap( + client_id, + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(x_pixmap), + drawable: ROOT_WINDOW, + width: 64, + height: 32, + }, + ); + let glx_xid: u32 = 0x4000_0001; + state.glx_drawables.insert( + glx_xid, + GlxDrawable { + owner: client_id, + kind: GlxDrawableKind::Pixmap, + x_drawable: x_pixmap, + fbconfig: 0x101, + width: 0, + height: 0, + event_mask: 0, + glx_export_host_xid: None, + texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, + }, + ); + + let attribs = drawable_attributes_for(&state, glx_xid); + assert_eq!( + attribs, + vec![ + (g::GLX_Y_INVERTED_EXT, 0), + (g::GLX_WIDTH, 64), + (g::GLX_HEIGHT, 32), + (g::GLX_SCREEN, 0), + (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_2D_EXT), + (g::GLX_EVENT_MASK, 0), + (g::GLX_FBCONFIG_ID, 0x101), + (g::GLX_DRAWABLE_TYPE, g::GLX_PIXMAP_BIT), + ], + "GLXPixmap attribute set and order must match glxcmds.c:1889-1914" + ); +} + +/// Registered pbuffer: geometry from the record, +/// `GLX_PRESERVED_CONTENTS = 1` (pbuffer-only) and +/// `GLX_DRAWABLE_TYPE = GLX_PBUFFER_BIT`. +#[test] +fn glx_drawable_attributes_pbuffer_matches_xorg() { + use crate::server::{GlxDrawable, GlxDrawableKind}; + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let client_id = ClientId(1); + let glx_xid: u32 = 0x4000_0001; + state.glx_drawables.insert( + glx_xid, + GlxDrawable { + owner: client_id, + kind: GlxDrawableKind::Pbuffer, + x_drawable: glx_xid, + fbconfig: 0x101, + width: 64, + height: 32, + event_mask: 0, + glx_export_host_xid: None, + texture_target: yserver_protocol::x11::glx::GLX_TEXTURE_2D_EXT, + }, + ); + + let attribs = drawable_attributes_for(&state, glx_xid); + assert_eq!( + attribs, + vec![ + (g::GLX_Y_INVERTED_EXT, 0), + (g::GLX_WIDTH, 64), + (g::GLX_HEIGHT, 32), + (g::GLX_SCREEN, 0), + (g::GLX_TEXTURE_TARGET_EXT, g::GLX_TEXTURE_2D_EXT), + (g::GLX_EVENT_MASK, 0), + (g::GLX_FBCONFIG_ID, 0x101), + (g::GLX_PRESERVED_CONTENTS, 1), + (g::GLX_DRAWABLE_TYPE, g::GLX_PBUFFER_BIT), + ], + "pbuffer attribute set and order must match glxcmds.c:1889-1914" + ); +} + +/// Request-level wire test: `GET_DRAWABLE_ATTRIBUTES` on a naked X +/// window must deliver a well-formed reply — `length = 2n` 4-byte +/// units, `numAttribs = n`, pairs in Xorg order — with no +/// `GLX_FBCONFIG_ID` anywhere in the payload. +#[test] +fn glx_get_drawable_attributes_naked_window_wire_reply() { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + let window_xid: u32 = 0x2000; + state.resources.create_window( + client_id, + CreateWindowRequest { + depth: 24, + window: ResourceId(window_xid), + parent: ROOT_WINDOW, + width: 64, + height: 32, + ..Default::default() + }, + ); + + let body = window_xid.to_le_bytes().to_vec(); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(7), + RequestHeader { + opcode: 148, + data: g::GET_DRAWABLE_ATTRIBUTES, + length_units, + }, + &body, + None, + ) + .expect("process_request GET_DRAWABLE_ATTRIBUTES"); + + let expected: [(u32, u32); 5] = [ + (g::GLX_Y_INVERTED_EXT, 0), + (g::GLX_WIDTH, 64), + (g::GLX_HEIGHT, 32), + (g::GLX_SCREEN, 0), + (g::GLX_DRAWABLE_TYPE, g::GLX_WINDOW_BIT), + ]; + let n = u32::try_from(expected.len()).expect("fits"); + + peer.set_nonblocking(true).unwrap(); + let mut header = [0u8; 32]; + peer.read_exact(&mut header) + .expect("reply header delivered"); + assert_eq!(header[0], 1, "byte 0 must be 1 (Reply)"); + assert_eq!(u16::from_le_bytes([header[2], header[3]]), 7, "sequence"); + assert_eq!( + u32::from_le_bytes([header[4], header[5], header[6], header[7]]), + 2 * n, + "length must be 2 * numAttribs 4-byte units" + ); + assert_eq!( + u32::from_le_bytes([header[8], header[9], header[10], header[11]]), + n, + "numAttribs" + ); + + let mut pairs = vec![0u8; (2 * n) as usize * 4]; + peer.read_exact(&mut pairs) + .expect("attribute pairs delivered"); + for (i, &(key, value)) in expected.iter().enumerate() { + let got_key = u32::from_le_bytes([ + pairs[i * 8], + pairs[i * 8 + 1], + pairs[i * 8 + 2], + pairs[i * 8 + 3], + ]); + let got_value = u32::from_le_bytes([ + pairs[i * 8 + 4], + pairs[i * 8 + 5], + pairs[i * 8 + 6], + pairs[i * 8 + 7], + ]); + assert_eq!((got_key, got_value), (key, value), "pair {i}"); + } +} + +#[test] +fn glx_vendor_names_query_answers_from_server_state() { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // The value the backend derived at startup, not the constant. + state.glx_vendor_names = "nvidia mesa".to_string(); + + // QueryServerString body: screen (u32), name (u32). + let mut body = Vec::new(); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&g::VENDOR_NAMES_EXT.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(9), + RequestHeader { + opcode: 148, + data: g::QUERY_SERVER_STRING, + length_units, + }, + &body, + None, + ) + .expect("process_request QUERY_SERVER_STRING"); + + peer.set_nonblocking(true).unwrap(); + let mut header = [0u8; 32]; + peer.read_exact(&mut header) + .expect("reply header delivered"); + assert_eq!(header[0], 1, "byte 0 must be 1 (Reply)"); + assert_eq!(u16::from_le_bytes([header[2], header[3]]), 9, "sequence"); + + // Reply layout, read off encode_string_reply (glx.rs:267-291): + // 0 1 (Reply) 1 0 (pad) + // 2..4 sequence 4..8 length_units = padded / 4 + // 8..12 pad1 12..16 n (string length INCLUDING NUL) + // 16..32 pad3..pad6 then bytes + NUL + zero padding + // Note n sits at 12, not 8 -- offset 8 is pad1. The + // GetDrawableAttributes reply carries numAttribs at 8, which is a + // different reply shape; do not copy that offset here. + let n = u32::from_le_bytes([header[12], header[13], header[14], header[15]]); + assert_eq!(n as usize, "nvidia mesa".len() + 1, "n counts the NUL"); + + let padded = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize * 4; + assert_eq!(padded, 12, "11 bytes + NUL, already 4-aligned"); + let mut tail = vec![0u8; padded]; + peer.read_exact(&mut tail).expect("reply tail delivered"); + let s = String::from_utf8_lossy(&tail); + assert!( + s.starts_with("nvidia mesa"), + "arm must read state, not the VENDOR_NAMES constant; got {s:?}" + ); +} + +/// Error arm 1: a naked X **pixmap** (resolvable as a drawable but not +/// a window, no GLX record) gets the extension error `GLXBadDrawable` +/// (`GLX_FIRST_ERROR + 2`) — GLXVND forwards pixmaps because they carry +/// RC_DRAWABLE, then `dixLookupWindow` fails (glxcmds.c:1873-1880). +#[test] +fn glx_get_drawable_attributes_naked_pixmap_returns_glx_bad_drawable() { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + let pixmap_xid: u32 = 0x2000; + state.resources.create_pixmap( + client_id, + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap_xid), + drawable: ROOT_WINDOW, + width: 64, + height: 32, + }, + ); + + let body = pixmap_xid.to_le_bytes().to_vec(); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: g::GET_DRAWABLE_ATTRIBUTES, + length_units, + }, + &body, + None, + ) + .expect("process_request should not hard-error"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("GLXBadDrawable error packet must be delivered"); + assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); + let expected_code = + crate::nested::GLX_FIRST_ERROR + yserver_protocol::x11::glx::ERROR_GLX_BAD_DRAWABLE; + assert_eq!( + buf[1], expected_code, + "expected GLXBadDrawable ({}), got {}", + expected_code, buf[1] + ); +} + +/// Error arm 2: an XID that is not a drawable at all gets **core +/// `BadDrawable` (9)** — GLXVND's XID-map lookup returns NULL and the +/// dispatch stub errors out before `DoGetDrawableAttributes` is ever +/// reached (glx/vnd_dispatch_stubs.c:456-472). The two error arms must +/// not be collapsed. +#[test] +fn glx_get_drawable_attributes_unknown_xid_returns_core_bad_drawable() { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + let unknown_xid: u32 = 0x9999; + let body = unknown_xid.to_le_bytes().to_vec(); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: g::GET_DRAWABLE_ATTRIBUTES, + length_units, + }, + &body, + None, + ) + .expect("process_request should not hard-error"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("core BadDrawable error packet must be delivered"); + assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_DRAWABLE, + "expected core BadDrawable (9), got {}", + buf[1] + ); + assert_eq!( + u16::from_le_bytes([buf[8], buf[9]]), + u16::from(g::GET_DRAWABLE_ATTRIBUTES), + "error must identify GLX::GetDrawableAttributes as the minor opcode" + ); + assert_eq!( + buf[10], + crate::nested::GLX_MAJOR_OPCODE, + "error must identify GLX as the major opcode" + ); +} + +/// Read the `contextTag` field (bytes 8..12) out of a 32-byte +/// `MakeCurrent` reply. +fn make_current_reply_tag(buf: &[u8; 32]) -> u32 { + u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]) +} + +/// Drive a `MakeCurrent`/`MakeContextCurrent` request and return the +/// 32-byte reply. `context` is placed at the minor-specific offset. +fn drive_make_current(minor: u8, context: u32) -> [u8; 32] { + use yserver_protocol::x11::glx as g; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Layouts (glxproto.h:225-233, :471-481), body-relative: + // minor 5 MakeCurrent: drawable, context, oldContextTag + // minor 26 MakeContextCurrent: oldContextTag, drawable, readdrawable, context + let mut body = Vec::new(); + if minor == g::MAKE_CURRENT { + body.extend_from_slice(&0x2000u32.to_le_bytes()); // drawable + body.extend_from_slice(&context.to_le_bytes()); // context + body.extend_from_slice(&0u32.to_le_bytes()); // oldContextTag + } else { + body.extend_from_slice(&0u32.to_le_bytes()); // oldContextTag + body.extend_from_slice(&0x2000u32.to_le_bytes()); // drawable + body.extend_from_slice(&0x2000u32.to_le_bytes()); // readdrawable + body.extend_from_slice(&context.to_le_bytes()); // context + } + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: minor, + length_units, + }, + &body, + None, + ) + .expect("process_request MakeCurrent"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("MakeCurrent reply delivered"); + assert_eq!(buf[0], 1, "byte 0 must be 1 (Reply)"); + buf +} + +/// D6: the release form (`context == None`) must return +/// `contextTag = 0` — tag 0 is reserved by the protocol to mean "no +/// context current" (Xorg vndcmds.c:232-234, :271-273). Both minors. +#[test] +fn glx_make_current_release_returns_zero_tag() { + use yserver_protocol::x11::glx as g; + + let buf = drive_make_current(g::MAKE_CURRENT, 0); + assert_eq!( + make_current_reply_tag(&buf), + 0, + "MakeCurrent release must return contextTag = 0" + ); +} + +#[test] +fn glx_make_context_current_release_returns_zero_tag() { + use yserver_protocol::x11::glx as g; + + let buf = drive_make_current(g::MAKE_CONTEXT_CURRENT, 0); + assert_eq!( + make_current_reply_tag(&buf), + 0, + "MakeContextCurrent release must return contextTag = 0" + ); +} + +/// D6: a non-null context still gets a fresh non-zero tag, for both +/// minors (regression guard on the release fix). +#[test] +fn glx_make_current_non_null_context_returns_nonzero_tag() { + use yserver_protocol::x11::glx as g; + + let buf = drive_make_current(g::MAKE_CURRENT, 0x3000); + assert_ne!( + make_current_reply_tag(&buf), + 0, + "MakeCurrent with a context must return a non-zero tag" + ); +} + +#[test] +fn glx_make_context_current_non_null_context_returns_nonzero_tag() { + use yserver_protocol::x11::glx as g; + + let buf = drive_make_current(g::MAKE_CONTEXT_CURRENT, 0x3000); + assert_ne!( + make_current_reply_tag(&buf), + 0, + "MakeContextCurrent with a context must return a non-zero tag" + ); +} + +/// GLX Task 3.4 regression: the export ref must be released on +/// `glXDestroyPixmap` even when the client called X11 `FreePixmap` on +/// the underlying X pixmap FIRST (a common compositor ordering). The +/// release site must use the host_xid stored at acquire time, NOT a +/// re-resolution via `resources.pixmap(x_drawable)` (which is gone after +/// FreePixmap). Against the old re-resolving logic this test FAILS: +/// ReleaseGlxPixmapExport is never recorded → the export ref leaks. +#[test] +fn glx_destroy_releases_export_even_after_free_pixmap() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Register an X pixmap with a known host_xid. + let x_pixmap_xid: u32 = 0x3000; + let host_xid_raw: u32 = 0xdead_0002; + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(x_pixmap_xid), + drawable: ROOT_WINDOW, + width: 64, + height: 32, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(x_pixmap_xid), + crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), + )); + + let glx_xid: u32 = 0x4000_0003; + + // glXCreatePixmap — acquire. + let mut create_body = Vec::new(); + create_body.extend_from_slice(&0u32.to_le_bytes()); // screen + create_body.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig + create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); + create_body.extend_from_slice(&glx_xid.to_le_bytes()); + let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::CREATE_PIXMAP, + length_units, + }, + &create_body, + None, + ) + .expect("process_request CREATE_PIXMAP"); + assert!( + backend + .calls() + .contains(&RecordedCall::AcquireGlxPixmapExport(host_xid_raw)), + "AcquireGlxPixmapExport must be recorded" + ); + + // X11 FreePixmap on the underlying X pixmap BEFORE glXDestroyPixmap. + // This removes the pixmap from the resource table — any subsequent + // re-resolution of x_drawable→host_xid would fail. + let free_body = x_pixmap_xid.to_le_bytes().to_vec(); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(2), + RequestHeader { + opcode: 54, // FreePixmap + data: 0, + length_units: 2, + }, + &free_body, + None, + ) + .expect("process_request FreePixmap"); + // Sanity: the pixmap resource is really gone. + assert!( + state.resources.pixmap(ResourceId(x_pixmap_xid)).is_none(), + "X pixmap must be freed by FreePixmap" + ); + + // glXDestroyPixmap — must still release using the stored host_xid. + let destroy_body = glx_xid.to_le_bytes().to_vec(); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(3), + RequestHeader { + opcode: 148, + data: x11glx::DESTROY_PIXMAP, + length_units: 2, + }, + &destroy_body, + None, + ) + .expect("process_request DESTROY_PIXMAP"); + + assert!( + !state.glx_drawables.contains_key(&glx_xid), + "GlxDrawable must be removed after DestroyPixmap" + ); + // THE REGRESSION ASSERTION: release must fire despite the early FreePixmap. + assert!( + backend + .calls() + .contains(&RecordedCall::ReleaseGlxPixmapExport(host_xid_raw)), + "ReleaseGlxPixmapExport must be recorded even after the X pixmap was \ + freed before glXDestroyPixmap (no export-ref leak)" + ); +} + +/// GLX Task 3.4: `glXCreatePixmap` with a non-existent X pixmap XID +/// must reply with a GLXBadPixmap error rather than silently inserting. +#[test] +fn glx_create_pixmap_with_missing_x_pixmap_returns_glx_bad_pixmap() { + use yserver_protocol::x11::glx as x11glx; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Use an XID that was never registered. + let bad_x_pixmap_xid: u32 = 0x9999; + let glx_xid: u32 = 0x4000_0002; + + let mut create_body = Vec::new(); + create_body.extend_from_slice(&0u32.to_le_bytes()); // screen + create_body.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig + create_body.extend_from_slice(&bad_x_pixmap_xid.to_le_bytes()); + create_body.extend_from_slice(&glx_xid.to_le_bytes()); + let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); + + let outcome = process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::CREATE_PIXMAP, + length_units, + }, + &create_body, + None, + ) + .expect("process_request should not hard-error"); + assert!(matches!(outcome, RequestOutcome::Handled)); + + // Nothing inserted in glx_drawables. + assert!( + !state.glx_drawables.contains_key(&glx_xid), + "GlxDrawable must NOT be inserted when X pixmap does not exist" + ); + + // Error packet must be delivered: GLXBadPixmap = GLX_FIRST_ERROR + 3 = 172. + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .expect("GLXBadPixmap error packet must be delivered"); + assert_eq!(buf[0], 0, "byte 0 must be 0 (Error class)"); + let expected_code = + crate::nested::GLX_FIRST_ERROR + yserver_protocol::x11::glx::ERROR_GLX_BAD_PIXMAP; + assert_eq!( + buf[1], expected_code, + "expected GLXBadPixmap ({}), got {}", + expected_code, buf[1] + ); +} + +/// GLX Task 3.5: `VendorPrivate` with vendor_code 1330 (`BindTexImageEXT`) +/// over a valid GLXPixmap must NOT be rejected with +/// `GLXUnsupportedPrivateRequest`; it must succeed (return `Handled` +/// with no error packet delivered to the client). +/// +/// Secondary assertion: an unknown vendor code still gets +/// `GLXUnsupportedPrivateRequest` (preservation of the fallthrough). +#[test] +fn bind_tex_image_ext_is_dispatched_not_rejected() { + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Register an X pixmap with a known host_xid — mirrors the + // Task 3.4 test setup so we can get a GlxDrawable into state. + let x_pixmap_xid: u32 = 0x2000; + let host_xid_raw: u32 = 0xdead_1330; + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: yserver_protocol::x11::ResourceId(x_pixmap_xid), + drawable: ROOT_WINDOW, + width: 32, + height: 32, + }, + ); + assert!( + state.resources.set_pixmap_host_xid( + yserver_protocol::x11::ResourceId(x_pixmap_xid), + crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), + ), + "set_pixmap_host_xid must succeed" + ); + + // First, call GLX::CreatePixmap to insert a GlxDrawable. + let glx_xid: u32 = 0x4000_0002; + let fbconfig: u32 = 0x101; + let mut create_body = Vec::new(); + create_body.extend_from_slice(&0u32.to_le_bytes()); // screen = 0 + create_body.extend_from_slice(&fbconfig.to_le_bytes()); + create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); + create_body.extend_from_slice(&glx_xid.to_le_bytes()); + let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::CREATE_PIXMAP, + length_units, + }, + &create_body, + None, + ) + .expect("process_request CREATE_PIXMAP"); + + // Build a VendorPrivate body for BindTexImageEXT (1330): + // [vendor_code=1330][context_tag=0][glx_drawable=glx_xid][buffer=GLX_FRONT_LEFT_EXT] + let mut bind_body = Vec::new(); + bind_body.extend_from_slice(&x11glx::VENDOR_CODE_BIND_TEX_IMAGE.to_le_bytes()); + bind_body.extend_from_slice(&0u32.to_le_bytes()); // context_tag + bind_body.extend_from_slice(&glx_xid.to_le_bytes()); + bind_body.extend_from_slice(&x11glx::GLX_FRONT_LEFT_EXT.to_le_bytes()); + let length_units = u32::try_from(1 + bind_body.len().div_ceil(4)).expect("fits"); + let outcome = process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(2), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE, // minor = 16 + length_units, + }, + &bind_body, + None, + ) + .expect("process_request VENDOR_PRIVATE BindTexImageEXT must not hard-error"); + assert!( + matches!(outcome, RequestOutcome::Handled), + "BindTexImageEXT must return Handled, got {outcome:?}" + ); + + // No error packet must be delivered to the client. + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + match peer.read(&mut buf) { + Ok(0) | Err(_) => { /* no data written — correct */ } + Ok(n) => { + assert_ne!( + buf[0], 0, + "BindTexImageEXT must not deliver an X11 error packet; \ + got {n} bytes, first byte={} (0=Error)", + buf[0] + ); + } + } + peer.set_nonblocking(false).unwrap(); + + // The unsupported-private rejection must still fire for unknown codes. + let mut unknown_body = Vec::new(); + unknown_body.extend_from_slice(&9999u32.to_le_bytes()); // unknown vendor code + unknown_body.extend_from_slice(&0u32.to_le_bytes()); + unknown_body.extend_from_slice(&0u32.to_le_bytes()); + unknown_body.extend_from_slice(&0u32.to_le_bytes()); + let length_units = u32::try_from(1 + unknown_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(3), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE, + length_units, + }, + &unknown_body, + None, + ) + .expect("process_request VENDOR_PRIVATE unknown must not hard-error"); + + // Error packet for the unknown vendor code. + peer.set_nonblocking(true).unwrap(); + let mut buf2 = [0u8; 32]; + peer.read_exact(&mut buf2) + .expect("GLXUnsupportedPrivateRequest error packet must be delivered"); + assert_eq!(buf2[0], 0, "byte 0 must be 0 (Error class)"); + let expected_unsupported = crate::nested::GLX_FIRST_ERROR + + yserver_protocol::x11::glx::ERROR_GLX_UNSUPPORTED_PRIVATE_REQUEST; + assert_eq!( + buf2[1], expected_unsupported, + "expected GLXUnsupportedPrivateRequest ({expected_unsupported}), got {}", + buf2[1] + ); + peer.set_nonblocking(false).unwrap(); +} + +/// GLX Task 3.5 regression (codex review): `BindTexImageEXT` / +/// `ReleaseTexImageEXT` must be DECOUPLED from the GLXPixmap LIFETIME +/// refcount (`glx_refs`). +/// +/// Bind uses the promote-only hook (`promote_pixmap_exportable`), +/// idempotently, taking NO lifetime ref — so repeated rebinds (the +/// normal TFP per-frame pattern) do not grow `glx_refs` and leak the +/// backing. Release is a lifetime no-op — it must NOT call +/// `release_glx_pixmap_export`, or a release without a matching bind +/// would tear the backing down while the GLXPixmap is still alive. +/// +/// Against the OLD acquire/release-based logic this test FAILS: the +/// three binds would record three `AcquireGlxPixmapExport` (and no +/// `PromotePixmapExportable`), and the release would record a +/// `ReleaseGlxPixmapExport`. +#[test] +fn bind_release_tex_image_do_not_touch_lifetime_refcount() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Register an X pixmap with a known host_xid. + let x_pixmap_xid: u32 = 0x2100; + let host_xid_raw: u32 = 0xdead_1331; + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: yserver_protocol::x11::ResourceId(x_pixmap_xid), + drawable: ROOT_WINDOW, + width: 32, + height: 32, + }, + ); + assert!( + state.resources.set_pixmap_host_xid( + yserver_protocol::x11::ResourceId(x_pixmap_xid), + crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), + ), + "set_pixmap_host_xid must succeed" + ); + + // glXCreatePixmap inserts the GlxDrawable and takes the ONE lifetime + // acquire ref (this is the legitimate AcquireGlxPixmapExport). + let glx_xid: u32 = 0x4000_0003; + let mut create_body = Vec::new(); + create_body.extend_from_slice(&0u32.to_le_bytes()); // screen + create_body.extend_from_slice(&0x101u32.to_le_bytes()); // fbconfig + create_body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); + create_body.extend_from_slice(&glx_xid.to_le_bytes()); + let length_units = u32::try_from(1 + create_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::CREATE_PIXMAP, + length_units, + }, + &create_body, + None, + ) + .expect("process_request CREATE_PIXMAP"); + + // Exactly one acquire (the lifetime ref) so far; no promote yet. + let after_create = backend.calls(); + assert_eq!( + after_create + .iter() + .filter(|c| matches!(c, RecordedCall::AcquireGlxPixmapExport(_))) + .count(), + 1, + "glXCreatePixmap must take exactly one lifetime acquire ref" + ); + let acquires_before_binds = after_create + .iter() + .filter(|c| matches!(c, RecordedCall::AcquireGlxPixmapExport(_))) + .count(); + let releases_before_binds = after_create + .iter() + .filter(|c| matches!(c, RecordedCall::ReleaseGlxPixmapExport(_))) + .count(); + + // Build a BindTexImageEXT VendorPrivate body. + let mut bind_body = Vec::new(); + bind_body.extend_from_slice(&x11glx::VENDOR_CODE_BIND_TEX_IMAGE.to_le_bytes()); + bind_body.extend_from_slice(&0u32.to_le_bytes()); // context_tag + bind_body.extend_from_slice(&glx_xid.to_le_bytes()); + bind_body.extend_from_slice(&x11glx::GLX_FRONT_LEFT_EXT.to_le_bytes()); + let bind_units = u32::try_from(1 + bind_body.len().div_ceil(4)).expect("fits"); + + // Bind THREE times (compositor per-frame / implicit-rebind pattern). + for seq in 2u16..=4 { + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(seq), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE, + length_units: bind_units, + }, + &bind_body, + None, + ) + .expect("process_request BindTexImageEXT"); + } + + let after_binds = backend.calls(); + // Each bind recorded a PromotePixmapExportable (the lightweight hook). + assert_eq!( + after_binds + .iter() + .filter(|c| matches!( + c, + RecordedCall::PromotePixmapExportable(h) if *h == host_xid_raw + )) + .count(), + 3, + "each BindTexImageEXT must record PromotePixmapExportable, not Acquire" + ); + // The binds must NOT have taken any extra lifetime ref. + assert_eq!( + after_binds + .iter() + .filter(|c| matches!(c, RecordedCall::AcquireGlxPixmapExport(_))) + .count(), + acquires_before_binds, + "BindTexImageEXT must NOT take a lifetime acquire ref (no leak on rebind)" + ); + assert_eq!( + after_binds + .iter() + .filter(|c| matches!(c, RecordedCall::ReleaseGlxPixmapExport(_))) + .count(), + releases_before_binds, + "BindTexImageEXT must NOT change the lifetime release count" + ); + + // Now ReleaseTexImageEXT — must be a lifetime no-op. + let mut rel_body = Vec::new(); + rel_body.extend_from_slice(&x11glx::VENDOR_CODE_RELEASE_TEX_IMAGE.to_le_bytes()); + rel_body.extend_from_slice(&0u32.to_le_bytes()); // context_tag + rel_body.extend_from_slice(&glx_xid.to_le_bytes()); + rel_body.extend_from_slice(&x11glx::GLX_FRONT_LEFT_EXT.to_le_bytes()); + let rel_units = u32::try_from(1 + rel_body.len().div_ceil(4)).expect("fits"); + process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(5), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE, + length_units: rel_units, + }, + &rel_body, + None, + ) + .expect("process_request ReleaseTexImageEXT"); + + // THE REGRESSION ASSERTION: release must NOT have dropped the + // lifetime ref — the backing survives until glXDestroyPixmap. + let after_release = backend.calls(); + assert_eq!( + after_release + .iter() + .filter(|c| matches!(c, RecordedCall::ReleaseGlxPixmapExport(_))) + .count(), + releases_before_binds, + "ReleaseTexImageEXT must NOT call release_glx_pixmap_export \ + (lifetime ref untouched; backing survives until glXDestroyPixmap)" + ); +} + +// ── GLX_SGIX_fbconfig dispatch tests ───────────────────────────────────── + +/// Build a VendorPrivateWithReply body for `GetFBConfigsSGIX` (vendor +/// code 65540): +/// [0..4] vendorCode +/// [4..8] pad1 = 0 +/// [8..12] screen = 0 +fn build_get_fb_configs_sgix_body(screen: u32) -> Vec { + use yserver_protocol::x11::glx as x11glx; + let mut body = Vec::new(); + body.extend_from_slice(&x11glx::VENDOR_CODE_GET_FB_CONFIGS_SGIX.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // pad1 + body.extend_from_slice(&screen.to_le_bytes()); + body +} + +/// `VendorPrivateWithReply` with vendor_code `GetFBConfigsSGIX` (65540) +/// must NOT be rejected with `GLXUnsupportedPrivateRequest`; it must +/// return a non-empty GetFBConfigs reply (real configs, not a stub). +#[test] +fn get_fb_configs_sgix_is_dispatched_not_rejected() { + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + let body = build_get_fb_configs_sgix_body(0); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + + let outcome = process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE_WITH_REPLY, + length_units, + }, + &body, + None, + ) + .expect("process_request must not hard-error"); + + assert!( + matches!(outcome, RequestOutcome::Handled), + "GetFBConfigsSGIX must return Handled, got {outcome:?}" + ); + + // Must NOT deliver an error packet. + peer.set_nonblocking(true).unwrap(); + let bytes = read_all_available(&mut peer); + assert!( + !bytes.is_empty(), + "GetFBConfigsSGIX must deliver a reply packet" + ); + assert_ne!( + bytes[0], 0, + "byte 0 must not be 0 (Error); got {bytes:02x?}" + ); + // byte 0 = 1 (Reply), byte 8..12 = num_FB_configs > 0. + assert_eq!(bytes[0], 1, "byte 0 must be Reply type"); + let num_configs = u32::from_le_bytes(bytes[8..12].try_into().unwrap()); + assert!( + num_configs > 0, + "GetFBConfigsSGIX must return at least one FBConfig, got {num_configs}" + ); + peer.set_nonblocking(false).unwrap(); +} + +/// `VendorPrivate` with vendor_code `CreateContextWithConfigSGIX` +/// (65541) must insert a `GlxContext` entry (no reply, no error). +#[test] +fn create_context_with_config_sgix_inserts_context() { + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + let context_xid: u32 = 0xABCD_0001; + let fbconfig: u32 = 0x101; + + // Build CreateContextWithConfigSGIX body: + // [0..4] vendorCode = 65541 + // [4..8] pad1 = 0 + // [8..12] context = context_xid + // [12..16] fbconfig = 0x101 + // [16..20] screen = 0 + // [20..24] renderType = 1 + // [24..28] shareList = 0 + // [28] isDirect = 1 + // [29..32] reserved = 0 + let mut body = Vec::new(); + body.extend_from_slice(&x11glx::VENDOR_CODE_CREATE_CONTEXT_WITH_CONFIG_SGIX.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // pad1 + body.extend_from_slice(&context_xid.to_le_bytes()); + body.extend_from_slice(&fbconfig.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // screen + body.extend_from_slice(&1u32.to_le_bytes()); // renderType + body.extend_from_slice(&0u32.to_le_bytes()); // shareList + body.push(1u8); // isDirect + body.push(0u8); // reserved1 + body.extend_from_slice(&0u16.to_le_bytes()); // reserved2 + + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + + let outcome = process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE, + length_units, + }, + &body, + None, + ) + .expect("process_request must not hard-error"); + + assert!( + matches!(outcome, RequestOutcome::Handled), + "CreateContextWithConfigSGIX must return Handled, got {outcome:?}" + ); + + // GlxContext must be inserted. + assert!( + state.glx_contexts.contains_key(&context_xid), + "GlxContext must be inserted for xid=0x{context_xid:x}" + ); + let ctx = &state.glx_contexts[&context_xid]; + assert_eq!(ctx.fbconfig, fbconfig, "fbconfig must be recorded"); + + // No error packet. + peer.set_nonblocking(true).unwrap(); + let bytes = read_all_available(&mut peer); + assert!( + bytes.is_empty(), + "CreateContextWithConfigSGIX must not deliver an error; got {bytes:02x?}" + ); + peer.set_nonblocking(false).unwrap(); +} + +/// `VendorPrivate` with vendor_code `CreateGLXPixmapWithConfigSGIX` +/// (65542) must insert a `GlxDrawable` entry and call +/// `acquire_glx_pixmap_export` — same semantics as `CREATE_PIXMAP`. +#[test] +fn create_glx_pixmap_with_config_sgix_inserts_drawable_and_acquires() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::glx as x11glx; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let client_id = ClientId(1); + + // Register an X pixmap with a known host_xid. + let x_pixmap_xid: u32 = 0x3000; + let host_xid_raw: u32 = 0xdead_5542; + state.resources.create_pixmap( + client_id, + yserver_protocol::x11::CreatePixmapRequest { + depth: 24, + pixmap: yserver_protocol::x11::ResourceId(x_pixmap_xid), + drawable: ROOT_WINDOW, + width: 64, + height: 64, + }, + ); + assert!( + state.resources.set_pixmap_host_xid( + yserver_protocol::x11::ResourceId(x_pixmap_xid), + crate::backend::PixmapHandle::from_raw(host_xid_raw).unwrap(), + ), + "set_pixmap_host_xid must succeed" + ); + + let glx_xid: u32 = 0x5000_0010; + let fbconfig: u32 = 0x101; + + // Build CreateGLXPixmapWithConfigSGIX body: + // [0..4] vendorCode = 65542 + // [4..8] pad1 = 0 + // [8..12] screen = 0 + // [12..16] fbconfig = 0x101 + // [16..20] pixmap = x_pixmap_xid + // [20..24] glxpixmap = glx_xid + let mut body = Vec::new(); + body.extend_from_slice(&x11glx::VENDOR_CODE_CREATE_GLX_PIXMAP_WITH_CONFIG_SGIX.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // pad1 + body.extend_from_slice(&0u32.to_le_bytes()); // screen + body.extend_from_slice(&fbconfig.to_le_bytes()); + body.extend_from_slice(&x_pixmap_xid.to_le_bytes()); + body.extend_from_slice(&glx_xid.to_le_bytes()); + + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("fits"); + + let outcome = process_request( + &mut state, + &mut backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 148, + data: x11glx::VENDOR_PRIVATE, + length_units, + }, + &body, + None, + ) + .expect("process_request must not hard-error"); + + assert!( + matches!(outcome, RequestOutcome::Handled), + "CreateGLXPixmapWithConfigSGIX must return Handled, got {outcome:?}" + ); + + // GlxDrawable must be inserted. + assert!( + state.glx_drawables.contains_key(&glx_xid), + "GlxDrawable must be inserted for glx_xid=0x{glx_xid:x}" + ); + let drawable = &state.glx_drawables[&glx_xid]; + assert_eq!(drawable.x_drawable, x_pixmap_xid, "x_drawable must be set"); + assert_eq!(drawable.fbconfig, fbconfig, "fbconfig must be recorded"); + assert_eq!( + drawable.glx_export_host_xid, + Some(host_xid_raw), + "host_xid must be stored for later release" + ); + + // acquire_glx_pixmap_export must have been called (same as CREATE_PIXMAP). + assert!( + backend + .calls() + .contains(&RecordedCall::AcquireGlxPixmapExport(host_xid_raw)), + "AcquireGlxPixmapExport must be recorded" + ); + + // No error packet. + peer.set_nonblocking(true).unwrap(); + let bytes = read_all_available(&mut peer); + assert!( + bytes.is_empty(), + "CreateGLXPixmapWithConfigSGIX must not deliver an error; got {bytes:02x?}" + ); + peer.set_nonblocking(false).unwrap(); +} + +/// After both dispatch and extension-string advertisement are live, +/// the computed GLX extension string must advertise +/// `GLX_SGIX_fbconfig` as a whole token, under both TFP settings. +/// +/// This test used to re-implement `glx_extension_string`'s body and +/// assert against its own copy, so it would have passed even if the +/// builder were deleted. It calls the real function now. +#[test] +fn glx_extension_string_contains_sgix_fbconfig() { + use yserver_protocol::x11::glx as x11glx; + for tfp_supported in [false, true] { + let s = glx_extension_string(tfp_supported); + assert!( + s.split_whitespace() + .any(|token| token == x11glx::SGIX_FBCONFIG_EXTENSION), + "glx_extension_string must advertise GLX_SGIX_fbconfig as a \ + whole token; tfp_supported={tfp_supported} produced {s:?}" + ); + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/input_control.rs b/crates/yserver-core/src/core_loop/process_request/tests/input_control.rs new file mode 100644 index 000000000..739a7a82a --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/input_control.rs @@ -0,0 +1,436 @@ +use super::*; + +/// Build a ChangeKeyboardControl body: mask + one u32 per set bit. +fn kbctrl_body(mask: u32, values: &[u32]) -> Vec { + let mut body = mask.to_le_bytes().to_vec(); + for v in values { + body.extend_from_slice(&v.to_le_bytes()); + } + body +} + +fn kbctrl_header() -> RequestHeader { + RequestHeader { + opcode: 102, + data: 0, + length_units: 2, + } +} + +#[test] +fn change_keyboard_control_stores_bell_fields() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + // key-click(0x01)=30, bell-percent(0x02)=80, bell-pitch(0x04)=528, + // bell-duration(0x08)=200 + let body = kbctrl_body(0x0f, &[30, 80, 528, 200]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + assert_eq!(state.keyboard_control.key_click_percent, 30); + assert_eq!(state.keyboard_control.bell_percent, 80); + assert_eq!(state.keyboard_control.bell_pitch, 528); + assert_eq!(state.keyboard_control.bell_duration, 200); +} + +#[test] +fn change_keyboard_control_minus_one_restores_defaults() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state.keyboard_control.bell_percent = 7; + state.keyboard_control.bell_pitch = 7; + let neg1 = 0xffff_ffffu32; + let body = kbctrl_body(0x0f, &[neg1, neg1, neg1, neg1]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + assert_eq!(state.keyboard_control.key_click_percent, 0); + assert_eq!(state.keyboard_control.bell_percent, 50); + assert_eq!(state.keyboard_control.bell_pitch, 400); + assert_eq!(state.keyboard_control.bell_duration, 100); +} + +#[test] +fn change_keyboard_control_led_without_mode_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // led(0x10)=3 without led-mode(0x20) → BadMatch (Xorg + // dix/devices.c:2121). + let body = kbctrl_body(0x10, &[3]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_MATCH); +} + +#[test] +fn change_keyboard_control_key_without_repeat_mode_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // key(0x40)=64 without auto-repeat-mode(0x80) → BadMatch + // (Xorg dix/devices.c:2158). + let body = kbctrl_body(0x40, &[64]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_MATCH); +} + +#[test] +fn change_keyboard_control_led_mask_bits() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + // led-mode On for leds 1, 20, 32 → bits 0, 19, 31. + for led in [1u32, 20, 32] { + let body = kbctrl_body(0x30, &[led, 1]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + } + assert_eq!(state.keyboard_control.led_mask, 0x8008_0001); + // led-mode Off with no led → all off. + let body = kbctrl_body(0x20, &[0]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + assert_eq!(state.keyboard_control.led_mask, 0); +} + +#[test] +fn change_keyboard_control_per_key_and_global_auto_repeat() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + // key=64 auto-repeat-mode=Off → clear bit (64>>3=8, bit 0). + let body = kbctrl_body(0xc0, &[64, 0]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + assert_eq!(state.keyboard_control.auto_repeats[8] & 0x01, 0); + // global auto-repeat Off (no key). + let body = kbctrl_body(0x80, &[0]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + assert!(!state.keyboard_control.global_auto_repeat); +} + +/// Xorg `DoChangeKeyboardControl` calls `XkbDisableComputedAutoRepeats` +/// for a per-key auto-repeat change: the key gets +/// `XkbExplicitAutoRepeatMask`, so a later mapping change leaves its bit +/// alone (`XkbUpdateDescActions`), while other keys' bits follow the +/// keymap and a change reports `XkbControlsNotify(PerKeyRepeat)`. +#[test] +fn per_key_auto_repeat_set_by_a_client_survives_a_mapping_change() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + crate::core_loop::xkb_select::xkb_select_events(&mut state, 1, 0x0100, 0x0008); + // key=64 auto-repeat-mode=On (already on by default). + let body = kbctrl_body(0xc0, &[64, 1]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + assert_eq!(state.keyboard_control.auto_repeats_explicit[8], 0x01); + let change = crate::backend::KeyboardMappingChange { + map_notify: x11::XkbMapNotify::default(), + num_groups: 1, + enabled_controls: 1, + repeats: vec![(64, false), (65, false)], + indicator_map_changed: 0, + indicator_state: 0, + compat_changed_groups: 0, + compat_total_si: 0, + }; + crate::core_loop::xkb_layout::apply_keyboard_mapping_repeats( + &mut state, + 85, + &change, + (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), + ); + assert_eq!( + state.keyboard_control.auto_repeats[8] & 0x03, + 0x01, + "64 keeps the client's bit, 65 follows the keymap" + ); + let ev = read_all_available(&mut peer); + assert_eq!(ev.len(), 32, "one ControlsNotify"); + assert_eq!((ev[0], ev[1]), (85, 3)); + assert_eq!(&ev[12..16], &0x4000_0000u32.to_le_bytes()); + + // Nothing changes: no event. + crate::core_loop::xkb_layout::apply_keyboard_mapping_repeats( + &mut state, + 85, + &change, + (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), + ); + assert!(read_all_available(&mut peer).is_empty()); +} + +/// SetModifierMapping through the dispatcher on a backend without an XKB +/// keymap (the fallback store); returns everything the client received. +fn set_modifier_mapping( + state: &mut ServerState, + peer: &mut UnixStream, + kpm: u8, + keys: &[u8], +) -> Vec { + let mut backend = RecordingBackend::new(); + process_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 118, + data: kpm, + length_units: u32::try_from(1 + keys.len() / 4).unwrap(), + }, + keys, + None, + ) + .expect("SetModifierMapping dispatch"); + read_all_or_buffered(state, 1, peer) +} + +/// Xorg `build_modmap_from_modkeymap`: a keycode listed twice is +/// BadValue with value 0 (golden `duplicate-keycode`), before the range +/// check; `check_modmap_change`: a keycode below 8 is BadValue with that +/// keycode, the lowest one (golden `keycode-out-of-range`). Nothing is +/// stored or notified. +#[test] +fn set_modifier_mapping_refusals_as_xorg() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let r = set_modifier_mapping(&mut state, &mut peer, 1, &[50, 0, 37, 0, 0, 0, 0, 50]); + assert_eq!(r.len(), 32); + assert_eq!((r[0], r[1]), (0, x11::error::BAD_VALUE), "{r:02x?}"); + assert_eq!(&r[4..8], &0u32.to_le_bytes(), "duplicate: value 0"); + + let r = set_modifier_mapping(&mut state, &mut peer, 1, &[50, 5, 37, 3, 0, 0, 0, 0]); + assert_eq!(r.len(), 32); + assert_eq!((r[0], r[1]), (0, x11::error::BAD_VALUE)); + assert_eq!(&r[4..8], &3u32.to_le_bytes(), "the lowest keycode below 8"); + assert_eq!(state.modifier_mapping_override, None); +} + +/// Xorg `check_modmap_change`: MappingBusy (reply status 1, nothing +/// applied, no MappingNotify) when a key of the new map is down or a key +/// of the old one is — golden `busy-held-key-changes`, +/// `busy-held-modifier-unchanged`, `busy-held-key-becomes-modifier`; a +/// held key that is in neither doesn't block (`held-nonmodifier- +/// unaffected`). Xorg's loop over the old modifiers stops before the +/// last keycode, so a held keycode 255 in the old map doesn't block. +#[test] +fn set_modifier_mapping_busy_as_xorg() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let old = [50u8, 0, 66, 0, 37, 0, 0, 255]; + let r = set_modifier_mapping(&mut state, &mut peer, 1, &old); + assert_eq!(r.len(), 64, "MappingNotify then the reply: {r:02x?}"); + assert_eq!(r[0] & 0x7f, 34); + assert_eq!((r[32], r[33]), (1, 0), "Success"); + + let press = |state: &mut ServerState, kc: u8, down: bool| { + if down { + state.keys_down[usize::from(kc >> 3)] |= 1 << (kc & 7); + } else { + state.keys_down[usize::from(kc >> 3)] &= !(1 << (kc & 7)); + } + }; + let new = [62u8, 0, 66, 0, 37, 0, 0, 0]; + // 50 held: an old modifier, not in the new map. + press(&mut state, 50, true); + let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); + assert_eq!(r.len(), 32, "only the reply: {r:02x?}"); + assert_eq!((r[0], r[1]), (1, 1), "MappingBusy"); + press(&mut state, 50, false); + // 62 held: a new modifier. + press(&mut state, 62, true); + let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); + assert_eq!((r.len(), r[1]), (32, 1), "MappingBusy"); + press(&mut state, 62, false); + assert_eq!(state.modifier_mapping_override, Some((1, old.to_vec()))); + // 38 held: neither. + press(&mut state, 38, true); + let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); + assert_eq!((r.len(), r[33]), (64, 0), "applied"); + press(&mut state, 38, false); + + // 255 held and in the old map only: not checked by Xorg. + let with_255 = [62u8, 0, 66, 0, 37, 0, 0, 255]; + let _ = set_modifier_mapping(&mut state, &mut peer, 1, &with_255); + press(&mut state, 255, true); + let r = set_modifier_mapping(&mut state, &mut peer, 1, &new); + assert_eq!((r.len(), r[33]), (64, 0), "held 255 doesn't block"); + assert_eq!(state.modifier_mapping_override, Some((1, new.to_vec()))); +} + +#[test] +fn change_keyboard_control_bad_value_does_not_commit() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // valid bell-percent(0x02)=80 staged, then key-click... order is + // mask-bit order: key-click(0x01)=101 (out of range) errors and + // nothing commits. + let body = kbctrl_body(0x03, &[101, 80]); + let _ = handle_change_keyboard_control( + &mut state, + ClientId(1), + SequenceNumber(1), + kbctrl_header(), + &body, + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert_eq!( + u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), + 101 + ); + assert_eq!(state.keyboard_control.bell_percent, 50, "no partial commit"); +} + +#[test] +fn get_keyboard_control_reflects_state() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.keyboard_control.key_click_percent = 21; + state.keyboard_control.bell_percent = 12; + state.keyboard_control.bell_pitch = 402; + state.keyboard_control.bell_duration = 222; + state.keyboard_control.global_auto_repeat = false; + state.keyboard_control.led_mask = 0x8008_000f; + let _ = handle_get_keyboard_control(&mut state, ClientId(1), SequenceNumber(1)); + let bytes = read_all_available(&mut peer); + // reply(0) global_auto_repeat(1) seq(2-3) len(4-7) led_mask(8-11) + // key_click(12) bell_pct(13) bell_pitch(14-15) bell_duration(16-17) + assert_eq!(bytes[0], 1); + assert_eq!(bytes[1], 0, "global_auto_repeat off"); + assert_eq!( + u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]), + 0x8008_000f + ); + assert_eq!(bytes[12], 21); + assert_eq!(bytes[13], 12); + assert_eq!(u16::from_le_bytes([bytes[14], bytes[15]]), 402); + assert_eq!(u16::from_le_bytes([bytes[16], bytes[17]]), 222); + assert_eq!(&bytes[20..52], &crate::server::DEFAULT_AUTO_REPEATS); +} + +#[test] +fn bell_out_of_range_percent_is_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let header = RequestHeader { + opcode: 104, + data: 101u8, // percent=101 (and -101 = 155u8 also invalid) + length_units: 1, + }; + let _ = handle_bell(&mut state, ClientId(1), SequenceNumber(1), header); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_VALUE); +} + +#[test] +fn change_pointer_control_stores_and_restores() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let header = RequestHeader { + opcode: 105, + data: 0, + length_units: 3, + }; + // accel 12/11, threshold 43, do_accel=1 do_thresh=1 + let body = [12, 0, 11, 0, 43, 0, 1, 1]; + let _ = + handle_change_pointer_control(&mut state, ClientId(1), SequenceNumber(1), header, &body); + assert_eq!(state.pointer_control.accel_numerator, 12); + assert_eq!(state.pointer_control.accel_denominator, 11); + assert_eq!(state.pointer_control.threshold, 43); + // -1 everywhere restores defaults 2/1, threshold 4. + let body = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, 1]; + let _ = + handle_change_pointer_control(&mut state, ClientId(1), SequenceNumber(1), header, &body); + assert_eq!(state.pointer_control.accel_numerator, 2); + assert_eq!(state.pointer_control.accel_denominator, 1); + assert_eq!(state.pointer_control.threshold, 4); +} + +#[test] +fn change_pointer_control_zero_denominator_is_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let header = RequestHeader { + opcode: 105, + data: 0, + length_units: 3, + }; + // denominator 0 → BadValue (Xorg dix/devices.c:2362 `<= 0`). + let body = [2, 0, 0, 0, 4, 0, 1, 0]; + let _ = + handle_change_pointer_control(&mut state, ClientId(1), SequenceNumber(1), header, &body); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert_eq!( + state.pointer_control.accel_numerator, 2, + "no partial commit" + ); +} + +#[test] +fn get_pointer_control_reflects_state() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.pointer_control.accel_numerator = 34; + state.pointer_control.accel_denominator = 35; + state.pointer_control.threshold = 36; + let _ = handle_get_pointer_control(&mut state, ClientId(1), SequenceNumber(1)); + let bytes = read_all_available(&mut peer); + // reply(0) pad(1) seq(2-3) len(4-7) accel_num(8-9) accel_den(10-11) + // threshold(12-13) + assert_eq!(u16::from_le_bytes([bytes[8], bytes[9]]), 34); + assert_eq!(u16::from_le_bytes([bytes[10], bytes[11]]), 35); + assert_eq!(u16::from_le_bytes([bytes[12], bytes[13]]), 36); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs new file mode 100644 index 000000000..7ad20b636 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs @@ -0,0 +1,1360 @@ +mod access_grabs; +mod access_properties; +mod access_resources; +mod composite; +mod core_misc; +mod damage_ext; +mod drawing; +mod dri3_shm; +mod expose_probe; +mod extensions; +mod fonts; +mod gc_pixmap; +mod glx; +mod input_control; +mod present_pixmap; +mod present_supersede; +mod props; +mod randr_crtc; +mod randr_output; +mod region_probe; +mod render; +mod saver_dpms; +mod selection; +mod sync; +mod vidmode; +mod window; +mod xfixes_shape; +mod xi1; +mod xi2; +mod xi2_allow; +mod xi2_grabs; +mod xi_config; +mod xi_hotplug; +mod xkb; +use std::{ + collections::{HashMap, HashSet, VecDeque}, + io::Read, + os::unix::net::UnixStream, + sync::{Arc, Mutex, atomic::AtomicU16}, +}; + +use yserver_protocol::x11::{ + ClientByteOrder, ClientId, CreateGcRequest, CreatePixmapRequest, CreateWindowRequest, + RequestHeader, ResourceId, SequenceNumber, screensaver as x11screensaver, sync as x11sync, +}; + +use super::{window_destroy::destroy_window_subtree, *}; +use crate::{ + backend::{ + FillStyle, + recording::{RecordedCall, RecordingBackend}, + }, + resources::ROOT_WINDOW, + server::{ClientState, ScreenSaverActive, ServerState}, + xinput::XI2_PROPERTY_EVENT_MASK, +}; +use yserver_protocol::x11::AtomId; + +fn seed_present_clock(state: &mut ServerState, msc: u64, ust: u64) { + seed_present_domain_clock(state, 0, 0, msc, ust); +} + +fn seed_present_domain_clock( + state: &mut ServerState, + crtc_id: u32, + crtc_epoch: u64, + msc: u64, + ust: u64, +) { + let completion = crate::backend::PresentClockSample { + msc, + ust, + source: crate::backend::PresentClockSource::PageFlip, + }; + state.present_crtc_clocks.insert( + (crtc_id, crtc_epoch), + crate::server::PresentCrtcClock { + epoch: crtc_epoch, + msc, + ust, + completion, + }, + ); +} + +fn create_present_test_window( + state: &mut ServerState, + xid: u32, + x: i16, + y: i16, + width: u16, + height: u16, +) { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x, + y, + width, + height, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); +} + +fn install_client_with_transport( + state: &mut ServerState, + id: u32, + transport: crate::transport::Transport, +) { + // SAFETY: plain getters with no preconditions. + let (euid, egid) = unsafe { (libc::geteuid(), libc::getegid()) }; + state.clients.insert( + id, + ClientState { + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(transport)), + byte_order: ClientByteOrder::LittleEndian, + last_sequence: Arc::new(AtomicU16::new(0)), + // Permissive resource-id range so tests driving + // `process_request` can use arbitrary non-zero + // resource xids without tripping + // `xid_out_of_client_range`. Real clients get a + // tight base/mask from the connection handshake; + // this is the test-fixture analogue of "every xid + // is in range". + resource_id_base: 0, + resource_id_mask: u32::MAX, + event_masks: HashMap::new(), + save_set: HashSet::new(), + big_requests_enabled: false, + xi2_masks: HashMap::new(), + xi1_event_classes: HashSet::new(), + xi1_window_event_classes: HashMap::new(), + outbound: VecDeque::new(), + outbound_fds: Default::default(), + watching_writable: false, + write_failed: false, + gone: false, + focused_window: ROOT_WINDOW, + reader_control: None, + is_local: true, + fd_passing: true, + internal: false, + // A local peer with this process's credentials, so request + // tests do not depend on per-OS socket APIs (`peer.rs` tests + // those). + peer: crate::peer::PeerIdentity { + transport: crate::core_loop::auth::AuthTransport::Unix, + addr: None, + cred: Some(crate::peer::PeerCred { + uid: euid, + gid: egid, + pid: Some(std::process::id()), + }), + }, + }, + ); +} + +fn install_client(state: &mut ServerState, id: u32) -> UnixStream { + let (writer, peer) = UnixStream::pair().unwrap(); + install_client_with_transport(state, id, crate::transport::Transport::Unix(writer)); + peer +} + +fn install_capture_client(state: &mut ServerState, id: u32) -> crate::transport::CapturedPeer { + let (transport, peer) = crate::transport::Transport::capture_pair(); + install_client_with_transport(state, id, transport); + peer +} + +trait TestPeer: Read { + fn set_nonblocking(&mut self, nonblocking: bool) -> io::Result<()>; +} + +impl TestPeer for UnixStream { + fn set_nonblocking(&mut self, nonblocking: bool) -> io::Result<()> { + UnixStream::set_nonblocking(self, nonblocking) + } +} + +impl TestPeer for crate::transport::CapturedPeer { + fn set_nonblocking(&mut self, nonblocking: bool) -> io::Result<()> { + crate::transport::CapturedPeer::set_nonblocking(self, nonblocking) + } +} + +fn set_test_pointer_grab( + state: &mut ServerState, + owner: u32, + window: u32, + passive: bool, + via_xi2: bool, +) { + state.set_pointer_grab(crate::server::ActivePointerGrab { + owner: ClientId(owner), + grab_window: ResourceId(window), + event_mask: u16::MAX, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2, + implicit: false, + passive, + xi2_mask: if via_xi2 { u64::MAX } else { 0 }, + }); +} + +fn read_all_available(peer: &mut impl TestPeer) -> Vec { + peer.set_nonblocking(true).expect("set_nonblocking"); + let mut out = Vec::new(); + let mut buf = [0u8; 512]; + loop { + match peer.read(&mut buf) { + Ok(0) => break, + Ok(n) => out.extend_from_slice(&buf[..n]), + Err(err) if err.kind() == io::ErrorKind::WouldBlock => break, + Err(err) => panic!("read failed: {err}"), + } + } + peer.set_nonblocking(false).expect("unset_nonblocking"); + out +} + +fn read_all_or_buffered(state: &mut ServerState, client_id: u32, peer: &mut UnixStream) -> Vec { + let mut out = read_all_available(peer); + let client = state.clients.get_mut(&client_id).expect("test client"); + out.extend(client.outbound.drain(..)); + out +} + +fn poly_fill_rectangle_body(drawable: u32, gc: u32) -> Vec { + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&drawable.to_le_bytes()); + body.extend_from_slice(&gc.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body +} + +fn free_pixmap_body(pixmap: u32) -> Vec { + pixmap.to_le_bytes().to_vec() +} + +/// Wire body for a ConfigureWindow request: window, value_mask, the +/// 2-byte request pad, then one CARD32 per set value-mask bit in bit +/// order (x,y,w,h,border,sibling,stack_mode). +fn cw_restack_body(window: u32, value_mask: u16, values: &[u32]) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&value_mask.to_le_bytes()); + body.extend_from_slice(&[0u8, 0u8]); // request pad + for v in values { + body.extend_from_slice(&v.to_le_bytes()); + } + body +} + +/// Two children (0x200 created first, then 0x300 → 0x300 ends on top) +/// under root, plus client 1's drained peer socket. +fn two_children_under_root() -> (ServerState, UnixStream) { + let mut state = ServerState::new(); + let peer = install_client(&mut state, 1); + for id in [0x200u32, 0x300u32] { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(id), + parent: ROOT_WINDOW, + width: 50, + height: 50, + ..Default::default() + }, + ); + } + (state, peer) +} + +/// Extract the `mode` byte (wire offset 11) of every Present +/// `CompleteNotify` in a raw byte stream, in wire order — an +/// emit_idle-independent delivery-order oracle for tests mixing Copy +/// and Skip (Skip's gated `signal_present_wake` means +/// `RecordingBackend::signalled_present_wakes` alone can't order +/// them). Callers must select ONLY `EVENT_MASK_COMPLETE_NOTIFY` (no +/// `IdleNotify`/`ConfigureNotify`), so every event in the stream is a +/// fixed 40-byte `CompleteNotify` and the chunking can't desync. +fn complete_notify_modes(bytes: &[u8]) -> Vec { + bytes + .chunks(40) + .map(|chunk| { + assert_eq!(chunk.len(), 40, "truncated CompleteNotify"); + assert_eq!(chunk[0], 35, "GenericEvent"); + assert_eq!(chunk[1], 145, "PRESENT major opcode"); + chunk[11] + }) + .collect() +} + +/// A request body in the client's byte order. +struct WireBody(ClientByteOrder, Vec); + +impl WireBody { + fn u32(mut self, v: u32) -> Self { + match self.0 { + ClientByteOrder::LittleEndian => self.1.extend_from_slice(&v.to_le_bytes()), + ClientByteOrder::BigEndian => self.1.extend_from_slice(&v.to_be_bytes()), + } + self + } + fn u16(mut self, v: u16) -> Self { + match self.0 { + ClientByteOrder::LittleEndian => self.1.extend_from_slice(&v.to_le_bytes()), + ClientByteOrder::BigEndian => self.1.extend_from_slice(&v.to_be_bytes()), + } + self + } + fn bytes(mut self, v: &[u8]) -> Self { + self.1.extend_from_slice(v); + self + } +} + +mod x11randr_minor { + pub const SET_MONITOR: u8 = yserver_protocol::x11::randr::RR_SET_MONITOR; + pub const DELETE_MONITOR: u8 = yserver_protocol::x11::randr::RR_DELETE_MONITOR; +} + +fn rr_scale(word: i32) -> [i32; 9] { + [word, 0, 0, 0, word, 0, 0, 0, 0x0001_0000] +} +const MUFFIN_2_0: i32 = 131_072; + +fn host_frees(backend: &RecordingBackend) -> Vec { + let mut out: Vec = backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::FreePixmap(xid) => Some(*xid), + _ => None, + }) + .collect(); + out.sort_unstable(); + out +} + +/// Drive one XI request through the core dispatcher and return its wire +/// reply. The actual XInput extension major opcode is 137; `minor` is the +/// XI 1.x / XI2 request number in the data byte. +fn dispatch_xi_request_wire( + state: &mut ServerState, + peer: &mut UnixStream, + sequence: u16, + minor: u8, + body: &[u8], +) -> Vec { + dispatch_wire_request(state, peer, sequence, XI2_MAJOR_OPCODE, minor, body) +} + +/// Drive any core or extension request through `process_request` and +/// return the bytes written for it. +fn dispatch_wire_request( + state: &mut ServerState, + peer: &mut UnixStream, + sequence: u16, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + let mut backend = RecordingBackend::new(); + process_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("request through core dispatcher"); + read_all_available(peer) +} + +/// Read-only XI replies must leave the registry, holds, floating state, +/// property maps, and every client selection unchanged. +fn xi_query_side_effect_snapshot(state: &ServerState, client_id: u32) -> String { + let client = &state.clients[&client_id]; + format!( + "registry={:?}; keys={:?}; buttons={}; device_buttons={:?}; \ + detached={:?}; floating={:?}; properties={:?}; selections={:?}", + state.xi_devices, + state.keys_down, + state.buttons_down, + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down)) + .collect::>(), + state.xi2_detached_masters, + state.floating_pointer_positions, + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, &device.properties)) + .collect::>(), + ( + &client.event_masks, + &client.xi2_masks, + &client.xi1_event_classes, + &client.xi1_window_event_classes, + ), + ) +} + +// ----------------------------------------------------------------- +// Tier 2 Task 3: XI2 device-property requests (dispatch-level, wire bytes) +// ----------------------------------------------------------------- + +/// Header for an XI2 (major 131) request with the given minor opcode. +fn xi2_header(minor: u8) -> RequestHeader { + // Declare the spec-correct request length so the dispatcher's + // REQUEST_SIZE_MATCH gate (validate_xi_request_length) doesn't + // BadLength the request before it reaches the handler. These + // fixtures pre-date that XTS-driven length gate and used a + // placeholder length_units=1; for Fixed-size minors the table + // value IS the exact wire length, for variable minors it is the + // spec minimum (payload-carrying variable requests build their + // own header — see xi2_header_for_body). + use yserver_protocol::x11::request_lengths::{LenSpec, xi_request_length}; + let length_units = match xi_request_length(minor) { + Some(LenSpec::Fixed(n) | LenSpec::AtLeast(n)) => n, + None => 1, + }; + RequestHeader { + opcode: 131, + data: minor, + length_units, + } +} + +/// Header for a variable-length XI minor whose body carries a payload +/// (e.g. XIChangeProperty value bytes): the exact-length gate requires +/// `length_units` to match the actual body, so derive it from `body`. +fn xi2_header_for_body(minor: u8, body: &[u8]) -> RequestHeader { + RequestHeader { + opcode: 131, + data: minor, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap_or(1), + } +} + +/// Seed the XTEST pointer (id 4) with one INTEGER/8 property +/// keyed by a synthetic atom whose numeric id is supplied by the +/// caller. The atom is registered into `state.atoms` so it passes +/// the T3 BadAtom guard in the property dispatch arms — historical +/// test fixtures pass 100/200, which sit outside the well-known +/// range and would otherwise look "uninterned" to the dispatcher. +fn seed_one_prop(state: &mut ServerState, atom: u32, format: u8, data: Vec) { + state + .atoms + .register_for_test(AtomId(atom), &format!("test-prop-{atom}")); + let dev = state + .xi_devices + .device_mut(crate::xinput::DEVICEID_XTEST_POINTER) + .expect("XTEST pointer"); + dev.properties.insert( + AtomId(atom), + crate::xinput::XiProperty { + type_atom: crate::xinput::XA_INTEGER, + format, + data, + read_only: false, + deletable: true, + }, + ); +} + +// ----------------------------------------------------------------- +// T3 dispatch: validate→apply→commit + BadAtom/BadAccess/BadValue. +// These exercise the new descriptor-aware path against a seeded +// touchpad; the recording backend's default `apply_device_config` +// returns `Ok(())`, so successful writes commit to the registry. +// ----------------------------------------------------------------- + +/// Build an `xXIChangePropertyReq` body (after the 4-byte generic +/// header): deviceid(2), mode(1), format(1), property(4), type(4), +/// num_items(4), value(num_items * format/8). The caller is +/// responsible for any 4-byte pad on the wire — the body slice we +/// hand to `handle_xi2_request` doesn't need it because each test +/// passes the raw data block directly. +fn xi2_change_property_body( + deviceid: u16, + mode: u8, + format: u8, + property: u32, + type_atom: u32, + data: &[u8], +) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&deviceid.to_le_bytes()); + body.push(mode); + body.push(format); + body.extend_from_slice(&property.to_le_bytes()); + body.extend_from_slice(&type_atom.to_le_bytes()); + let num_items = data.len() / usize::from(format / 8); + body.extend_from_slice(&(num_items as u32).to_le_bytes()); + body.extend_from_slice(data); + // 4-byte pad on the value tail. + while body.len() % 4 != 0 { + body.push(0); + } + body +} + +const TEST_PHYSICAL_POINTER_ID: u16 = 6; + +/// Register a source and return its registry-owned pointer facet for +/// property dispatch fixtures. +fn seed_physical_pointer_fixture( + state: &mut ServerState, + info: &crate::core_loop::DeviceInfo, +) -> u16 { + state + .xi_register_source(info) + .into_iter() + .find(|id| { + state.xi_devices.device(*id).is_some_and(|device| { + device.facet == Some(crate::xinput::XiFacetKind::PointerTouch) + }) + }) + .expect("test source publishes a pointer facet") +} + +/// Seed a touchpad on physical XI ID 6 with tap available+current+default. +/// Mirrors the MATE test fixture without using virtual XTEST device 4. +fn seed_pointer_for_t3(state: &mut ServerState) -> u16 { + let info = crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(u64::from(line!())), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: "SynPS/2 Synaptics TouchPad".into(), + device_node: "/dev/input/event4".into(), + sysname: "event4".into(), + vendor_id: 0x046d, + product_id: 0xc52f, + is_touchpad: true, + config: crate::core_loop::message::LibinputConfigSnapshot { + tap: crate::core_loop::message::BoolSetting { + available: true, + current: true, + default: false, + }, + natural_scroll: crate::core_loop::message::BoolSetting { + available: true, + current: false, + default: true, + }, + dwt: crate::core_loop::message::BoolSetting { + available: true, + current: true, + default: true, + }, + scroll_method: crate::core_loop::message::OneHot3 { + available_mask: 0b111, + current: Some(0), + default: Some(0), + }, + accel: crate::core_loop::message::FloatSetting { + available: true, + current: 0.0, + default: 0.0, + }, + scroll_button: crate::core_loop::message::U32Setting { + available: true, + current: 0, + default: 0, + }, + accel_profile: crate::core_loop::message::OneHot2 { + available: true, + current: Some(0), + default: Some(0), + }, + accel_profile_available_mask: 0b011, + ..Default::default() + }, + }; + seed_physical_pointer_fixture(state, &info) +} + +fn inventory_for_t3_source( + state: &ServerState, +) -> ( + crate::core_loop::input_inventory::InputInventory, + crate::xinput::InputSourceId, +) { + let source = state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .and_then(|device| device.source_id) + .expect("physical pointer source"); + let mut inventory = crate::core_loop::input_inventory::InputInventory::new(); + inventory.add( + state + .xi_devices + .source(source) + .expect("source facts") + .clone(), + ); + (inventory, source) +} + +fn route_t3_config_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + inventory: &mut crate::core_loop::input_inventory::InputInventory, + pending: &mut crate::core_loop::run::PendingBackendRequests, + lane: &mut crate::core_loop::run::XiConfigLane, + request: crate::core_loop::message::XiConfigRequest, +) { + crate::core_loop::run::route_pending_xi_config( + state, + backend, + inventory, + pending, + lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + request, + 32, + crate::core_loop::generation::Generation::default(), + ); +} + +fn xi_property_snapshot( + state: &ServerState, +) -> Vec<( + u16, + std::collections::BTreeMap, +)> { + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.properties.clone())) + .collect() +} + +/// Parse a recognized XI1/XI2 write, prove parsing has no side effects, +/// and then drive the production core lane. This is the shared route for +/// the migrated property-dispatch tests. +fn drive_t3_config_wire_request( + state: &mut ServerState, + peer: &mut impl TestPeer, + backend: &mut RecordingBackend, + inventory: &mut crate::core_loop::input_inventory::InputInventory, + pending: &mut crate::core_loop::run::PendingBackendRequests, + lane: &mut crate::core_loop::run::XiConfigLane, + client: u32, + sequence: u16, + header: RequestHeader, + body: &[u8], +) -> crate::core_loop::message::XiConfigRequest { + let properties_before = xi_property_snapshot(state); + let calls_before = backend.started_device_configs.len(); + let outcome = handle_xi2_request( + state, + backend, + None, + ClientId(client), + SequenceNumber(sequence), + header, + body, + ) + .expect("parse XI property request"); + let RequestOutcome::PendingXiConfig(request) = outcome else { + panic!("recognized physical write must return PendingXiConfig, got {outcome:?}"); + }; + assert_eq!( + xi_property_snapshot(state), + properties_before, + "parsing does not mutate XI properties" + ); + assert_eq!( + backend.started_device_configs.len(), + calls_before, + "parsing does not call the backend" + ); + assert!( + read_all_available(peer).is_empty(), + "parsing produces no reply, error, or property notification" + ); + let captured = request.clone(); + route_t3_config_request(state, backend, inventory, pending, lane, request); + captured +} + +fn assert_xi_config_error(wire: &[u8], code: u8, sequence: u16, minor_opcode: u16) { + assert_eq!(wire.len(), 32, "one X error packet"); + assert_eq!(wire[0], 0, "X_Error"); + assert_eq!(wire[1], code, "error code"); + assert_eq!( + u16::from_le_bytes([wire[2], wire[3]]), + sequence, + "original request sequence" + ); + assert_eq!( + u16::from_le_bytes([wire[8], wire[9]]), + minor_opcode, + "original XI minor opcode" + ); + assert_eq!(wire[10], 137, "XInput extension major opcode"); +} + +fn assert_confirmed_tap_write( + state: &ServerState, + inventory: &crate::core_loop::input_inventory::InputInventory, + source: crate::xinput::InputSourceId, + property: AtomId, +) { + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&property] + .data, + [0], + "confirmed tap write commits the requested XI bytes" + ); + assert!(!inventory.get(source).unwrap().config.tap.current); +} + +// ----------------------------------------------------------------- +// XI2 XI_PropertyEvent fan-out on change / delete / get(delete=1). +// The dispatch arm must wire `emit_property_change` into all six +// property-write sites so every client that selected +// `XI_PropertyEventMask` on the affected device receives a +// 32-byte XI2 GenericEvent (evtype 12) with the right `what` byte. +// ----------------------------------------------------------------- + +/// Scan a wire buffer for the first XI2 GenericEvent (`type == 35`) +/// of evtype 12 (XI_PropertyEvent) and return the 32-byte slice +/// pointing at the event header. Used by the T5 tests below; we +/// can't anchor at offset 0 because some arms emit a reply (e.g. +/// `XIGetProperty(delete=1)`) before the event. +/// +/// Window: `0..=wire.len()-32` (inclusive) so a 32-byte buffer +/// matches at offset 0. +fn find_xi2_property_event(wire: &[u8]) -> Option<&[u8]> { + let end = wire.len().checked_sub(32)?; + (0..=end).find_map(|i| { + (wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 12) + .then(|| &wire[i..i + 32]) + }) +} + +/// Subscribe `client_id` to `XI_PropertyEventMask` for one device at +/// the root window — the selection MATE / GDK make after learning its id. +fn select_xi2_property_event_on_root(state: &mut ServerState, client_id: u32, deviceid: u16) { + state + .clients + .get_mut(&client_id) + .expect("client installed") + .xi2_masks + .insert((ROOT_WINDOW, deviceid), u64::from(XI2_PROPERTY_EVENT_MASK)); +} + +fn xi_hotplug_dispatch( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + opcode: u8, + minor: u8, + body: &[u8], +) { + let header = RequestHeader { + opcode, + data: minor, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap_or(1), + }; + let outcome = process_request( + state, + backend, + ClientId(client), + SequenceNumber(sequence), + header, + body, + None, + ) + .expect("hotplug test request dispatch"); + assert!( + matches!(outcome, RequestOutcome::Handled), + "hotplug request should complete synchronously: {outcome:?}" + ); +} + +fn xi_hotplug_create_window_body(window: u32, parent: u32) -> Vec { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&parent.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); // x + body.extend_from_slice(&0i16.to_le_bytes()); // y + body.extend_from_slice(&32u16.to_le_bytes()); // width + body.extend_from_slice(&32u16.to_le_bytes()); // height + body.extend_from_slice(&0u16.to_le_bytes()); // border_width + body.extend_from_slice(&0u16.to_le_bytes()); // CopyFromParent class + body.extend_from_slice(&0u32.to_le_bytes()); // CopyFromParent visual + body.extend_from_slice(&0u32.to_le_bytes()); // no attributes + body +} + +/// Build an `xSelectExtensionEventReq` body (the bytes after the +/// 4-byte X request header) for a single XEventClass list. +fn xi1_select_extension_event_body(window: u32, classes: &[u32]) -> Vec { + let mut body = Vec::with_capacity(8 + classes.len() * 4); + body.extend_from_slice(&window.to_le_bytes()); // window + #[allow(clippy::cast_possible_truncation)] + let count = classes.len() as u16; + body.extend_from_slice(&count.to_le_bytes()); // count + body.extend_from_slice(&0u16.to_le_bytes()); // pad + for c in classes { + body.extend_from_slice(&c.to_le_bytes()); + } + body +} + +fn read_error(buf: &[u8]) -> u8 { + // X error: type=0, error-code at byte 1. + assert_eq!(buf[0], 0, "expected an X error, got type {}", buf[0]); + buf[1] +} + +fn create_root_child(state: &mut ServerState, window: u32) { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); +} + +/// A minimal `PendingPresentEntry` for `present_pending_exec`, only +/// carrying what the Task 6 hold-back tests below need: which window +/// it targets. Everything else is inert filler. +fn stub_pending_present_entry(window: u32, present_id: u64) -> crate::server::PendingPresentEntry { + use crate::server::{PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest}; + use yserver_protocol::x11::present::PixmapRequest; + + PendingPresentEntry { + pending: PendingPresentPixmap { + origin: None, + client_id: ClientId(1), + request: PendingPresentRequest::Pixmap(PixmapRequest { + window, + pixmap: 0x1, + serial: 1, + valid: 0, + update: 0, + x_off: 0, + y_off: 0, + target_crtc: 0, + wait_fence: 0, + idle_fence: 0, + options: 0, + target_msc: 0, + divisor: 0, + remainder: 0, + notifies: Vec::new(), + }), + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + masked_options: 0, + src_host_xid: 0x2, + // Deliberately DISTINCT from `window` (the client-visible + // XID the blocked-check keys on via `request.window()`): + // if a future edit mistakenly keyed the hold-back off a + // host-xid field instead, these tests must fail rather + // than pass by accident on identical values. + paint_dst_host_xid: window | 0x0040_0000, + completion_dst_host_xid: window | 0x0040_0000, + src_width: 1, + src_height: 1, + update_rects: None, + present_id, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: None, + }, + source_ready: false, + superseded_by_executed_present_id: None, + wait_id: None, + pin: None, + } +} + +/// Builds a minimal `PendingPresentEntry` for the msc-due tests below — +/// deliberately distinct host xids for source/dest (window_host_xid | +/// 0 stays the "destination", pixmap_host_xid the "source") so a +/// `CopyArea` assertion can't pass by coincidence. +fn present_pending_entry_with( + present_id: u64, + window_host_xid: u32, + pixmap_host_xid: u32, + effective_target_msc: Option, + source_ready: bool, +) -> crate::server::PendingPresentEntry { + use crate::server::{PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest}; + use yserver_protocol::x11::present::PixmapRequest; + + PendingPresentEntry { + pending: PendingPresentPixmap { + origin: None, + client_id: ClientId(1), + request: PendingPresentRequest::Pixmap(PixmapRequest { + window: window_host_xid, + pixmap: pixmap_host_xid, + serial: 1, + valid: 0, + update: 0, + x_off: 0, + y_off: 0, + target_crtc: 0, + wait_fence: 0, + idle_fence: 0, + options: 0, + target_msc: 0, + divisor: 0, + remainder: 0, + notifies: Vec::new(), + }), + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + masked_options: 0, + src_host_xid: pixmap_host_xid, + paint_dst_host_xid: window_host_xid, + completion_dst_host_xid: window_host_xid, + src_width: 4, + src_height: 4, + update_rects: None, + present_id, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc, + }, + source_ready, + superseded_by_executed_present_id: None, + wait_id: None, + pin: Some(present_id), // distinct-ish pin id for release assertions + } +} + +// ===================================================================== +// Task 8: supersession (coverage-gated scrap + parked Skip) and the +// copy-failure reroute. Spec §Supersession + §"Ordered completion +// delivery"; plan `docs/superpowers/plans/ +// 2026-08-01-present-deferred-execution-supersession.md` Task 8. +// ===================================================================== + +use yserver_protocol::x11::xfixes; + +/// Full-control `PendingPresentPixmap`/`PendingPresentEntry` builder +/// for the Task 8 tests below — unlike `stub_pending_present_entry` +/// (window/present_id only) and `present_pending_entry_with` +/// (window/pixmap host xids/eff/source_ready only), these tests need +/// to vary geometry, update region, and wake identity (`Pixmap` +/// idle_fence vs `PixmapSynced` release syncobj). +#[derive(Clone)] +struct SupersessionFixture { + present_id: u64, + window: u32, + effective_target_msc: Option, + x_off: i16, + y_off: i16, + src_width: u16, + src_height: u16, + update_rects: Option>, + /// The wire `update` field (an XFixes region XID or 0) — + /// independent of `update_rects` (the server-resolved rects, or + /// `None` when the region was unresolvable). Task 13: needed to + /// exercise `execute_present_pixmap_copy`'s damage arm with + /// `update != 0` + `update_rects == None` (unresolvable region). + update: u32, + idle_fence: u32, + synced_release: Option<(u32, u64)>, +} + +impl SupersessionFixture { + fn new(present_id: u64, window: u32) -> Self { + Self { + present_id, + window, + effective_target_msc: Some(100), + x_off: 0, + y_off: 0, + src_width: 100, + src_height: 100, + update_rects: None, + update: 0, + idle_fence: 0, + synced_release: None, + } + } + + fn eff(mut self, eff: Option) -> Self { + self.effective_target_msc = eff; + self + } + + fn geometry(mut self, x_off: i16, y_off: i16, src_width: u16, src_height: u16) -> Self { + self.x_off = x_off; + self.y_off = y_off; + self.src_width = src_width; + self.src_height = src_height; + self + } + + fn update_rects(mut self, rects: Option>) -> Self { + self.update_rects = rects; + self + } + + fn update(mut self, update: u32) -> Self { + self.update = update; + self + } + + fn idle_fence(mut self, fence: u32) -> Self { + self.idle_fence = fence; + self + } + + fn synced_release(mut self, release_syncobj: u32, release_value: u64) -> Self { + self.synced_release = Some((release_syncobj, release_value)); + self + } + + fn pending(&self) -> crate::server::PendingPresentPixmap { + use crate::server::{PendingPresentPixmap, PendingPresentRequest}; + use yserver_protocol::x11::present::{PixmapRequest, PixmapSyncedRequest}; + + let request = if let Some((release_syncobj, release_value)) = self.synced_release { + PendingPresentRequest::PixmapSynced(PixmapSyncedRequest { + window: self.window, + pixmap: 0x1, + serial: 1, + valid: 0, + update: self.update, + x_off: self.x_off, + y_off: self.y_off, + target_crtc: 0, + acquire_syncobj: 0, + release_syncobj, + acquire_value: 0, + release_value, + options: 0, + target_msc: 0, + divisor: 0, + remainder: 0, + notifies: Vec::new(), + }) + } else { + PendingPresentRequest::Pixmap(PixmapRequest { + window: self.window, + pixmap: 0x1, + serial: 1, + valid: 0, + update: self.update, + x_off: self.x_off, + y_off: self.y_off, + target_crtc: 0, + wait_fence: 0, + idle_fence: self.idle_fence, + options: 0, + target_msc: 0, + divisor: 0, + remainder: 0, + notifies: Vec::new(), + }) + }; + + PendingPresentPixmap { + origin: None, + client_id: ClientId(1), + request, + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: self.idle_fence, + }, + masked_options: 0, + src_host_xid: 0x2, + paint_dst_host_xid: self.window | 0x0040_0000, + completion_dst_host_xid: self.window | 0x0040_0000, + src_width: self.src_width, + src_height: self.src_height, + update_rects: self.update_rects.clone(), + present_id: self.present_id, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: self.effective_target_msc, + } + } + + fn entry(&self) -> crate::server::PendingPresentEntry { + crate::server::PendingPresentEntry { + pending: self.pending(), + source_ready: true, + superseded_by_executed_present_id: None, + wait_id: None, + pin: None, + } + } +} + +// ---------------- Stage 4d gate: COW host_xid wiring ---------------- +// +// Marco-with-compositing uses **pure PRESENT-pixmap onto COW** with zero +// `RedirectSubwindows` / `NameWindowPixmap` calls — it repeatedly emits +// `PRESENT::Pixmap(window=0x103 /* COW */, pixmap=client_offscreen)`. +// +// `process_present_pixmap` resolves both endpoints via +// `state.resources.host_drawable_target(...)`, which returns `None` when +// `window.host_xid` is `None`. Stage 4d allocated COW storage on the +// backend (`KmsBackend.cow_id`) and registered with the scene, but +// left `host_xid` `None` on the yserver-core resource record (seeded +// that way at `ResourceTable::new` since the COW xid pre-exists the +// backend-side allocation). Every `PresentPixmap → COW` therefore +// silently fell through the `if let (Some, Some)` guard at +// `process_request.rs:~4124` and dropped paint. +// +// Fix: on the GET_OVERLAY_WINDOW arm, after the backend hook lands +// successfully, wire `host_xid = Some(0x103)` and copy root dimensions +// onto the COW resource record. On the final RELEASE_OVERLAY_WINDOW, +// destroy the record so the next GET re-wires fresh storage. +// +// These tests use `RecordingBackend`. Which release is final is +// decided by core's claim list (`ServerState::cow_claims`), not by +// the backend — the backend counts nothing. + +fn dispatch_composite_minor( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + client_id: ClientId, + sequence: u16, + minor: u8, + body: &[u8], +) -> RequestOutcome { + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + process_request( + state, + backend, + client_id, + SequenceNumber(sequence), + RequestHeader { + opcode: 144, // COMPOSITE + data: minor, + length_units, + }, + body, + None, + ) + .unwrap() +} + +fn xi_dynamic_grab_source( + state: &mut ServerState, + source: u64, + keyboard: bool, + pointer: bool, + name: &str, +) -> (crate::xinput::InputSourceId, u16) { + let source_id = crate::xinput::InputSourceId(source); + let info = crate::core_loop::DeviceInfo { + source_id, + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard, + pointer, + touch: false, + }, + name: name.to_owned(), + device_node: format!("/dev/input/{name}"), + sysname: name.to_owned(), + vendor_id: 0, + product_id: 0, + is_touchpad: false, + config: crate::core_loop::message::LibinputConfigSnapshot::default(), + }; + let facet = if keyboard { + crate::xinput::XiFacetKind::Keyboard + } else { + crate::xinput::XiFacetKind::PointerTouch + }; + let ids = state.xi_register_source(&info); + let device_id = ids + .into_iter() + .find(|id| { + state + .xi_devices + .device(*id) + .is_some_and(|device| device.facet == Some(facet)) + }) + .expect("requested physical facet was registered"); + (source_id, device_id) +} + +/// Split queued 32-byte packets (errors, events, fixed replies). +fn wire_packets(peer: &mut UnixStream) -> Vec<[u8; 32]> { + read_all_available(peer) + .chunks_exact(32) + .map(|c| <[u8; 32]>::try_from(c).unwrap()) + .collect() +} + +fn le_u32(p: &[u8], at: usize) -> u32 { + u32::from_le_bytes(p[at..at + 4].try_into().unwrap()) +} + +/// Error packet → (code, bad value, minor, major). +fn error_fields(p: &[u8; 32]) -> (u8, u32, u16, u8) { + assert_eq!(p[0], 0, "expected an error packet, got type {}", p[0]); + (p[1], le_u32(p, 4), u16::from_le_bytes([p[8], p[9]]), p[10]) +} + +/// Seed a `Window` resource under `parent` with the given size +/// and a deterministic `host_xid` derived from the nested xid. +/// Mirrors what the production `CreateWindow` path leaves in +/// `state.resources` once the host create has roundtripped. +fn seed_window( + state: &mut ServerState, + xid: ResourceId, + parent: ResourceId, + width: u16, + height: u16, +) { + use yserver_protocol::x11::CreateWindowRequest; + state.resources.create_window( + ClientId(14), + CreateWindowRequest { + depth: 24, + window: xid, + parent, + x: 0, + y: 0, + width, + height, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + if let Some(w) = state.resources.window_mut(xid) { + // Synthesise a host_xid from the nested xid (high bit + // set so it can't collide with a low-numbered nested + // xid in a different role). Production assigns these + // out of the backend; tests just need stable values. + w.host_xid = crate::backend::WindowHandle::from_raw(0x8000_0000 | xid.0); + } + // As CreateWindow does. + state + .composite_redirects + .redirect_new_subwindow(parent, xid); +} + +// ── Border attribute validation (#133, plan step 1.3 / 1.4) ──────── + +const CWA_BORDER_PIXMAP: u32 = 0x0004; +const CWA_BORDER_PIXEL: u32 = 0x0008; + +fn border_cwa_body(window: u32, value_mask: u32, values: &[u32]) -> Vec { + let mut body = Vec::with_capacity(8 + values.len() * 4); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&value_mask.to_le_bytes()); + for v in values { + body.extend_from_slice(&v.to_le_bytes()); + } + body +} + +fn run_border_request(state: &mut ServerState, opcode: u8, depth: u8, body: &[u8]) { + run_border_request_recording(state, opcode, depth, body); +} + +/// Same as `run_border_request` but hands back what the backend +/// saw, for the #133 step 2 (P3) forward-path assertions. +fn run_border_request_recording( + state: &mut ServerState, + opcode: u8, + depth: u8, + body: &[u8], +) -> Vec { + let mut backend = RecordingBackend::new(); + process_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode, + data: depth, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("process_request"); + backend.calls() +} + +fn assert_error_code(bytes: &[u8], expected: u8, what: &str) { + assert!( + bytes.len() >= 32, + "{what}: expected a 32-byte error reply, got {} bytes: {:02x?}", + bytes.len(), + bytes + ); + assert_eq!(bytes[0], 0, "{what}: expected an Error reply"); + assert_eq!(bytes[1], expected, "{what}: wrong error code"); +} + +fn assert_no_error(bytes: &[u8], what: &str) { + assert!( + bytes.is_empty() || bytes[0] != 0, + "{what}: expected no error, got {:02x?}", + bytes + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/present_pixmap.rs b/crates/yserver-core/src/core_loop/process_request/tests/present_pixmap.rs new file mode 100644 index 000000000..25cd4089e --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/present_pixmap.rs @@ -0,0 +1,5981 @@ +use super::*; + +fn present_test_output( + output_id: u32, + crtc_id: u32, + x: i16, + y: i16, + width: u16, + height: u16, + enabled: bool, +) -> crate::randr::RandrOutput { + let mode_id = if enabled { + crtc_id.wrapping_add(0x1000) + } else { + 0 + }; + crate::randr::RandrOutput { + name: format!("test-{output_id}"), + output_id, + crtc_id, + mode_id, + connected: true, + x, + y, + width: if enabled { width } else { 0 }, + height: if enabled { height } else { 0 }, + vrefresh: if enabled { 60 } else { 0 }, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![crtc_id.wrapping_add(0x1000)], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + } +} + +/// Present family: a Present ConfigureNotify selector over +/// `OUTBOUND_CAP` is flagged for the core loop to disconnect, and the +/// reading selector still gets the event. +#[test] +fn overflowing_present_selector_is_flagged_for_disconnect() { + use crate::server::PresentEventSelection; + use yserver_protocol::x11::present as x11present; + + const WINDOW: ResourceId = ResourceId(0x200); + let mut state = ServerState::new(); + let _slow = install_client(&mut state, 1); + let mut fast = install_client(&mut state, 2); + for (eid, owner) in [(0x0010_0042, 1), (0x0020_0042, 2)] { + state.present_event_selections.insert( + eid, + PresentEventSelection { + owner: ClientId(owner), + window: WINDOW, + event_mask: x11present::EVENT_MASK_CONFIGURE_NOTIFY, + }, + ); + } + client_io::saturate_for_test(state.clients.get_mut(&1).unwrap()); + fire_present_configure_notify_for_window( + &mut state, + WINDOW, + yserver_protocol::x11::Geometry { + root: crate::resources::ROOT_WINDOW, + x: 1, + y: 2, + width: 30, + height: 40, + border_width: 0, + depth: 24, + }, + ); + assert_eq!(client_io::failed_writers(&state.clients), [ClientId(1)]); + let bytes = read_all_available(&mut fast); + assert_eq!(bytes.first(), Some(&35), "Present GenericEvent"); +} + +/// Xorg's Present screen hook receives every real ConfigNotify, including +/// a pure move. Steam's DRI3 popup windows select this event and use its +/// x/y to keep the presentation surface synchronized with the native +/// override-redirect window. +#[test] +fn configure_window_pure_move_emits_present_configure_notify() { + use crate::server::PresentEventSelection; + use yserver_protocol::x11::present as x11present; + + const WINDOW: ResourceId = ResourceId(0x200); + const PRESENT_EID: u32 = 0x0010_0042; + + let (mut state, mut peer) = two_children_under_root(); + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(WINDOW, 0x0002_0000); + state.present_event_selections.insert( + PRESENT_EID, + PresentEventSelection { + owner: ClientId(1), + window: WINDOW, + event_mask: x11present::EVENT_MASK_CONFIGURE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + + let body = cw_restack_body(WINDOW.0, 0x0003, &[610, 250]); // CWX|CWY + let mut backend = RecordingBackend::new(); + handle_configure_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &body, + ) + .expect("handle_configure_window"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 72, "Present XGE plus core ConfigureNotify"); + // Xorg dix/window.c invokes the Present ConfigNotify screen hook + // before DeliverEvents sends the core ConfigureNotify. This ordering + // matters to clients which merge the two configure streams. + assert_eq!(bytes[0], 35, "GenericEvent"); + assert_eq!(bytes[1], 145, "PRESENT major opcode"); + assert_eq!( + u16::from_le_bytes(bytes[8..10].try_into().unwrap()), + u16::from(x11present::EVENT_CONFIGURE_NOTIFY), + ); + assert_eq!( + u32::from_le_bytes(bytes[12..16].try_into().unwrap()), + PRESENT_EID, + ); + assert_eq!( + u32::from_le_bytes(bytes[16..20].try_into().unwrap()), + WINDOW.0, + ); + assert_eq!(i16::from_le_bytes(bytes[20..22].try_into().unwrap()), 610); + assert_eq!(i16::from_le_bytes(bytes[22..24].try_into().unwrap()), 250); + assert_eq!(u16::from_le_bytes(bytes[24..26].try_into().unwrap()), 50); + assert_eq!(u16::from_le_bytes(bytes[26..28].try_into().unwrap()), 50); + assert_eq!(bytes[40] & 0x7f, 22, "core ConfigureNotify follows Present"); + assert_eq!( + u32::from_le_bytes(bytes[48..52].try_into().unwrap()), + WINDOW.0, + ); +} + +#[test] +fn present_default_crtc_uses_the_transformed_footprint() { + const WINDOW: u32 = 0x0001_1001; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![ + present_test_output(1, 11, 0, 0, 2560, 1440, true), + present_test_output(2, 22, 2560, 0, 2560, 1440, true), + ], + ); + state.randr.primary_output = 1; + // Below CRTC 22's mode but inside its 2.0 footprint. + create_present_test_window(&mut state, WINDOW, 2600, 1500, 500, 500); + assert_eq!( + default_present_crtc_for_window(&state, ResourceId(WINDOW)), + 11 + ); + state.randr.outputs[1].current_transform = + crate::randr::CrtcTransform::new(rr_scale(MUFFIN_2_0), None, Vec::new()).unwrap(); + assert_eq!( + default_present_crtc_for_window(&state, ResourceId(WINDOW)), + 22 + ); +} + +/// PresentPixmapSynced 84-byte fixed prefix. Offsets per the :40644 +/// test's comment: window(0) pixmap(4) serial(8) valid(12) update(16) +/// x_off(20) y_off(22) target_crtc(24) acquire_syncobj(28) +/// release_syncobj(32) acquire_point(36) release_point(44) options(52) +/// pad(56) target_msc(60) divisor(68) remainder(76). +fn pixmap_synced_body( + window: u32, + pixmap: u32, + acquire_syncobj: u32, + release_syncobj: u32, + acquire_point: u64, + release_point: u64, +) -> Vec { + let mut body = vec![0u8; 84]; + body[0..4].copy_from_slice(&window.to_le_bytes()); + body[4..8].copy_from_slice(&pixmap.to_le_bytes()); + body[28..32].copy_from_slice(&acquire_syncobj.to_le_bytes()); + body[32..36].copy_from_slice(&release_syncobj.to_le_bytes()); + body[36..44].copy_from_slice(&acquire_point.to_le_bytes()); + body[44..52].copy_from_slice(&release_point.to_le_bytes()); + body +} + +fn pixmap_body(window: u32, pixmap: u32) -> Vec { + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&window.to_le_bytes()); + body[4..8].copy_from_slice(&pixmap.to_le_bytes()); + body +} + +fn dispatch_present_body( + state: &mut ServerState, + backend: &mut RecordingBackend, + client_id: ClientId, + sequence: u16, + minor: u8, + body: &[u8], +) { + process_request( + state, + backend, + client_id, + SequenceNumber(sequence), + RequestHeader { + opcode: 145, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + None, + ) + .unwrap(); +} + +fn future_present_pixmap_request( + state: &mut ServerState, + window: u32, + pixmap: u32, + present_id: u32, + target_msc: u64, +) -> Vec { + if state.resources.window(ResourceId(window)).is_none() { + create_present_test_window(state, window, 0, 0, 32, 32); + let target = state + .resources + .window_mut(ResourceId(window)) + .expect("created Present window"); + target.host_xid = crate::backend::WindowHandle::from_raw(window | 0x0040_0000); + target.map_state = crate::resources::MapState::Viewable; + } + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap), + drawable: ResourceId(window), + width: 32, + height: 32, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(pixmap), + crate::backend::PixmapHandle::from_raw(pixmap | 0x0040_0000) + .expect("valid test pixmap host xid"), + ); + let mut body = pixmap_body(window, pixmap); + body[8..12].copy_from_slice(&present_id.to_le_bytes()); + body[44..52].copy_from_slice(&target_msc.to_le_bytes()); + body +} + +fn dispatch_future_present_pixmap( + state: &mut ServerState, + backend: &mut RecordingBackend, + window: u32, + pixmap: u32, + present_id: u32, + target_msc: u64, +) { + let body = future_present_pixmap_request(state, window, pixmap, present_id, target_msc); + dispatch_present_body( + state, + backend, + ClientId(1), + u16::try_from(present_id).unwrap(), + yserver_protocol::x11::present::PIXMAP, + &body, + ); +} + +fn run_core_present_wait_drain( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + sequence: u16, +) -> Vec { + run_core_present_requests_and_wait( + state, + backend, + peer, + vec![( + SequenceNumber(sequence), + RequestHeader { + opcode: 43, // GetInputFocus: round-trip after the core drains backend waits. + data: 0, + length_units: 1, + }, + Vec::new(), + )], + ) +} + +fn run_core_present_request_and_wait( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + present_sequence: u16, + round_trip_sequence: u16, + minor: u8, + body: &[u8], +) -> Vec { + run_core_present_requests_and_wait( + state, + backend, + peer, + vec![ + ( + SequenceNumber(present_sequence), + RequestHeader { + opcode: 145, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body.to_vec(), + ), + ( + SequenceNumber(round_trip_sequence), + RequestHeader { + opcode: 43, // GetInputFocus: confirms Present dispatch and wait drain. + data: 0, + length_units: 1, + }, + Vec::new(), + ), + ], + ) +} + +fn run_core_present_requests_and_wait( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + requests: Vec<(SequenceNumber, RequestHeader, Vec)>, +) -> Vec { + use std::io::Read; + + struct ShutdownOnDrop { + sender: crate::core_loop::CoreSender, + active: bool, + } + + impl Drop for ShutdownOnDrop { + fn drop(&mut self) { + if self.active { + let _ = self.sender.send(crate::core_loop::Message::Shutdown); + } + } + } + + let (poll, sender, receiver) = crate::core_loop::channel().expect("core channel"); + let request_sender = sender.bind(); + for (sequence, header, body) in requests { + request_sender + .send(crate::core_loop::Message::Request { + id: ClientId(1), + sequence, + accepted_at: None, + header, + body, + attached_fd: None, + }) + .expect("queue request for run_core"); + } + let sender_for_core = sender.clone_handle(); + + std::thread::scope(|scope| { + let runner = scope.spawn(|| { + crate::core_loop::run_core( + poll, + receiver, + sender_for_core, + state, + backend, + [], + &crate::core_loop::poll_tokens::ClientIdAllocator::new(), + crate::core_loop::auth::AuthState::new(None), + crate::core_loop::ResetPolicy::NoReset, + None, + ) + }); + let mut shutdown = ShutdownOnDrop { + sender: sender.clone_handle(), + active: true, + }; + + let mut reply = [0; 32]; + peer.read_exact(&mut reply) + .expect("GetInputFocus response proves request processing completed"); + assert_eq!(reply[0], 1, "GetInputFocus reply"); + shutdown + .sender + .send(crate::core_loop::Message::Shutdown) + .expect("stop run_core after its iteration tail"); + shutdown.active = false; + runner.join().expect("run_core thread panicked").unwrap(); + }); + read_all_available(peer) +} + +fn assert_present_error(peer: &mut UnixStream, expected_code: u8, expected_value: u32) { + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(read_error(&error), expected_code); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + expected_value + ); +} + +#[test] +fn future_synced_acquire_wait_is_superseded_without_blocking_successor_completion() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, present as x11present}; + + const CLIENT: u32 = 1; + const WINDOW: u32 = 0x00e0_0e01; + const WINDOW_HOST: u32 = 0x0040_0e01; + const OLDER_PIXMAP: u32 = 0x00e0_0e10; + const SUCCESSOR_PIXMAP: u32 = 0x00e0_0e11; + const OLDER_HOST: u32 = 0x0040_0e10; + const SUCCESSOR_HOST: u32 = 0x0040_0e11; + const ACQUIRE: u32 = 0x00e0_0e30; + const RELEASE: u32 = 0x00e0_0e31; + const WAIT_ID: u64 = 0x7200; + const PRESENT_EID: u32 = 0x0020_0e40; + const TARGET_MSC: u64 = 105; + + // Mutation: restore the `!entry.source_ready` skip; the future fence + // waiter must be scrapped, while due fence waiters remain protected by + // `synced_async_present_acquire_waits_survive_the_next_frame_and_execute`. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound core round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_display_idle = false; + backend.present_absolute_vblank_arm_supported = true; + backend.present_scanout_blackout = false; + backend.present_syncobj_wait = crate::backend::PresentSourceWait::Deferred(WAIT_ID); + backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(CLIENT)); + backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(CLIENT)); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(CLIENT), + window: ResourceId(WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW)); + state + .resources + .window_mut(ResourceId(WINDOW)) + .expect("destination window") + .host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST); + for (pixmap, host_xid) in [ + (OLDER_PIXMAP, OLDER_HOST), + (SUCCESSOR_PIXMAP, SUCCESSOR_HOST), + ] { + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap), + drawable: ResourceId(WINDOW), + width: 100, + height: 100, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(pixmap), + crate::backend::PixmapHandle::from_raw(host_xid).expect("valid test pixmap host xid"), + )); + } + + let mut older = pixmap_synced_body(WINDOW, OLDER_PIXMAP, ACQUIRE, RELEASE, 1, 2); + older[8..12].copy_from_slice(&1_u32.to_le_bytes()); + older[60..68].copy_from_slice(&TARGET_MSC.to_le_bytes()); + let _ = run_core_present_request_and_wait( + &mut state, + &mut backend, + &mut peer, + 1, + 2, + x11present::PIXMAP_SYNCED, + &older, + ); + assert!( + state + .present_pending_exec + .get(&1) + .is_some_and(|entry| !entry.source_ready && entry.wait_id == Some(WAIT_ID)) + ); + + let mut successor = pixmap_body(WINDOW, SUCCESSOR_PIXMAP); + successor[8..12].copy_from_slice(&2_u32.to_le_bytes()); + successor[44..52].copy_from_slice(&TARGET_MSC.to_le_bytes()); + let _ = run_core_present_request_and_wait( + &mut state, + &mut backend, + &mut peer, + 3, + 4, + x11present::PIXMAP, + &successor, + ); + assert!(state.present_pending_exec.contains_key(&2)); + assert!(!state.present_pending_exec.contains_key(&1)); + assert!(state.present_wait_to_id.is_empty()); + assert_eq!(backend.finished_present_source_waits, vec![WAIT_ID]); + assert_eq!(backend.present_skip_count, 1); + + // The successor was parked at MSC 105. Advancing the real run_core clock + // executes it while the older acquire point remains unsignalled. + backend.present_ust_msc = (TARGET_MSC, 0x2000); + let mut wire = run_core_present_wait_drain(&mut state, &mut backend, &mut peer, 5); + let successor_completion = backend + .enqueued_present_completions + .iter() + .find(|(event, _)| event.present_id == 2) + .expect("the executed successor enqueued its completion") + .0 + .clone(); + backend + .completed_present_events_to_drain + .push(successor_completion); + wire.extend(run_core_present_wait_drain( + &mut state, + &mut backend, + &mut peer, + 6, + )); + let copied_sources: Vec = backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::CopyArea { src_host_xid, .. } => Some(*src_host_xid), + _ => None, + }) + .collect(); + assert_eq!(copied_sources, vec![SUCCESSOR_HOST]); + assert_eq!( + complete_notify_modes(&wire), + vec![ + x11present::COMPLETE_MODE_SKIP, + x11present::COMPLETE_MODE_COPY + ], + "the scrapped future waiter completes as Skip before its successor's Copy" + ); + assert_eq!( + *backend.signalled_dri3_syncobjs.lock().unwrap(), + vec![(RELEASE, 2)], + "scrapping releases the older synced buffer through its release point" + ); + assert_eq!(backend.finished_present_source_waits, vec![WAIT_ID]); + assert_eq!(backend.present_skip_count, 1); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_wait_to_id.is_empty()); + assert!(state.present_pending_complete.is_empty()); + assert!(state.present_complete_gate.is_empty()); + assert!(backend.ready_present_source_waits.is_empty()); +} + +#[test] +fn synced_async_present_acquire_waits_survive_the_next_frame_and_execute() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; + + const CLIENT: u32 = 1; + const WINDOW: u32 = 0x00e0_0b01; + const WINDOW_HOST: u32 = 0x0040_0b01; + const PIXMAP_BASE: u32 = 0x00e0_0b10; + const PIXMAP_HOST_BASE: u32 = 0x0040_0b10; + const ACQUIRE: u32 = 0x00e0_0b30; + const RELEASE: u32 = 0x00e0_0b31; + const WAIT_BASE: u64 = 0x7000; + const FRAME_COUNT: u32 = 20; + + // Mutation: remove the `source_ready` gate from core supersession so a + // successor scraps an entry still waiting on its acquire point. + // Logical timing: submit every 3 ms and signal that frame's acquire point + // 4 ms later, after the next submission. The explicit Backend wait ids + // keep this schedule deterministic without sleeping. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound core round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (10, 0x1000); + backend.present_flip_in_flight = true; + backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(CLIENT)); + backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(CLIENT)); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW)); + state + .resources + .window_mut(ResourceId(WINDOW)) + .expect("destination window") + .host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST); + + for frame in 0..FRAME_COUNT { + let pixmap = PIXMAP_BASE + frame; + let pixmap_host = PIXMAP_HOST_BASE + frame; + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap), + drawable: ResourceId(WINDOW), + width: 100, + height: 100, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(pixmap), + crate::backend::PixmapHandle::from_raw(pixmap_host) + .expect("valid test pixmap host xid"), + ); + + let acquire_point = u64::from(frame) + 1; + let release_point = acquire_point + 1; + let mut body = pixmap_synced_body( + WINDOW, + pixmap, + ACQUIRE, + RELEASE, + acquire_point, + release_point, + ); + body[8..12].copy_from_slice(&(frame + 1).to_le_bytes()); + body[52..56].copy_from_slice(&crate::present_scheduler::PRESENT_OPTION_ASYNC.to_le_bytes()); + let wait_id = WAIT_BASE + u64::from(frame); + if frame > 0 { + let preceding_present_id = u64::from(frame); + let preceding_wait_id = WAIT_BASE + u64::from(frame - 1); + assert!( + state + .present_pending_exec + .get(&preceding_present_id) + .is_some_and( + |entry| !entry.source_ready && entry.wait_id == Some(preceding_wait_id) + ), + "frame {frame} arrives at 3 ms while the preceding frame's 4 ms acquire wait is pending" + ); + backend.ready_present_source_waits.push(preceding_wait_id); + } + backend.present_syncobj_wait = crate::backend::PresentSourceWait::Deferred(wait_id); + let present_sequence = frame * 3 + 1; + let _ = run_core_present_request_and_wait( + &mut state, + &mut backend, + &mut peer, + u16::try_from(present_sequence).unwrap(), + u16::try_from(present_sequence + 1).unwrap(), + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + } + + backend + .ready_present_source_waits + .push(WAIT_BASE + u64::from(FRAME_COUNT - 1)); + let _ = run_core_present_wait_drain( + &mut state, + &mut backend, + &mut peer, + u16::try_from(FRAME_COUNT * 3).unwrap(), + ); + + let copied_sources: Vec = backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::CopyArea { src_host_xid, .. } => Some(*src_host_xid), + _ => None, + }) + .collect(); + assert_eq!( + copied_sources, + (0..FRAME_COUNT) + .map(|frame| PIXMAP_HOST_BASE + frame) + .collect::>(), + "all 20 acquire-waiting frames execute once, in arrival order" + ); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_wait_to_id.is_empty()); + assert!(state.present_pending_complete.is_empty()); + assert_eq!( + backend.present_skip_count, 0, + "no acquire-waiting frame is scrapped" + ); + let mut completion_gates: Vec = state.present_complete_gate.keys().copied().collect(); + completion_gates.sort_unstable(); + assert_eq!( + completion_gates, + (1..=u64::from(FRAME_COUNT)).collect::>() + ); +} + +#[test] +fn ready_present_acquire_waits_in_one_drain_execute_in_arrival_order() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; + + const CLIENT: u32 = 1; + const WINDOW: u32 = 0x00e0_0d01; + const WINDOW_HOST: u32 = 0x0040_0d01; + const PIXMAP_BASE: u32 = 0x00e0_0d10; + const PIXMAP_HOST_BASE: u32 = 0x0040_0d10; + const ACQUIRE: u32 = 0x00e0_0d30; + const RELEASE: u32 = 0x00e0_0d31; + const WAIT_BASE: u64 = 0x7100; + const FRAME_COUNT: u32 = 3; + + // Mutation: remove the ready-wait sort by Present ID; reversed ready IDs + // must then copy in the wrong order. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound core round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (10, 0x1000); + backend.present_flip_in_flight = true; + backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(CLIENT)); + backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(CLIENT)); + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW)); + state + .resources + .window_mut(ResourceId(WINDOW)) + .expect("destination window") + .host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST); + + for frame in 0..FRAME_COUNT { + let pixmap = PIXMAP_BASE + frame; + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap), + drawable: ResourceId(WINDOW), + width: 100, + height: 100, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(pixmap), + crate::backend::PixmapHandle::from_raw(PIXMAP_HOST_BASE + frame) + .expect("valid test pixmap host xid"), + ); + + let present_id = u64::from(frame + 1); + let wait_id = WAIT_BASE + u64::from(frame); + let mut body = + pixmap_synced_body(WINDOW, pixmap, ACQUIRE, RELEASE, present_id, present_id + 1); + body[8..12].copy_from_slice(&(frame + 1).to_le_bytes()); + body[52..56].copy_from_slice(&crate::present_scheduler::PRESENT_OPTION_ASYNC.to_le_bytes()); + backend.present_syncobj_wait = crate::backend::PresentSourceWait::Deferred(wait_id); + let present_sequence = frame * 2 + 1; + let _ = run_core_present_request_and_wait( + &mut state, + &mut backend, + &mut peer, + u16::try_from(present_sequence).unwrap(), + u16::try_from(present_sequence + 1).unwrap(), + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert!(state.present_pending_exec.contains_key(&present_id)); + } + + for frame in (0..FRAME_COUNT).rev() { + backend + .ready_present_source_waits + .push(WAIT_BASE + u64::from(frame)); + } + let _ = run_core_present_wait_drain( + &mut state, + &mut backend, + &mut peer, + u16::try_from(FRAME_COUNT * 2 + 1).unwrap(), + ); + + let copied_sources: Vec = backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::CopyArea { src_host_xid, .. } => Some(*src_host_xid), + _ => None, + }) + .collect(); + assert_eq!( + copied_sources, + (0..FRAME_COUNT) + .map(|frame| PIXMAP_HOST_BASE + frame) + .collect::>(), + "a single reversed readiness drain still executes in Present arrival order" + ); + assert_eq!( + backend.finished_present_source_waits, + (0..FRAME_COUNT) + .map(|frame| WAIT_BASE + u64::from(frame)) + .collect::>(), + "each waiter is finished once in arrival order" + ); + assert_eq!(backend.present_skip_count, 0); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_wait_to_id.is_empty()); + assert!(state.present_pending_complete.is_empty()); +} + +#[test] +fn late_older_acquire_wait_completes_as_skip_after_newer_same_target_executes() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, present as x11present}; + + const CLIENT: u32 = 1; + const WINDOW: u32 = 0x00e0_0c01; + const WINDOW_HOST: u32 = 0x0040_0c01; + const OLDER_PIXMAP: u32 = 0x00e0_0c10; + const NEWER_PIXMAP: u32 = 0x00e0_0c11; + const OLDER_HOST: u32 = 0x0040_0c10; + const NEWER_HOST: u32 = 0x0040_0c11; + const ACQUIRE: u32 = 0x00e0_0c30; + const RELEASE: u32 = 0x00e0_0c31; + const OLDER_WAIT: u64 = 0x7100; + const NEWER_WAIT: u64 = 0x7101; + const PRESENT_EID: u32 = 0x0020_0c40; + + // Mutation: remove the stale-wait check after a newer covered Present + // executes; the older source must not be copied after the newer one. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound core round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (10, 0x1000); + backend.present_flip_in_flight = true; + backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(CLIENT)); + backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(CLIENT)); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(CLIENT), + window: ResourceId(WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW)); + state + .resources + .window_mut(ResourceId(WINDOW)) + .expect("destination window") + .host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST); + for (pixmap, host_xid) in [(OLDER_PIXMAP, OLDER_HOST), (NEWER_PIXMAP, NEWER_HOST)] { + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap), + drawable: ResourceId(WINDOW), + width: 100, + height: 100, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(pixmap), + crate::backend::PixmapHandle::from_raw(host_xid).expect("valid test pixmap host xid"), + ); + } + + for (pixmap, serial, wait_id) in [ + (OLDER_PIXMAP, 1_u32, OLDER_WAIT), + (NEWER_PIXMAP, 2_u32, NEWER_WAIT), + ] { + let mut body = pixmap_synced_body(WINDOW, pixmap, ACQUIRE, RELEASE, u64::from(serial), 10); + body[8..12].copy_from_slice(&serial.to_le_bytes()); + body[52..56].copy_from_slice(&crate::present_scheduler::PRESENT_OPTION_ASYNC.to_le_bytes()); + backend.present_syncobj_wait = crate::backend::PresentSourceWait::Deferred(wait_id); + let present_sequence = serial * 2 - 1; + let _ = run_core_present_request_and_wait( + &mut state, + &mut backend, + &mut peer, + u16::try_from(present_sequence).unwrap(), + u16::try_from(present_sequence + 1).unwrap(), + x11present::PIXMAP_SYNCED, + &body, + ); + } + assert_eq!(state.present_pending_exec.len(), 2); + + backend.ready_present_source_waits.push(NEWER_WAIT); + let _ = run_core_present_wait_drain(&mut state, &mut backend, &mut peer, 5); + assert_eq!(state.present_pending_exec.len(), 1); + assert!(state.present_pending_exec.contains_key(&1)); + + backend.ready_present_source_waits.push(OLDER_WAIT); + let late_older_wire = run_core_present_wait_drain(&mut state, &mut backend, &mut peer, 6); + + let copied_sources: Vec = backend + .calls() + .iter() + .filter_map(|call| match call { + RecordedCall::CopyArea { src_host_xid, .. } => Some(*src_host_xid), + _ => None, + }) + .collect(); + assert_eq!(copied_sources, vec![NEWER_HOST]); + assert_eq!( + complete_notify_modes(&late_older_wire), + vec![x11present::COMPLETE_MODE_SKIP], + "the older frame completes as Skip only after its acquire point signals" + ); + assert_eq!( + *backend.signalled_dri3_syncobjs.lock().unwrap(), + vec![(RELEASE, 10)], + "the skipped older Present releases its synced buffer after its wait resolves" + ); + assert_eq!(backend.present_skip_count, 1); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_wait_to_id.is_empty()); + assert!(state.present_pending_complete.is_empty()); + assert_eq!( + state + .present_complete_gate + .keys() + .copied() + .collect::>(), + vec![2] + ); +} + +fn dispatch_pixmap_synced( + state: &mut ServerState, + backend: &mut RecordingBackend, + client_id: yserver_protocol::x11::ClientId, + body: &[u8], +) { + process_request( + state, + backend, + client_id, + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP_SYNCED, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + None, + ) + .unwrap(); +} + +#[test] +fn present_pixmap_common_validation_order_and_card32_remainder() { + const PIXMAP: u32 = 0x0010_2001; + const VALID: u32 = 0x0010_2002; + const UPDATE: u32 = 0x0010_2003; + const BAD_CRTC: u32 = 0x0010_2004; + const WAIT_FENCE: u32 = 0x0010_2005; + const IDLE_FENCE: u32 = 0x0010_2006; + const BAD_OPTIONS: u32 = 0x8000_001f; + const LARGE_REMAINDER: u64 = 0x1_9abc_def0; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + }, + ); + + let mut body = pixmap_body(ROOT_WINDOW.0, PIXMAP); + body[12..16].copy_from_slice(&VALID.to_le_bytes()); + body[16..20].copy_from_slice(&UPDATE.to_le_bytes()); + body[24..28].copy_from_slice(&BAD_CRTC.to_le_bytes()); + body[28..32].copy_from_slice(&WAIT_FENCE.to_le_bytes()); + body[32..36].copy_from_slice(&IDLE_FENCE.to_le_bytes()); + body[36..40].copy_from_slice(&BAD_OPTIONS.to_le_bytes()); + body[60..68].copy_from_slice(&LARGE_REMAINDER.to_le_bytes()); + + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, XFIXES_BAD_REGION, VALID); + + state.xfixes_regions.insert( + VALID, + crate::server::XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, XFIXES_BAD_REGION, UPDATE); + + state.xfixes_regions.insert( + UPDATE, + crate::server::XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 3, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, RANDR_BAD_CRTC, BAD_CRTC); + + body[24..28].copy_from_slice(&0u32.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 4, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, SYNC_BAD_FENCE, WAIT_FENCE); + + state.sync_fences.insert( + WAIT_FENCE, + crate::server::SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 5, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, SYNC_BAD_FENCE, IDLE_FENCE); + + state.sync_fences.insert( + IDLE_FENCE, + crate::server::SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 6, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_OPTIONS); + + body[36..40].copy_from_slice(&0u32.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 7, + yserver_protocol::x11::present::PIXMAP, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, LARGE_REMAINDER as u32); + assert!(!state.present_window_msc.contains_key(&ROOT_WINDOW.0)); +} + +#[test] +fn present_pixmap_synced_validation_order_and_card32_remainder() { + const PIXMAP: u32 = 0x0010_2101; + const ACQUIRE: u32 = 0x0010_2102; + const RELEASE: u32 = 0x0010_2103; + const BAD_ACQUIRE: u32 = 0x0010_21a2; + const BAD_RELEASE: u32 = 0x0010_21a3; + const VALID: u32 = 0x0010_2104; + const UPDATE: u32 = 0x0010_2105; + const BAD_CRTC: u32 = 0x0010_2106; + const BAD_OPTIONS: u32 = 0x4000_001f; + const LARGE_REMAINDER: u64 = 0x1_7654_3210; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(1)); + backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(1)); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + }, + ); + + let mut body = pixmap_synced_body(ROOT_WINDOW.0, PIXMAP, BAD_ACQUIRE, RELEASE, 1, 2); + body[12..16].copy_from_slice(&VALID.to_le_bytes()); + body[16..20].copy_from_slice(&UPDATE.to_le_bytes()); + body[24..28].copy_from_slice(&BAD_CRTC.to_le_bytes()); + body[52..56].copy_from_slice(&BAD_OPTIONS.to_le_bytes()); + body[76..84].copy_from_slice(&LARGE_REMAINDER.to_le_bytes()); + + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_ACQUIRE); + + body[28..32].copy_from_slice(&ACQUIRE.to_le_bytes()); + body[32..36].copy_from_slice(&BAD_RELEASE.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_RELEASE); + + body[32..36].copy_from_slice(&RELEASE.to_le_bytes()); + body[36..44].copy_from_slice(&0u64.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 3, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, 0); + + body[36..44].copy_from_slice(&1u64.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 4, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, XFIXES_BAD_REGION, VALID); + + state.xfixes_regions.insert( + VALID, + crate::server::XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 5, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, XFIXES_BAD_REGION, UPDATE); + + state.xfixes_regions.insert( + UPDATE, + crate::server::XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::default(), + }, + ); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 6, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, RANDR_BAD_CRTC, BAD_CRTC); + + body[24..28].copy_from_slice(&0u32.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 7, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, BAD_OPTIONS); + + body[52..56].copy_from_slice(&0u32.to_le_bytes()); + dispatch_present_body( + &mut state, + &mut backend, + ClientId(1), + 8, + yserver_protocol::x11::present::PIXMAP_SYNCED, + &body, + ); + assert_present_error(&mut peer, x11::error::BAD_VALUE, LARGE_REMAINDER as u32); + assert!(!state.present_window_msc.contains_key(&ROOT_WINDOW.0)); +} + +#[test] +fn present_pixmap_synced_unknown_acquire_syncobj_is_bad_value() { + use yserver_protocol::x11::{ClientId, CreatePixmapRequest, CreateWindowRequest}; + const WINDOW_XID: u32 = 0x00e0_0403; + const PIXMAP_XID: u32 = 0x00e0_0404; + const ACQUIRE_SYNCOBJ: u32 = 0x00e0_0bad; // never imported + const RELEASE_SYNCOBJ: u32 = 0x00e0_0408; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 17); + let mut backend = RecordingBackend::new(); + // The release syncobj is a valid, imported resource; the acquire is + // NOT. Row 4: an unknown acquire xid must produce a Value error, not + // a silent no-reply hang. + backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(17)); + + state.resources.create_window( + ClientId(17), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0x400403); + } + state.resources.create_pixmap( + ClientId(17), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(0x400404).expect("valid host pixmap"), + ); + + let mut body = pixmap_synced_body( + WINDOW_XID, + PIXMAP_XID, + ACQUIRE_SYNCOBJ, + RELEASE_SYNCOBJ, + 1, + 1, + ); + body[76..84].copy_from_slice(&1u64.to_le_bytes()); + dispatch_pixmap_synced(&mut state, &mut backend, ClientId(17), &body); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_VALUE, + "unknown acquire syncobj must be BadValue, not a silent no-reply wait", + ); + // X error: bytes 4-7 are the bad-value argument. It must carry the + // offending xid, mirroring Xorg's VERIFY_DRI3_SYNCOBJ + // (client->errorValue = id). + assert_eq!( + u32::from_le_bytes(buf[4..8].try_into().unwrap()), + ACQUIRE_SYNCOBJ, + "BadValue must carry the offending syncobj xid", + ); +} + +#[test] +fn rejected_synced_depth_mismatch_does_not_change_remembered_crtc() { + const CLIENT: u32 = 17; + const WINDOW: u32 = 0x00e0_0451; + const PIXMAP: u32 = 0x00e0_0452; + const ACQUIRE: u32 = 0x00e0_0453; + const RELEASE: u32 = 0x00e0_0454; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![ + present_test_output(1, 11, 0, 0, 100, 100, true), + present_test_output(2, 22, 100, 0, 100, 100, true), + ], + ); + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 64, + height: 64, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(WINDOW)) + .unwrap() + .host_xid = crate::backend::WindowHandle::from_raw(0x0040_0451); + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 32, + pixmap: ResourceId(PIXMAP), + drawable: ResourceId(WINDOW), + width: 64, + height: 64, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP), + crate::backend::PixmapHandle::from_raw(0x0040_0452).unwrap(), + ); + let mut backend = RecordingBackend::new(); + backend.seed_dri3_syncobj_for_test(ACQUIRE, ClientId(CLIENT)); + backend.seed_dri3_syncobj_for_test(RELEASE, ClientId(CLIENT)); + let original = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); + + let mut body = pixmap_synced_body(WINDOW, PIXMAP, ACQUIRE, RELEASE, 1, 1); + body[24..28].copy_from_slice(&22u32.to_le_bytes()); + dispatch_pixmap_synced(&mut state, &mut backend, ClientId(CLIENT), &body); + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[1], x11::error::BAD_MATCH); + let remembered = state.present_window_msc[&WINDOW]; + assert_eq!(remembered.last_crtc, original.crtc_id); + assert_eq!(remembered.last_crtc_epoch, original.crtc_epoch); + assert!(!state.present_window_generations.contains_key(&WINDOW)); +} + +#[test] +fn present_pixmap_synced_zero_point_is_bad_value() { + use yserver_protocol::x11::ClientId; + const WINDOW_XID: u32 = 0x00e0_0403; + const PIXMAP_XID: u32 = 0x00e0_0404; + const SYNCOBJ: u32 = 0x00e0_0407; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 17); + let mut backend = RecordingBackend::new(); + backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(17)); + + // Both syncobjs imported; acquire_point == 0 is the violation. + dispatch_pixmap_synced( + &mut state, + &mut backend, + ClientId(17), + &pixmap_synced_body(WINDOW_XID, PIXMAP_XID, SYNCOBJ, SYNCOBJ, 0, 2), + ); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_VALUE, + "acquire_point 0 must be BadValue" + ); +} + +#[test] +fn present_pixmap_synced_acquire_gte_release_is_bad_value() { + use yserver_protocol::x11::ClientId; + const WINDOW_XID: u32 = 0x00e0_0403; + const PIXMAP_XID: u32 = 0x00e0_0404; + const SYNCOBJ: u32 = 0x00e0_0407; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 17); + let mut backend = RecordingBackend::new(); + backend.seed_dri3_syncobj_for_test(SYNCOBJ, ClientId(17)); + + // Same syncobj for acquire and release: acquire_value >= + // release_value is the violation. + dispatch_pixmap_synced( + &mut state, + &mut backend, + ClientId(17), + &pixmap_synced_body(WINDOW_XID, PIXMAP_XID, SYNCOBJ, SYNCOBJ, 5, 5), + ); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_VALUE, + "acquire_value >= release_value on the same syncobj must be BadValue", + ); +} + +#[test] +fn present_pixmap_synced_another_clients_acquire_syncobj_is_bad_value() { + use yserver_protocol::x11::{ClientId, CreatePixmapRequest, CreateWindowRequest}; + const WINDOW_XID: u32 = 0x00e0_0403; + const PIXMAP_XID: u32 = 0x00e0_0404; + const ACQUIRE_SYNCOBJ: u32 = 0x00e0_0bad; // owned by client A (17) + const RELEASE_SYNCOBJ: u32 = 0x00e0_0408; // owned by client B (18) + + let mut state = ServerState::new(); + let _peer_a = install_client(&mut state, 17); + let mut peer_b = install_client(&mut state, 18); + let mut backend = RecordingBackend::new(); + backend.seed_dri3_syncobj_for_test(ACQUIRE_SYNCOBJ, ClientId(17)); + backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(18)); + + state.resources.create_window( + ClientId(17), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0x400403); + } + state.resources.create_pixmap( + ClientId(17), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(0x400404).expect("valid host pixmap"), + ); + + // B presents using A's acquire syncobj. Xorg's VERIFY_DRI3_SYNCOBJ is + // client-scoped, so the ownership check must reject B as BadValue — + // otherwise B could advance A's timeline on completion and corrupt A's + // buffer reuse. + dispatch_pixmap_synced( + &mut state, + &mut backend, + ClientId(18), + &pixmap_synced_body( + WINDOW_XID, + PIXMAP_XID, + ACQUIRE_SYNCOBJ, + RELEASE_SYNCOBJ, + 1, + 1, + ), + ); + + peer_b.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer_b.read_exact(&mut buf).unwrap(); + assert_eq!( + read_error(&buf), + x11::error::BAD_VALUE, + "B must not be able to present against A's acquire syncobj", + ); + // X error: bytes 4-7 are the bad-value argument — the offending + // acquire xid, mirroring Xorg's VERIFY_DRI3_SYNCOBJ. + assert_eq!( + u32::from_le_bytes(buf[4..8].try_into().unwrap()), + ACQUIRE_SYNCOBJ, + "BadValue must carry the offending acquire xid", + ); +} + +#[test] +fn present_default_crtc_uses_overlap_primary_tie_and_stable_order() { + const WINDOW: u32 = 0x0001_1001; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![ + present_test_output(2, 22, 0, 0, 100, 100, true), + present_test_output(1, 11, 100, 0, 100, 100, true), + ], + ); + state.randr.primary_output = 1; + create_present_test_window(&mut state, WINDOW, 50, 0, 100, 50); + + assert_eq!( + default_present_crtc_for_window(&state, ResourceId(WINDOW)), + 11, + "the primary output wins an equal-area overlap" + ); + state.randr.primary_output = 999; + assert_eq!( + default_present_crtc_for_window(&state, ResourceId(WINDOW)), + 22, + "without a primary tie, stable output enumeration wins" + ); + let window = state.resources.window_mut(ResourceId(WINDOW)).unwrap(); + window.x = 10; + window.width = 70; + assert_eq!( + default_present_crtc_for_window(&state, ResourceId(WINDOW)), + 22, + "greatest intersection wins before tie-breaking" + ); + + for output in &mut state.randr.outputs { + output.mode_id = 0; + } + assert_eq!( + default_present_crtc_for_window(&state, ResourceId(WINDOW)), + 0, + "zero enabled outputs use the synthetic headless domain" + ); +} + +#[test] +fn explicit_off_crtc_is_valid_but_unpaced() { + const CRTC: u32 = 55; + const WINDOW: u32 = 0x0001_1051; + const PIXMAP: u32 = 0x0001_1052; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![present_test_output(5, CRTC, 0, 0, 1920, 1080, false)], + ); + create_present_test_window(&mut state, WINDOW, 0, 0, 64, 64); + { + let window = state.resources.window_mut(ResourceId(WINDOW)).unwrap(); + window.host_xid = crate::backend::WindowHandle::from_raw(0x0040_1051); + // A Present to an unviewable window copies nothing (Xorg micopy.c:157). + window.map_state = crate::resources::MapState::Viewable; + } + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP), + drawable: ResourceId(WINDOW), + width: 64, + height: 64, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP), + crate::backend::PixmapHandle::from_raw(0x0040_1052).unwrap(), + ); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc_by_crtc.insert(CRTC, (999, 0x1234)); + + let domain = select_present_domain(&mut state, &mut backend, ROOT_WINDOW.0, CRTC, false) + .expect("a valid-but-Off RANDR CRTC is accepted"); + assert_eq!((domain.crtc_id, domain.crtc_epoch), (CRTC, 0)); + assert_eq!((domain.raw_msc, domain.raw_ust), (0, 0)); + assert_eq!( + effective_present_target_raw(domain, 500, 7, 3, 0), + None, + "Off CRTCs degrade to immediate/unpaced operation" + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP.to_le_bytes()); + body[24..28].copy_from_slice(&CRTC.to_le_bytes()); + body[44..52].copy_from_slice(&500u64.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: 18, + }, + &body, + None, + ) + .unwrap(); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_complete_gate.is_empty()); + assert!(backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: 0x0040_1052, + dst_host_xid: 0x0040_1051, + .. + } + ))); + assert!(read_all_available(&mut peer).is_empty(), "no X error"); +} + +#[test] +fn clocked_async_present_keeps_xorg_current_msc_target_identity() { + let domain = PresentDomainSelection { + crtc_id: 55, + crtc_epoch: 7, + msc_offset: 0, + raw_msc: 500, + raw_ust: 50_000, + }; + + assert_eq!( + effective_present_target_raw( + domain, + 0, + 0, + 0, + crate::present_scheduler::PRESENT_OPTION_ASYNC, + ), + Some(500), + "Xorg retains the current CRTC MSC as the target identity for an immediate async Present", + ); +} + +#[test] +fn invalid_explicit_present_crtc_is_bad_crtc_with_error_value() { + const PIXMAP: u32 = 0x0001_1101; + const BAD_CRTC: u32 = 0xdead_beef; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + }, + ); + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP.to_le_bytes()); + body[24..28].copy_from_slice(&BAD_CRTC.to_le_bytes()); + body[60..68].copy_from_slice(&1u64.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: 18, + }, + &body, + None, + ) + .unwrap(); + + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[0], 0); + assert_eq!(error[1], RANDR_BAD_CRTC); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + BAD_CRTC + ); + assert!( + !state.present_window_msc.contains_key(&ROOT_WINDOW.0), + "a rejected request must not bind the window domain" + ); +} + +#[test] +fn notify_msc_reuses_last_present_domain_while_pixmap_reselects() { + const WINDOW: u32 = 0x0001_1201; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![ + present_test_output(1, 11, 0, 0, 100, 100, true), + present_test_output(2, 22, 100, 0, 100, 100, true), + ], + ); + create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); + let mut backend = RecordingBackend::new(); + + let explicit = select_present_domain(&mut state, &mut backend, WINDOW, 22, false).unwrap(); + assert_eq!(explicit.crtc_id, 22); + let notify = select_present_domain(&mut state, &mut backend, WINDOW, 0, true).unwrap(); + assert_eq!(notify.crtc_id, 22, "NotifyMSC reuses the remembered CRTC"); + let pixmap = select_present_domain(&mut state, &mut backend, WINDOW, 0, false).unwrap(); + assert_eq!(pixmap.crtc_id, 11, "Pixmap reselects from current coverage"); +} + +#[test] +fn domain_switch_preserves_window_msc_and_unshifted_remainder_snapshot() { + const WINDOW: u32 = 0x0001_1301; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![ + present_test_output(1, 11, 0, 0, 100, 100, true), + present_test_output(2, 22, 100, 0, 100, 100, true), + ], + ); + create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + backend.present_crtc_clock_epoch_by_crtc.insert(22, 7); + backend.present_ust_msc_by_crtc.insert(11, (100, 1)); + backend.present_ust_msc_by_crtc.insert(22, (1_007, 2)); + + let first = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); + assert_eq!(first.raw_msc.wrapping_sub(first.msc_offset), 100); + backend.present_ust_msc_by_crtc.insert(11, (120, 3)); + let switched = select_present_domain(&mut state, &mut backend, WINDOW, 22, false).unwrap(); + assert_eq!(switched.msc_offset, 887); + assert_eq!(switched.raw_msc.wrapping_sub(switched.msc_offset), 120); + + let effective = effective_present_target_raw(switched, 100, 10, 3, 0).unwrap(); + assert_eq!(effective, 1_013); + assert_eq!( + effective % 10, + 3, + "the wire remainder is not offset-shifted" + ); + + let mut pending = + present_pending_entry_with(700, WINDOW, 0x0040_1302, Some(effective), true).pending; + pending.crtc_id = switched.crtc_id; + pending.crtc_epoch = switched.crtc_epoch; + pending.msc_offset = switched.msc_offset; + let event = completed_event_for_pending(&pending); + backend.present_ust_msc_by_crtc.insert(11, (200, 4)); + let _later = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); + assert_eq!( + event.msc_offset, 887, + "in-flight events retain their offset snapshot" + ); + assert_eq!( + present_wire_clock( + crate::backend::PresentClockSample { + msc: effective, + ust: 5, + source: crate::backend::PresentClockSource::PageFlip, + }, + event.msc_offset, + ) + .msc, + 126 + ); +} + +#[test] +fn notify_msc_reaches_wrapped_raw_target_after_domain_switch() { + const WINDOW: u32 = 0x0001_1351; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![ + present_test_output(1, 11, 0, 0, 100, 100, true), + present_test_output(2, 22, 100, 0, 100, 100, true), + ], + ); + create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + backend.present_crtc_clock_epoch_by_crtc.insert(22, 1); + backend.present_ust_msc_by_crtc.insert(11, (20, 1)); + backend.present_ust_msc_by_crtc.insert(22, (10, 2)); + let _ = select_present_domain(&mut state, &mut backend, WINDOW, 11, false).unwrap(); + let switched = select_present_domain(&mut state, &mut backend, WINDOW, 22, false).unwrap(); + assert_eq!(switched.msc_offset, u64::MAX - 9); + let raw_target = 9u64.wrapping_add(switched.msc_offset); + assert_eq!(raw_target, u64::MAX); + state + .present_pending_msc + .push(crate::server::PendingNotifyMsc { + owner: ClientId(1), + window: WINDOW, + crtc_id: 22, + crtc_epoch: 1, + msc_offset: switched.msc_offset, + serial: 1, + target_msc: raw_target, + divisor: 0, + remainder: 0, + byte_order: ClientByteOrder::LittleEndian, + }); + + fire_due_present_notify_msc_for_domain(&mut state, 22, 1, 1, 3, false); + assert!( + state.present_pending_msc.is_empty(), + "raw MSC 1 is after wrapped target u64::MAX" + ); +} + +#[test] +fn same_crtc_new_epoch_rebases_from_cached_old_raw_clock() { + const WINDOW: u32 = 0x0001_1401; + const CRTC: u32 = 11; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![present_test_output(1, CRTC, 0, 0, 100, 100, true)], + ); + create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(CRTC, 1); + backend.present_ust_msc_by_crtc.insert(CRTC, (100, 1)); + let _ = select_present_domain(&mut state, &mut backend, WINDOW, CRTC, false).unwrap(); + backend.present_ust_msc_by_crtc.insert(CRTC, (120, 2)); + refresh_present_crtc_general_clock(&mut state, &mut backend, CRTC, 1); + + backend.present_crtc_clock_epoch_by_crtc.insert(CRTC, 2); + backend.present_ust_msc_by_crtc.insert(CRTC, (1_000, 3)); + let rebound = select_present_domain(&mut state, &mut backend, WINDOW, CRTC, false).unwrap(); + assert_eq!(rebound.msc_offset, 880); + assert_eq!(rebound.raw_msc.wrapping_sub(rebound.msc_offset), 120); + assert!(state.present_crtc_clocks.contains_key(&(CRTC, 1))); + assert!(state.present_crtc_clocks.contains_key(&(CRTC, 2))); +} + +#[test] +fn exact_completion_sample_does_not_regress_domain_due_clock() { + let mut state = ServerState::new(); + seed_present_domain_clock(&mut state, 11, 1, 200, 2); + let older = crate::backend::PresentClockSample { + msc: 150, + ust: 1, + source: crate::backend::PresentClockSource::PageFlip, + }; + let mut backend = RecordingBackend::new(); + let returned = + refresh_present_crtc_completion_clock(&mut state, &mut backend, 11, 1, Some(older)); + assert_eq!(returned.msc, 150, "the event retains its exact stamp"); + assert_eq!( + state.present_crtc_clocks[&(11, 1)].completion.msc, + 200, + "the shared due clock never regresses" + ); + fire_due_present_completions_for_domain(&mut state, &mut backend, 11, 1, older); + assert_eq!(state.present_crtc_clocks[&(11, 1)].completion.msc, 200); +} + +#[test] +fn older_exact_sample_stamps_event_but_domain_clock_decides_due() { + const WINDOW: u32 = 0x0001_1451; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + 0x0001_14e1, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + seed_present_domain_clock(&mut state, 11, 1, 120, 12); + let mut pending = due_pending_complete( + WINDOW, + 750, + 100, + yserver_protocol::x11::present::COMPLETE_MODE_COPY, + false, + ); + pending.event.crtc_id = 11; + pending.event.crtc_epoch = 1; + pending.event.completion_clock = Some(crate::backend::PresentClockSample { + msc: 90, + ust: 9, + source: crate::backend::PresentClockSource::PageFlip, + }); + state.present_pending_complete.push(pending); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + + fire_due_present_completions_for_domain( + &mut state, + &mut backend, + 11, + 1, + crate::backend::PresentClockSample { + msc: 120, + ust: 12, + source: crate::backend::PresentClockSource::PageFlip, + }, + ); + assert!( + state.present_pending_complete.is_empty(), + "cached domain MSC 120 releases target 100 despite exact stamp 90" + ); + let mut event = [0u8; 40]; + peer.read_exact(&mut event).unwrap(); + assert_eq!( + u64::from_le_bytes(event[32..40].try_into().unwrap()), + 90, + "the grouped-direct reference sample remains the wire timestamp" + ); +} + +#[test] +fn supersession_never_crosses_crtc_or_epoch_domains() { + const WINDOW: u32 = 0x0001_1501; + const PREDECESSOR: u64 = 800; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + backend.present_ust_msc_by_crtc.insert(11, (100, 1)); + let mut predecessor = + present_pending_entry_with(PREDECESSOR, WINDOW, 0x0040_1502, Some(500), true); + predecessor.pending.crtc_id = 11; + predecessor.pending.crtc_epoch = 1; + state.present_pending_exec.insert(PREDECESSOR, predecessor); + + let mut successor = + present_pending_entry_with(801, WINDOW, 0x0040_1503, Some(500), true).pending; + successor.crtc_id = 22; + successor.crtc_epoch = 1; + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + assert!(state.present_pending_exec.contains_key(&PREDECESSOR)); + successor.crtc_id = 11; + successor.crtc_epoch = 2; + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + assert!(state.present_pending_exec.contains_key(&PREDECESSOR)); + successor.crtc_epoch = 1; + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + assert!( + !state.present_pending_exec.contains_key(&PREDECESSOR), + "the control case scraps only inside the identical raw clock domain" + ); +} + +#[test] +fn epoch_mismatch_is_not_rearmed_and_fails_open_unpaced() { + const PRESENT_ID: u64 = 900; + let mut state = ServerState::new(); + let mut entry = + present_pending_entry_with(PRESENT_ID, 0x0001_1601, 0x0040_1602, Some(1_000), true); + entry.pending.crtc_id = 11; + entry.pending.crtc_epoch = 1; + state.present_pending_exec.insert(PRESENT_ID, entry); + seed_present_domain_clock(&mut state, 11, 1, 10, 1); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 2); + backend.present_absolute_vblank_arm_supported = true; + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + assert!(backend.armed_shared_wake_crtcs.is_empty()); + assert!(state.present_pending_exec.contains_key(&PRESENT_ID)); + drain_due_present_pending_exec(&mut state, &mut backend); + assert!(state.present_pending_exec.is_empty()); + assert!(backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: 0x0040_1602, + .. + } + ))); +} + +#[test] +fn destroyed_window_generation_suppresses_hidden_direct_events_after_xid_reuse() { + const WINDOW: u32 = 0x0001_1701; + const DIRECT_ID: u64 = 901; + const ABSENT_COPY_ID: u64 = 902; + const REUSED_COPY_ID: u64 = 903; + const PURGED_COPY_ID: u64 = 904; + const ABSENT_FENCE: u32 = 0x0001_17f1; + const REUSED_FENCE: u32 = 0x0001_17f2; + const PURGED_FENCE: u32 = 0x0001_17f3; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); + let old_generation = state.present_window_generation(WINDOW); + state.present_event_selections.insert( + 0x0001_17e1, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + state.present_complete_gate.insert( + DIRECT_ID, + crate::server::PresentCompleteGate { + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: 1, + owner: ClientId(1), + dst_window_xid: WINDOW, + }, + ); + let event = crate::backend::CompletedPresentEvent { + client_id: ClientId(1), + serial: 1, + host_xid: 0x0001_1702, + dst_host_xid: WINDOW, + options: 0, + present_id: DIRECT_ID, + window_generation: old_generation, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + completion_clock: None, + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_FLIP, + emit_idle: false, + }; + let absent_copy = crate::backend::CompletedPresentEvent { + present_id: ABSENT_COPY_ID, + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: ABSENT_FENCE, + }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + ..event.clone() + }; + let reused_copy = crate::backend::CompletedPresentEvent { + present_id: REUSED_COPY_ID, + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: REUSED_FENCE, + }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + ..event.clone() + }; + let purged_copy = crate::backend::CompletedPresentEvent { + present_id: PURGED_COPY_ID, + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: PURGED_FENCE, + }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + ..event.clone() + }; + for fence in [ABSENT_FENCE, REUSED_FENCE, PURGED_FENCE] { + state.sync_fences.insert( + fence, + crate::server::SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + } + state + .present_pending_complete + .push(crate::server::PendingPresentComplete { + event: purged_copy, + effective_target_msc: 1, + mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }); + let mut backend = RecordingBackend::new(); + + destroy_window_subtree(&mut state, &mut backend, None, ResourceId(WINDOW)).expect("destroy"); + assert!(!state.present_window_generations.contains_key(&WINDOW)); + assert!(state.present_complete_gate.is_empty()); + assert!(state.present_event_selections.is_empty()); + assert_eq!(backend.signalled_present_wakes, vec![PURGED_COPY_ID]); + assert!(state.sync_fences[&PURGED_FENCE].triggered); + + backend.completed_present_events_to_drain.push(absent_copy); + let _ = read_all_available(&mut peer); + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + assert_eq!( + backend.signalled_present_wakes, + vec![PURGED_COPY_ID, ABSENT_COPY_ID], + "a stale hidden Copy releases exactly when its GPU completion drains" + ); + assert!(state.sync_fences[&ABSENT_FENCE].triggered); + assert!(read_all_available(&mut peer).is_empty()); + + create_present_test_window(&mut state, WINDOW, 0, 0, 50, 50); + let new_generation = state.present_window_generation(WINDOW); + assert_ne!(new_generation, old_generation); + state.present_event_selections.insert( + 0x0001_17e2, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + backend + .completed_present_events_to_drain + .push(event.clone()); + backend.completed_present_events_to_drain.push(reused_copy); + let _ = read_all_available(&mut peer); + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + assert!(read_all_available(&mut peer).is_empty()); + assert_eq!( + backend.signalled_present_wakes, + vec![PURGED_COPY_ID, ABSENT_COPY_ID, REUSED_COPY_ID], + "stale Copy releases, but stale direct Complete does not idle early" + ); + assert!(state.sync_fences[&REUSED_FENCE].triggered); + + backend.retired_present_idle_events_to_drain.push(event); + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + assert_eq!( + backend.signalled_present_wakes, + vec![PURGED_COPY_ID, ABSENT_COPY_ID, REUSED_COPY_ID, DIRECT_ID] + ); + assert!(read_all_available(&mut peer).is_empty()); +} + +#[test] +fn run_loop_groups_all_present_arm_sites_by_crtc_epoch() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + backend.present_crtc_clock_epoch_by_crtc.insert(22, 2); + state.present_pending_msc.extend([ + crate::server::PendingNotifyMsc { + owner: ClientId(1), + window: 1, + crtc_id: 11, + crtc_epoch: 1, + msc_offset: 0, + serial: 1, + target_msc: 101, + divisor: 0, + remainder: 0, + byte_order: ClientByteOrder::LittleEndian, + }, + crate::server::PendingNotifyMsc { + owner: ClientId(1), + window: 2, + crtc_id: 11, + crtc_epoch: 1, + msc_offset: 0, + serial: 2, + target_msc: 102, + divisor: 0, + remainder: 0, + byte_order: ClientByteOrder::LittleEndian, + }, + crate::server::PendingNotifyMsc { + owner: ClientId(1), + window: 3, + crtc_id: 22, + crtc_epoch: 2, + msc_offset: 0, + serial: 3, + target_msc: 201, + divisor: 0, + remainder: 0, + byte_order: ClientByteOrder::LittleEndian, + }, + ]); + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + assert_eq!( + backend.armed_idle_vblank_targets, + vec![(11, vec![101, 102]), (22, vec![201])] + ); + + state.present_pending_msc.clear(); + let mut c1 = due_pending_complete(10, 1, 111, 0, true); + c1.event.crtc_id = 11; + c1.event.crtc_epoch = 1; + let mut c2 = due_pending_complete(20, 2, 222, 0, true); + c2.event.crtc_id = 22; + c2.event.crtc_epoch = 2; + state.present_pending_complete.extend([c1, c2]); + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + assert_eq!( + backend.armed_completion_idle_vblank_targets, + vec![(11, vec![111]), (22, vec![222])] + ); + + state.present_pending_complete.clear(); + let mut e1 = present_pending_entry_with(3, 30, 31, Some(110), true); + e1.pending.crtc_id = 11; + e1.pending.crtc_epoch = 1; + let mut e2 = present_pending_entry_with(4, 40, 41, Some(220), true); + e2.pending.crtc_id = 22; + e2.pending.crtc_epoch = 2; + state.present_pending_exec.insert(3, e1); + state.present_pending_exec.insert(4, e2); + seed_present_domain_clock(&mut state, 11, 1, 100, 1); + seed_present_domain_clock(&mut state, 22, 2, 200, 2); + backend.present_absolute_vblank_arm_supported = true; + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + assert_eq!(backend.armed_shared_wake_crtcs, vec![11, 22]); +} + +#[test] +fn headless_notify_msc_completes_without_parking() { + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs(1, Vec::new()); + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + 1, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ROOT_WINDOW, + event_mask: yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let mut body = vec![0u8; 36]; + body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body[4..8].copy_from_slice(&1u32.to_le_bytes()); + body[12..20].copy_from_slice(&500u64.to_le_bytes()); + let mut backend = RecordingBackend::new(); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::NOTIFY_MSC, + length_units: 10, + }, + &body, + None, + ) + .unwrap(); + assert!(state.present_pending_msc.is_empty()); + assert_eq!(state.present_window_msc[&ROOT_WINDOW.0].last_crtc, 0); + let mut event = [0u8; 40]; + peer.read_exact(&mut event).unwrap(); + assert_eq!(u64::from_le_bytes(event[32..40].try_into().unwrap()), 0); +} + +#[test] +fn present_notify_msc_parks_then_fires_on_vblank_advance() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + const WINDOW: u32 = 0x100; + const EID: u32 = 0x0100_0001; + const SERIAL: u32 = 0x0100_0002; + const COMPLETE_NOTIFY_MASK: u32 = 0x2; + + let mut select_body = Vec::new(); + select_body.extend_from_slice(&EID.to_le_bytes()); + select_body.extend_from_slice(&WINDOW.to_le_bytes()); + select_body.extend_from_slice(&COMPLETE_NOTIFY_MASK.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::SELECT_INPUT, + length_units: 4, + }, + &select_body, + None, + ) + .expect("Present SelectInput"); + + let mut notify_body = Vec::new(); + notify_body.extend_from_slice(&WINDOW.to_le_bytes()); + notify_body.extend_from_slice(&SERIAL.to_le_bytes()); + notify_body.extend_from_slice(&0_u32.to_le_bytes()); // pad + notify_body.extend_from_slice(&0_u64.to_le_bytes()); // target_msc + notify_body.extend_from_slice(&0_u64.to_le_bytes()); // divisor + notify_body.extend_from_slice(&0_u64.to_le_bytes()); // remainder + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::NOTIFY_MSC, + length_units: 10, + }, + ¬ify_body, + None, + ) + .expect("Present NotifyMSC"); + + // Vblank-paced clock: with no pageflip yet (present_kernel_msc == 0) + // the request is PARKED rather than completed immediately — emitting + // ust=0 would be rejected by a `present`-scheduler compositor (picom). + assert_eq!( + state.present_pending_msc.len(), + 1, + "NotifyMSC parks until a real (msc, ust) is available" + ); + + // Simulate a pageflip / armed-vblank advancing the kernel clock. This + // is what `drain_present_completions` does after the backend reports a + // retirement; it drains every parked request whose target is satisfied. + const FIRED_MSC: u64 = 100; + const FIRED_UST: u64 = 0x1234_5678; + fire_due_present_notify_msc(&mut state, FIRED_MSC, FIRED_UST); + assert!( + state.present_pending_msc.is_empty(), + "satisfied parked request is removed after firing" + ); + + let mut event = [0u8; 40]; + peer.read_exact(&mut event).expect("CompleteNotify event"); + assert_eq!(event[0], 35, "GenericEvent"); + assert_eq!(event[1], 145, "Present extension major opcode"); + assert_eq!( + u16::from_le_bytes([event[8], event[9]]), + u16::from(yserver_protocol::x11::present::EVENT_COMPLETE_NOTIFY) + ); + assert_eq!( + event[10], + yserver_protocol::x11::present::COMPLETE_KIND_NOTIFY_MSC + ); + assert_eq!( + u32::from_le_bytes([event[12], event[13], event[14], event[15]]), + EID + ); + assert_eq!( + u32::from_le_bytes([event[16], event[17], event[18], event[19]]), + WINDOW + ); + assert_eq!( + u32::from_le_bytes([event[20], event[21], event[22], event[23]]), + SERIAL + ); + // UST (offset 24) and MSC (offset 32) carry the real kernel values. + assert_eq!( + u64::from_le_bytes([ + event[24], event[25], event[26], event[27], event[28], event[29], event[30], event[31], + ]), + FIRED_UST, + "CompleteNotify reports the real UST from the vblank advance" + ); + assert_eq!( + u64::from_le_bytes([ + event[32], event[33], event[34], event[35], event[36], event[37], event[38], event[39], + ]), + FIRED_MSC, + "CompleteNotify reports the real MSC from the vblank advance" + ); +} + +#[test] +fn notify_msc_resource_precedence_and_card32_remainder_error_value() { + const UNKNOWN_WINDOW: u32 = 0x00ff_aa01; + const LARGE_REMAINDER: u64 = 0x1_0000_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = vec![0u8; 36]; + body[0..4].copy_from_slice(&UNKNOWN_WINDOW.to_le_bytes()); + body[28..36].copy_from_slice(&LARGE_REMAINDER.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::NOTIFY_MSC, + length_units: 10, + }, + &body, + None, + ) + .unwrap(); + let mut error = [0u8; 32]; + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[1], x11::error::BAD_WINDOW); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + UNKNOWN_WINDOW + ); + + body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::NOTIFY_MSC, + length_units: 10, + }, + &body, + None, + ) + .unwrap(); + peer.read_exact(&mut error).unwrap(); + assert_eq!(error[1], x11::error::BAD_VALUE); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + 1, + "Xorg stores remainder in CARD32 errorValue (low-32 truncation)" + ); + assert!(!state.present_window_msc.contains_key(&ROOT_WINDOW.0)); +} + +#[test] +fn present_notify_msc_remainder_ge_divisor_is_rejected_not_parked() { + // Xorg rejects remainder >= divisor with BadValue. Pre-fix, such a + // request parked forever: current_msc % divisor is always < divisor, so + // it could never equal a remainder >= divisor, growing the parked list + // unbounded and re-scanning it every vblank. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + const WINDOW: u32 = 0x100; + + let mut notify_body = Vec::new(); + notify_body.extend_from_slice(&WINDOW.to_le_bytes()); + notify_body.extend_from_slice(&1_u32.to_le_bytes()); // serial + notify_body.extend_from_slice(&0_u32.to_le_bytes()); // pad + notify_body.extend_from_slice(&0_u64.to_le_bytes()); // target_msc + notify_body.extend_from_slice(&2_u64.to_le_bytes()); // divisor + notify_body.extend_from_slice(&5_u64.to_le_bytes()); // remainder >= divisor + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::NOTIFY_MSC, + length_units: 10, + }, + ¬ify_body, + None, + ) + .expect("Present NotifyMSC (invalid divisor/remainder)"); + + assert!( + state.present_pending_msc.is_empty(), + "remainder >= divisor must be rejected, not parked forever" + ); +} + +#[test] +fn present_pending_msc_purged_on_client_disconnect() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + const WINDOW: u32 = 0x100; + + // Park a NotifyMSC (present_kernel_msc == 0 → always parks). + let mut notify_body = Vec::new(); + notify_body.extend_from_slice(&WINDOW.to_le_bytes()); + notify_body.extend_from_slice(&1_u32.to_le_bytes()); // serial + notify_body.extend_from_slice(&0_u32.to_le_bytes()); // pad + notify_body.extend_from_slice(&1_u64.to_le_bytes()); // target_msc + notify_body.extend_from_slice(&0_u64.to_le_bytes()); // divisor + notify_body.extend_from_slice(&0_u64.to_le_bytes()); // remainder + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::NOTIFY_MSC, + length_units: 10, + }, + ¬ify_body, + None, + ) + .expect("Present NotifyMSC"); + assert_eq!(state.present_pending_msc.len(), 1, "request parked"); + + // Client disconnects → its parked requests must be purged, else they + // are re-scanned every vblank forever with no client to satisfy them. + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + assert!( + state.present_pending_msc.is_empty(), + "parked NotifyMSC purged when its owning client disconnects" + ); +} + +#[test] +fn deferred_present_pixmap_copies_only_after_source_readiness() { + use crate::server::{PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest}; + use yserver_protocol::x11::present::PixmapRequest; + + const WAIT_ID: u64 = 7; + const PRESENT_ID: u64 = 42; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let pending = PendingPresentPixmap { + origin: None, + client_id: ClientId(1), + request: PendingPresentRequest::Pixmap(PixmapRequest { + window: 0x101, + pixmap: 0x102, + serial: 3, + valid: 0, + update: 0, + x_off: 4, + y_off: 5, + target_crtc: 0, + wait_fence: 0, + idle_fence: 0, + options: 0, + target_msc: 0, + divisor: 0, + remainder: 0, + notifies: Vec::new(), + }), + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + masked_options: 0, + src_host_xid: 0x400102, + paint_dst_host_xid: 0x400101, + completion_dst_host_xid: 0x400101, + src_width: 800, + src_height: 600, + update_rects: None, + present_id: PRESENT_ID, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: None, + }; + state.present_wait_to_id.insert(WAIT_ID, PRESENT_ID); + state.present_pending_exec.insert( + PRESENT_ID, + PendingPresentEntry { + pending, + source_ready: false, + superseded_by_executed_present_id: None, + wait_id: Some(WAIT_ID), + pin: Some(999), + }, + ); + + drain_ready_present_pixmaps(&mut state, &mut backend); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })) + ); + + backend.ready_present_source_waits.push(WAIT_ID); + drain_ready_present_pixmaps(&mut state, &mut backend); + assert!(backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: 0x400102, + dst_host_xid: 0x400101, + dst_x: 4, + dst_y: 5, + width: 800, + height: 600, + .. + } + ))); + // The WAIT pin (finish_present_source_wait) and the ENTRY pin + // (release_present_source) are distinct releases — both fire + // exactly once for this one parked entry. + assert_eq!(backend.finished_present_source_waits, vec![WAIT_ID]); + assert_eq!(backend.released_present_sources, vec![999]); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_wait_to_id.is_empty()); +} + +#[test] +fn destroyed_window_purges_parked_present_wait_before_producer_ready() { + // Task 8 Step 1b (extended for Task 5's unified store): a + // PresentPixmap still parked on its async source wait when its + // destination window is destroyed must be purged so it can never + // execute against a dead drawable. The idle fence is released + // by-xid (client still alive), the WAIT pin + // (`finish_present_source_wait`) and the distinct ENTRY pin + // (`release_present_source`) each drop exactly once, the side map + // row is cleaned up, and a later producer-ready drain then creates + // NO copy and NO gate. + use crate::server::{ + PendingPresentEntry, PendingPresentPixmap, PendingPresentRequest, SyncFence, + }; + use yserver_protocol::x11::{CreateWindowRequest, present::PixmapRequest}; + + const CLIENT: u32 = 1; + const WINDOW_XID: u32 = 0x0000_0101; + const IDLE_FENCE: u32 = 0x0000_0555; + const WAIT_ID: u64 = 7; + const PRESENT_ID: u64 = 4242; + const PIN_ID: u64 = 8181; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.sync_fences.insert( + IDLE_FENCE, + SyncFence { + owner: ClientId(CLIENT), + triggered: false, + }, + ); + + let pending = PendingPresentPixmap { + origin: None, + client_id: ClientId(CLIENT), + request: PendingPresentRequest::Pixmap(PixmapRequest { + window: WINDOW_XID, + pixmap: 0x102, + serial: 3, + valid: 0, + update: 0, + x_off: 4, + y_off: 5, + target_crtc: 0, + wait_fence: 0, + idle_fence: IDLE_FENCE, + options: 0, + target_msc: 0, + divisor: 0, + remainder: 0, + notifies: Vec::new(), + }), + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: IDLE_FENCE, + }, + masked_options: 0, + src_host_xid: 0x400102, + paint_dst_host_xid: 0x400101, + completion_dst_host_xid: 0x400101, + src_width: 800, + src_height: 600, + update_rects: None, + present_id: PRESENT_ID, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: None, + }; + state.present_wait_to_id.insert(WAIT_ID, PRESENT_ID); + state.present_pending_exec.insert( + PRESENT_ID, + PendingPresentEntry { + pending, + source_ready: false, + superseded_by_executed_present_id: None, + wait_id: Some(WAIT_ID), + pin: Some(PIN_ID), + }, + ); + + destroy_window_subtree(&mut state, &mut backend, None, ResourceId(WINDOW_XID)) + .expect("destroy"); + + // (a) the parked entry and its side-map row are removed, + assert!( + state.present_pending_exec.is_empty(), + "parked PresentPixmap purged when its destination window is destroyed" + ); + assert!( + state.present_wait_to_id.is_empty(), + "wait_id -> present_id side map row dropped alongside the entry" + ); + // (b) its idle fence was triggered by-xid (client alive), and both + // the WAIT pin and the distinct ENTRY pin dropped exactly once, + assert_eq!( + backend.triggered_dri3_fences, + vec![IDLE_FENCE], + "idle fence released exactly once on window-destroy teardown" + ); + assert!( + state.sync_fences[&IDLE_FENCE].triggered, + "QueryFence mirror must agree with the released idle fence" + ); + assert_eq!( + backend.finished_present_source_waits, + vec![WAIT_ID], + "wait pin dropped exactly once on window-destroy teardown" + ); + assert_eq!( + backend.released_present_sources, + vec![PIN_ID], + "entry pin dropped exactly once on window-destroy teardown" + ); + + // (c) a later producer-ready drain creates no orphan copy + no gate. + let calls_before = backend.calls().len(); + backend.ready_present_source_waits.push(WAIT_ID); + drain_ready_present_pixmaps(&mut state, &mut backend); + assert!( + backend.calls()[calls_before..] + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "no copy is issued for a present whose window was destroyed" + ); + assert!( + state.present_complete_gate.is_empty(), + "no completion gate is inserted for a purged present" + ); + // The later drain reports an unknown wait_id (the entry was + // already purged) — must not double-release either pin. + assert_eq!( + backend.finished_present_source_waits, + vec![WAIT_ID, WAIT_ID], + "backend's own unknown-wait_id report is a no-op guard at the caller, \ + but finish_present_source_wait is still invoked once per drain call" + ); + assert_eq!( + backend.released_present_sources, + vec![PIN_ID], + "entry pin must not be released a second time by the later drain" + ); +} + +fn due_pending_complete( + window: u32, + present_id: u64, + effective_target_msc: u64, + mode: u8, + emit_idle: bool, +) -> crate::server::PendingPresentComplete { + use crate::backend::{CompletedPresentEvent, PresentWake}; + + crate::server::PendingPresentComplete { + event: CompletedPresentEvent { + client_id: ClientId(1), + serial: 1, + host_xid: window, + dst_host_xid: window, + options: 0, + present_id, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + completion_clock: None, + wake: PresentWake::Pixmap { idle_fence_xid: 0 }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }, + effective_target_msc, + mode, + emit_idle, + } +} + +/// Round-3 inversion vector (spec §"Ordered completion delivery +/// (per-window `present_id` order)", blocked-check state 2: +/// executed-but-undrained). P1 executed already (its GPU copy is +/// done) but its completion event has not drained yet — it still sits +/// in `present_complete_gate`. P3 (not modelled — Task 8 doesn't +/// exist on this branch yet) scrapped P2 and parked `Skip(P2)` +/// directly into `present_pending_complete`, already due. Pre-fix, +/// `fire_due_present_completions` swept the queue in raw order and +/// had no notion of the gate at all, so it would deliver the due +/// Skip(P2) immediately — a backward serial, since P1 < P2 for the +/// same window. The per-window hold-back must block Skip(P2) until +/// P1 resolves, then deliver Copy(P1) before Skip(P2). +#[test] +fn due_skip_is_held_back_behind_a_smaller_id_undrained_gate_entry() { + use crate::server::PresentCompleteGate; + use yserver_protocol::x11::present as x11present; + + const WINDOW_XID: u32 = 0x0000_0101; + const PRESENT_EID: u32 = 0x0010_0011; + const P1: u64 = 10; + const P2: u64 = 11; + const TARGET_MSC: u64 = 100; + let clock = crate::backend::PresentClockSample { + msc: TARGET_MSC, + ust: 0x1000, + source: crate::backend::PresentClockSource::PageFlip, + }; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // COMPLETE_NOTIFY_MASK only, so `complete_notify_modes` doesn't + // have to skate around IdleNotify sizes/interleaving. + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW_XID), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + let mut backend = RecordingBackend::new(); + + state.present_complete_gate.insert( + P1, + PresentCompleteGate { + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: TARGET_MSC, + owner: ClientId(1), + dst_window_xid: WINDOW_XID, + }, + ); + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + P2, + TARGET_MSC, + x11present::COMPLETE_MODE_SKIP, + false, + )); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert!( + backend.signalled_present_wakes.is_empty(), + "Skip(P2) must not deliver while P1 (smaller present_id) is \ + still undrained in present_complete_gate — pre-fix this fires" + ); + assert_eq!( + state.present_pending_complete.len(), + 1, + "Skip(P2) stays parked, held back" + ); + assert!( + read_all_available(&mut peer).is_empty(), + "no CompleteNotify reaches the client while held back" + ); + + // P1 resolves (its fence retires late): the gate empties and its + // own completion joins the queue, due, same as Skip(P2). + state.present_complete_gate.remove(&P1); + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + P1, + TARGET_MSC, + x11present::COMPLETE_MODE_COPY, + true, + )); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert!( + state.present_pending_complete.is_empty(), + "both entries deliver once P1 is no longer blocking" + ); + assert_eq!( + backend.signalled_present_wakes, + vec![P1], + "Copy(P1) signals its wake; Skip(P2)'s emit_idle=false gates \ + signal_present_wake off (fix 3 — its wake was already \ + released at scrap)" + ); + // Order proof independent of the (now Skip-gated) wake log: the + // wire itself must read Copy(P1) then Skip(P2). + assert_eq!( + complete_notify_modes(&read_all_available(&mut peer)), + vec![ + x11present::COMPLETE_MODE_COPY, + x11present::COMPLETE_MODE_SKIP + ], + "Copy(P1) delivers before Skip(P2): per-window present_id order" + ); +} + +/// Blocked-check state 1: msc-parked-unexecuted (`present_pending_exec`). +/// Entry A (smaller present_id) is still parked, unexecuted, in the +/// store for window W; Skip(B) (larger present_id) is already due in +/// the queue. B must be held back until A leaves the store, then both +/// deliver in id order. +#[test] +fn due_skip_is_held_back_behind_a_smaller_id_unexecuted_store_entry() { + use yserver_protocol::x11::present as x11present; + + const WINDOW_XID: u32 = 0x0000_0202; + const PRESENT_EID: u32 = 0x0010_0022; + const A: u64 = 20; + const B: u64 = 21; + const TARGET_MSC: u64 = 50; + let clock = crate::backend::PresentClockSample { + msc: TARGET_MSC, + ust: 0x2000, + source: crate::backend::PresentClockSource::PageFlip, + }; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW_XID), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + let mut backend = RecordingBackend::new(); + + state + .present_pending_exec + .insert(A, stub_pending_present_entry(WINDOW_XID, A)); + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + B, + TARGET_MSC, + x11present::COMPLETE_MODE_SKIP, + false, + )); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert!( + backend.signalled_present_wakes.is_empty(), + "Skip(B) held back while A (smaller present_id) is still \ + unexecuted in present_pending_exec" + ); + + // A executes and completes. + state.present_pending_exec.remove(&A); + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + A, + TARGET_MSC, + x11present::COMPLETE_MODE_COPY, + true, + )); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert_eq!( + backend.signalled_present_wakes, + vec![A], + "Copy(A) signals its wake; Skip(B)'s emit_idle=false gates it off" + ); + assert_eq!( + complete_notify_modes(&read_all_available(&mut peer)), + vec![ + x11present::COMPLETE_MODE_COPY, + x11present::COMPLETE_MODE_SKIP + ], + "both deliver in arrival (present_id) order once A clears the store" + ); +} + +/// Per-window isolation: window X's stalled completion must not delay +/// window Y's due completion in the same sweep. +#[test] +fn per_window_hold_back_does_not_cross_windows() { + use crate::server::PresentCompleteGate; + use yserver_protocol::x11::present as x11present; + + const WINDOW_X: u32 = 0x0000_0303; + const WINDOW_Y: u32 = 0x0000_0404; + const X_SMALL: u64 = 30; + const X_SKIP: u64 = 31; + const Y_ID: u64 = 32; + const TARGET_MSC: u64 = 70; + let clock = crate::backend::PresentClockSample { + msc: TARGET_MSC, + ust: 0x3000, + source: crate::backend::PresentClockSource::PageFlip, + }; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + state.present_complete_gate.insert( + X_SMALL, + PresentCompleteGate { + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + effective_target_msc: TARGET_MSC, + owner: ClientId(1), + dst_window_xid: WINDOW_X, + }, + ); + state.present_pending_complete.push(due_pending_complete( + WINDOW_X, + X_SKIP, + TARGET_MSC, + x11present::COMPLETE_MODE_SKIP, + false, + )); + state.present_pending_complete.push(due_pending_complete( + WINDOW_Y, + Y_ID, + TARGET_MSC, + x11present::COMPLETE_MODE_COPY, + true, + )); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert_eq!( + backend.signalled_present_wakes, + vec![Y_ID], + "window Y's due completion delivers even though window X is stalled" + ); + assert_eq!( + state.present_pending_complete.len(), + 1, + "window X's Skip stays held back" + ); + assert_eq!(state.present_pending_complete[0].event.present_id, X_SKIP); +} + +/// Blocked-check state 3: parked-not-yet-due, i.e. an earlier entry +/// in the very same queue group. id=5 (smaller, Copy) has a FUTURE +/// target; id=7 (larger, Skip) is due right now. Even though id=7 is +/// individually due, it must not be delivered ahead of id=5 — the +/// per-window walk has to stop (not skip past) the first blocked +/// entry it meets. Reworded as a mutation check: a `break`→`continue` +/// slip in the sweep's inner loop would let id=7 slide through on the +/// first pass while id=5 stays parked — this test's first-pass +/// assertion (nothing delivered) catches exactly that; verified by +/// hand-applying the mutation locally (see report). +#[test] +fn future_smaller_id_blocks_due_larger_id_in_same_queue_group() { + use yserver_protocol::x11::present as x11present; + + const WINDOW_XID: u32 = 0x0000_0707; + const PRESENT_EID: u32 = 0x0010_0077; + const SMALLER_FUTURE: u64 = 5; + const LARGER_DUE: u64 = 7; + const FUTURE_MSC: u64 = 1_000; + const DUE_MSC: u64 = 10; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW_XID), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + let mut backend = RecordingBackend::new(); + + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + SMALLER_FUTURE, + FUTURE_MSC, + x11present::COMPLETE_MODE_COPY, + true, + )); + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + LARGER_DUE, + DUE_MSC, + x11present::COMPLETE_MODE_SKIP, + false, + )); + + // First sweep: clock is past id=7's target but nowhere near + // id=5's. Nothing for this window may deliver. + let clock_mid = crate::backend::PresentClockSample { + msc: 50, + ust: 0x7000, + source: crate::backend::PresentClockSource::PageFlip, + }; + fire_due_present_completions(&mut state, &mut backend, clock_mid); + assert!( + backend.signalled_present_wakes.is_empty(), + "neither entry delivers: id=7 is due but held behind id=5's \ + still-future target (state 3 — parked-not-yet-due)" + ); + assert_eq!( + state.present_pending_complete.len(), + 2, + "both entries retained" + ); + assert!( + read_all_available(&mut peer).is_empty(), + "no CompleteNotify reaches the client on the blocked first sweep" + ); + + // Second sweep: clock passes both targets — both deliver, in order. + let clock_late = crate::backend::PresentClockSample { + msc: FUTURE_MSC + 1, + ust: 0x7001, + source: crate::backend::PresentClockSource::PageFlip, + }; + fire_due_present_completions(&mut state, &mut backend, clock_late); + assert!(state.present_pending_complete.is_empty()); + assert_eq!( + complete_notify_modes(&read_all_available(&mut peer)), + vec![ + x11present::COMPLETE_MODE_COPY, + x11present::COMPLETE_MODE_SKIP + ], + "Copy(5) then Skip(7), once both are due" + ); +} + +/// A parked Skip (supersession scrap) must emit no second IdleNotify +/// and touch no fence mirror at delivery — both were already handled +/// at scrap time (spec §"Ordered completion delivery" item 1). Only +/// the CompleteNotify goes out, with mode byte `COMPLETE_MODE_SKIP`. +#[test] +fn parked_skip_delivery_emits_only_complete_notify_mode_skip() { + use crate::{backend::CompletedPresentEvent, server::SyncFence}; + use yserver_protocol::x11::present as x11present; + + const WINDOW_XID: u32 = 0x0000_0505; + const PRESENT_EID: u32 = 0x0010_0099; + const IDLE_FENCE: u32 = 0x0000_0777; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW_XID), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY | x11present::EVENT_MASK_IDLE_NOTIFY, + }, + ); + // A live fence the scrap path already triggered; delivery must + // not touch it (it's already `true`, but the *write* itself must + // not happen — a real regression would re-trigger a fence a + // client has since reused for a fresh present, per the spec). + state.sync_fences.insert( + IDLE_FENCE, + SyncFence { + owner: ClientId(1), + triggered: true, + }, + ); + let _ = read_all_available(&mut peer); + + let mut backend = RecordingBackend::new(); + let event = CompletedPresentEvent { + client_id: ClientId(1), + serial: 5, + host_xid: WINDOW_XID, + dst_host_xid: WINDOW_XID, + options: 0, + present_id: 99, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + completion_clock: None, + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: IDLE_FENCE, + }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }; + let clock = crate::backend::PresentClockSample { + msc: 42, + ust: 0x9999, + source: crate::backend::PresentClockSource::PageFlip, + }; + complete_present_with_clock( + &mut state, + &mut backend, + &event, + clock, + x11present::COMPLETE_MODE_SKIP, + false, + ); + + let bytes = read_all_available(&mut peer); + assert_eq!( + bytes.len(), + 40, + "exactly one event (CompleteNotify only, no IdleNotify): got {} bytes", + bytes.len() + ); + assert_eq!(bytes[0], 35, "GenericEvent"); + assert_eq!(bytes[1], 145, "PRESENT major opcode"); + assert_eq!( + u16::from_le_bytes(bytes[8..10].try_into().unwrap()), + u16::from(x11present::EVENT_COMPLETE_NOTIFY), + ); + assert_eq!(bytes[11], x11present::COMPLETE_MODE_SKIP); + assert!( + state.sync_fences[&IDLE_FENCE].triggered, + "fence mirror must still read triggered=true (scrap set it) — \ + this only proves delivery didn't touch it; a fresh false->false \ + would look identical, so this test also relies on \ + `complete_present_with_clock`'s emit_idle=false code path \ + skipping the write entirely (see source)" + ); +} + +#[test] +fn direct_flip_completion_and_buffer_idle_are_separate_retirements() { + use crate::{backend::CompletedPresentEvent, server::SyncFence}; + use yserver_protocol::x11::present as x11present; + + const WINDOW_XID: u32 = 0x0000_0606; + const PIXMAP_XID: u32 = 0x0000_0607; + const PRESENT_EID: u32 = 0x0010_00aa; + const IDLE_FENCE: u32 = 0x0000_0888; + const PRESENT_ID: u64 = 123; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW_XID), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY | x11present::EVENT_MASK_IDLE_NOTIFY, + }, + ); + state.sync_fences.insert( + IDLE_FENCE, + SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + let _ = read_all_available(&mut peer); + + let event = CompletedPresentEvent { + client_id: ClientId(1), + serial: 7, + host_xid: PIXMAP_XID, + dst_host_xid: WINDOW_XID, + options: 0, + present_id: PRESENT_ID, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + completion_clock: None, + wake: crate::backend::PresentWake::Pixmap { + idle_fence_xid: IDLE_FENCE, + }, + completion_mode: x11present::COMPLETE_MODE_FLIP, + emit_idle: false, + }; + let clock = crate::backend::PresentClockSample { + msc: 55, + ust: 66, + source: crate::backend::PresentClockSource::PageFlip, + }; + let mut backend = RecordingBackend::new(); + + complete_present_with_clock( + &mut state, + &mut backend, + &event, + clock, + event.completion_mode, + event.emit_idle, + ); + let complete = read_all_available(&mut peer); + assert_eq!(complete.len(), 40, "flip retirement emits one event"); + assert_eq!( + u16::from_le_bytes(complete[8..10].try_into().unwrap()), + u16::from(x11present::EVENT_COMPLETE_NOTIFY) + ); + assert_eq!(complete[11], x11present::COMPLETE_MODE_FLIP); + assert!(!state.sync_fences[&IDLE_FENCE].triggered); + assert!(backend.signalled_present_wakes.is_empty()); + + retire_present_idle(&mut state, &mut backend, &event); + let idle = read_all_available(&mut peer); + assert_eq!(idle.len(), 32, "replacement retirement emits one event"); + assert_eq!( + u16::from_le_bytes(idle[8..10].try_into().unwrap()), + u16::from(x11present::EVENT_IDLE_NOTIFY) + ); + assert!(state.sync_fences[&IDLE_FENCE].triggered); + assert_eq!(backend.signalled_present_wakes, vec![PRESENT_ID]); +} + +#[test] +fn free_pixmap_between_park_and_drain_still_executes_the_pinned_copy() { + // Task 5 TDD (iii): `FreePixmap` on the *source* pixmap is legal + // immediately after `PresentPixmap` — Xorg refs the vblank's + // pixmap for exactly this reason. The entry pin exists so a copy + // still parked on its producer-fence wait at that point keeps + // targeting the pinned drawable rather than a dead xid. Drive the + // real Deferred arm through `process_request` (not a manually + // constructed entry) so the pin comes from the production code + // path, `FreePixmap` the source in between, then verify the drain + // still issues the copy and releases the entry pin exactly once. + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; + + const CLIENT: u32 = 21; + const WINDOW_XID: u32 = 0x00e0_2103; + const PIXMAP_XID: u32 = 0x00e0_2104; + const WINDOW_HOST_XID: u32 = 0x0040_2103; + const PIXMAP_HOST_XID: u32 = 0x0040_2104; + const WAIT_ID: u64 = 33; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + backend.present_source_wait = crate::backend::PresentSourceWait::Deferred(WAIT_ID); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST_XID); + } + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(PIXMAP_HOST_XID).expect("valid host pixmap"), + ); + + // PresentPixmap (opcode 1) fixed prefix, mirroring the 68-byte + // body other tests in this module build: window pixmap serial + // valid update x_off y_off ... (only window/pixmap set here — a + // full-pixmap copy, no update region). + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert_eq!( + state.present_pending_exec.len(), + 1, + "the source wait parks exactly one entry" + ); + let pin = state + .present_pending_exec + .values() + .next() + .unwrap() + .pin + .expect("Deferred arm takes an entry pin"); + + // FreePixmap the source in between park and drain. + handle_free_pixmap( + &mut state, + &mut backend, + None, + ClientId(CLIENT), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 54, + minor: 0, + }, + &free_pixmap_body(PIXMAP_XID), + ) + .expect("free pixmap"); + assert!( + backend + .calls() + .iter() + .any(|call| matches!(call, RecordedCall::FreePixmap(PIXMAP_HOST_XID))), + "FreePixmap on the source must still free the host pixmap" + ); + + let calls_before = backend.calls().len(); + backend.ready_present_source_waits.push(WAIT_ID); + drain_ready_present_pixmaps(&mut state, &mut backend); + + assert!( + backend.calls()[calls_before..].iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + dst_host_xid: WINDOW_HOST_XID, + .. + } + )), + "the drain still executes the copy against the pinned source xid, \ + not a dropped/dead one" + ); + assert_eq!( + backend.released_present_sources, + vec![pin], + "the entry pin is released exactly once, at execution" + ); + assert!(state.present_pending_exec.is_empty()); + assert!(state.present_wait_to_id.is_empty()); +} + +// ──────────────────────────────────────────────────────────────── +// Task 7 Step 4: msc-due classification + deferral. +// ──────────────────────────────────────────────────────────────── + +/// (i) A future-target present must not copy or damage anything until +/// it becomes due. Drives `drain_due_present_pending_exec` directly +/// against a manually parked (source-ready) entry — the due-pass is +/// the sole place a still-parked future-target entry can execute. +#[test] +fn future_target_present_produces_no_copy_until_due() { + const PRESENT_ID: u64 = 500; + const WINDOW_HOST_XID: u32 = 0x0040_0601; + const PIXMAP_HOST_XID: u32 = 0x0040_0602; + const EFF: u64 = 105; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); // clock=100, eff(105) > 101: future. + seed_present_clock(&mut state, 100, 0x1000); + // Isolate the plain clock-driven due rule from the idle-display + // fallback (RecordingBackend defaults `present_display_idle` to + // `true`, matching "no backend ever composes" — which would + // otherwise execute this future-target entry immediately via + // that separate fallback rung, not the one this test pins). + backend.present_display_idle = false; + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(EFF), + true, // source_ready + ), + ); + + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "no copy while the target is still in the future" + ); + assert_eq!( + state.present_pending_exec.len(), + 1, + "the entry stays parked" + ); + + // Clock catches up to the target: now due. + backend.present_ust_msc = (EFF, 0x2000); + seed_present_clock(&mut state, EFF, 0x2000); + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + dst_host_xid: WINDOW_HOST_XID, + .. + } + )), + "the copy executes once the clock reaches the target" + ); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +// Mutation: treat an unsupported wake capability as a failed supported arm and execute the target early. +fn unsupported_wake_keeps_flip_driven_present_paced() { + const PRESENT_ID: u64 = 508; + const WINDOW_HOST_XID: u32 = 0x0040_0701; + const PIXMAP_HOST_XID: u32 = 0x0040_0702; + const TARGET_MSC: u64 = 120; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_flip_in_flight = true; + backend.present_display_idle = false; + backend.present_absolute_vblank_arm_supported = false; + seed_present_clock(&mut state, 100, 0x1000); + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(TARGET_MSC), + true, + ), + ); + + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "unsupported wake capability alone must not copy a future target while the flip advances" + ); + assert!( + state.present_pending_exec.contains_key(&PRESENT_ID), + "the Present remains parked until the advancing flip clock reaches MSC 120" + ); + + backend.present_ust_msc = (TARGET_MSC, 0x2000); + backend.present_flip_in_flight = false; + seed_present_clock(&mut state, TARGET_MSC, 0x2000); + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + dst_host_xid: WINDOW_HOST_XID, + .. + } + )), + "the parked Present copies when the general MSC reaches its target" + ); + assert!(state.present_pending_exec.is_empty()); +} + +/// Review fix (test addition b): the due-pass must RE-PARK an +/// immediate-target entry when `flip_in_flight` is STILL true at +/// drain time — the previously-covered vector only pinned the park +/// decision at ARRIVAL, not the due-pass's own re-evaluation using a +/// freshly sampled `flip_in_flight`. +#[test] +fn due_pass_reparks_immediate_target_when_flip_still_in_flight() { + const PRESENT_ID: u64 = 509; + const WINDOW_HOST_XID: u32 = 0x0040_0f01; + const PIXMAP_HOST_XID: u32 = 0x0040_0f02; + const CLOCK: u64 = 300; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 0x1000); + backend.present_flip_in_flight = true; // still in flight at drain time. + // Isolate the plain due-pass decision from the fallback rungs. + backend.present_display_idle = false; + backend.present_absolute_vblank_arm_supported = false; + backend.present_scanout_blackout = false; + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(CLOCK + 1), // immediate target. + true, + ), + ); + + drain_due_present_pending_exec(&mut state, &mut backend); + + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "an immediate target must stay parked while a flip is still in \ + flight at the due-pass's own re-evaluation, not just at arrival" + ); + assert_eq!(state.present_pending_exec.len(), 1, "entry stays parked"); +} + +/// (ii) Immediate-target arrival: executes with no flip in flight, +/// parks with one — driven end-to-end through `process_request` so +/// the arrival evaluation (not just the pure classifier) is pinned. +#[test] +fn immediate_target_present_executes_at_arrival_without_flip_in_flight() { + const CLIENT: u32 = 30; + const WINDOW_XID: u32 = 0x00e0_3001; + const PIXMAP_XID: u32 = 0x00e0_3002; + const WINDOW_HOST_XID: u32 = 0x0040_3001; + const PIXMAP_HOST_XID: u32 = 0x0040_3002; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (10, 0x1000); // eff will land at clock+1 = 11. + backend.present_flip_in_flight = false; + + setup_present_pixmap_source_and_dest( + &mut state, + CLIENT, + WINDOW_XID, + PIXMAP_XID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + dst_host_xid: WINDOW_HOST_XID, + .. + } + )), + "immediate target with no flip in flight executes at arrival" + ); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +fn immediate_target_present_parks_at_arrival_with_flip_in_flight() { + const CLIENT: u32 = 31; + const WINDOW_XID: u32 = 0x00e0_3101; + const PIXMAP_XID: u32 = 0x00e0_3102; + const WINDOW_HOST_XID: u32 = 0x0040_3101; + const PIXMAP_HOST_XID: u32 = 0x0040_3102; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (10, 0x1000); + backend.present_flip_in_flight = true; + + setup_present_pixmap_source_and_dest( + &mut state, + CLIENT, + WINDOW_XID, + PIXMAP_XID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "immediate target with a flip in flight must not copy at arrival" + ); + assert_eq!( + state.present_pending_exec.len(), + 1, + "the present parks instead" + ); + assert!( + state + .present_pending_exec + .values() + .next() + .unwrap() + .source_ready, + "parked-for-msc entries are source_ready (only the clock is blocking)" + ); +} + +#[test] +fn clocked_async_present_executes_during_in_flight_flip() { + const CLIENT: u32 = 32; + const WINDOW_XID: u32 = 0x00e0_3201; + const PIXMAP_XID: u32 = 0x00e0_3202; + const WINDOW_HOST_XID: u32 = 0x0040_3201; + const PIXMAP_HOST_XID: u32 = 0x0040_3202; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (10, 0x1000); + backend.present_flip_in_flight = true; + + setup_present_pixmap_source_and_dest( + &mut state, + CLIENT, + WINDOW_XID, + PIXMAP_XID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + body[36..40].copy_from_slice(&crate::present_scheduler::PRESENT_OPTION_ASYNC.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + dst_host_xid: WINDOW_HOST_XID, + .. + } + )), + "a clocked immediate async Present must reach the backend successor path instead of parking behind the current flip", + ); + assert!( + state.present_pending_exec.is_empty(), + "the core scheduler must not retain the async successor until vblank", + ); + assert_eq!( + state + .present_complete_gate + .values() + .next() + .map(|gate| gate.effective_target_msc), + Some(10), + "the Xorg current-MSC identity must survive through backend completion gating", + ); +} + +/// Shared window+pixmap setup for the arrival-evaluation tests above. +fn setup_present_pixmap_source_and_dest( + state: &mut ServerState, + client: u32, + window_xid: u32, + pixmap_xid: u32, + window_host_xid: u32, + pixmap_host_xid: u32, +) { + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; + + state.resources.create_window( + ClientId(client), + CreateWindowRequest { + depth: 24, + window: ResourceId(window_xid), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(window_xid)); + if let Some(w) = state.resources.window_mut(ResourceId(window_xid)) { + w.host_xid = crate::backend::WindowHandle::from_raw(window_host_xid); + } + state.resources.create_pixmap( + ClientId(client), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap_xid), + drawable: ResourceId(window_xid), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(pixmap_xid), + crate::backend::PixmapHandle::from_raw(pixmap_host_xid).expect("valid host pixmap"), + ); +} + +/// (iii) A parked immediate-target entry executes on the flip- +/// retirement wakeup, and its `mark_dirty` precedes `maybe_composite` +/// in the SAME `run_iteration_tail` call — reusing Task 4's call-order +/// instrumentation, now exercised via the msc-due path (source_ready, +/// no wait_id) rather than the source-wait path. +#[test] +fn parked_immediate_target_executes_and_marks_dirty_before_compose_in_same_tail() { + use crate::backend::recording::RecordedCall; + + const PRESENT_ID: u64 = 0x9001; + const WINDOW_HOST_XID: u32 = 0x0040_9001; + const PIXMAP_HOST_XID: u32 = 0x0040_9002; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + // The entry parked earlier because a flip was in flight; that + // flip has now retired (this iteration's fresh sample) and the + // clock has caught up so the target is due. + backend.present_ust_msc = (200, 0x3000); + backend.present_flip_in_flight = false; + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(200), // eff <= clock: due now. + true, + ), + ); + + crate::core_loop::run::run_iteration_tail(&mut state, &mut backend); + + let calls = backend.calls(); + let mark_dirty_idx = calls + .iter() + .position(|c| matches!(c, RecordedCall::MarkDirty)) + .expect("due entry executed and marked dirty"); + let composite_idx = calls + .iter() + .position(|c| matches!(c, RecordedCall::MaybeComposite)) + .expect("maybe_composite invoked"); + assert!( + mark_dirty_idx < composite_idx, + "due-pass mark_dirty ({mark_dirty_idx}) must precede maybe_composite ({composite_idx})" + ); + assert!(state.present_pending_exec.is_empty()); +} + +/// (iv) Idle-display fallback: only on `!present_absolute_vblank_arm_supported()` +/// backends, and only when `present_display_idle()` is true, does a +/// still-parked source-ready entry execute early. +#[test] +fn idle_display_fallback_executes_parked_entry_when_display_idle() { + const PRESENT_ID: u64 = 501; + const WINDOW_HOST_XID: u32 = 0x0040_0701; + const PIXMAP_HOST_XID: u32 = 0x0040_0702; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_absolute_vblank_arm_supported = false; + backend.present_display_idle = true; + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(200), // far future — never due by clock alone here. + true, + ), + ); + + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + .. + } + )), + "an idle display with no absolute-arm support must execute the parked entry" + ); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +fn idle_display_fallback_does_not_fire_when_display_not_idle() { + const PRESENT_ID: u64 = 502; + const WINDOW_HOST_XID: u32 = 0x0040_0801; + const PIXMAP_HOST_XID: u32 = 0x0040_0802; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_absolute_vblank_arm_supported = false; + backend.present_display_idle = false; + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(200), + true, + ), + ); + + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "not-idle display must not trigger the idle fallback" + ); + assert_eq!(state.present_pending_exec.len(), 1, "entry stays parked"); +} + +#[test] +fn idle_display_fallback_does_not_apply_when_arm_supported() { + // Spec §msc-due: the idle-display fallback applies ONLY on + // `!present_absolute_vblank_arm_supported()` drivers — even with + // `present_display_idle() == true`, an arm-capable driver must not + // take this shortcut (it would reintroduce the early-frame bug + // for mpv on sequence-capable drivers). + const PRESENT_ID: u64 = 503; + const WINDOW_HOST_XID: u32 = 0x0040_0901; + const PIXMAP_HOST_XID: u32 = 0x0040_0902; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_absolute_vblank_arm_supported = true; + backend.present_display_idle = true; + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(200), + true, + ), + ); + + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "arm-supported backends never take the idle-display shortcut" + ); + assert_eq!(state.present_pending_exec.len(), 1); +} + +/// (v) Blackout: parked entries execute AND queued completions deliver +/// with the frozen clock, independent of clock advance. +#[test] +fn blackout_flushes_parked_entries_and_queued_completions() { + use yserver_protocol::x11::present as x11present; + + const PRESENT_ID: u64 = 504; + const WINDOW_HOST_XID: u32 = 0x0040_0a01; + const PIXMAP_HOST_XID: u32 = 0x0040_0a02; + const QUEUED_ID: u64 = 900; + const WINDOW_XID: u32 = 0x0000_0a03; // dst_host_xid key for the queued completion + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); // frozen: never advances during blackout. + backend.present_scanout_blackout = true; + backend.present_absolute_vblank_arm_supported = false; + backend.present_display_idle = false; // prove blackout fires independent of idle. + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(5_000), // far future — would never be due by clock or idle alone. + true, + ), + ); + // A queued completion whose target is also far in the future — + // must still flush, stamped with the frozen clock. + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + QUEUED_ID, + 5_000, + x11present::COMPLETE_MODE_COPY, + true, + )); + + drain_due_present_pending_exec(&mut state, &mut backend); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + .. + } + )), + "blackout must force-execute the parked msc-due entry" + ); + assert!(state.present_pending_exec.is_empty()); + assert!( + state.present_pending_complete.is_empty(), + "the queued completion must flush too, not just the parked entry" + ); + assert_eq!( + backend.signalled_present_wakes, + vec![QUEUED_ID], + "the queued completion delivers despite its target being far in the future" + ); +} + +/// Review fix (blocker): blackout must flush queued completions even +/// when `present_pending_exec` is completely EMPTY — the DPMS-off +/// case where flips keep retiring normally (so every arrival +/// classifies `ExecuteNow` and the store never accumulates an entry) +/// but `present_pending_complete` still carries an entry gated +/// against a frozen completion clock. Pre-fix, `drain_due_present_pending_exec`'s +/// leading `present_pending_exec.is_empty()` check returned before +/// ever reaching the blackout branch (the sole caller of +/// `fire_all_present_completions_now`), so this entry would park +/// forever. +#[test] +fn blackout_flushes_queued_completions_even_with_empty_exec_store() { + use yserver_protocol::x11::present as x11present; + + const QUEUED_ID: u64 = 901; + const WINDOW_XID: u32 = 0x0000_0a04; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_scanout_blackout = true; + + assert!( + state.present_pending_exec.is_empty(), + "precondition: the msc-due store is empty — this is the DPMS-off \ + case where flips keep retiring so nothing ever msc-parks" + ); + state.present_pending_complete.push(due_pending_complete( + WINDOW_XID, + QUEUED_ID, + 5_000, // far future — would never be due by clock alone. + x11present::COMPLETE_MODE_COPY, + true, + )); + + drain_due_present_pending_exec(&mut state, &mut backend); + + assert!( + state.present_pending_complete.is_empty(), + "the queued completion must flush during blackout even with an \ + empty present_pending_exec store" + ); + assert_eq!(backend.signalled_present_wakes, vec![QUEUED_ID]); +} + +/// Review fix: pin the residual blackout hold-back case documented on +/// `fire_all_present_completions_now` — `drain_due_present_pending_exec`'s +/// blackout branch force-executes only `source_ready` entries, so a +/// `source_ready:false` entry (still waiting on its own producer +/// fence — e.g. an uncovered sliver the successor gate declined to +/// scrap) keeps its window's parked completions held back through +/// the flush, even with blackout on. Once the producer fence signals +/// (`source_ready` flips true), the next due-pass + flush drains +/// both. +#[test] +fn blackout_holds_back_completions_behind_a_not_source_ready_entry_until_it_resolves() { + use yserver_protocol::x11::present as x11present; + + const WINDOW_HOST_XID: u32 = 0x0040_0a05; + const PIXMAP_HOST_XID: u32 = 0x0040_0a06; + const BLOCKER_ID: u64 = 1; + const QUEUED_ID: u64 = 2; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); + backend.present_scanout_blackout = true; + + // `effective_target_msc: None` for the no-clock blocker so its own + // execution delivers inline with no `present_complete_gate` row + // (the no-target arm at `execute_present_pixmap_copy`'s + // gate insert — `if let Some(eff) = ... `) — otherwise resolving + // it would additionally require draining the gate (a distinct, + // already-covered mechanism), which would muddy this test's + // narrow point: every execution filter here (`due`, idle + // fallback, blackout) is gated on `source_ready` alone, so this + // entry is blocked purely by that flag regardless of clock/eff. + state.present_pending_exec.insert( + BLOCKER_ID, + present_pending_entry_with( + BLOCKER_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + None, + false, // still waiting on its own producer fence + ), + ); + state.present_pending_complete.push(due_pending_complete( + WINDOW_HOST_XID, + QUEUED_ID, + 5_000, // far future — only "due" via the blackout force. + x11present::COMPLETE_MODE_COPY, + true, + )); + + drain_due_present_pending_exec(&mut state, &mut backend); + + assert_eq!( + state.present_pending_exec.len(), + 1, + "blackout must NOT force-execute a source_ready:false entry" + ); + assert_eq!( + state.present_pending_complete.len(), + 1, + "the due completion for the same window must stay held back behind \ + the unresolved blocker, even during blackout" + ); + assert!(backend.signalled_present_wakes.is_empty()); + + // The blocker's own producer fence signals. + state + .present_pending_exec + .get_mut(&BLOCKER_ID) + .unwrap() + .source_ready = true; + + drain_due_present_pending_exec(&mut state, &mut backend); + + assert!( + state.present_pending_exec.is_empty(), + "the next blackout pass must force-execute the now-source_ready blocker" + ); + assert!( + state.present_pending_complete.is_empty(), + "and the queue drains: the held-back completion delivers in the same pass" + ); + assert_eq!(backend.signalled_present_wakes, vec![QUEUED_ID]); +} + +/// (vi) Arm failure / `Ok(0)`: entries execute immediately in the +/// same pass (the third arming call site, `run::arm_present_idle_vblanks`). +#[test] +fn shared_wake_false_executes_distant_parked_entries_immediately() { + const PRESENT_ID: u64 = 505; + const WINDOW_HOST_XID: u32 = 0x0040_0b01; + const PIXMAP_HOST_XID: u32 = 0x0040_0b02; + const CLOCK: u64 = 100; + const EFF: u64 = 110; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 0x1000); + seed_present_clock(&mut state, CLOCK, 0x1000); + backend.present_absolute_vblank_arm_supported = true; + backend.arm_present_shared_wake_result = Some(Ok(false)); + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(EFF), + true, + ), + ); + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + + assert_eq!(backend.armed_shared_wake_crtcs, [0]); + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + .. + } + )), + "Ok(0) (nothing covered) must execute the entry immediately" + ); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +fn shared_wake_err_executes_distant_parked_entries_immediately() { + const PRESENT_ID: u64 = 506; + const WINDOW_HOST_XID: u32 = 0x0040_0c01; + const PIXMAP_HOST_XID: u32 = 0x0040_0c02; + const CLOCK: u64 = 100; + const EFF: u64 = 110; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 0x1000); + seed_present_clock(&mut state, CLOCK, 0x1000); + backend.present_absolute_vblank_arm_supported = true; + backend.arm_present_shared_wake_result = Some(Err(std::io::ErrorKind::Other)); + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(EFF), + true, + ), + ); + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + .. + } + )), + "Err must execute the entry immediately, same as Ok(0)" + ); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +fn shared_wake_success_leaves_entry_parked() { + const PRESENT_ID: u64 = 507; + const WINDOW_HOST_XID: u32 = 0x0040_0d01; + const PIXMAP_HOST_XID: u32 = 0x0040_0d02; + const CLOCK: u64 = 100; + const EFF: u64 = 110; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 0x1000); + seed_present_clock(&mut state, CLOCK, 0x1000); + backend.present_absolute_vblank_arm_supported = true; + // Default (None) result mimics a real always-succeeds arm. + + state.present_pending_exec.insert( + PRESENT_ID, + present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(EFF), + true, + ), + ); + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "a successful arm must not execute — the entry stays parked, awaiting the arm's event" + ); + assert_eq!(backend.armed_shared_wake_crtcs, [0]); + assert_eq!(state.present_pending_exec.len(), 1); +} + +// Mutation: treat a target at or before the completion clock as ahead. +#[test] +fn shared_wake_held_presents_past_target_arm_nothing() { + use crate::server::PresentCompleteGate; + use yserver_protocol::x11::present as x11present; + + const WINDOW: u32 = 0x0001_5101; + const EVENT_ID: u32 = 0x0010_5101; + const BLOCKER: u64 = 0; + const FIRST: u64 = 1; + const COUNT: u64 = 40; + const CLOCK: u64 = 100; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound core round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 1_000); + backend.present_absolute_vblank_arm_supported = true; + seed_present_domain_clock(&mut state, 11, 1, CLOCK, 1_000); + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + state.present_event_selections.insert( + EVENT_ID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + state.present_complete_gate.insert( + BLOCKER, + PresentCompleteGate { + crtc_id: 11, + crtc_epoch: 1, + msc_offset: 0, + effective_target_msc: CLOCK, + owner: ClientId(1), + dst_window_xid: WINDOW, + }, + ); + create_present_test_window(&mut state, WINDOW, 0, 0, 32, 32); + let target = state + .resources + .window_mut(ResourceId(WINDOW)) + .expect("created Present window"); + target.host_xid = crate::backend::WindowHandle::from_raw(WINDOW | 0x0040_0000); + target.map_state = crate::resources::MapState::Viewable; + for present_id in FIRST..FIRST + COUNT { + let pixmap = 0x0041_5100 + present_id as u32; + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(pixmap), + drawable: ResourceId(WINDOW), + width: 32, + height: 32, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(pixmap), + crate::backend::PixmapHandle::from_raw(pixmap).expect("valid Present pixmap host xid"), + )); + let mut body = pixmap_body(WINDOW, pixmap); + body[8..12].copy_from_slice(&(present_id as u32).to_le_bytes()); + body[36..40].copy_from_slice(&crate::present_scheduler::PRESENT_OPTION_ASYNC.to_le_bytes()); + body[44..52].copy_from_slice(&CLOCK.to_le_bytes()); + let sequence = u16::try_from((present_id - FIRST) * 2 + 1).unwrap(); + assert!( + run_core_present_request_and_wait( + &mut state, + &mut backend, + &mut peer, + sequence, + sequence + 1, + x11present::PIXMAP, + &body, + ) + .is_empty() + ); + } + assert!(state.present_complete_gate.contains_key(&BLOCKER)); + assert_eq!(backend.enqueued_present_completions.len(), COUNT as usize); + assert_eq!( + backend + .enqueued_present_completions + .iter() + .map(|(event, _)| event.present_id) + .collect::>(), + (FIRST..FIRST + COUNT).collect::>() + ); + backend.completed_present_events_to_drain.extend( + std::mem::take(&mut backend.enqueued_present_completions) + .into_iter() + .map(|(event, _)| event), + ); + let blocked_wire = run_core_present_wait_drain( + &mut state, + &mut backend, + &mut peer, + u16::try_from(COUNT * 2 + 1).unwrap(), + ); + assert!( + blocked_wire.is_empty(), + "the older gate must hold the real completions: wire={}, pending={}, gates={:?}", + blocked_wire.len(), + state.present_pending_complete.len(), + state.present_complete_gate + ); + assert_eq!(state.present_pending_complete.len(), COUNT as usize); + + assert!( + backend.armed_shared_wake_crtcs.is_empty(), + "reached completions must not arm: arms={:?}, targets={:?}, clocks={:?}", + backend.armed_shared_wake_crtcs, + state + .present_pending_complete + .iter() + .map(|pending| pending.effective_target_msc) + .collect::>(), + state.present_crtc_clocks + ); + state.present_complete_gate.remove(&BLOCKER); + let wire = run_core_present_wait_drain( + &mut state, + &mut backend, + &mut peer, + u16::try_from(COUNT * 2 + 2).unwrap(), + ); + assert!(state.present_pending_complete.is_empty()); + let serials: Vec = wire + .chunks_exact(40) + .map(|event| u32::from_le_bytes(event[20..24].try_into().unwrap())) + .collect(); + assert_eq!( + serials, + (FIRST..FIRST + COUNT) + .map(|id| id as u32) + .collect::>() + ); +} + +// Mutation: restore per-target arming, stop re-arming after the first wake, or skip DestroyWindow cleanup. +#[test] +fn shared_wake_future_targets_make_one_call_per_domain_per_iteration() { + use yserver_protocol::x11::present as x11present; + + const FIRST_WINDOW: u32 = 0x0001_5201; + const SECOND_WINDOW: u32 = 0x0001_5202; + const DESTROYED_WINDOW: u32 = 0x0001_5203; + const FIRST_EVENT: u32 = 0x0010_5201; + const SECOND_EVENT: u32 = 0x0010_5202; + const COUNT_PER_WINDOW: u64 = 130; + const FIRST_ID: u32 = 1; + const SECOND_ID: u32 = 1001; + const CLOCK: u64 = u64::MAX - 32; + let tick_msc = |step: u64| { + if step <= 32 { + CLOCK.wrapping_add(step) + } else { + step - 32 + } + }; + + let mut state = ServerState::new(); + let mut first_peer = install_client(&mut state, 1); + first_peer + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound completion round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 1_000); + backend.present_flip_in_flight = true; + backend.present_absolute_vblank_arm_supported = true; + state.present_event_selections.extend([ + ( + FIRST_EVENT, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(FIRST_WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ), + ( + SECOND_EVENT, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(SECOND_WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ), + ]); + + let mut requests = Vec::with_capacity((COUNT_PER_WINDOW * 2 + 3) as usize); + let mut sequence = 1_u16; + for step in 1..=COUNT_PER_WINDOW { + let target = tick_msc(step); + for (window, pixmap, present_id) in [ + ( + FIRST_WINDOW, + 0x0040_5200 + step as u32, + FIRST_ID + step as u32 - 1, + ), + ( + SECOND_WINDOW, + 0x0041_5200 + step as u32, + SECOND_ID + step as u32 - 1, + ), + ] { + let body = + future_present_pixmap_request(&mut state, window, pixmap, present_id, target); + requests.push(( + SequenceNumber(sequence), + RequestHeader { + opcode: 145, + data: x11present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + )); + sequence = sequence.checked_add(1).expect("test sequence fits"); + } + } + let destroyed_body = future_present_pixmap_request( + &mut state, + DESTROYED_WINDOW, + 0x0042_5201, + 0x5201, + tick_msc(COUNT_PER_WINDOW), + ); + requests.push(( + SequenceNumber(sequence), + RequestHeader { + opcode: 145, + data: x11present::PIXMAP, + length_units: u32::try_from(1 + destroyed_body.len() / 4).unwrap(), + }, + destroyed_body, + )); + sequence = sequence.checked_add(1).expect("test sequence fits"); + requests.push(( + SequenceNumber(sequence), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + DESTROYED_WINDOW.to_le_bytes().to_vec(), + )); + sequence = sequence.checked_add(1).expect("test sequence fits"); + requests.push(( + SequenceNumber(sequence), + RequestHeader { + opcode: 43, + data: 0, + length_units: 1, + }, + Vec::new(), + )); + + seed_present_clock(&mut state, CLOCK, 1_000); + let wire = + run_core_present_requests_and_wait(&mut state, &mut backend, &mut first_peer, requests); + assert!( + wire.is_empty(), + "future requests and DestroyWindow emit no completion" + ); + assert_eq!( + state.present_pending_exec.len(), + (COUNT_PER_WINDOW * 2) as usize + ); + assert!( + state + .present_pending_exec + .values() + .all(|entry| { entry.pending.request.window() != DESTROYED_WINDOW }) + ); + assert_eq!(state.present_pending_complete.len(), 0); + let shared_crtc = *backend + .armed_shared_wake_crtcs + .first() + .expect("future Present targets request a shared wake"); + seed_present_domain_clock(&mut state, shared_crtc, 0, CLOCK, 1_000); + assert!( + backend + .armed_shared_wake_crtcs + .iter() + .all(|&crtc| crtc == shared_crtc) + ); + + let mut observed_by_window = std::collections::BTreeMap::>::new(); + for step in 1..=COUNT_PER_WINDOW { + let msc = tick_msc(step); + let ust = 1_000 + step; + backend + .present_ust_msc_by_crtc + .insert(shared_crtc, (msc, ust)); + seed_present_domain_clock(&mut state, shared_crtc, 0, msc, ust); + let calls_before = backend.armed_shared_wake_crtcs.len(); + let first_wire = + run_core_present_wait_drain(&mut state, &mut backend, &mut first_peer, sequence); + sequence = sequence.checked_add(1).expect("test sequence fits"); + assert!( + first_wire.is_empty(), + "copies enqueue completion events for the next drain" + ); + let expect_wake = step < COUNT_PER_WINDOW; + assert_eq!( + backend.armed_shared_wake_crtcs.len() - calls_before, + usize::from(expect_wake), + "one shared wake for this CRTC while any future work remains at target {step}" + ); + backend.completed_present_events_to_drain.extend( + std::mem::take(&mut backend.enqueued_present_completions) + .into_iter() + .map(|(event, _)| event), + ); + + let calls_before = backend.armed_shared_wake_crtcs.len(); + let wire = run_core_present_wait_drain(&mut state, &mut backend, &mut first_peer, sequence); + sequence = sequence.checked_add(1).expect("test sequence fits"); + assert_eq!( + backend.armed_shared_wake_crtcs.len() - calls_before, + usize::from(expect_wake), + "one shared wake for this CRTC while any future work remains during completion drain" + ); + assert_eq!(wire.len(), 80, "both windows complete at target {step}"); + for event in wire.chunks_exact(40) { + assert_eq!(u64::from_le_bytes(event[32..40].try_into().unwrap()), msc); + let window = u32::from_le_bytes(event[16..20].try_into().unwrap()); + let present_id = u32::from_le_bytes(event[20..24].try_into().unwrap()); + observed_by_window + .entry(window) + .or_default() + .push((present_id, msc)); + } + assert_eq!( + state.present_pending_complete.len(), + 0, + "all due completions drain at step={step}, msc={msc}" + ); + assert_eq!( + state.present_pending_exec.len(), + ((COUNT_PER_WINDOW - step) * 2) as usize + ); + } + + for (window, first_id) in [(FIRST_WINDOW, FIRST_ID), (SECOND_WINDOW, SECOND_ID)] { + let observed = observed_by_window + .remove(&window) + .expect("each Present window emitted completions"); + let expected = (0..COUNT_PER_WINDOW) + .map(|offset| (first_id + offset as u32, tick_msc(offset + 1))) + .collect::>(); + assert_eq!( + observed, expected, + "window 0x{window:x} completion order and MSC" + ); + } + assert!(observed_by_window.is_empty()); + assert!(state.present_pending_complete.is_empty()); + assert!(state.present_pending_exec.is_empty()); + assert!( + backend + .armed_shared_wake_crtcs + .iter() + .all(|&crtc| crtc == shared_crtc) + ); +} + +// Mutation: require a nonzero MSC even when there is no usable clock. +#[test] +fn shared_wake_no_usable_clock_counts_as_ahead() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_absolute_vblank_arm_supported = true; + backend.present_crtc_clock_epoch_by_crtc.insert(11, 1); + let mut pending = due_pending_complete(0x1521, 1, 20, 0, false); + pending.event.crtc_id = 11; + pending.event.crtc_epoch = 1; + state.present_pending_complete.push(pending); + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + + assert_eq!(backend.armed_shared_wake_crtcs, [11]); +} + +// Mutation: use the completion clock for failure fallback (or report covered on failure). +#[test] +fn shared_wake_failure_executes_parked_entries_immediately() { + use crate::backend::recording::RecordedCall; + + const FAR_ID: u64 = 1; + const NEXT_ID: u64 = 2; + const DISTANT_ID: u64 = 3; + const FAR_PIXMAP: u32 = 0x0040_5301; + const NEXT_PIXMAP: u32 = 0x0040_5302; + const DISTANT_PIXMAP: u32 = 0x0040_5303; + + for result in [Some(Ok(false)), Some(Err(std::io::ErrorKind::Other))] { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 1_000); + backend.present_absolute_vblank_arm_supported = true; + backend.arm_present_shared_wake_result = result; + seed_present_clock(&mut state, 100, 1_000); + backend.present_flip_in_flight = true; + dispatch_future_present_pixmap( + &mut state, + &mut backend, + 0x1531, + FAR_PIXMAP, + FAR_ID as u32, + 120, + ); + dispatch_future_present_pixmap( + &mut state, + &mut backend, + 0x1532, + NEXT_PIXMAP, + NEXT_ID as u32, + 101, + ); + dispatch_future_present_pixmap( + &mut state, + &mut backend, + 0x1533, + DISTANT_PIXMAP, + DISTANT_ID as u32, + 102, + ); + let parked = state + .present_pending_exec + .values() + .next() + .expect("future Present is parked"); + state + .present_crtc_clocks + .get_mut(&(parked.pending.crtc_id, parked.pending.crtc_epoch)) + .expect("Present's general clock was cached at arrival") + .completion = crate::backend::PresentClockSample { + msc: 90, + ust: 900, + source: crate::backend::PresentClockSource::PageFlip, + }; + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + + assert!(backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: FAR_PIXMAP, + .. + } + ))); + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: DISTANT_PIXMAP, + .. + } + )), + "general MSC 100 makes target 102 distant despite completion MSC 90" + ); + assert!(!backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: NEXT_PIXMAP, + .. + } + ))); + assert!(!state.present_pending_exec.contains_key(&FAR_ID)); + assert!(!state.present_pending_exec.contains_key(&DISTANT_ID)); + assert!(state.present_pending_exec.contains_key(&NEXT_ID)); + } +} + +// Mutation: omit next-MSC entries while a page flip is in flight. +#[test] +fn shared_wake_next_msc_entry_behind_a_flip_is_armed() { + const PRESENT_ID: u64 = 1; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 1_000); + backend.present_absolute_vblank_arm_supported = true; + backend.present_flip_in_flight = true; + seed_present_clock(&mut state, 100, 1_000); + dispatch_future_present_pixmap(&mut state, &mut backend, 0x1541, 0x5401, 1, 101); + + crate::core_loop::run::arm_present_idle_vblanks(&mut state, &mut backend); + + assert_eq!(backend.armed_shared_wake_crtcs, [2]); + assert!(state.present_pending_exec.contains_key(&PRESENT_ID)); + assert!(backend.calls().iter().all(|call| !matches!( + call, + crate::backend::recording::RecordedCall::CopyArea { .. } + ))); +} + +// Mutation: route NotifyMSC through the tagged shared slot instead of the idle vblank path. +#[test] +fn notify_msc_pacing_unchanged_with_shared_wake() { + use yserver_protocol::x11::present as x11present; + + const WINDOW: u32 = 0x0000_1551; + const EVENT_ID: u32 = 0x0010_1551; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound core round-trip waits"); + let mut backend = RecordingBackend::new(); + backend.present_absolute_vblank_arm_supported = true; + backend.present_ust_msc = (100, 1_000); + seed_present_clock(&mut state, 100, 1_000); + state.present_event_selections.insert( + EVENT_ID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + state + .present_pending_msc + .push(crate::server::PendingNotifyMsc { + owner: ClientId(1), + window: WINDOW, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + serial: 77, + target_msc: 110, + divisor: 0, + remainder: 0, + byte_order: ClientByteOrder::LittleEndian, + }); + + assert!(run_core_present_wait_drain(&mut state, &mut backend, &mut peer, 1).is_empty()); + assert_eq!(backend.armed_idle_vblank_targets, [(0, vec![110])]); + assert!(backend.armed_shared_wake_crtcs.is_empty()); + + assert_eq!(state.present_pending_msc.len(), 1); + backend.present_ust_msc = (110, 2_000); + seed_present_clock(&mut state, 110, 2_000); + let wire = run_core_present_wait_drain(&mut state, &mut backend, &mut peer, 2); + assert!(state.present_pending_msc.is_empty()); + assert_eq!( + wire.len(), + 40, + "one NotifyMSC event is emitted on its target" + ); + assert_eq!(wire[0], 35, "GenericEvent"); + assert_eq!(wire[10], x11present::COMPLETE_KIND_NOTIFY_MSC); + assert_eq!( + u32::from_le_bytes(wire[12..16].try_into().unwrap()), + EVENT_ID + ); + assert_eq!(u32::from_le_bytes(wire[20..24].try_into().unwrap()), 77); + assert_eq!(u64::from_le_bytes(wire[24..32].try_into().unwrap()), 2_000); + assert_eq!(u64::from_le_bytes(wire[32..40].try_into().unwrap()), 110); +} + +/// (vii) One-clock contract / no-reclassification: a present arriving +/// when the GENERAL clock is ahead of the (deliberately stale) +/// completion clock must classify against the general clock alone — +/// eff == general + 1 reads as immediate-target, never future. +#[test] +fn arrival_classifies_against_general_clock_not_completion_clock() { + const CLIENT: u32 = 32; + const WINDOW_XID: u32 = 0x00e0_3201; + const PIXMAP_XID: u32 = 0x00e0_3202; + const WINDOW_HOST_XID: u32 = 0x0040_3201; + const PIXMAP_HOST_XID: u32 = 0x0040_3202; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + // General clock (used for eff + msc-due) is well ahead of the + // completion clock (used only for stamping/gate release — + // untouched by this path). If the arrival evaluation mistakenly + // read the completion clock, eff (general_clock + 1 = 101) would + // be far past completion_clock + 1 (11) and misclassify as + // future-target, parking instead of executing. + backend.present_ust_msc = (100, 0x1000); + backend.present_completion_clock = Some(crate::backend::PresentClockSample { + msc: 10, + ust: 0x0010, + source: crate::backend::PresentClockSource::PageFlip, + }); + backend.present_flip_in_flight = false; + + setup_present_pixmap_source_and_dest( + &mut state, + CLIENT, + WINDOW_XID, + PIXMAP_XID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + .. + } + )), + "eff == general_clock + 1 must classify as immediate-target (execute at arrival), \ + not future-target — a completion-clock-driven misclassification would park instead" + ); + assert!(state.present_pending_exec.is_empty()); +} + +/// (viii) Combined source-wait + msc-due: the source wait signals +/// (source_ready becomes true) but msc-due says Park — the entry +/// stays parked with no copy; only once the clock catches up does the +/// due-pass execute it. +#[test] +fn source_wait_resolution_reclassifies_and_stays_parked_until_due() { + const WAIT_ID: u64 = 44; + const PRESENT_ID: u64 = 600; + const WINDOW_HOST_XID: u32 = 0x0040_0e01; + const PIXMAP_HOST_XID: u32 = 0x0040_0e02; + const EFF: u64 = 205; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (100, 0x1000); // eff(205) is far future at wait-resolution time. + + let mut entry = present_pending_entry_with( + PRESENT_ID, + WINDOW_HOST_XID, + PIXMAP_HOST_XID, + Some(EFF), + false, + ); + entry.wait_id = Some(WAIT_ID); + state.present_wait_to_id.insert(WAIT_ID, PRESENT_ID); + state.present_pending_exec.insert(PRESENT_ID, entry); + + backend.ready_present_source_waits.push(WAIT_ID); + drain_ready_present_pixmaps(&mut state, &mut backend); + + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "source signalled but msc-due says Park: no copy yet" + ); + assert_eq!( + state.present_pending_exec.len(), + 1, + "the entry stays parked, now purely on msc-due" + ); + let reclassified = state.present_pending_exec.get(&PRESENT_ID).unwrap(); + assert!( + reclassified.source_ready, + "wait resolution still marks source_ready = true" + ); + assert!( + reclassified.wait_id.is_none(), + "the wait_id clears — this entry no longer waits on the source" + ); + assert_eq!( + backend.finished_present_source_waits, + vec![WAIT_ID], + "the WAIT pin still drops at wait resolution regardless of the msc-due outcome" + ); + assert!( + backend.released_present_sources.is_empty(), + "the ENTRY pin must NOT be released yet — the entry is still parked" + ); + + // Clock catches up: the due-pass executes it. + backend.present_ust_msc = (EFF, 0x2000); + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_host_xid: PIXMAP_HOST_XID, + .. + } + )), + "once due, the due-pass executes the copy" + ); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +fn present_pixmap_update_region_emits_damage_on_destination_window() { + use crate::server::DamageObject; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, xfixes::RegionRect}; + + const CLIENT: u32 = 14; + const WINDOW_XID: u32 = 0x00e0_0103; + const PIXMAP_XID: u32 = 0x00e0_0104; + const DAMAGE_XID: u32 = 0x00e0_0105; + const UPDATE_REGION_XID: u32 = 0x00e0_0106; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0x400103); + } + + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(0x400104).expect("valid host pixmap"), + ); + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(CLIENT), + drawable: ResourceId(WINDOW_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + state.xfixes_regions.insert( + UPDATE_REGION_XID, + crate::server::XFixesRegion { + owner: ClientId(CLIENT), + region: crate::region::Region::from_rects(&[ + RegionRect { + x: 100, + y: 120, + width: 80, + height: 40, + }, + RegionRect { + x: 220, + y: 260, + width: 25, + height: 35, + }, + ]), + }, + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + body[16..20].copy_from_slice(&UPDATE_REGION_XID.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + let damage = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object"); + assert_eq!( + damage.rects, + state.xfixes_regions[&UPDATE_REGION_XID].rects(), + "PresentPixmap must feed its update region into DAMAGE on the destination window", + ); +} + +#[test] +fn present_pixmap_synced_update_region_emits_damage_on_destination_window() { + // Regression: the explicit-sync (v1.4) PixmapSynced path copied + // the client pixmap into the window but never reported X11 damage, + // unlike the v1.0 Pixmap path. Under an external compositor + // (fastcompmgr) the missing DamageNotify meant the window never + // recomposited — vkcube froze until a drag forced a repaint. + use crate::server::DamageObject; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, xfixes::RegionRect}; + + const CLIENT: u32 = 17; + const WINDOW_XID: u32 = 0x00e0_0403; + const PIXMAP_XID: u32 = 0x00e0_0404; + const DAMAGE_XID: u32 = 0x00e0_0405; + const UPDATE_REGION_XID: u32 = 0x00e0_0406; + const ACQUIRE_SYNCOBJ: u32 = 0x00e0_0407; + const ACQUIRE_VALUE: u64 = 42; + const RELEASE_SYNCOBJ: u32 = 0x00e0_0408; + const RELEASE_VALUE: u64 = 43; + const WAIT_ID: u64 = 77; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + backend.present_syncobj_wait = crate::backend::PresentSourceWait::Deferred(WAIT_ID); + // Task 3: PresentPixmapSynced now validates both syncobjs per + // presentproto 1.4 — an unregistered xid (or a None release syncobj) + // is a Value error before any arm. Register both as imported so this + // test exercises the copy/damage path, not the new rejection. + backend.seed_dri3_syncobj_for_test(ACQUIRE_SYNCOBJ, ClientId(CLIENT)); + let original_release = backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(CLIENT)); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0x400403); + } + + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(0x400404).expect("valid host pixmap"), + ); + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(CLIENT), + drawable: ResourceId(WINDOW_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + state.xfixes_regions.insert( + UPDATE_REGION_XID, + crate::server::XFixesRegion { + owner: ClientId(CLIENT), + region: crate::region::Region::from_rects(&[ + RegionRect { + x: 100, + y: 120, + width: 80, + height: 40, + }, + RegionRect { + x: 220, + y: 260, + width: 25, + height: 35, + }, + ]), + }, + ); + + // PixmapSynced (opcode 5) fixed prefix = 84 bytes: + // window(4) pixmap(4) serial(4) valid(4) update(4) x_off(2) + // y_off(2) target_crtc(4) acquire_syncobj(4) release_syncobj(4) + // acquire_point(8) release_point(8) options(4) pad(4) + // target_msc(8) divisor(8) remainder(8). + let mut body = vec![0u8; 84]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + body[16..20].copy_from_slice(&UPDATE_REGION_XID.to_le_bytes()); + body[28..32].copy_from_slice(&ACQUIRE_SYNCOBJ.to_le_bytes()); + body[32..36].copy_from_slice(&RELEASE_SYNCOBJ.to_le_bytes()); + body[36..44].copy_from_slice(&ACQUIRE_VALUE.to_le_bytes()); + body[44..52].copy_from_slice(&RELEASE_VALUE.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP_SYNCED, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert_eq!( + backend.armed_present_syncobj_waits, + vec![(0x400404, ACQUIRE_SYNCOBJ, ACQUIRE_VALUE)], + "PixmapSynced must arm its explicit acquire timeline point", + ); + assert!( + state.damage_objects[&DAMAGE_XID].rects.is_empty(), + "the destination must not be copied or damaged before acquire signals", + ); + assert_eq!(state.present_pending_exec.len(), 1); + backend + .dri3_free_syncobj(ClientId(CLIENT), RELEASE_SYNCOBJ) + .expect("free original release syncobj"); + let replacement = backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(CLIENT)); + let parked_release = match &state + .present_pending_exec + .values() + .next() + .expect("parked synced Present") + .pending + .wake + { + crate::backend::PresentWake::PixmapSynced { release, .. } => release, + crate::backend::PresentWake::Pixmap { .. } => panic!("expected synced wake"), + }; + assert!( + std::sync::Arc::ptr_eq(parked_release, &original_release), + "accepted Present must retain the original release object" + ); + assert!( + !std::sync::Arc::ptr_eq(parked_release, &replacement), + "reusing the XID must not retarget the parked Present" + ); + parked_release + .signal(RELEASE_VALUE) + .expect("pinned release remains usable after FreeSyncobj"); + assert_eq!( + *backend.signalled_dri3_syncobjs.lock().unwrap(), + vec![(RELEASE_SYNCOBJ, RELEASE_VALUE)] + ); + assert_eq!( + state.present_pending_exec.values().next().unwrap().pin, + Some(1), + "the Deferred arm takes an entry pin on the source drawable" + ); + + backend.ready_present_source_waits.push(WAIT_ID); + drain_ready_present_pixmaps(&mut state, &mut backend); + + let damage = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object"); + assert_eq!( + damage.rects, + state.xfixes_regions[&UPDATE_REGION_XID].rects(), + "PresentPixmapSynced must feed its update region into DAMAGE on the destination window", + ); +} + +#[test] +fn present_pixmap_copy_uses_update_region_rects_as_copy_clips() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, xfixes::RegionRect}; + + const CLIENT: u32 = 15; + const WINDOW_XID: u32 = 0x00e0_0203; + const PIXMAP_XID: u32 = 0x00e0_0204; + const UPDATE_REGION_XID: u32 = 0x00e0_0206; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0x400203); + } + + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 800, + height: 600, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(0x400204).expect("valid host pixmap"), + ); + + state.xfixes_regions.insert( + UPDATE_REGION_XID, + crate::server::XFixesRegion { + owner: ClientId(CLIENT), + region: crate::region::Region::from_rects(&[ + RegionRect { + x: 100, + y: 120, + width: 80, + height: 40, + }, + RegionRect { + x: 220, + y: 260, + width: 25, + height: 35, + }, + ]), + }, + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + body[16..20].copy_from_slice(&UPDATE_REGION_XID.to_le_bytes()); + body[20..22].copy_from_slice(&7_i16.to_le_bytes()); + body[22..24].copy_from_slice(&11_i16.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + let copies: Vec<_> = backend + .calls() + .into_iter() + .filter_map(|call| match call { + RecordedCall::CopyArea { + src_host_xid, + dst_host_xid, + src_x, + src_y, + dst_x, + dst_y, + width, + height, + } => Some(( + src_host_xid, + dst_host_xid, + src_x, + src_y, + dst_x, + dst_y, + width, + height, + )), + _ => None, + }) + .collect(); + + assert_eq!( + copies, + vec![ + (0x400204, 0x400203, 100, 120, 107, 131, 80, 40), + (0x400204, 0x400203, 220, 260, 227, 271, 25, 35), + ], + "PresentPixmap Copy must copy only the update rects, offset into the destination by x_off/y_off", + ); +} + +#[test] +fn present_pixmap_copy_to_redirected_window_preserves_window_destination() { + use crate::backend::recording::RecordedCall; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest}; + + const CLIENT: u32 = 16; + const WINDOW_XID: u32 = 0x00e0_0303; + const PIXMAP_XID: u32 = 0x00e0_0304; + const BACKING_XID: u32 = 0x0040_03ff; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 640, + height: 480, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + if let Some(w) = state.resources.window_mut(ResourceId(WINDOW_XID)) { + w.host_xid = crate::backend::WindowHandle::from_raw(0x400303); + w.redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(BACKING_XID), + width: 640, + height: 480, + depth: 24, + }); + } + + state.resources.create_pixmap( + ClientId(CLIENT), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP_XID), + drawable: ResourceId(WINDOW_XID), + width: 640, + height: 480, + }, + ); + let _ = state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP_XID), + crate::backend::PixmapHandle::from_raw(0x400304).expect("valid host pixmap"), + ); + + let mut body = vec![0u8; 68]; + body[0..4].copy_from_slice(&WINDOW_XID.to_le_bytes()); + body[4..8].copy_from_slice(&PIXMAP_XID.to_le_bytes()); + body[20..22].copy_from_slice(&13_i16.to_le_bytes()); + body[22..24].copy_from_slice(&17_i16.to_le_bytes()); + + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: yserver_protocol::x11::present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + let copies: Vec<_> = backend + .calls() + .into_iter() + .filter_map(|call| match call { + RecordedCall::CopyArea { + src_host_xid, + dst_host_xid, + src_x, + src_y, + dst_x, + dst_y, + width, + height, + } => Some(( + src_host_xid, + dst_host_xid, + src_x, + src_y, + dst_x, + dst_y, + width, + height, + )), + _ => None, + }) + .collect(); + + assert_eq!( + copies, + vec![(0x400304, 0x400303, 0, 0, 13, 17, 640, 480)], + "PresentPixmap must paint through the destination window xid, not its redirected backing xid, so the backend can retain ClipByChildren and hierarchy stacking while resolving that window to the backing", + ); + let completion_hosts: Vec = backend + .enqueued_present_completions + .iter() + .map(|(_, host)| *host) + .collect(); + assert_eq!( + completion_hosts, + vec![BACKING_XID], + "present_completion_keeps_backing_identity: the completion fence attaches to the backing", + ); +} + +/// Xorg: the flip check fails on the empty clipList (present_scmd.c:122), +/// the Copy to an unrealized window is a no-op (micopy.c:157), and idle +/// plus CompleteModeCopy are still sent (present_execute.c:137-156). +#[test] +fn present_to_unviewable_window_skips_copy_and_damage_but_completes() { + use crate::{backend::recording::RecordedCall, resources::MapState, server::DamageObject}; + + const PARENT: u32 = 0x0002_0021; + const WINDOW: u32 = 0x0002_0022; + const DAMAGE_XID: u32 = 0x0002_0023; + const PRESENT_ID: u64 = 0x45; + const TARGET_MSC: u64 = 600; + + for (parent_state, window_state, hidden) in [ + (MapState::Viewable, MapState::Unmapped, true), + (MapState::Unmapped, MapState::Unviewable, true), + (MapState::Viewable, MapState::Viewable, false), + ] { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_direct_result = true; + for (xid, parent, map_state) in [ + (PARENT, ROOT_WINDOW, parent_state), + (WINDOW, ResourceId(PARENT), window_state), + ] { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(xid)) + .expect("window") + .map_state = map_state; + } + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(WINDOW), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + let pending = SupersessionFixture::new(PRESENT_ID, WINDOW) + .eff(Some(TARGET_MSC)) + .geometry(0, 0, 100, 100) + .pending(); + + execute_present_pixmap_copy(&mut state, &mut backend, pending).expect("present"); + + let copies = backend + .calls() + .iter() + .filter(|call| matches!(call, RecordedCall::CopyArea { .. })) + .count(); + let damaged = !state.damage_objects[&DAMAGE_XID].rects.is_empty(); + let gate = state.present_complete_gate.get(&PRESENT_ID).expect("gate"); + assert_eq!(gate.effective_target_msc, TARGET_MSC); + if hidden { + assert!( + backend.present_direct_candidates.is_empty(), + "{window_state:?}: no direct attempt" + ); + assert_eq!(copies, 0, "{window_state:?}: no copy"); + assert!(!damaged, "{window_state:?}: no damage"); + assert_eq!(backend.enqueued_present_completions.len(), 1); + let (event, _) = &backend.enqueued_present_completions[0]; + assert_eq!( + event.completion_mode, + yserver_protocol::x11::present::COMPLETE_MODE_COPY + ); + assert!(event.emit_idle, "{window_state:?}: idle still sent"); + assert_eq!(event.present_id, PRESENT_ID); + } else { + // Viewable control: direct path taken as before. + assert_eq!(backend.present_direct_candidates.len(), 1); + assert!(damaged); + assert!(backend.enqueued_present_completions.is_empty()); + } + } +} + +#[test] +// Mutation: restore the CARDINAL type check or exact-one check; INTEGER/1 and CARDINAL/2 must grant permission. +// Mutation: make the shared peer-PID helper return None on Linux. +fn present_candidate_reports_variable_refresh_property() { + use crate::backend::recording::RecordingBackend; + use yserver_protocol::x11::{CreatePixmapRequest, CreateWindowRequest, present as x11present}; + + const WINDOW: u32 = 0x0002_1021; + const WINDOW_HOST: u32 = 0x0040_1021; + const PIXMAP: u32 = 0x0002_1022; + const PIXMAP_HOST: u32 = 0x0040_1022; + const PROPERTY_NAME: &str = "_VARIABLE_REFRESH"; + const CARDINAL: u32 = 6; + const INTEGER: u32 = 19; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.present_direct_result = true; + state.randr = crate::randr::RandrState::from_outputs( + 1, + vec![present_test_output(1, 11, 0, 0, 100, 100, true)], + ); + state.randr.primary_output = 1; + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW)); + state + .resources + .window_mut(ResourceId(WINDOW)) + .expect("destination window") + .host_xid = crate::backend::WindowHandle::from_raw(WINDOW_HOST); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP), + drawable: ResourceId(WINDOW), + width: 100, + height: 100, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(PIXMAP), + crate::backend::PixmapHandle::from_raw(PIXMAP_HOST).expect("test pixmap host xid"), + )); + + fn present(state: &mut ServerState, backend: &mut RecordingBackend, serial: u32) { + let mut body = pixmap_body(WINDOW, PIXMAP); + body[8..12].copy_from_slice(&serial.to_le_bytes()); + process_request( + state, + backend, + ClientId(1), + SequenceNumber(u16::try_from(serial).unwrap()), + RequestHeader { + opcode: 145, + data: x11present::PIXMAP, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("Present request"); + } + + fn change_property( + state: &mut ServerState, + backend: &mut RecordingBackend, + property: u32, + property_type: u32, + format: u8, + items: &[u32], + sequence: u16, + ) { + let mut body = vec![0_u8; 20]; + body[0..4].copy_from_slice(&WINDOW.to_le_bytes()); + body[4..8].copy_from_slice(&property.to_le_bytes()); + body[8..12].copy_from_slice(&property_type.to_le_bytes()); + body[12] = format; + body[16..20].copy_from_slice(&u32::try_from(items.len()).unwrap().to_le_bytes()); + for item in items { + match format { + 8 => body.push(u8::try_from(*item).unwrap()), + _ => body.extend_from_slice(&item.to_le_bytes()), + } + } + while !body.len().is_multiple_of(4) { + body.push(0); + } + process_request( + state, + backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode: 18, + data: 0, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("ChangeProperty request"); + } + + present(&mut state, &mut backend, 1); + assert_eq!( + state.atoms.id_for(PROPERTY_NAME), + None, + "Present does not intern the property atom" + ); + assert_eq!( + backend + .present_direct_candidates + .first() + .expect("initial Present reaches Backend") + .client_pid, + Some(std::process::id()), + "PresentScanoutCandidate carries the peer PID captured at setup" + ); + assert!( + !backend + .present_direct_candidates + .first() + .expect("initial Present reaches Backend") + .variable_refresh, + "a missing _VARIABLE_REFRESH property does not grant permission" + ); + let property = state.atoms.intern(PROPERTY_NAME, false).0; + for (sequence, property_type, format, values, expected) in [ + (2, CARDINAL, 32, vec![], false), + (3, CARDINAL, 32, vec![0], false), + (4, CARDINAL, 32, vec![2], true), + (5, INTEGER, 32, vec![1], true), + (6, CARDINAL, 8, vec![1], false), + (7, CARDINAL, 32, vec![1, 2], false), + (8, CARDINAL, 32, vec![1], true), + ] { + change_property( + &mut state, + &mut backend, + property, + property_type, + format, + &values, + sequence, + ); + present(&mut state, &mut backend, u32::from(sequence) + 10); + assert_eq!( + backend + .present_direct_candidates + .last() + .expect("Present reaches Backend") + .variable_refresh, + expected, + "type={property_type} format={format} value={values:?}" + ); + } + assert_eq!(backend.present_direct_candidates.len(), 8); +} + +#[test] +fn present_async_may_tear_bit_is_0x10() { + // presenttokens.h: PresentOptionAsyncMayTear = (1 << 4). + assert_eq!(0x10u32, 1u32 << 4); + // Stripping AsyncMayTear must NOT strip Suboptimal (0x8) or Async (0x1). + let opts = 0x1 | 0x8 | 0x10; + assert_eq!(opts & !0x10u32, 0x1 | 0x8); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/present_supersede.rs b/crates/yserver-core/src/core_loop/process_request/tests/present_supersede.rs new file mode 100644 index 000000000..5b3fc0c2d --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/present_supersede.rs @@ -0,0 +1,1877 @@ +use super::*; + +// ---------------- Step 1: present_supersession_covers ---------------- + +#[test] +fn coverage_full_predecessor_under_full_successor_is_covered() { + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + assert!(present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_sliver_predecessor_under_full_successor_is_covered() { + // Xorg semantics (verification item (d)): a full-frame successor + // scraps a sliver predecessor — the successor gate cares only + // about ITS OWN update region, not the predecessor's. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 10, + y: 10, + width: 5, + height: 5, + }])) + .pending(); + assert!( + present_supersession_covers(&successor, &predecessor), + "a full-frame successor covers a thin sliver predecessor" + ); +} + +#[test] +fn coverage_partial_region_successor_never_scraps_regardless_of_coverage() { + // Xorg gate (present_scmd.c:802), amended (Task 13, spec + // §"Amendment 2026-08-01"): a successor carrying a PARTIAL update + // region — one that does not clear `successor_presents_full_extent` + // — never scraps, even when its rects would geometrically cover + // the predecessor. This is what protects marco/picom's + // drag-sliver presents from scrapping each other. (NOT a + // full-extent fixture: the successor's rect is a genuine sliver + // of its 100x100 source, distinct from the full-extent case + // covered by `coverage_single_rect_full_extent_region_scraps_like_none`.) + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 10, + y: 10, + width: 5, + height: 5, + }])) + .pending(); + // Predecessor's footprint sits exactly inside the successor's + // rect — geometrically "coverable" — yet the gate still declines + // because the successor's region isn't full-extent. + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(10, 10, 5, 5) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_negative_offsets_fitting_is_covered() { + // Offsets are i16 and may be negative (a window partially + // off-screen) — the arithmetic must not saturate. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(-50, -50, 200, 200) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(-40, -40, 50, 50) + .pending(); + assert!(present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_negative_offsets_not_fitting_is_not_covered() { + let successor = SupersessionFixture::new(2, 0x100) + .geometry(-50, -50, 100, 100) + .pending(); + // Predecessor's left edge (-60) is outside the successor's rect + // (starts at -50). + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(-60, -50, 20, 20) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_full_frame_successor_from_smaller_resize_source_does_not_cover_larger_predecessor() { + // Mid-resize: Mesa reallocated a smaller swapchain pixmap for the + // successor, but a larger predecessor from before the resize is + // still parked. The successor's full-extent rect is + // SOURCE-pixmap-bounded, so it must NOT cover a predecessor + // extending beyond it — yserver's strictly conservative extra on + // top of Xorg's geometry-blind scrap. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 50, 50) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_zero_pixel_successor_never_scraps() { + // The documented zero-pixel present: `update_rects = Some(empty)` + // still satisfies the successor gate's `is_some()` check, so it + // never scraps — regardless of how trivially "coverable" the + // predecessor is. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(Vec::new())) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 1, 1) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_zero_pixel_predecessor_is_trivially_covered() { + // A predecessor with `Some(empty)` has no content, so it is + // covered by any (gate-passing) successor — falls out of + // `.all()` on an empty iterator. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(Vec::new())) + .pending(); + assert!(present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_near_i16_max_rect_offset_saturates_like_the_real_copy() { + // Review fix: the predicate must judge coverage at exactly the + // position the real copy lands, not at an unsaturated `i32` sum. + // Predecessor `x_off=32000` with rect `r.x=1000` sums to an + // unsaturated `i32` 33000, but `execute_present_pixmap_copy` + // computes the dest x as `x_off.saturating_add(rect.x)` in `i16`, + // which clamps to `i16::MAX` (32767) — the real copy never draws + // past that. The successor's extent below ends exactly at 32767 + // (`x_off` is itself `i16`-bounded, so its extent can only reach + // i16::MAX from below, never past it), so the saturated dest + // (32767 + rect width 100 = 32867) overruns the successor's real + // right edge by exactly 100px and must NOT be judged covered — a + // covered-but-not-actually-copied verdict here would lose that + // sliver. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(32700, 0, 67, 100) // extent x in [32700, 32767) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(32000, 0, 1000, 1000) + .update_rects(Some(vec![xfixes::RegionRect { + x: 1000, + y: 0, + width: 100, + height: 100, + }])) + .pending(); + assert!( + !present_supersession_covers(&successor, &predecessor), + "the real copy saturates the dest x to i16::MAX = 32767, and \ + 32767 + rect width 100 = 32867 overruns the successor's real \ + right edge (32767) by 100px — must not be judged covered" + ); +} + +// ---------------- Task 13: successor-gate relaxation (spec +// §"Amendment 2026-08-01 — successor-gate relaxation") ---------------- + +#[test] +fn coverage_single_rect_full_extent_region_scraps_like_none() { + // The NVIDIA-WSI shape from the CS2 capture: a single rect that + // exactly equals the source extent. Must scrap exactly like + // `update_rects == None`. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 50, 50) + .pending(); + assert!( + present_supersession_covers(&successor, &predecessor), + "a single-rect full-extent update region scraps exactly like None" + ); +} + +#[test] +fn coverage_over_large_rect_passes() { + // A rect with negative origin and an extent past the source + // bounds still provably contains the full extent. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: -10, + y: -10, + width: 300, + height: 300, + }])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + assert!(present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_superset_region_passes_via_containing_rect() { + // `rects = [full-extent rect, extra sliver]` passes via the + // containing rect — the executed copy writes the union, a + // superset of the extent (spec amendment's "superset region" + // paragraph). + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![ + xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }, + xfixes::RegionRect { + x: 150, + y: 150, + width: 10, + height: 10, + }, + ])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + assert!(present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_multirect_union_but_no_single_rect_covers_declines() { + // Two rects whose UNION covers the full extent, but neither rect + // alone does — union coverage is deliberately not computed, so + // this declines (the documented conservative bound). This also + // bites harder on yserver than Xorg: yserver's y-band region + // normalization doesn't re-coalesce vertically/horizontally + // adjacent identical bands. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![ + xfixes::RegionRect { + x: 0, + y: 0, + width: 50, + height: 100, + }, + xfixes::RegionRect { + x: 50, + y: 0, + width: 50, + height: 100, + }, + ])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 10, 10) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_marco_style_multirect_sliver_declines() { + // A realistic marco/picom drag-update shape: two thin horizontal + // strips (top + bottom), whose union does NOT even cover the + // full extent. Never scraps. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![ + xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 10, + }, + xfixes::RegionRect { + x: 0, + y: 90, + width: 100, + height: 10, + }, + ])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 100, 100) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_region_full_extent_one_axis_only_declines() { + // Padded / mid-resize shape: the rect is full-extent in width but + // not in height, on a source taller than the rect. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 50, + }])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 10, 10) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn coverage_zero_area_rect_declines() { + // `Some([zero-area rect])` — reachable via the + // `CREATE_REGION_FROM_GC` path, which inserts parsed rects raw, + // bypassing `normalize_region_rects`. A zero-area rect can never + // satisfy both `>=` conditions. + let successor = SupersessionFixture::new(2, 0x100) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 0, + height: 100, + }])) + .pending(); + let predecessor = SupersessionFixture::new(1, 0x100) + .geometry(0, 0, 1, 1) + .pending(); + assert!(!present_supersession_covers(&successor, &predecessor)); +} + +#[test] +fn supersede_single_rect_full_extent_region_scraps_like_none() { + // End-to-end: `supersede_covered_pending_presents` scraps a + // covered victim behind a successor carrying the NVIDIA-WSI + // full-extent single-rect shape. + const WINDOW: u32 = 0x0001_0009; + const VICTIM_ID: u64 = 90; + const SUCCESSOR_ID: u64 = 91; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 50, 50) + .entry(); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }])) + .update(1) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert!( + state.present_pending_exec.is_empty(), + "a full-extent single-rect successor must scrap a covered victim" + ); +} + +// ---------------- Task 13: damage-arm fix (spec §"Amendment +// 2026-08-01" — damage-arm dependency) ---------------- + +#[test] +fn damage_full_extent_region_present_with_offset_translates_position() { + // Failing test first (plan Task 13 Step 3): a full-extent-region + // present with `x_off`/`y_off != 0` accumulates damage at the + // TRANSLATED position, matching the copy arm's + // `x_off.saturating_add(rect.x)`. + use crate::{backend::recording::RecordedCall, server::DamageObject}; + + const WINDOW: u32 = 0x0002_0001; + const DAMAGE_XID: u32 = 0x0002_0002; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(WINDOW), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let pending = SupersessionFixture::new(1, WINDOW) + .geometry(20, 30, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }])) + .update(1) + .pending(); + + execute_present_pixmap_copy(&mut state, &mut backend, pending) + .expect("copy succeeds against RecordingBackend"); + + assert!( + backend.calls().iter().any(|call| matches!( + call, + RecordedCall::CopyArea { + src_x: 0, + src_y: 0, + dst_x: 20, + dst_y: 30, + width: 100, + height: 100, + .. + } + )), + "the copy arm translates by x_off/y_off: {:?}", + backend.calls() + ); + let damage = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object"); + assert_eq!( + damage.rects, + vec![xfixes::RegionRect { + x: 20, + y: 30, + width: 100, + height: 100, + }], + "the damage arm must translate per-rect damage by x_off/y_off \ + exactly like the copy arm" + ); +} + +#[test] +fn direct_present_success_bypasses_copy_and_keeps_completion_gate() { + use crate::backend::recording::RecordedCall; + + const WINDOW: u32 = 0x0002_0011; + const PRESENT_ID: u64 = 0x44; + const TARGET_MSC: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_direct_result = true; + let pending = SupersessionFixture::new(PRESENT_ID, WINDOW) + .eff(Some(TARGET_MSC)) + .geometry(0, 0, 100, 100) + .pending(); + + execute_present_pixmap_copy(&mut state, &mut backend, pending) + .expect("direct ownership succeeds"); + + assert_eq!(backend.present_direct_candidates.len(), 1); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::CopyArea { .. })), + "M2b success must not record the normal source-to-COW Copy" + ); + let gate = state + .present_complete_gate + .get(&PRESENT_ID) + .expect("direct completion gate installed before ownership handoff"); + assert_eq!(gate.effective_target_msc, TARGET_MSC); +} + +#[test] +fn damage_unresolvable_region_with_update_flag_accumulates_full_extent() { + // Failing test first (plan Task 13 Step 3): an `update != 0` + + // unresolvable-region (`update_rects == None`) present + // accumulates FULL-EXTENT damage, not nothing — the branch is + // re-keyed off `update_rects.is_none()`, not the raw `update` + // xid, so this can no longer silently drop all damage. + use crate::server::DamageObject; + + const WINDOW: u32 = 0x0002_0003; + const DAMAGE_XID: u32 = 0x0002_0004; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: ResourceId(WINDOW), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let pending = SupersessionFixture::new(1, WINDOW) + .geometry(5, 7, 60, 40) + .update_rects(None) + .update(1) + .pending(); + + execute_present_pixmap_copy(&mut state, &mut backend, pending) + .expect("copy succeeds against RecordingBackend"); + + let damage = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object"); + assert_eq!( + damage.rects, + vec![xfixes::RegionRect { + x: 5, + y: 7, + width: 60, + height: 40, + }], + "update != 0 with an unresolvable region must still damage \ + full-extent, not nothing" + ); +} + +// ---------------- Step 2: supersede_covered_pending_presents ---------------- + +/// Seed one `Present` event selection for `window` with the given +/// mask, draining the connection setup traffic first. Tests that +/// decode the wire with `complete_notify_modes` (fixed 40-byte +/// chunks) pass `EVENT_MASK_COMPLETE_NOTIFY` alone — mixing in +/// `EVENT_MASK_IDLE_NOTIFY` would interleave 32-byte `IdleNotify` +/// events into that fixed-width chunking (Task 6's +/// `due_skip_is_held_back_behind_a_smaller_id_undrained_gate_entry` +/// makes the same choice for the same reason). +fn seed_present_selection( + state: &mut ServerState, + peer: &mut UnixStream, + eid: u32, + window: u32, + mask: u32, +) { + state.present_event_selections.insert( + eid, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(window), + event_mask: mask, + }, + ); + let _ = read_all_available(peer); +} + +#[test] +fn supersede_scraps_covered_msc_parked_same_window_same_target_entry() { + const WINDOW: u32 = 0x0001_0001; + const PRESENT_EID: u32 = 0x0020_1001; + const VICTIM_ID: u64 = 10; + const SUCCESSOR_ID: u64 = 11; + const TARGET: u64 = 500; + const IDLE_FENCE: u32 = 0x0030_1001; + const PIN_ID: u64 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_present_selection( + &mut state, + &mut peer, + PRESENT_EID, + WINDOW, + yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY + | yserver_protocol::x11::present::EVENT_MASK_IDLE_NOTIFY, + ); + let mut backend = RecordingBackend::new(); + + state.sync_fences.insert( + IDLE_FENCE, + crate::server::SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + + let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 50, 50) + .idle_fence(IDLE_FENCE) + .entry(); + victim.pin = Some(PIN_ID); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert!( + state.present_pending_exec.is_empty(), + "the covered victim must be removed from the store" + ); + assert!( + state.present_wait_to_id.is_empty(), + "the side-map row must be dropped with the entry" + ); + assert_eq!( + backend.finished_present_source_waits, + Vec::::new(), + "an MSC-parked victim has no source wait to cancel" + ); + assert_eq!( + backend.released_present_sources, + vec![PIN_ID], + "the entry pin must be released" + ); + assert_eq!( + backend.triggered_dri3_fences, + vec![IDLE_FENCE], + "the idle fence must be triggered by XID, immediately" + ); + assert!( + state.sync_fences[&IDLE_FENCE].triggered, + "the X11 fence mirror must be set at scrap time" + ); + assert_eq!( + state.present_pending_complete.len(), + 1, + "a Skip completion must be parked for ordered delivery" + ); + let parked = &state.present_pending_complete[0]; + assert_eq!(parked.event.present_id, VICTIM_ID); + assert_eq!(parked.effective_target_msc, TARGET); + assert_eq!( + parked.mode, + yserver_protocol::x11::present::COMPLETE_MODE_SKIP + ); + assert!(!parked.emit_idle, "IdleNotify already fired at scrap"); + + // Review fix (5a): actually decode the IdleNotify wire bytes + // (layout per `encode_idle_notify`), not just count them — + // pins event type, eid, window, pixmap xid, and fence xid. + let idle_bytes = read_all_available(&mut peer); + assert_eq!( + idle_bytes.len(), + 32, + "exactly one IdleNotify (32 bytes) must be delivered on the wire right \ + now, at scrap time — no CompleteNotify yet" + ); + assert_eq!(idle_bytes[0], 35, "GenericEvent"); + assert_eq!(idle_bytes[1], 145, "PRESENT major opcode"); + assert_eq!( + idle_bytes[8], + yserver_protocol::x11::present::EVENT_IDLE_NOTIFY, + "evtype must be IdleNotify" + ); + assert_eq!( + u32::from_le_bytes(idle_bytes[12..16].try_into().unwrap()), + PRESENT_EID, + "eid must be the selection that requested IdleNotify" + ); + assert_eq!( + u32::from_le_bytes(idle_bytes[16..20].try_into().unwrap()), + WINDOW, + "window xid" + ); + assert_eq!( + u32::from_le_bytes(idle_bytes[24..28].try_into().unwrap()), + 0x1, + "pixmap xid — the victim's own client-visible pixmap (SupersessionFixture \ + hardcodes 0x1)" + ); + assert_eq!( + u32::from_le_bytes(idle_bytes[28..32].try_into().unwrap()), + IDLE_FENCE, + "fence xid" + ); +} + +#[test] +fn supersede_note_present_skip_once_per_scrapped_victim() { + // Task 10 telemetry: `Backend::note_present_skip` must fire exactly + // once per victim actually scrapped by supersession — not once per + // call, not for a survivor, and not double-counted. + const WINDOW: u32 = 0x0001_1002; + const VICTIM_A: u64 = 200; + const VICTIM_B: u64 = 201; + const SUCCESSOR_ID: u64 = 202; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let victim_a = SupersessionFixture::new(VICTIM_A, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 10, 10) + .entry(); + let victim_b = SupersessionFixture::new(VICTIM_B, WINDOW) + .eff(Some(TARGET)) + .geometry(20, 20, 10, 10) + .entry(); + state.present_pending_exec.insert(VICTIM_A, victim_a); + state.present_pending_exec.insert(VICTIM_B, victim_b); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert!( + state.present_pending_exec.is_empty(), + "both covered victims must be scrapped" + ); + assert_eq!( + backend.present_skip_count, 2, + "note_present_skip must fire exactly once per scrapped victim" + ); +} + +#[test] +fn supersede_leaves_entry_with_different_effective_target_msc() { + const WINDOW: u32 = 0x0001_0002; + const VICTIM_ID: u64 = 20; + const SUCCESSOR_ID: u64 = 21; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(500)) + .geometry(0, 0, 50, 50) + .entry(); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(600)) // different target + .geometry(0, 0, 100, 100) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert_eq!( + state.present_pending_exec.len(), + 1, + "an entry targeting a different effective MSC must survive" + ); + assert!(state.present_pending_complete.is_empty()); +} + +#[test] +fn supersede_leaves_entry_in_different_window() { + const WINDOW_A: u32 = 0x0001_0003; + const WINDOW_B: u32 = 0x0001_0004; + const VICTIM_ID: u64 = 30; + const SUCCESSOR_ID: u64 = 31; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let victim = SupersessionFixture::new(VICTIM_ID, WINDOW_A) + .eff(Some(TARGET)) + .geometry(0, 0, 50, 50) + .entry(); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW_B) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert_eq!( + state.present_pending_exec.len(), + 1, + "an entry in a different window must survive" + ); + assert!(state.present_pending_complete.is_empty()); +} + +#[test] +fn supersede_partial_region_successor_with_update_rects_never_scraps() { + // Task 13 refit (spec §"Amendment 2026-08-01"): the fixture's + // successor rect is a genuine sliver of its 100x100 source, not + // an accidentally-full-extent one — post-amendment a full-extent + // single rect WOULD clear the gate (see + // `coverage_single_rect_full_extent_region_scraps_like_none`), + // so this test's coverage of "a partial-region successor never + // scraps" depends on the rect staying genuinely partial. + const WINDOW: u32 = 0x0001_0005; + const VICTIM_ID: u64 = 40; + const SUCCESSOR_ID: u64 = 41; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + // Victim's footprint sits exactly inside the successor's rect — + // geometrically "coverable" — yet the gate still declines because + // the successor's region isn't full-extent. + let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(10, 10, 5, 5) + .entry(); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 10, + y: 10, + width: 5, + height: 5, + }])) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert_eq!( + state.present_pending_exec.len(), + 1, + "a successor carrying a partial update region must never scrap" + ); + assert!(state.present_pending_complete.is_empty()); +} + +#[test] +fn supersede_successor_with_no_effective_target_never_scraps() { + // With `eff = None`, equivalence with any pending request is unknown. + const WINDOW: u32 = 0x0001_0006; + const VICTIM_ID: u64 = 50; + const SUCCESSOR_ID: u64 = 51; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(500)) + .geometry(0, 0, 50, 50) + .entry(); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(None) // no effective target: no shared Some target to scrap on + .geometry(0, 0, 100, 100) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert_eq!( + state.present_pending_exec.len(), + 1, + "a successor with no effective target never scraps" + ); + assert!(state.present_pending_complete.is_empty()); +} + +#[test] +fn async_requests_with_same_effective_target_supersede() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut pred_entry = present_pending_entry_with(1, 0x00e0_3001, 0x00e0_3002, Some(500), true); + pred_entry.pending.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; + let pred = pred_entry.pending.clone(); + state.present_pending_exec.insert(1, pred_entry); + let succ = crate::server::PendingPresentPixmap { + present_id: 2, + effective_target_msc: Some(500), + masked_options: crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS, + ..pred + }; + supersede_covered_pending_presents(&mut state, &mut backend, &succ); + assert!( + !state.present_pending_exec.contains_key(&1), + "async requests with the same known effective target must supersede" + ); + assert_eq!(backend.present_skip_count, 1); + assert_eq!( + state.present_pending_complete.len(), + 1, + "Skip parked for ordered delivery" + ); +} + +#[test] +fn async_requests_with_unknown_effective_targets_do_not_supersede() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut pred_entry = present_pending_entry_with(1, 0x00e0_3001, 0x00e0_3002, None, true); + pred_entry.pending.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; + let pred = pred_entry.pending.clone(); + state.present_pending_exec.insert(1, pred_entry); + let succ = crate::server::PendingPresentPixmap { + present_id: 2, + effective_target_msc: None, + masked_options: crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS, + ..pred + }; + supersede_covered_pending_presents(&mut state, &mut backend, &succ); + assert!( + state.present_pending_exec.contains_key(&1), + "None does not establish target equivalence, even for two async requests" + ); + assert_eq!(backend.present_skip_count, 0); +} + +#[test] +fn supersede_pixmap_synced_victim_releases_via_syncobj() { + const WINDOW: u32 = 0x0001_0007; + const VICTIM_ID: u64 = 60; + const SUCCESSOR_ID: u64 = 61; + const TARGET: u64 = 500; + const RELEASE_SYNCOBJ: u32 = 0x0030_1007; + const RELEASE_VALUE: u64 = 42; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let release = backend.seed_dri3_syncobj_for_test(RELEASE_SYNCOBJ, ClientId(1)); + let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 50, 50) + .synced_release(RELEASE_SYNCOBJ, RELEASE_VALUE) + .entry(); + victim.pending.wake = crate::backend::PresentWake::PixmapSynced { + release, + release_syncobj: RELEASE_SYNCOBJ, + release_value: RELEASE_VALUE, + }; + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert!(state.present_pending_exec.is_empty()); + assert_eq!( + *backend.signalled_dri3_syncobjs.lock().unwrap(), + vec![(RELEASE_SYNCOBJ, RELEASE_VALUE)], + "a PixmapSynced victim releases via dri3_signal_syncobj, not dri3_trigger_fence" + ); + assert!(backend.triggered_dri3_fences.is_empty()); + assert_eq!(state.present_pending_complete.len(), 1); +} + +#[test] +fn arm_before_scrap_syncobj_failure_leaves_covered_victim_untouched() { + // Regression for the adversarial-review blocker: the successor's + // own `arm_present_syncobj_wait` is client-reachably fallible + // (e.g. an unknown acquire syncobj). If supersession scrapped + // covered victims BEFORE that arm, a failed arm would unwind via + // `?` with the victim already destroyed and nothing committed to + // replace it — leaving the window with no frame at the target + // MSC where Xorg would still have shown the victim. This drives + // the real `arm_present_pixmap_synced_source_then_supersede` + // helper — the exact arm+scrap sequence the PixmapSynced handler + // calls — rather than invoking + // `supersede_covered_pending_presents` directly, so it actually + // exercises production ordering rather than hand-waving it. + const WINDOW: u32 = 0x0001_0008; + const VICTIM_ID: u64 = 62; + const SUCCESSOR_ID: u64 = 63; + const TARGET: u64 = 500; + const IDLE_FENCE: u32 = 0x0030_1008; + const PIN_ID: u64 = 2; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.arm_present_syncobj_wait_result = Some(std::io::ErrorKind::InvalidInput); + + state.sync_fences.insert( + IDLE_FENCE, + crate::server::SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + + let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 50, 50) + .idle_fence(IDLE_FENCE) + .entry(); + victim.pin = Some(PIN_ID); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + + let result = + arm_present_pixmap_synced_source_then_supersede(&mut state, &mut backend, 0, 0, &successor); + + assert!( + result.is_err(), + "the canned arm failure must propagate as Err" + ); + assert_eq!( + state.present_pending_exec.len(), + 1, + "the covered victim must still be in present_pending_exec — scrap must \ + not run ahead of a failed arm" + ); + assert!( + state.present_pending_exec.contains_key(&VICTIM_ID), + "specifically the victim, untouched" + ); + assert!(state.present_wait_to_id.is_empty()); + assert!( + backend.finished_present_source_waits.is_empty(), + "the MSC-parked victim has no producer wait to finish" + ); + assert!( + backend.released_present_sources.is_empty(), + "the victim's pin must not be released" + ); + assert!( + backend.triggered_dri3_fences.is_empty(), + "the victim's idle fence must NOT be triggered" + ); + assert!( + !state.sync_fences[&IDLE_FENCE].triggered, + "the X11 fence mirror must NOT be set — the victim's fence never fired" + ); + assert!( + state.present_pending_complete.is_empty(), + "no Skip completion may be parked for a victim that was never scrapped" + ); +} + +// ---------------- Step 3: copy-failure reroute ---------------- + +#[test] +fn failing_copy_at_arrival_parks_ordered_copy_completion_and_preserves_window_order() { + const WINDOW: u32 = 0x0001_0101; + const PRESENT_EID: u32 = 0x0020_1101; + const BLOCKER_ID: u64 = 70; + const FAILING_ID: u64 = 71; + const TARGET: u64 = 500; + const IDLE_FENCE: u32 = 0x0030_1101; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // Review fix (5b): also select IdleNotify, so this test can pin + // that exactly one fires — at failure time, with the right fence + // — and none at delivery. + seed_present_selection( + &mut state, + &mut peer, + PRESENT_EID, + WINDOW, + yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY + | yserver_protocol::x11::present::EVENT_MASK_IDLE_NOTIFY, + ); + let mut backend = RecordingBackend::new(); + backend.fail_copy_area = true; + + state.sync_fences.insert( + IDLE_FENCE, + crate::server::SyncFence { + owner: ClientId(1), + triggered: false, + }, + ); + + // An earlier same-window present is still unresolved (msc-parked) + // — the failing present's completion must be held back behind it. + state + .present_pending_exec + .insert(BLOCKER_ID, stub_pending_present_entry(WINDOW, BLOCKER_ID)); + + let failing = SupersessionFixture::new(FAILING_ID, WINDOW) + .eff(Some(TARGET)) + .idle_fence(IDLE_FENCE) + .pending(); + + let ok = execute_present_pixmap_copy_or_reroute(&mut state, &mut backend, failing); + assert!(!ok, "a failing copy_area must report failure"); + + assert!( + backend + .calls() + .iter() + .any(|c| matches!(c, crate::backend::recording::RecordedCall::CopyArea { .. })), + "the copy must actually be attempted" + ); + assert!( + state.present_complete_gate.is_empty(), + "a failed copy runs before the gate insert — no gate row must exist" + ); + assert_eq!( + backend.triggered_dri3_fences, + vec![IDLE_FENCE], + "the buffer must be released by XID immediately, like scrap" + ); + assert!(state.sync_fences[&IDLE_FENCE].triggered); + + // Exactly one IdleNotify must be on the wire NOW, at failure time + // — the reroute's by-XID release fires it immediately, same as + // scrap (Fix 5a's decode pattern). + let idle_bytes = read_all_available(&mut peer); + assert_eq!( + idle_bytes.len(), + 32, + "exactly one IdleNotify (32 bytes) must fire at failure time" + ); + assert_eq!(idle_bytes[0], 35, "GenericEvent"); + assert_eq!(idle_bytes[1], 145, "PRESENT major opcode"); + assert_eq!( + idle_bytes[8], + yserver_protocol::x11::present::EVENT_IDLE_NOTIFY, + "evtype must be IdleNotify" + ); + assert_eq!( + u32::from_le_bytes(idle_bytes[28..32].try_into().unwrap()), + IDLE_FENCE, + "fence xid" + ); + + assert_eq!(state.present_pending_complete.len(), 1); + let parked = &state.present_pending_complete[0]; + assert_eq!(parked.event.present_id, FAILING_ID); + assert_eq!(parked.effective_target_msc, TARGET); + assert_eq!( + parked.mode, + yserver_protocol::x11::present::COMPLETE_MODE_COPY + ); + assert!(!parked.emit_idle); + + let clock = crate::backend::PresentClockSample { + msc: TARGET, + ust: 0x1000, + source: crate::backend::PresentClockSource::PageFlip, + }; + fire_due_present_completions(&mut state, &mut backend, clock); + assert_eq!( + state.present_pending_complete.len(), + 1, + "the parked Copy completion stays held back behind the still-\ + unexecuted blocker in present_pending_exec" + ); + + // The blocker resolves. + state.present_pending_exec.remove(&BLOCKER_ID); + fire_due_present_completions(&mut state, &mut backend, clock); + assert!( + state.present_pending_complete.is_empty(), + "the rerouted Copy completion delivers once the blocker clears" + ); + assert!( + backend.signalled_present_wakes.is_empty(), + "emit_idle=false must not signal the (already-released) wake a second time" + ); + // No second IdleNotify at delivery: `complete_notify_modes` chunks + // strictly by 40 bytes and asserts each chunk is a well-formed + // CompleteNotify, so a stray 32-byte IdleNotify here would + // misalign the chunking and fail loudly rather than pass + // silently. + let wire = read_all_available(&mut peer); + assert_eq!( + complete_notify_modes(&wire), + vec![yserver_protocol::x11::present::COMPLETE_MODE_COPY] + ); +} + +#[test] +fn failing_copy_without_clock_delivers_complete_notify_inline() { + const WINDOW: u32 = 0x0001_0102; + const PRESENT_EID: u32 = 0x0020_1102; + const FAILING_ID: u64 = 72; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_present_selection( + &mut state, + &mut peer, + PRESENT_EID, + WINDOW, + yserver_protocol::x11::present::EVENT_MASK_COMPLETE_NOTIFY, + ); + let mut backend = RecordingBackend::new(); + backend.fail_copy_area = true; + seed_present_clock(&mut state, 100, 0x2000); + + let failing = SupersessionFixture::new(FAILING_ID, WINDOW) + .eff(None) // no usable CRTC clock + .pending(); + + let ok = execute_present_pixmap_copy_or_reroute(&mut state, &mut backend, failing); + assert!(!ok); + + assert!( + state.present_pending_complete.is_empty(), + "a no-clock (eff=None) failing copy must deliver inline, not park" + ); + assert!( + backend.signalled_present_wakes.is_empty(), + "emit_idle=false: no wake is signalled" + ); + let wire = read_all_available(&mut peer); + assert_eq!( + complete_notify_modes(&wire), + vec![yserver_protocol::x11::present::COMPLETE_MODE_COPY], + "the completion delivers immediately with mode Copy" + ); +} + +#[test] +fn failing_copy_in_due_pass_releases_entry_pin_exactly_once() { + const WINDOW: u32 = 0x0001_0103; + const FAILING_ID: u64 = 73; + const PIN_ID: u64 = 9; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.fail_copy_area = true; + + let mut entry = SupersessionFixture::new(FAILING_ID, WINDOW) + .eff(Some(TARGET)) + .entry(); + entry.pin = Some(PIN_ID); + state.present_pending_exec.insert(FAILING_ID, entry); + + execute_parked_present_ids(&mut state, &mut backend, &[FAILING_ID], "drain"); + + assert!(state.present_pending_exec.is_empty()); + assert_eq!( + backend.released_present_sources, + vec![PIN_ID], + "the entry pin must be released exactly once, even on copy failure" + ); + assert!( + backend + .calls() + .iter() + .all(|c| !matches!(c, crate::backend::recording::RecordedCall::MarkDirty)), + "mark_dirty must not fire when the copy failed" + ); + assert_eq!(state.present_pending_complete.len(), 1); +} + +// ---------------- Step 4: end-to-end vectors ---------------- + +/// Round-3 inversion vector, now driven by REAL scrap (Task 6's +/// version at `due_skip_is_held_back_behind_a_smaller_id_undrained_gate_entry` +/// inserted the Skip row by hand): P1 executes at arrival (no flip in +/// flight), P2 parks (a flip is in flight), P3 arrives full-frame at +/// the same effective target and scraps P2 via +/// `supersede_covered_pending_presents`. Skip(P2) must not deliver +/// before Copy(P1) even though it was parked first (at P3's arrival, +/// before P1's GPU fence retired). +#[test] +fn supersession_e2e_p1_executes_p2_parks_p3_scraps_p2_delivery_order_preserved() { + use yserver_protocol::x11::present as x11present; + + const WINDOW: u32 = 0x0001_0201; + const PRESENT_EID: u32 = 0x0020_1201; + const P1_ID: u64 = 80; + const P2_ID: u64 = 81; + const P3_ID: u64 = 82; + const CLOCK: u64 = 10; + const TARGET: u64 = CLOCK + 1; // eff for target_msc=0/divisor=0/remainder=0 + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (CLOCK, 0x1000); // held fixed across all three arrivals + seed_present_clock(&mut state, CLOCK, 0x1000); + + // P1: no flip in flight -> ExecuteNow. + backend.present_flip_in_flight = false; + let p1 = SupersessionFixture::new(P1_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + supersede_covered_pending_presents(&mut state, &mut backend, &p1); + arrival_execute_or_park_present_pixmap(&mut state, &mut backend, P1_ID, p1); + assert!( + state.present_complete_gate.contains_key(&P1_ID), + "P1 executed at arrival and inserted its completion gate" + ); + + // P2: a flip is now in flight -> Park. + backend.present_flip_in_flight = true; + let p2 = SupersessionFixture::new(P2_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + supersede_covered_pending_presents(&mut state, &mut backend, &p2); + arrival_execute_or_park_present_pixmap(&mut state, &mut backend, P2_ID, p2); + assert!(state.present_pending_exec.contains_key(&P2_ID)); + + // P3: full-frame, same effective target -> scraps P2, then parks + // itself (flip still in flight). + let p3 = SupersessionFixture::new(P3_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + supersede_covered_pending_presents(&mut state, &mut backend, &p3); + assert!( + !state.present_pending_exec.contains_key(&P2_ID), + "P3 scrapped P2" + ); + arrival_execute_or_park_present_pixmap(&mut state, &mut backend, P3_ID, p3); + assert!(state.present_pending_exec.contains_key(&P3_ID)); + + assert_eq!( + state.present_pending_complete.len(), + 1, + "Skip(P2) is parked" + ); + assert_eq!(state.present_pending_complete[0].event.present_id, P2_ID); + + // Wire up the completion-notify subscriber now that the store + // setup above is done, and drain its connection setup traffic. + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + + let clock = crate::backend::PresentClockSample { + msc: TARGET, + ust: 0x2000, + source: crate::backend::PresentClockSource::PageFlip, + }; + fire_due_present_completions(&mut state, &mut backend, clock); + assert_eq!( + state.present_pending_complete.len(), + 1, + "Skip(P2) held back behind P1's still-undrained completion gate" + ); + + // P1's fence retires late: the gate empties and its completion + // joins the queue, as run.rs's Some(gate) arm does. + state.present_complete_gate.remove(&P1_ID); + state + .present_pending_complete + .push(crate::server::PendingPresentComplete { + event: crate::backend::CompletedPresentEvent { + client_id: ClientId(1), + serial: 1, + host_xid: 0x1, + dst_host_xid: WINDOW, + options: 0, + present_id: P1_ID, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + completion_clock: None, + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }, + effective_target_msc: TARGET, + mode: x11present::COMPLETE_MODE_COPY, + emit_idle: true, + }); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert!(state.present_pending_complete.is_empty()); + assert_eq!( + complete_notify_modes(&read_all_available(&mut peer)), + vec![ + x11present::COMPLETE_MODE_COPY, + x11present::COMPLETE_MODE_SKIP + ], + "Copy(P1) must deliver before Skip(P2) — never inverted" + ); +} + +/// Uncovered survivor (spec vector (ii)): A carries a sliver update +/// region NOT covered by successor C's extent, so C's scrap declines +/// it; B is full-frame and covered, so C scraps it. A later executes +/// via the due-pass; Skip(B) must not deliver before Copy(A) even +/// though B has the larger present_id and was scrapped (queued) +/// first. +#[test] +fn supersede_declined_uncovered_survivor_holds_back_covered_scrap_skip() { + use yserver_protocol::x11::present as x11present; + + const WINDOW: u32 = 0x0001_0202; + const PRESENT_EID: u32 = 0x0020_1202; + const A_ID: u64 = 90; + const B_ID: u64 = 91; + const C_ID: u64 = 92; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (TARGET, 0x1000); // due at TARGET. + + // A: sliver update region far outside C's extent (declines). + let a = SupersessionFixture::new(A_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .update_rects(Some(vec![xfixes::RegionRect { + x: 200, + y: 200, + width: 5, + height: 5, + }])) + .entry(); + state.present_pending_exec.insert(A_ID, a); + + // B: full-frame, covered. + let b = SupersessionFixture::new(B_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .entry(); + state.present_pending_exec.insert(B_ID, b); + + let c = SupersessionFixture::new(C_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + supersede_covered_pending_presents(&mut state, &mut backend, &c); + + assert!( + state.present_pending_exec.contains_key(&A_ID), + "A's sliver update region is not covered by C's extent — declined" + ); + assert!( + !state.present_pending_exec.contains_key(&B_ID), + "B is full-frame and covered — scrapped" + ); + assert_eq!(state.present_pending_complete.len(), 1); + assert_eq!(state.present_pending_complete[0].event.present_id, B_ID); + + let mut peer = install_client(&mut state, 1); + state.present_event_selections.insert( + PRESENT_EID, + crate::server::PresentEventSelection { + owner: ClientId(1), + window: ResourceId(WINDOW), + event_mask: x11present::EVENT_MASK_COMPLETE_NOTIFY, + }, + ); + let _ = read_all_available(&mut peer); + + drain_due_present_pending_exec(&mut state, &mut backend); + assert!( + state.present_pending_exec.is_empty(), + "A executes in the due-pass" + ); + assert!( + state.present_complete_gate.contains_key(&A_ID), + "A's execute_present_pixmap_copy inserted its completion gate" + ); + + let clock = crate::backend::PresentClockSample { + msc: TARGET, + ust: 0x1000, + source: crate::backend::PresentClockSource::PageFlip, + }; + fire_due_present_completions(&mut state, &mut backend, clock); + assert_eq!( + state.present_pending_complete.len(), + 1, + "Skip(B) held back behind A's still-undrained completion gate" + ); + + // A's fence retires: the gate empties and its completion joins + // the queue, as run.rs's Some(gate) arm does. + state.present_complete_gate.remove(&A_ID); + state + .present_pending_complete + .push(crate::server::PendingPresentComplete { + event: crate::backend::CompletedPresentEvent { + client_id: ClientId(1), + serial: 1, + host_xid: 0x1, + dst_host_xid: WINDOW, + options: 0, + present_id: A_ID, + window_generation: 0, + crtc_id: 0, + crtc_epoch: 0, + msc_offset: 0, + completion_clock: None, + wake: crate::backend::PresentWake::Pixmap { idle_fence_xid: 0 }, + completion_mode: yserver_protocol::x11::present::COMPLETE_MODE_COPY, + emit_idle: true, + }, + effective_target_msc: TARGET, + mode: x11present::COMPLETE_MODE_COPY, + emit_idle: true, + }); + + fire_due_present_completions(&mut state, &mut backend, clock); + assert!(state.present_pending_complete.is_empty()); + assert_eq!( + complete_notify_modes(&read_all_available(&mut peer)), + vec![ + x11present::COMPLETE_MODE_COPY, + x11present::COMPLETE_MODE_SKIP + ], + "Copy(A) must deliver before Skip(B): A < B for the same window" + ); +} + +/// Same-target entries whose successor declines (or never arrives) +/// all execute at their due point in arrival (`present_id`) order. +#[test] +fn uncovered_same_target_entries_execute_in_arrival_order() { + use crate::backend::recording::RecordedCall; + + const WINDOW: u32 = 0x0001_0203; + const A_ID: u64 = 100; + const B_ID: u64 = 101; + const TARGET: u64 = 500; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.present_ust_msc = (TARGET, 0x1000); + + // Both carry a sliver update region, so a would-be successor + // would decline both — but here we just prove arrival order + // survives when nothing scraps at all (present_id insertion + // order == BTreeMap iteration order). + let a = SupersessionFixture::new(A_ID, WINDOW) + .eff(Some(TARGET)) + .update_rects(Some(vec![xfixes::RegionRect { + x: 0, + y: 0, + width: 10, + height: 10, + }])) + .entry(); + state.present_pending_exec.insert(A_ID, a); + let b = SupersessionFixture::new(B_ID, WINDOW) + .eff(Some(TARGET)) + .update_rects(Some(vec![xfixes::RegionRect { + x: 20, + y: 20, + width: 10, + height: 10, + }])) + .entry(); + state.present_pending_exec.insert(B_ID, b); + + drain_due_present_pending_exec(&mut state, &mut backend); + + let order: Vec = backend + .calls() + .iter() + .filter_map(|c| match c { + RecordedCall::CopyArea { dst_x, .. } => Some(*dst_x), + _ => None, + }) + .collect(); + // dst_x mirrors the rect's x (0 for A, 20 for B) — arrival order. + assert_eq!(order, vec![0, 20], "A executes before B: arrival order"); + assert!(state.present_pending_exec.is_empty()); +} + +#[test] +fn distinct_effective_targets_never_supersede() { + const WINDOW: u32 = 0x0001_0204; + const A_ID: u64 = 110; + const C_ID: u64 = 111; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + + let mut a = SupersessionFixture::new(A_ID, WINDOW) + .eff(Some(500)) + .geometry(0, 0, 100, 100) + .entry(); + a.pending.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; + state.present_pending_exec.insert(A_ID, a); + + let mut c = SupersessionFixture::new(C_ID, WINDOW) + .eff(Some(600)) // distinct target + .geometry(0, 0, 100, 100) + .pending(); + c.masked_options = crate::present_scheduler::PRESENT_ALL_ASYNC_OPTIONS; + supersede_covered_pending_presents(&mut state, &mut backend, &c); + + assert!( + state.present_pending_exec.contains_key(&A_ID), + "a distinct effective target must never supersede" + ); + assert!(state.present_pending_complete.is_empty()); +} + +/// Scrap × window-destroy race: a present is scrapped first (fence +/// triggered, entry pin released, Skip parked), then the +/// window-destroy purge runs for the same window. The purge must not +/// find the (already-removed) entry again — no double fence trigger, +/// no double pin release. The purge's `signal_present_wake` on the +/// now-parked Skip row (a completion, not a pending-exec entry) is a +/// separate, harmless no-op backend-side; not exercised here. +#[test] +fn scrap_then_window_destroy_purge_releases_exactly_once() { + const WINDOW: u32 = 0x0001_0205; + const VICTIM_ID: u64 = 120; + const SUCCESSOR_ID: u64 = 121; + const TARGET: u64 = 500; + const IDLE_FENCE: u32 = 0x0030_1205; + const PIN_ID: u64 = 5; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + let mut victim = SupersessionFixture::new(VICTIM_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 50, 50) + .idle_fence(IDLE_FENCE) + .entry(); + victim.pin = Some(PIN_ID); + state.present_pending_exec.insert(VICTIM_ID, victim); + + let successor = SupersessionFixture::new(SUCCESSOR_ID, WINDOW) + .eff(Some(TARGET)) + .geometry(0, 0, 100, 100) + .pending(); + supersede_covered_pending_presents(&mut state, &mut backend, &successor); + + assert_eq!(backend.triggered_dri3_fences, vec![IDLE_FENCE]); + assert_eq!(backend.released_present_sources, vec![PIN_ID]); + assert!(state.present_pending_exec.is_empty()); + + // Now destroy the window: the by-XID purge scans + // `present_pending_exec` for this window and finds nothing (the + // entry is already gone), so it must not touch the backend again. + destroy_window_subtree(&mut state, &mut backend, None, ResourceId(WINDOW)).expect("destroy"); + + assert_eq!( + backend.triggered_dri3_fences, + vec![IDLE_FENCE], + "the window-destroy purge must not re-trigger an already-scrapped fence" + ); + assert_eq!( + backend.released_present_sources, + vec![PIN_ID], + "the window-destroy purge must not re-release an already-released pin" + ); + // Review fix (5c): the destroy purge's parked-completions sweep + // (process_request.rs, `destroy_window_subtree`'s + // `present_pending_complete` loop) DOES call `signal_present_wake` + // for every row matching this window — including the Skip row the + // scrap above just parked, since scrap does not remove it from + // `present_pending_complete`. This is a no-op on a real backend + // (the scrapped present_id was never retained as a `PinnedWake` — + // scrap's own by-XID release is what actually signalled the + // client), but `RecordingBackend` records the call regardless, so + // pin the exact expected content: exactly the victim's id, and no + // other wake. + assert_eq!( + backend.signalled_present_wakes, + vec![VICTIM_ID], + "the purge's parked-completion sweep signals the scrapped Skip row's \ + present_id (harmless no-op on a real backend) and nothing else" + ); +} + +/// Xorg rejects reuse of another client's Present event XID. +/// Mutation: overwriting the existing selection lets this request succeed +/// and changes the original owner's selection. +#[test] +fn present_select_input_on_other_clients_event_id_is_bad_match() { + use yserver_protocol::x11::present as x11present; + + const OWNER: u32 = 1; + const WRITER: u32 = 2; + const EID: u32 = 0x0100_0042; + const OWNER_MASK: u32 = x11present::EVENT_MASK_COMPLETE_NOTIFY; + + let mut state = ServerState::new(); + let mut owner_peer = install_client(&mut state, OWNER); + let mut writer_peer = install_client(&mut state, WRITER); + let mut backend = RecordingBackend::new(); + + let select_body = |window: ResourceId, mask: u32| { + let mut body = EID.to_le_bytes().to_vec(); + body.extend_from_slice(&window.0.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); + body + }; + process_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(1), + RequestHeader { + opcode: 145, + data: x11present::SELECT_INPUT, + length_units: 4, + }, + &select_body(ROOT_WINDOW, OWNER_MASK), + None, + ) + .expect("owner SelectInput"); + + process_request( + &mut state, + &mut backend, + ClientId(WRITER), + SequenceNumber(7), + RequestHeader { + opcode: 145, + data: x11present::SELECT_INPUT, + length_units: 4, + }, + &select_body(ROOT_WINDOW, x11present::EVENT_MASK_IDLE_NOTIFY), + None, + ) + .expect("writer SelectInput"); + + let errors = wire_packets(&mut writer_peer); + assert_eq!( + errors.len(), + 1, + "reusing another client's eid returns BadMatch" + ); + assert_eq!( + error_fields(&errors[0]), + ( + yserver_protocol::x11::error::BAD_MATCH, + EID, + u16::from(x11present::SELECT_INPUT), + 145, + ), + "BadMatch carries the eid and Present SelectInput opcodes", + ); + + // The same owner cannot retarget an existing eid to a different window. + process_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(2), + RequestHeader { + opcode: 145, + data: x11present::SELECT_INPUT, + length_units: 4, + }, + &select_body(ResourceId(0x0000_0010), OWNER_MASK), + None, + ) + .expect("owner SelectInput with another window"); + let owner_errors = wire_packets(&mut owner_peer); + assert_eq!( + owner_errors.len(), + 1, + "retargeting an existing eid to another window returns BadMatch", + ); + assert_eq!( + error_fields(&owner_errors[0]), + ( + yserver_protocol::x11::error::BAD_MATCH, + EID, + u16::from(x11present::SELECT_INPUT), + 145, + ), + "BadMatch carries the eid and Present SelectInput opcodes", + ); + let selection = state + .present_event_selections + .get(&EID) + .expect("owner selection remains present"); + assert_eq!(selection.owner, ClientId(OWNER)); + assert_eq!(selection.window, ROOT_WINDOW); + assert_eq!(selection.event_mask, OWNER_MASK); +} + +/// Mutation: return BadMatch for every existing eid; the owner's same-window +/// reselection must instead update only the event mask. +#[test] +fn present_select_input_on_existing_owned_event_id_updates_mask() { + use yserver_protocol::x11::present as x11present; + + const OWNER: u32 = 1; + const EID: u32 = 0x0100_0052; + const INITIAL_MASK: u32 = x11present::EVENT_MASK_COMPLETE_NOTIFY; + const UPDATED_MASK: u32 = x11present::EVENT_MASK_IDLE_NOTIFY; + + let mut state = ServerState::new(); + let mut owner_peer = install_client(&mut state, OWNER); + let mut backend = RecordingBackend::new(); + + let select_body = |mask: u32| { + let mut body = EID.to_le_bytes().to_vec(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); + body + }; + for (sequence, mask) in [(1, INITIAL_MASK), (2, UPDATED_MASK)] { + process_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(sequence), + RequestHeader { + opcode: 145, + data: x11present::SELECT_INPUT, + length_units: 4, + }, + &select_body(mask), + None, + ) + .expect("owner SelectInput"); + } + + assert!( + wire_packets(&mut owner_peer).is_empty(), + "reselection has no error" + ); + let selection = state + .present_event_selections + .get(&EID) + .expect("owner selection remains present"); + assert_eq!(selection.owner, ClientId(OWNER)); + assert_eq!(selection.window, ROOT_WINDOW); + assert_eq!(selection.event_mask, UPDATED_MASK); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/props.rs b/crates/yserver-core/src/core_loop/process_request/tests/props.rs new file mode 100644 index 000000000..780814824 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/props.rs @@ -0,0 +1,617 @@ +//! Property data byte order across big- and little-endian clients. +//! +//! Every expected value below was measured on Xorg 21.1.24 (vng, a raw +//! `B` client and a raw `l` client on the same window): Xorg swaps +//! format-16/32 data on the way in (`dix/swapreq.c:209-229`) and on the +//! way out (`dix/property.c:535-549`), so a property reads the same to +//! every client whatever byte order wrote it. Format 8 is never swapped. + +use super::*; + +const BE: u32 = 1; +const LE: u32 = 2; +const WIN: u32 = 0x0040_0001; +const CARDINAL: u32 = 6; +const INTEGER: u32 = 19; +const STRING: u32 = 31; + +struct Pair { + state: ServerState, + be: UnixStream, + le: UnixStream, + seq: u16, +} + +impl Pair { + fn new() -> Self { + let mut state = ServerState::new(); + let be = install_client(&mut state, BE); + let le = install_client(&mut state, LE); + state.clients.get_mut(&BE).expect("BE client").byte_order = ClientByteOrder::BigEndian; + create_root_child(&mut state, WIN); + Self { + state, + be, + le, + seq: 0, + } + } + + fn order(client: u32) -> ClientByteOrder { + if client == BE { + ClientByteOrder::BigEndian + } else { + ClientByteOrder::LittleEndian + } + } + + fn atom(&mut self, name: &str) -> u32 { + self.state.atoms.intern(name, false).0 + } + + /// Send a request built in `client`'s byte order through the reader's + /// swap and `process_request`; return what that client received. + fn send(&mut self, client: u32, opcode: u8, data: u8, body: WireBody) -> Vec { + let mut body = body.1; + yserver_protocol::x11::request_swap::swap_request_body( + opcode, + data, + Self::order(client), + &mut body, + ); + self.seq += 1; + let mut backend = RecordingBackend::new(); + process_request( + &mut self.state, + &mut backend, + ClientId(client), + SequenceNumber(self.seq), + RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("request"); + self.read(client) + } + + fn read(&mut self, client: u32) -> Vec { + if client == BE { + read_all_available(&mut self.be) + } else { + read_all_available(&mut self.le) + } + } + + fn change(&mut self, client: u32, mode: u8, prop: u32, ty: u32, format: u8, items: &[u32]) { + let mut body = WireBody(Self::order(client), Vec::new()) + .u32(WIN) + .u32(prop) + .u32(ty) + .bytes(&[format, 0, 0, 0]) + .u32(u32::try_from(items.len()).unwrap()); + for &item in items { + body = match format { + 8 => body.bytes(&[u8::try_from(item).unwrap()]), + 16 => body.u16(u16::try_from(item).unwrap()), + _ => body.u32(item), + }; + } + while !body.1.len().is_multiple_of(4) { + body.1.push(0); + } + let reply = self.send(client, 18, mode, body); + assert!(reply.is_empty(), "ChangeProperty answered {reply:02x?}"); + } + + fn get(&mut self, client: u32, prop: u32, ty: u32, offset: u32, length: u32) -> GetReply { + self.get_with(client, prop, ty, offset, length, false) + } + + fn get_with( + &mut self, + client: u32, + prop: u32, + ty: u32, + offset: u32, + length: u32, + delete: bool, + ) -> GetReply { + let body = WireBody(Self::order(client), Vec::new()) + .u32(WIN) + .u32(prop) + .u32(ty) + .u32(offset) + .u32(length); + let reply = self.send(client, 20, u8::from(delete), body); + assert_eq!(reply[0], 1, "GetProperty reply, got {reply:02x?}"); + let word = |at: usize| { + let b: [u8; 4] = reply[at..at + 4].try_into().unwrap(); + if client == BE { + u32::from_be_bytes(b) + } else { + u32::from_le_bytes(b) + } + }; + let format = reply[1]; + let nitems = word(16); + let len = usize::try_from(nitems).unwrap() * usize::from(format.max(8) / 8); + GetReply { + format, + ty: word(8), + bytes_after: word(12), + nitems, + raw: hex(&reply[32..32 + len]), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +struct GetReply { + format: u8, + ty: u32, + bytes_after: u32, + nitems: u32, + raw: String, +} + +fn reply(format: u8, ty: u32, nitems: u32, bytes_after: u32, raw: &str) -> GetReply { + GetReply { + format, + ty, + bytes_after, + nitems, + raw: raw.to_string(), + } +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// RL0's `WM_NORMAL_HINTS` case in miniature: a BE client's CARDINAL/32 +/// is stored in server order and reads as the same numbers to both. +#[test] +fn be_written_format32_reads_the_same_values_to_le_and_be() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_BE32"); + p.change(BE, 0, prop, CARDINAL, 32, &[0x0102_0304, 5]); + + let stored = p + .state + .resources + .window_property(ResourceId(WIN), AtomId(prop)) + .expect("stored"); + assert_eq!(hex(&stored.data), "0403020105000000", "server order"); + + assert_eq!( + p.get(LE, prop, 0, 0, 1000), + reply(32, CARDINAL, 2, 0, "0403020105000000") + ); + assert_eq!( + p.get(BE, prop, 0, 0, 1000), + reply(32, CARDINAL, 2, 0, "0102030400000005") + ); +} + +#[test] +fn le_written_format16_and_32_read_swapped_to_a_be_client() { + let mut p = Pair::new(); + let p32 = p.atom("PROBE_LE32"); + let p16 = p.atom("PROBE_LE16"); + p.change(LE, 0, p32, CARDINAL, 32, &[0x0102_0304, 5]); + p.change(LE, 0, p16, INTEGER, 16, &[0x0102, 0x0304, 7]); + + assert_eq!( + p.get(BE, p32, 0, 0, 1000), + reply(32, CARDINAL, 2, 0, "0102030400000005") + ); + assert_eq!( + p.get(BE, p16, 0, 0, 1000), + reply(16, INTEGER, 3, 0, "010203040007") + ); + assert_eq!( + p.get(LE, p16, 0, 0, 1000), + reply(16, INTEGER, 3, 0, "020104030700") + ); +} + +#[test] +fn be_written_format16_reads_the_same_values_to_le_and_be() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_BE16"); + p.change(BE, 0, prop, INTEGER, 16, &[0x0102, 0x0304, 7]); + assert_eq!( + p.get(LE, prop, 0, 0, 1000), + reply(16, INTEGER, 3, 0, "020104030700") + ); + assert_eq!( + p.get(BE, prop, 0, 0, 1000), + reply(16, INTEGER, 3, 0, "010203040007") + ); +} + +#[test] +fn format8_is_never_swapped() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_BE8"); + p.change(BE, 0, prop, STRING, 8, &[0x61, 0x62, 1, 2, 3]); + assert_eq!( + p.get(LE, prop, 0, 0, 1000), + reply(8, STRING, 5, 0, "6162010203") + ); + assert_eq!( + p.get(BE, prop, 0, 0, 1000), + reply(8, STRING, 5, 0, "6162010203") + ); + assert_eq!(p.get(BE, prop, 0, 1, 1), reply(8, STRING, 1, 0, "03")); +} + +/// Append and Prepend from both byte orders concatenate values, not bytes. +#[test] +fn mixed_order_append_and_prepend_concatenate_values() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_BE32"); + p.change(BE, 0, prop, CARDINAL, 32, &[0x0102_0304, 5]); + p.change(BE, 2, prop, CARDINAL, 32, &[0x0A0B_0C0D]); + p.change(BE, 1, prop, CARDINAL, 32, &[0x1122_3344]); + p.change(LE, 2, prop, CARDINAL, 32, &[0x5566_7788]); + + assert_eq!( + p.get(BE, prop, 0, 0, 1000), + reply( + 32, + CARDINAL, + 5, + 0, + "1122334401020304000000050a0b0c0d55667788" + ) + ); + assert_eq!( + p.get(LE, prop, 0, 0, 1000), + reply( + 32, + CARDINAL, + 5, + 0, + "4433221104030201050000000d0c0b0a88776655" + ) + ); + // long_offset/long_length windows are swapped per item too. + assert_eq!( + p.get(BE, prop, 0, 1, 1), + reply(32, CARDINAL, 1, 12, "01020304") + ); + assert_eq!( + p.get(LE, prop, 0, 1, 1), + reply(32, CARDINAL, 1, 12, "04030201") + ); + assert_eq!( + p.get(BE, prop, 0, 2, 5), + reply(32, CARDINAL, 3, 0, "000000050a0b0c0d55667788") + ); +} + +#[test] +fn format16_windows_swap_each_item() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_BE16"); + p.change(BE, 0, prop, INTEGER, 16, &[0x0102, 0x0304, 7]); + assert_eq!( + p.get(BE, prop, 0, 0, 1), + reply(16, INTEGER, 2, 2, "01020304") + ); + assert_eq!( + p.get(LE, prop, 0, 0, 1), + reply(16, INTEGER, 2, 2, "02010403") + ); + assert_eq!(p.get(BE, prop, 0, 1, 1), reply(16, INTEGER, 1, 0, "0007")); + assert_eq!(p.get(LE, prop, 0, 1, 1), reply(16, INTEGER, 1, 0, "0700")); +} + +#[test] +fn delete_reply_is_in_the_reader_order_and_notifies_both() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_LE32"); + p.change(LE, 0, prop, CARDINAL, 32, &[0x0102_0304, 5]); + // PropertyChangeMask on the window for the LE client. + let cwa = WireBody(ClientByteOrder::LittleEndian, Vec::new()) + .u32(WIN) + .u32(0x800) + .u32(0x0040_0000); + p.send(LE, 2, 0, cwa); + + assert_eq!( + p.get_with(BE, prop, 0, 0, 1000, true), + reply(32, CARDINAL, 2, 0, "0102030400000005") + ); + let event = p.read(LE); + assert_eq!(event.len(), 32); + assert_eq!(event[0], 28, "PropertyNotify"); + assert_eq!(u32::from_le_bytes(event[8..12].try_into().unwrap()), prop); + assert_eq!(event[16], 1, "PropertyDelete"); + assert_eq!(p.get(LE, prop, 0, 0, 1000), reply(0, 0, 0, 0, "")); +} + +#[test] +fn list_properties_atoms_are_in_the_reader_order() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_BE32"); + p.change(BE, 0, prop, CARDINAL, 32, &[1]); + let reply = p.send( + BE, + 21, + 0, + WireBody(ClientByteOrder::BigEndian, Vec::new()).u32(WIN), + ); + assert_eq!(u16::from_be_bytes(reply[8..10].try_into().unwrap()), 1); + assert_eq!(u32::from_be_bytes(reply[32..36].try_into().unwrap()), prop); +} + +/// RandR output properties have their own store; Xorg swaps them on input +/// (`SProcRRChangeOutputProperty`) and on output (`ProcRRGetOutputProperty`), +/// so a BE writer reads its own `INTEGER/32` back unchanged. +#[test] +fn randr_output_property_reads_the_same_values_to_le_and_be() { + use yserver_protocol::x11::randr as x11randr; + + let mut p = Pair::new(); + let output = p.state.randr.outputs[0].output_id; + let prop = p.atom("PROBE_EXT32"); + let change = WireBody(ClientByteOrder::BigEndian, Vec::new()) + .u32(output) + .u32(prop) + .u32(INTEGER) + .bytes(&[32, 0, 0, 0]) + .u32(2) + .u32(0x0102_0304) + .u32(5); + p.send(BE, 128, x11randr::RR_CHANGE_OUTPUT_PROPERTY, change); + for (client, raw) in [(BE, "0102030400000005"), (LE, "0403020105000000")] { + let get = WireBody(Pair::order(client), Vec::new()) + .u32(output) + .u32(prop) + .u32(0) + .u32(0) + .u32(100) + .bytes(&[0, 0, 0, 0]); + let reply = p.send(client, 128, x11randr::RR_GET_OUTPUT_PROPERTY, get); + assert_eq!(reply[0], 1, "GetOutputProperty reply, got {reply:02x?}"); + assert_eq!(reply[1], 32); + assert_eq!(hex(&reply[32..40]), raw, "client {client}"); + } +} + +/// A type mismatch returns the property's type and format with no data, +/// and Xorg's `bytes_after` is the property's ITEM count +/// (`reply.bytesAfter = pProp->size`, `dix/property.c:492-501`), not the +/// byte length the protocol text describes. +#[test] +fn type_mismatch_bytes_after_counts_items() { + let mut p = Pair::new(); + let prop = p.atom("PROBE_LE32"); + p.change(LE, 0, prop, CARDINAL, 32, &[1, 2, 3, 4, 5]); + assert_eq!( + p.get(LE, prop, INTEGER, 0, 1000), + reply(32, CARDINAL, 0, 5, "") + ); + let p16 = p.atom("PROBE_LE16"); + p.change(LE, 0, p16, INTEGER, 16, &[1, 2, 3]); + assert_eq!( + p.get(LE, p16, CARDINAL, 0, 1000), + reply(16, INTEGER, 0, 3, "") + ); +} + +// ── RotateProperties ── +// +// Expected values measured on Xorg 21.1 (`prop-order` vng golden): rotating +// by `delta` moves property i's type, format and data to property +// `(i + delta) mod n`; one PropertyNotify NewValue per listed property, in +// list order; nothing (no events) when `delta mod n == 0`. Errors are +// checked atom by atom (`dix/property.c:157-176`). + +impl Pair { + fn rotate(&mut self, client: u32, window: u32, atoms: &[u32], delta: i16) -> Vec { + let mut body = WireBody(Self::order(client), Vec::new()) + .u32(window) + .u16(u16::try_from(atoms.len()).unwrap()) + .u16(delta.cast_unsigned()); + for &atom in atoms { + body = body.u32(atom); + } + self.send(client, 114, 0, body) + } + + fn select_property_change(&mut self, client: u32) { + let cwa = WireBody(Self::order(client), Vec::new()) + .u32(WIN) + .u32(0x800) + .u32(0x0040_0000); + self.send(client, 2, 0, cwa); + } + + /// The three `rotate` properties: CARDINAL/32, INTEGER/16, STRING/8. + fn rotate_setup(&mut self) -> [u32; 3] { + let r = [ + self.atom("PROBE_R1"), + self.atom("PROBE_R2"), + self.atom("PROBE_R3"), + ]; + self.change(BE, 0, r[0], CARDINAL, 32, &[0x0102_0304]); + self.change(BE, 0, r[1], INTEGER, 16, &[0x0102, 0x0304, 7]); + self.change(BE, 0, r[2], STRING, 8, &[0x61, 0x62, 0x63]); + self.read(LE); + r + } +} + +fn r1_value() -> GetReply { + reply(32, CARDINAL, 1, 0, "04030201") +} +fn r2_value() -> GetReply { + reply(16, INTEGER, 3, 0, "020104030700") +} +fn r3_value() -> GetReply { + reply(8, STRING, 3, 0, "616263") +} + +/// `PropertyNotify` (atom, state) pairs in an LE client's event stream. +fn property_notifies(events: &[u8]) -> Vec<(u32, u8)> { + assert!(events.len().is_multiple_of(32), "{events:02x?}"); + events + .chunks_exact(32) + .map(|ev| { + assert_eq!(ev[0], 28, "PropertyNotify, got {ev:02x?}"); + assert_eq!(u32::from_le_bytes(ev[4..8].try_into().unwrap()), WIN); + (u32::from_le_bytes(ev[8..12].try_into().unwrap()), ev[16]) + }) + .collect() +} + +/// (code, value, major) of the single X error in `bytes`. +fn x_error(bytes: &[u8], order: ClientByteOrder) -> (u8, u32, u8) { + assert_eq!(bytes.len(), 32, "one error, got {bytes:02x?}"); + assert_eq!(bytes[0], 0, "error, got {bytes:02x?}"); + let v: [u8; 4] = bytes[4..8].try_into().unwrap(); + let value = if order == ClientByteOrder::BigEndian { + u32::from_be_bytes(v) + } else { + u32::from_le_bytes(v) + }; + (bytes[1], value, bytes[10]) +} + +fn assert_values(p: &mut Pair, r: [u32; 3], want: [GetReply; 3]) { + for (atom, want) in r.into_iter().zip(want) { + assert_eq!(p.get(LE, atom, 0, 0, 1000), want); + } +} + +#[test] +fn rotate_plus_one_moves_each_value_to_the_next_property() { + let mut p = Pair::new(); + p.select_property_change(LE); + let r = p.rotate_setup(); + assert!(p.rotate(BE, WIN, &r, 1).is_empty()); + assert_eq!( + property_notifies(&p.read(LE)), + vec![(r[0], 0), (r[1], 0), (r[2], 0)] + ); + // Type and format travel with the data. + assert_values(&mut p, r, [r3_value(), r1_value(), r2_value()]); + // -1 from the LE client (the selecting one) rotates back. + assert_eq!( + property_notifies(&p.rotate(LE, WIN, &r, -1)), + vec![(r[0], 0), (r[1], 0), (r[2], 0)] + ); + assert_values(&mut p, r, [r1_value(), r2_value(), r3_value()]); +} + +#[test] +fn rotate_by_a_multiple_of_n_changes_nothing_and_sends_no_events() { + let mut p = Pair::new(); + p.select_property_change(LE); + let r = p.rotate_setup(); + for delta in [0, 3, -3, 6] { + assert!(p.rotate(BE, WIN, &r, delta).is_empty()); + assert!(p.read(LE).is_empty(), "delta {delta} sent events"); + assert_values(&mut p, r, [r1_value(), r2_value(), r3_value()]); + } +} + +#[test] +fn rotate_by_n_plus_one_equals_plus_one_and_minus_n_plus_one_equals_minus_one() { + let mut p = Pair::new(); + let r = p.rotate_setup(); + assert!(p.rotate(BE, WIN, &r, 4).is_empty()); + assert_values(&mut p, r, [r3_value(), r1_value(), r2_value()]); + assert!(p.rotate(LE, WIN, &r, -4).is_empty()); + assert_values(&mut p, r, [r1_value(), r2_value(), r3_value()]); +} + +#[test] +fn rotate_events_follow_the_request_list_order() { + let mut p = Pair::new(); + p.select_property_change(LE); + let r = p.rotate_setup(); + assert!(p.rotate(BE, WIN, &[r[2], r[0], r[1]], 1).is_empty()); + assert_eq!( + property_notifies(&p.read(LE)), + vec![(r[2], 0), (r[0], 0), (r[1], 0)] + ); + // R1 <- R3, R2 <- R1, R3 <- R2: the same as rotating [R1, R2, R3] by 1. + assert_values(&mut p, r, [r3_value(), r1_value(), r2_value()]); +} + +/// A BE client's nPositions must be swapped: unswapped, 1 reads as 0x0100, +/// which is 0 mod 2 and would rotate nothing. +#[test] +fn rotate_two_properties_by_one_from_a_big_endian_client() { + let mut p = Pair::new(); + let r4 = p.atom("PROBE_R4"); + let r5 = p.atom("PROBE_R5"); + p.change(BE, 0, r4, CARDINAL, 32, &[4]); + p.change(BE, 0, r5, INTEGER, 16, &[5]); + assert!(p.rotate(BE, WIN, &[r4, r5], 1).is_empty()); + assert_eq!(p.get(BE, r4, 0, 0, 1000), reply(16, INTEGER, 1, 0, "0005")); + assert_eq!( + p.get(BE, r5, 0, 0, 1000), + reply(32, CARDINAL, 1, 0, "00000004") + ); +} + +#[test] +fn rotate_an_empty_list_is_a_no_op() { + let mut p = Pair::new(); + assert!(p.rotate(BE, WIN, &[], 1).is_empty()); +} + +#[test] +fn rotate_errors_match_xorg_and_change_nothing() { + const BAD_WINDOW: u8 = 3; + const BAD_ATOM: u8 = 5; + const BAD_MATCH: u8 = 8; + const BAD_ATOM_ID: u32 = 0x00FF_FFF0; + const NO_WINDOW: u32 = 0x0060_0001; + + let mut p = Pair::new(); + p.select_property_change(LE); + let r = p.rotate_setup(); + let miss = p.atom("PROBE_RMISSING"); + + let cases = [ + (BE, WIN, vec![r[0], miss, r[1]], 1, (BAD_MATCH, miss)), + // A duplicate of the FIRST atom: Xorg's errorValue is still the + // window id the lookup left there. + (LE, WIN, vec![r[0], r[1], r[0]], 1, (BAD_MATCH, WIN)), + // A later duplicate: the previous atom's property lookup set it. + (LE, WIN, vec![r[0], r[1], r[1]], 1, (BAD_MATCH, r[0])), + ( + BE, + WIN, + vec![r[0], r[1], BAD_ATOM_ID], + 1, + (BAD_ATOM, BAD_ATOM_ID), + ), + (BE, WIN, vec![r[0], 0], 1, (BAD_ATOM, 0)), + (LE, WIN, vec![miss, BAD_ATOM_ID], 1, (BAD_MATCH, miss)), + (LE, WIN, vec![BAD_ATOM_ID, miss], 1, (BAD_ATOM, BAD_ATOM_ID)), + (BE, NO_WINDOW, r.to_vec(), 1, (BAD_WINDOW, NO_WINDOW)), + (BE, NO_WINDOW, vec![], 1, (BAD_WINDOW, NO_WINDOW)), + (LE, WIN, vec![r[0], miss], 0, (BAD_MATCH, miss)), + ]; + for (client, window, atoms, delta, (code, value)) in cases { + let got = p.rotate(client, window, &atoms, delta); + assert_eq!( + x_error(&got, Pair::order(client)), + (code, value, 114), + "{atoms:x?} on {window:#x}" + ); + assert!(p.read(LE).is_empty(), "{atoms:x?} sent events"); + assert_values(&mut p, r, [r1_value(), r2_value(), r3_value()]); + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/randr_crtc.rs b/crates/yserver-core/src/core_loop/process_request/tests/randr_crtc.rs new file mode 100644 index 000000000..c668c7ec1 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/randr_crtc.rs @@ -0,0 +1,2882 @@ +use super::*; +use crate::{ + backend::{CrtcConfigToken, ModeSpec}, + core_loop::process_request::vidmode::current_vidmode_output, +}; +use yserver_protocol::x11::AtomId; + +#[test] +fn active_monitors_matches_outputs_and_order() { + let mut state = ServerState::new(); + state.randr.outputs = vec![ + crate::randr::RandrOutput { + name: "DP-1".into(), + output_id: 1, + crtc_id: 1, + mode_id: 1, + connected: true, + x: 0, + y: 0, + width: 2560, + height: 1440, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![1], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }, + crate::randr::RandrOutput { + name: "HDMI-A-1".into(), + output_id: 2, + crtc_id: 2, + mode_id: 1, + connected: false, + x: 2560, + y: 0, + width: 2560, + height: 1440, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![1], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }, + ]; + + let monitors = active_monitors(&state, true); + assert_eq!(monitors.len(), state.randr.outputs.len()); + assert_eq!(monitors.len(), 2); + assert!(monitors[0].primary); + assert!(!monitors[1].primary); + assert_eq!(monitors[1].x, 2560); + assert_eq!( + (monitors[1].width_mm, monitors[1].height_mm), + (677, 381), + "automatic monitor geometry still derives physical size from its retained CRTC", + ); +} + +/// The two-output guest of `tools/vng-scenarios/xrandr-monitors.sh +/// --outputs 2` after `--right-of`: Virtual-1 1920x1440+0+0 (primary), +/// Virtual-2 1360x768+1920+0, both 325x203 mm. +fn monitor_fixture(byte_order: ClientByteOrder) -> (ServerState, UnixStream) { + let output = |name: &str, id: u32, x: i16, width: u16, height: u16| crate::randr::RandrOutput { + name: name.into(), + output_id: id, + crtc_id: id + 2, + mode_id: id + 4, + connected: true, + x, + y: 0, + width, + height, + vrefresh: 60, + timing: None, + mm_width: 325, + mm_height: 203, + mode_ids: vec![id + 4], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }; + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs( + 7, + vec![ + output("Virtual-1", 1, 0, 1920, 1440), + output("Virtual-2", 2, 1920, 1360, 768), + ], + ); + let peer = install_client(&mut state, 1); + state.clients.get_mut(&1).unwrap().byte_order = byte_order; + (state, peer) +} + +fn wire_u32(bo: ClientByteOrder, b: &[u8]) -> u32 { + let b: [u8; 4] = b[..4].try_into().unwrap(); + match bo { + ClientByteOrder::LittleEndian => u32::from_le_bytes(b), + ClientByteOrder::BigEndian => u32::from_be_bytes(b), + } +} + +fn wire_u16(bo: ClientByteOrder, b: &[u8]) -> u16 { + let b: [u8; 2] = b[..2].try_into().unwrap(); + match bo { + ClientByteOrder::LittleEndian => u16::from_le_bytes(b), + ClientByteOrder::BigEndian => u16::from_be_bytes(b), + } +} + +/// Swap `body` as the reader would, then dispatch it as RANDR `minor`. +fn randr_wire_request( + state: &mut ServerState, + peer: &mut UnixStream, + minor: u8, + body: WireBody, +) -> Vec { + let WireBody(byte_order, mut body) = body; + yserver_protocol::x11::request_swap::swap_request_body(128, minor, byte_order, &mut body); + handle_randr_request( + state, + &mut RecordingBackend::new(), + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + ) + .expect("RANDR request"); + read_all_available(peer) +} + +/// `SetMonitor` body: window, then name primary automatic noutput x y +/// width height mm-width mm-height outputs. +#[allow(clippy::too_many_arguments)] +fn set_monitor_body( + bo: ClientByteOrder, + window: u32, + name: u32, + primary: bool, + noutput: u16, + geometry: (i16, i16, u16, u16), + mm: (u32, u32), + outputs: &[u32], +) -> WireBody { + #[allow(clippy::cast_sign_loss)] + let mut body = WireBody(bo, Vec::new()) + .u32(window) + .u32(name) + .bytes(&[u8::from(primary), 0]) + .u16(noutput) + .u16(geometry.0 as u16) + .u16(geometry.1 as u16) + .u16(geometry.2) + .u16(geometry.3) + .u32(mm.0) + .u32(mm.1); + for &output in outputs { + body = body.u32(output); + } + body +} + +fn set_monitor( + state: &mut ServerState, + peer: &mut UnixStream, + name: &str, + primary: bool, + geometry: (i16, i16, u16, u16), + mm: (u32, u32), + outputs: &[u32], +) -> Vec { + let bo = state.clients[&1].byte_order; + let atom = state.atoms.intern(name, false).0; + #[allow(clippy::cast_possible_truncation)] + let body = set_monitor_body( + bo, + ROOT_WINDOW.0, + atom, + primary, + outputs.len() as u16, + geometry, + mm, + outputs, + ); + randr_wire_request(state, peer, x11randr_minor::SET_MONITOR, body) +} + +fn delete_monitor(state: &mut ServerState, peer: &mut UnixStream, name: u32) -> Vec { + let bo = state.clients[&1].byte_order; + let body = WireBody(bo, Vec::new()).u32(ROOT_WINDOW.0).u32(name); + randr_wire_request(state, peer, x11randr_minor::DELETE_MONITOR, body) +} + +/// One decoded `GetMonitors` entry: name, primary, automatic, +/// "WxH+X+Y", "mmWxmmH", outputs. +type WireMonitor = (String, bool, bool, String, (u32, u32), Vec); + +fn get_monitors( + state: &mut ServerState, + peer: &mut UnixStream, + get_active: bool, +) -> Vec { + let bo = state.clients[&1].byte_order; + let body = WireBody(bo, Vec::new()) + .u32(ROOT_WINDOW.0) + .bytes(&[u8::from(get_active), 0, 0, 0]); + let r = randr_wire_request( + state, + peer, + yserver_protocol::x11::randr::RR_GET_MONITORS, + body, + ); + assert_eq!(r[0], 1, "GetMonitors reply: {r:02x?}"); + assert_eq!( + wire_u32(bo, &r[4..]) as usize * 4 + 32, + r.len(), + "reply length" + ); + let count = wire_u32(bo, &r[12..]); + let mut total_outputs = 0; + let mut offset = 32; + let mut monitors = Vec::new(); + for _ in 0..count { + let m = &r[offset..]; + let n_out = usize::from(wire_u16(bo, &m[6..])); + #[allow(clippy::cast_possible_wrap)] + let geometry = format!( + "{}x{}+{}+{}", + wire_u16(bo, &m[12..]), + wire_u16(bo, &m[14..]), + wire_u16(bo, &m[8..]) as i16, + wire_u16(bo, &m[10..]) as i16, + ); + let name = state + .atoms + .name(AtomId(wire_u32(bo, m))) + .unwrap_or("?") + .to_string(); + let outputs = (0..n_out).map(|i| wire_u32(bo, &m[24 + i * 4..])).collect(); + monitors.push(( + name, + m[4] != 0, + m[5] != 0, + geometry, + (wire_u32(bo, &m[16..]), wire_u32(bo, &m[20..])), + outputs, + )); + total_outputs += n_out; + offset += 24 + n_out * 4; + } + assert_eq!(offset, r.len()); + assert_eq!(wire_u32(bo, &r[16..]) as usize, total_outputs, "noutputs"); + monitors +} + +fn wm( + name: &str, + primary: bool, + automatic: bool, + geometry: &str, + mm: (u32, u32), + outputs: &[u32], +) -> WireMonitor { + ( + name.into(), + primary, + automatic, + geometry.into(), + mm, + outputs.to_vec(), + ) +} + +/// XINERAMA `(GetScreenCount, QueryScreens)` in the client's order. +fn xinerama_heads(state: &mut ServerState, peer: &mut UnixStream) -> (u8, Vec) { + use yserver_protocol::x11::xinerama as xin; + let bo = state.clients[&1].byte_order; + let mut send = |state: &mut ServerState, minor: u8, body: &[u8]| { + handle_xinerama_request( + state, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 151, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + ) + .expect("XINERAMA request"); + read_all_available(peer) + }; + let window = WireBody(bo, Vec::new()).u32(ROOT_WINDOW.0).1; + let count = send(state, xin::GET_SCREEN_COUNT, &window); + let screens = send(state, xin::QUERY_SCREENS, &[]); + let n = wire_u32(bo, &screens[8..]) as usize; + #[allow(clippy::cast_possible_wrap)] + let heads = (0..n) + .map(|i| { + let s = &screens[32 + i * 8..]; + format!( + "{}x{}+{}+{}", + wire_u16(bo, &s[4..]), + wire_u16(bo, &s[6..]), + wire_u16(bo, s) as i16, + wire_u16(bo, &s[2..]) as i16, + ) + }) + .collect(); + (count[1], heads) +} + +const BOTH_ORDERS: [ClientByteOrder; 2] = + [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian]; + +/// Measured split: `--setmonitor left 960/170x1440/211+0+0 Virtual-1` +/// and `right ...+960+0 none` hide Virtual-1's automatic monitor, keep +/// Virtual-2's, and nobody is primary (the primary output is covered). +#[test] +fn set_monitor_split_replaces_the_covered_automatic_monitor() { + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + let r = set_monitor( + &mut state, + &mut peer, + "left", + false, + (0, 0, 960, 1440), + (170, 211), + &[1], + ); + assert!(r.is_empty(), "{r:02x?}"); + let r = set_monitor( + &mut state, + &mut peer, + "right", + false, + (960, 0, 960, 1440), + (170, 211), + &[], + ); + assert!(r.is_empty(), "{r:02x?}"); + let want = vec![ + wm("left", false, false, "960x1440+0+0", (170, 211), &[1]), + wm("right", false, false, "960x1440+960+0", (170, 211), &[]), + wm( + "Virtual-2", + false, + true, + "1360x768+1920+0", + (325, 203), + &[2], + ), + ]; + assert_eq!(get_monitors(&mut state, &mut peer, false), want, "{bo:?}"); + assert_eq!(get_monitors(&mut state, &mut peer, true), want, "{bo:?}"); + assert_eq!( + xinerama_heads(&mut state, &mut peer), + ( + 3, + vec![ + "960x1440+0+0".into(), + "960x1440+960+0".into(), + "1360x768+1920+0".into() + ] + ), + ); + } +} + +/// Measured: a 0x0+0+0 monitor over both outputs is their union, and +/// its physical size is Xorg 21.1's integer `last_w / first_w * +/// first_mm` — 1360/1920 = 0 — so 0x0 mm. With Virtual-2 off it is +/// Virtual-1's geometry alone. +#[test] +fn automatic_geometry_client_monitor_follows_the_crtc_layout() { + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + set_monitor( + &mut state, + &mut peer, + "both", + false, + (0, 0, 0, 0), + (0, 0), + &[1, 2], + ); + assert_eq!( + get_monitors(&mut state, &mut peer, false), + vec![wm("both", false, false, "3280x1440+0+0", (0, 0), &[1, 2])], + ); + state.randr.outputs[1].mode_id = 0; + assert_eq!( + get_monitors(&mut state, &mut peer, false), + vec![wm( + "both", + false, + false, + "1920x1440+0+0", + (325, 203), + &[1, 2] + )], + ); + } +} + +/// Measured `cprim`: a primary client monitor leads the list, and the +/// uncovered CRTC of the primary output is ALSO reported primary — +/// Xorg's leading entry does not count towards `has_primary`. +#[test] +fn client_primary_and_uncovered_primary_output_are_both_primary() { + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + state.randr.primary_output = 2; + set_monitor( + &mut state, + &mut peer, + "autogeo", + false, + (0, 0, 0, 0), + (0, 0), + &[1], + ); + set_monitor( + &mut state, + &mut peer, + "cprim", + true, + (0, 0, 0, 0), + (0, 0), + &[1], + ); + assert_eq!( + get_monitors(&mut state, &mut peer, true), + vec![ + wm("cprim", true, false, "1920x1440+0+0", (325, 203), &[1]), + wm("autogeo", false, false, "1920x1440+0+0", (325, 203), &[1]), + wm("Virtual-2", true, true, "1360x768+1920+0", (325, 203), &[2]), + ], + ); + } +} + +/// Measured `extra-primary`: a new primary monitor clears the old one's +/// flag; deleting it leaves no primary client monitor behind. +#[test] +fn a_new_primary_client_monitor_clears_the_previous_one() { + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + set_monitor( + &mut state, + &mut peer, + "left", + false, + (0, 0, 960, 1440), + (170, 211), + &[1], + ); + set_monitor( + &mut state, + &mut peer, + "right", + true, + (960, 0, 960, 1440), + (100, 50), + &[], + ); + set_monitor( + &mut state, + &mut peer, + "extra", + true, + (0, 0, 10, 10), + (100, 50), + &[], + ); + let names = |m: Vec| m.into_iter().map(|m| (m.0, m.1)).collect::>(); + assert_eq!( + names(get_monitors(&mut state, &mut peer, false)), + vec![ + ("extra".into(), true), + ("left".into(), false), + ("right".into(), false), + ("Virtual-2".into(), false), + ], + ); + let extra = state.atoms.intern("extra", true).0; + assert!(delete_monitor(&mut state, &mut peer, extra).is_empty()); + assert_eq!( + names(get_monitors(&mut state, &mut peer, false)), + vec![ + ("left".into(), false), + ("right".into(), false), + ("Virtual-2".into(), false), + ], + ); + } +} + +/// Measured `empty`: a 0x0 monitor with no outputs is listed by +/// `GetMonitors(get_active=0)` and counted by XINERAMA GetScreenCount, +/// but neither `get_active=1` nor QueryScreens reports it. +#[test] +fn an_empty_monitor_is_counted_but_not_active() { + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + set_monitor( + &mut state, + &mut peer, + "empty", + false, + (0, 0, 0, 0), + (100, 50), + &[], + ); + let all = get_monitors(&mut state, &mut peer, false); + assert_eq!(all.len(), 3); + assert_eq!(all[1], wm("empty", false, false, "0x0+0+0", (100, 50), &[])); + assert_eq!(get_monitors(&mut state, &mut peer, true).len(), 2); + let (count, heads) = xinerama_heads(&mut state, &mut peer); + assert_eq!((count, heads.len()), (3, 2)); + } +} + +/// The error table measured on Xorg 21.1 (`mon.py errors`): codes and +/// wire values, no state change on failure, and no validation of the +/// output ids. +#[test] +fn set_and_delete_monitor_errors_match_xorg() { + use yserver_protocol::x11::error; + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + let err = |r: &[u8]| { + assert_eq!(r.len(), 32, "one error: {r:02x?}"); + assert_eq!(r[0], 0); + (r[1], wire_u32(bo, &r[4..]), wire_u16(bo, &r[8..]), r[10]) + }; + let output_atom = state.atoms.intern("Virtual-1", false).0; + let name = state.atoms.intern("errmon", false).0; + let root = ROOT_WINDOW.0; + let set = |state: &mut ServerState, + peer: &mut UnixStream, + window, + name, + noutput, + outputs: &[u32]| { + let body = set_monitor_body( + bo, + window, + name, + false, + noutput, + (0, 0, 10, 10), + (100, 50), + outputs, + ); + randr_wire_request(state, peer, x11randr_minor::SET_MONITOR, body) + }; + let cases: Vec<(&str, Vec, (u8, u32))> = vec![ + ( + "name=output", + set(&mut state, &mut peer, root, output_atom, 0, &[]), + (error::BAD_VALUE, output_atom), + ), + ( + "name=None", + set(&mut state, &mut peer, root, 0, 0, &[]), + (error::BAD_ATOM, root), + ), + ( + "name=0x7fffff", + set(&mut state, &mut peer, root, 0x7f_ffff, 0, &[]), + (error::BAD_ATOM, root), + ), + ( + "bad window", + set(&mut state, &mut peer, 0x7ff_fffe, name, 0, &[]), + (error::BAD_WINDOW, 0x7ff_fffe), + ), + ( + "noutput=1, none sent", + set(&mut state, &mut peer, root, name, 1, &[]), + (error::BAD_LENGTH, 0), + ), + ( + "noutput=0, one sent", + set(&mut state, &mut peer, root, name, 0, &[1]), + (error::BAD_LENGTH, 0), + ), + ]; + for (label, r, (code, value)) in cases { + assert_eq!(err(&r), (code, value, 43, 128), "SetMonitor {label} {bo:?}"); + } + let short = randr_wire_request( + &mut state, + &mut peer, + x11randr_minor::SET_MONITOR, + WireBody(bo, Vec::new()).u32(root).u32(name), + ); + assert_eq!(err(&short).0, error::BAD_LENGTH); + assert!(state.randr_client_monitors.is_empty()); + + // Output ids are not validated (measured: `bogusout` succeeded). + let bogus = state.atoms.intern("bogusout", false).0; + assert!(set(&mut state, &mut peer, root, bogus, 1, &[0x7777]).is_empty()); + assert_eq!( + err(&set(&mut state, &mut peer, root, bogus, 0, &[])), + (error::BAD_VALUE, bogus, 43, 128), + "21.1 refuses a name already in use", + ); + + let never = state.atoms.intern("nosuchmon", false).0; + let del = |state: &mut ServerState, peer: &mut UnixStream, window: u32, name: u32| { + let body = WireBody(bo, Vec::new()).u32(window).u32(name); + randr_wire_request(state, peer, x11randr_minor::DELETE_MONITOR, body) + }; + let cases: Vec<(&str, Vec, (u8, u32))> = vec![ + ( + "never set", + del(&mut state, &mut peer, root, never), + (error::BAD_VALUE, never), + ), + ( + "None", + del(&mut state, &mut peer, root, 0), + (error::BAD_ATOM, 0), + ), + ( + "0x7fffff", + del(&mut state, &mut peer, root, 0x7f_ffff), + (error::BAD_ATOM, 0x7f_ffff), + ), + ( + "bad window", + del(&mut state, &mut peer, 0x7ff_fffe, bogus), + (error::BAD_WINDOW, 0x7ff_fffe), + ), + ( + "output name", + del(&mut state, &mut peer, root, output_atom), + (error::BAD_VALUE, output_atom), + ), + ]; + for (label, r, (code, value)) in cases { + assert_eq!( + err(&r), + (code, value, 44, 128), + "DeleteMonitor {label} {bo:?}" + ); + } + let long = randr_wire_request( + &mut state, + &mut peer, + x11randr_minor::DELETE_MONITOR, + WireBody(bo, Vec::new()).u32(root).u32(bogus).u32(0), + ); + assert_eq!(err(&long).0, error::BAD_LENGTH); + assert_eq!( + state.randr_client_monitors.len(), + 1, + "bogusout survived every failure" + ); + assert!(del(&mut state, &mut peer, root, bogus).is_empty()); + assert!(state.randr_client_monitors.is_empty()); + } +} + +/// Measured `mon.py events`: each successful Set/DeleteMonitor sends one +/// core ConfigureNotify on the root (`RRSendConfigNotify`) and no RANDR +/// event; a failed one sends nothing. +#[test] +fn set_and_delete_monitor_notify_with_a_root_configure_notify() { + for bo in BOTH_ORDERS { + let (mut state, mut peer) = monitor_fixture(bo); + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(ROOT_WINDOW, 0x0002_0000); + state.randr_select_masks.insert((1, ROOT_WINDOW), 0x1f); + let root = state + .resources + .window(ROOT_WINDOW) + .map(|w| (w.width, w.height)) + .unwrap(); + let configure_notify = |r: &[u8]| { + assert_eq!(r.len(), 32, "exactly one event: {r:02x?}"); + assert_eq!(r[0], 22, "ConfigureNotify"); + assert_eq!(wire_u32(bo, &r[4..]), ROOT_WINDOW.0, "event window"); + assert_eq!(wire_u32(bo, &r[8..]), ROOT_WINDOW.0, "window"); + assert_eq!(wire_u32(bo, &r[12..]), 0, "above-sibling None"); + assert_eq!((wire_u16(bo, &r[20..]), wire_u16(bo, &r[22..])), root); + }; + configure_notify(&set_monitor( + &mut state, + &mut peer, + "evmon", + false, + (0, 0, 100, 100), + (100, 50), + &[], + )); + let again = set_monitor( + &mut state, + &mut peer, + "evmon", + false, + (0, 0, 200, 100), + (100, 50), + &[], + ); + assert_eq!( + (again.len(), again[0]), + (32, 0), + "reused name: an error, no event" + ); + let evmon = state.atoms.intern("evmon", true).0; + configure_notify(&delete_monitor(&mut state, &mut peer, evmon)); + let again = delete_monitor(&mut state, &mut peer, evmon); + assert_eq!( + (again.len(), again[0]), + (32, 0), + "unknown name: an error, no event" + ); + } +} + +#[test] +fn vidmode_retains_a_light_disconnected_assigned_primary() { + let mut state = ServerState::new(); + let primary = state.randr.primary_output; + let expected = state + .randr + .outputs + .iter_mut() + .find(|output| output.output_id == primary) + .map(|output| { + output.connected = false; + (output.output_id, output.crtc_id) + }) + .unwrap(); + + let current = current_vidmode_output(&state).expect("the CRTC remains assigned"); + assert_eq!((current.output_id, current.crtc_id), expected); +} + +fn randr_unimplemented_reply_bearing(minor: u8) -> Vec { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 128, + data: minor, + length_units: 1, + }; + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[], + ) + .expect("process"); + read_all_available(&mut peer) +} + +fn randr_transform_body(crtc: u32, matrix: [i32; 9], filter_name: &[u8]) -> Vec { + let mut body = Vec::with_capacity(44 + filter_name.len().next_multiple_of(4)); + body.extend_from_slice(&crtc.to_le_bytes()); + for cell in matrix { + body.extend_from_slice(&cell.to_le_bytes()); + } + body.extend_from_slice(&(filter_name.len() as u16).to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(filter_name); + body.resize(body.len().next_multiple_of(4), 0); + body +} + +#[test] +fn randr_create_mode_unimplemented_returns_error_not_hang() { + // RRCreateMode (minor 16): reply-bearing, unimplemented → error. + let bytes = randr_unimplemented_reply_bearing(16); + assert!( + bytes.len() >= 32, + "expected error, not a hang: {bytes:02x?}" + ); + assert_eq!(bytes[1], x11::error::BAD_IMPLEMENTATION, "code"); + assert_eq!(&bytes[8..10], &16u16.to_le_bytes(), "minor"); + assert_eq!(bytes[10], 128, "major = RANDR"); +} + +#[test] +fn randr_crtc_setters_reject_short_bodies_with_bad_length() { + for minor in [ + yserver_protocol::x11::randr::RR_SET_CRTC_TRANSFORM, + yserver_protocol::x11::randr::RR_SET_PANNING, + ] { + let bytes = randr_unimplemented_reply_bearing(minor); + assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); + assert_eq!(bytes[1], x11::error::BAD_LENGTH, "minor {minor} code"); + assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); + assert_eq!(bytes[10], 128, "major = RANDR"); + } +} + +#[test] +fn randr_create_lease_unimplemented_returns_error_not_hang() { + // RRCreateLease (minor 45): reply-bearing, unimplemented → error. + let bytes = randr_unimplemented_reply_bearing(45); + assert!( + bytes.len() >= 32, + "expected error, not a hang: {bytes:02x?}" + ); + assert_eq!(bytes[1], x11::error::BAD_IMPLEMENTATION, "code"); + assert_eq!(&bytes[8..10], &45u16.to_le_bytes(), "minor"); + assert_eq!(bytes[10], 128, "major = RANDR"); +} + +#[test] +fn randr_unsupported_warning_latch_is_per_minor() { + let mut state = ServerState::new(); + assert!(mark_randr_unsupported_warned(&mut state, 18)); + assert!(!mark_randr_unsupported_warned(&mut state, 18)); + assert!(mark_randr_unsupported_warned(&mut state, 19)); +} + +const RR_IDENTITY: [i32; 9] = [0x0001_0000, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x0001_0000]; + +fn randr_transform_body_with_params( + crtc: u32, + matrix: [i32; 9], + filter_name: &[u8], + params: &[i32], +) -> Vec { + let mut body = randr_transform_body(crtc, matrix, filter_name); + for param in params { + body.extend_from_slice(¶m.to_le_bytes()); + } + body +} + +/// Send one SetCrtcTransform; the error code it produced, if any. +fn randr_set_crtc_transform( + state: &mut ServerState, + peer: &mut UnixStream, + body: &[u8], +) -> Option { + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_SET_CRTC_TRANSFORM, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }; + handle_randr_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + body, + ) + .expect("SetCrtcTransform"); + let out = read_all_available(peer); + if out.is_empty() { + return None; + } + assert_eq!(out.len(), 32, "one error"); + assert_eq!(out[0], 0, "error packet"); + assert_eq!(out[10], 128, "major = RANDR"); + Some(out[1]) +} + +#[test] +fn randr_set_crtc_transform_validates_in_xorg_order() { + // rrcrtc.c:1755-1785 and RRCrtcTransformSet, then D2. Each case + // also carries the fault of every later step, so it shows the + // earlier check wins. BadAccess (leased CRTC) is not reachable: + // yserver has no RANDR leases. + let mut state = ServerState::new(); + let crtc = state.randr.outputs[0].crtc_id; + let mut peer = install_client(&mut state, 1); + let bad_crtc = RANDR_BAD_CRTC; + let singular = [0i32; 9]; + let rotate = [0, -0x0001_0000, 0, 0x0001_0000, 0, 0, 0, 0, 0x0001_0000]; + let mut overrun = randr_transform_body(crtc, singular, b""); + overrun[40..42].copy_from_slice(&8u16.to_le_bytes()); + let mut overrun_bad_crtc = overrun.clone(); + overrun_bad_crtc[0..4].copy_from_slice(&0xdeadu32.to_le_bytes()); + let mut overrun_invertible = randr_transform_body(crtc, RR_IDENTITY, b""); + overrun_invertible[40..42].copy_from_slice(&8u16.to_le_bytes()); + let one = 0x0001_0000; + let cases: Vec<(&str, Vec, Option)> = vec![ + ("BadCrtc", overrun_bad_crtc, Some(bad_crtc)), + ("non-invertible", overrun, Some(x11::error::BAD_MATCH)), + ( + "negative nparams", + overrun_invertible, + Some(x11::error::BAD_LENGTH), + ), + ( + "unknown filter", + randr_transform_body(crtc, rotate, b"box"), + Some(x11::error::BAD_NAME), + ), + ( + "convolution parameter check", + randr_transform_body_with_params(crtc, RR_IDENTITY, b"convolution", &[one]), + Some(x11::error::BAD_MATCH), + ), + ( + "params without a filter", + randr_transform_body_with_params(crtc, rotate, b"", &[one]), + Some(x11::error::BAD_MATCH), + ), + ( + "D2: valid convolution", + randr_transform_body_with_params(crtc, RR_IDENTITY, b"convolution", &[one, one, one]), + Some(x11::error::BAD_MATCH), + ), + ( + "D2: rotation", + randr_transform_body(crtc, rotate, b"good"), + Some(x11::error::BAD_MATCH), + ), + ( + "D2: translation", + randr_transform_body(crtc, [one, 0, 5 * one, 0, one, 0, 0, 0, one], b""), + Some(x11::error::BAD_MATCH), + ), + ( + "pure scale", + randr_transform_body(crtc, rr_scale(104_857), b"good"), + None, + ), + ( + "bilinear keeps its parameters", + randr_transform_body_with_params(crtc, rr_scale(131_072), b"bilinear", &[one]), + None, + ), + ( + "identity with a filter", + randr_transform_body(crtc, RR_IDENTITY, b"FAST"), + None, + ), + ]; + for (name, body, expected) in cases { + assert_eq!( + randr_set_crtc_transform(&mut state, &mut peer, &body), + expected, + "{name}" + ); + } +} + +fn randr_get_crtc_transform(state: &mut ServerState, peer: &mut UnixStream, crtc: u32) -> Vec { + randr_get_crtc_transform_body(state, peer, &crtc.to_le_bytes()) +} + +fn randr_get_crtc_transform_body( + state: &mut ServerState, + peer: &mut UnixStream, + body: &[u8], +) -> Vec { + let mut backend = RecordingBackend::new(); + handle_randr_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_CRTC_TRANSFORM, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + ) + .expect("GetCrtcTransform"); + read_all_available(peer) +} + +#[test] +fn get_crtc_transform_of_the_wrong_length_is_bad_length_before_bad_crtc() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let crtc = state.randr.outputs[0].crtc_id; + // Short (header only) and oversized, for a real and a bogus CRTC. + for body in [ + Vec::new(), + [crtc.to_le_bytes(), 0u32.to_le_bytes()].concat(), + [0xdead_u32.to_le_bytes(), 0u32.to_le_bytes()].concat(), + ] { + let reply = randr_get_crtc_transform_body(&mut state, &mut peer, &body); + assert_eq!(reply.len(), 32, "{body:?}"); + assert_eq!( + (reply[0], reply[1]), + (0, x11::error::BAD_LENGTH), + "{body:?}" + ); + assert_eq!( + (reply[8], reply[10]), + (yserver_protocol::x11::randr::RR_GET_CRTC_TRANSFORM, 128) + ); + } + let reply = randr_get_crtc_transform(&mut state, &mut peer, 0xdead); + assert_eq!( + (reply[0], reply[1]), + (0, RANDR_BAD_CRTC), + "the right size looks up" + ); +} + +#[test] +fn randr_set_crtc_transform_stores_pending_for_get_crtc_transform() { + let mut state = ServerState::new(); + let crtc = state.randr.outputs[0].crtc_id; + let mut peer = install_client(&mut state, 1); + + let reply = randr_get_crtc_transform(&mut state, &mut peer, crtc); + assert_eq!(reply.len(), 96, "default: no filter bytes"); + assert_eq!(reply[44], 1, "hasTransforms"); + assert_eq!(&reply[88..96], &[0u8; 8]); + + // muffin's scale-down 125% CRTC 6 request (spec table): `good`. + let body = randr_transform_body_with_params(crtc, rr_scale(104_857), b"good", &[0x8000]); + assert_eq!(randr_set_crtc_transform(&mut state, &mut peer, &body), None); + let output = &state.randr.outputs[0]; + assert_eq!(output.pending_transform.matrix, rr_scale(104_857)); + assert_eq!( + output.pending_transform.filter, + Some(crate::randr::Filter::Bilinear) + ); + assert_eq!( + output.current_transform, + crate::randr::CrtcTransform::identity() + ); + + let reply = randr_get_crtc_transform(&mut state, &mut peer, crtc); + assert_eq!(reply.len(), 108); + assert_eq!( + u32::from_le_bytes(reply[8..12].try_into().unwrap()), + 104_857 + ); + assert_eq!( + u32::from_le_bytes(reply[48..52].try_into().unwrap()), + 0x0001_0000 + ); + assert_eq!(&reply[88..96], &[8, 0, 1, 0, 0, 0, 0, 0]); + assert_eq!(&reply[96..104], b"bilinear", "canonical name, not `good`"); + assert_eq!(&reply[104..108], &0x8000i32.to_le_bytes()); + + // A rejected request leaves the pending transform alone. + let rotate = [0, -0x0001_0000, 0, 0x0001_0000, 0, 0, 0, 0, 0x0001_0000]; + let body = randr_transform_body(crtc, rotate, b""); + assert_eq!( + randr_set_crtc_transform(&mut state, &mut peer, &body), + Some(x11::error::BAD_MATCH) + ); + assert_eq!( + state.randr.outputs[0].pending_transform.matrix, + rr_scale(104_857) + ); +} + +fn randr_crtc_config_body(crtc: u32, x: i16, y: i16, mode: u32, outputs: &[u32]) -> Vec { + let mut body = Vec::with_capacity(24 + outputs.len() * 4); + body.extend_from_slice(&crtc.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // timestamp + body.extend_from_slice(&0u32.to_le_bytes()); // config_timestamp + body.extend_from_slice(&x.to_le_bytes()); + body.extend_from_slice(&y.to_le_bytes()); + body.extend_from_slice(&mode.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); // RR_Rotate_0 + body.extend_from_slice(&[0u8; 2]); + for output in outputs { + body.extend_from_slice(&output.to_le_bytes()); + } + body +} + +fn randr_set_crtc_config( + state: &mut ServerState, + backend: &mut dyn Backend, + body: &[u8], +) -> io::Result { + handle_randr_request( + state, + backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_SET_CRTC_CONFIG, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + ) +} + +/// `(width, height)` of every CrtcChangeNotify in `wire`, and whether a +/// SetCrtcConfig Success reply is present. +fn randr_crtc_notifies_and_success(wire: &[u8]) -> (Vec<(u16, u16)>, bool) { + let u16_at = |c: &[u8], o: usize| u16::from_le_bytes(c[o..o + 2].try_into().unwrap()); + let notifies = wire + .chunks_exact(32) + .filter(|c| c[0] == 89 + 1 && c[1] == yserver_protocol::x11::randr::NOTIFY_CRTC_CHANGE) + .map(|c| (u16_at(c, 28), u16_at(c, 30))) + .collect(); + let success = wire.chunks_exact(32).any(|c| c[0] == 1 && c[1] == 0); + (notifies, success) +} + +#[test] +fn randr_set_crtc_config_applies_a_pending_transform_as_a_change() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].clone(); + let (crtc, mode) = (output.crtc_id, output.mode_id); + let mut peer = install_client(&mut state, 1); + state.randr_select_masks.insert( + (1, crate::resources::ROOT_WINDOW), + yserver_protocol::x11::randr::NOTIFY_MASK_CRTC_CHANGE, + ); + let mut backend = RecordingBackend::new(); + let same_config = randr_crtc_config_body(crtc, output.x, output.y, mode, &[output.output_id]); + + // Nothing pending: the backend's no-op stays a no-op. + randr_set_crtc_config(&mut state, &mut backend, &same_config).unwrap(); + let (notifies, success) = randr_crtc_notifies_and_success(&read_all_available(&mut peer)); + assert!(success); + assert!(notifies.is_empty()); + + // xrandr --scale 2 (spec, "What Xorg does"). + let body = randr_transform_body(crtc, rr_scale(131_072), b""); + assert_eq!(randr_set_crtc_transform(&mut state, &mut peer, &body), None); + randr_set_crtc_config(&mut state, &mut backend, &same_config).unwrap(); + let (notifies, success) = randr_crtc_notifies_and_success(&read_all_available(&mut peer)); + assert!(success); + assert_eq!( + notifies, + vec![(output.width, output.height)], + "one CrtcChangeNotify carrying the mode size" + ); + let applied = &state.randr.outputs[0]; + assert_eq!(applied.current_transform.matrix, rr_scale(131_072)); + assert_eq!(applied.footprint(), (output.width * 2, output.height * 2)); + + // Applied: the same config is a no-op again. + randr_set_crtc_config(&mut state, &mut backend, &same_config).unwrap(); + let (notifies, _) = randr_crtc_notifies_and_success(&read_all_available(&mut peer)); + assert!(notifies.is_empty()); + + // A disable leaves the current transform in place. + let body = randr_transform_body(crtc, rr_scale(32_768), b""); + assert_eq!(randr_set_crtc_transform(&mut state, &mut peer, &body), None); + randr_set_crtc_config( + &mut state, + &mut backend, + &randr_crtc_config_body(crtc, 0, 0, 0, &[]), + ) + .unwrap(); + let _ = read_all_available(&mut peer); + assert_eq!( + state.randr.outputs[0].current_transform.matrix, + rr_scale(131_072) + ); +} + +fn randr_get_crtc_info(state: &mut ServerState, peer: &mut UnixStream, crtc: u32) -> Vec { + let mut backend = RecordingBackend::new(); + let body = [crtc.to_le_bytes(), 0u32.to_le_bytes()].concat(); + handle_randr_request( + state, + &mut backend, + ClientId(1), + SequenceNumber(4), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_CRTC_INFO, + length_units: 3, + }, + &body, + ) + .expect("GetCrtcInfo"); + read_all_available(peer) +} + +#[test] +fn randr_set_crtc_config_rotation_is_a_change_reported_as_xorg() { + use crate::randr::{RR_REFLECT_X, RR_ROTATE_0, RR_ROTATE_90}; + let mut state = ServerState::new(); + let output = state.randr.outputs[0].clone(); + let (crtc, mode) = (output.crtc_id, output.mode_id); + let mut peer = install_client(&mut state, 1); + state.randr_select_masks.insert( + (1, crate::resources::ROOT_WINDOW), + yserver_protocol::x11::randr::NOTIFY_MASK_CRTC_CHANGE, + ); + let mut backend = RecordingBackend::new(); + let rotated = |rotation: u16| { + let mut body = randr_crtc_config_body(crtc, output.x, output.y, mode, &[output.output_id]); + body[20..22].copy_from_slice(&rotation.to_le_bytes()); + body + }; + let u16_at = |c: &[u8], o: usize| u16::from_le_bytes(c[o..o + 2].try_into().unwrap()); + + // `xrandr --rotate left`: same mode and origin, a new rotation. + randr_set_crtc_config(&mut state, &mut backend, &rotated(RR_ROTATE_90)).unwrap(); + let wire = read_all_available(&mut peer); + let (notifies, success) = randr_crtc_notifies_and_success(&wire); + assert!(success); + assert_eq!( + notifies, + vec![(output.width, output.height)], + "CrtcChangeNotify keeps the mode size (rrcrtc.c:249)" + ); + let notify = wire.chunks_exact(32).find(|c| c[0] == 90).unwrap(); + assert_eq!(u16_at(notify, 20), RR_ROTATE_90, "and carries the rotation"); + assert_eq!(state.randr.outputs[0].rotation, RR_ROTATE_90); + assert!(state.randr.outputs[0].current_transform.is_identity()); + + // GetCrtcInfo: the rotated footprint, rotation and modesetting's + // rotations 0x3f (measured, tools/vng-scenarios/xrandr-rotate.sh). + let reply = randr_get_crtc_info(&mut state, &mut peer, crtc); + assert_eq!(reply[0], 1); + assert_eq!( + (u16_at(&reply, 16), u16_at(&reply, 18)), + (output.height, output.width) + ); + assert_eq!(u16_at(&reply, 24), RR_ROTATE_90); + assert_eq!(u16_at(&reply, 26), 0x3f); + + // The same rotation again is a no-op. + randr_set_crtc_config(&mut state, &mut backend, &rotated(RR_ROTATE_90)).unwrap(); + let (notifies, _) = randr_crtc_notifies_and_success(&read_all_available(&mut peer)); + assert!(notifies.is_empty()); + + // A reflection bit is a change too. + randr_set_crtc_config( + &mut state, + &mut backend, + &rotated(RR_ROTATE_90 | RR_REFLECT_X), + ) + .unwrap(); + let (notifies, _) = randr_crtc_notifies_and_success(&read_all_available(&mut peer)); + assert_eq!(notifies.len(), 1); + assert_eq!(state.randr.outputs[0].rotation, RR_ROTATE_90 | RR_REFLECT_X); + + // A disable keeps the rotation, as xf86RandR12CrtcSet does. + randr_set_crtc_config( + &mut state, + &mut backend, + &randr_crtc_config_body(crtc, 0, 0, 0, &[]), + ) + .unwrap(); + let _ = read_all_available(&mut peer); + assert_eq!(state.randr.outputs[0].rotation, RR_ROTATE_90 | RR_REFLECT_X); + assert_ne!(state.randr.outputs[0].rotation, RR_ROTATE_0); +} + +/// A SetScreenConfig from client 1: `(status, new_timestamp, +/// new_config_timestamp, root)` of the reply, or `Err(error code)`. +fn randr_set_screen_config( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + body: &[u8], +) -> Result<(u8, u32, u32, u32), u8> { + handle_randr_request( + state, + backend, + ClientId(1), + SequenceNumber(5), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_SET_SCREEN_CONFIG, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + ) + .expect("SetScreenConfig"); + let wire = read_all_available(peer); + let reply = wire + .chunks_exact(32) + .find(|c| c[0] <= 1) + .expect("a reply or an error"); + let u32_at = |o: usize| u32::from_le_bytes(reply[o..o + 4].try_into().unwrap()); + if reply[0] == 0 { + return Err(reply[1]); + } + Ok((reply[1], u32_at(8), u32_at(12), u32_at(16))) +} + +/// drawable, timestamp, configTimestamp, sizeID, rotation[, rate, pad]. +fn screen_config_body( + config_timestamp: u32, + timestamp: u32, + size_id: u16, + rotation: u16, + rate: Option, +) -> Vec { + let mut body = crate::resources::ROOT_WINDOW.0.to_le_bytes().to_vec(); + body.extend_from_slice(×tamp.to_le_bytes()); + body.extend_from_slice(&config_timestamp.to_le_bytes()); + body.extend_from_slice(&size_id.to_le_bytes()); + body.extend_from_slice(&rotation.to_le_bytes()); + if let Some(rate) = rate { + body.extend_from_slice(&rate.to_le_bytes()); + body.extend_from_slice(&[0; 2]); + } + body +} + +#[test] +fn randr_set_screen_config_rotates_the_first_output_as_xorg() { + use crate::randr::{RR_ROTATE_90, RR_ROTATE_180}; + let mut state = ServerState::new(); + let output = state.randr.outputs[0].clone(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.randr_client_versions.insert(ClientId(1), (1, 5)); + let cts = state.randr.config_timestamp; + let (w, h) = (state.randr.screen_width, state.randr.screen_height); + let mm = (state.randr.width_mm, state.randr.height_mm); + + // `xrandr -o left` (tools/vng-scenarios/xrandr-orientation.sh on + // Xorg): screen and CRTC 800×1280 from 1280×800, mm unchanged, + // CRTC at 0,0, rotation Rotate_90. + let reply = randr_set_screen_config( + &mut state, + &mut backend, + &mut peer, + &screen_config_body(cts, 500, 0, RR_ROTATE_90, Some(0)), + ) + .unwrap(); + assert_eq!(reply, (0, 500, cts, crate::resources::ROOT_WINDOW.0)); + assert_eq!( + (state.randr.screen_width, state.randr.screen_height), + (h, w) + ); + assert_eq!((state.randr.width_mm, state.randr.height_mm), mm); + let applied = &state.randr.outputs[0]; + assert_eq!(applied.rotation, RR_ROTATE_90); + assert_eq!(applied.footprint(), (output.height, output.width)); + assert!(backend.calls().iter().any(|call| matches!( + call, + RecordedCall::ApplyCrtcConfig { + x: 0, + y: 0, + mode: Some(_), + .. + } + ))); + + // Xorg's statuses, in its order (same probe). + let body = + |cts, ts, size, rotation, rate| screen_config_body(cts, ts, size, rotation, Some(rate)); + let mut call = |state: &mut ServerState, b: Vec| { + randr_set_screen_config(state, &mut backend, &mut peer, &b) + }; + assert_eq!( + call(&mut state, body(cts + 1, 0, 0, 1, 0)).map(|r| r.0), + Ok(1) + ); + assert_eq!(call(&mut state, body(cts, 1, 0, 1, 0)).map(|r| r.0), Ok(2)); + assert_eq!( + call(&mut state, body(cts, 0, 1, 1, 0)), + Err(x11::error::BAD_VALUE), + "one mode size here" + ); + assert_eq!( + call(&mut state, body(cts, 0, 0, 3, 0)), + Err(x11::error::BAD_VALUE) + ); + assert_eq!( + call(&mut state, body(cts, 0, 0, 0x41, 0)), + Err(x11::error::BAD_MATCH) + ); + assert_eq!( + call(&mut state, body(cts, 0, 0, 1, 1)), + Err(x11::error::BAD_VALUE) + ); + let rate = state.randr.rr10_data().unwrap().rate; + assert_eq!( + call(&mut state, body(cts, 600, 0, RR_ROTATE_90, rate)).map(|r| (r.0, r.1)), + Ok((0, 600)), + "the current rate" + ); + // A no-op success still moves lastSetTime (rrscreen.c:1100). + assert_eq!( + call(&mut state, body(cts, 700, 0, RR_ROTATE_90, 0)).map(|r| (r.0, r.1)), + Ok((0, 700)) + ); + assert_eq!(state.randr.timestamp, 700); + // `-o inverted`: back to the mode's own size. + assert_eq!( + call(&mut state, body(cts, 800, 0, RR_ROTATE_180, 0)).map(|r| r.0), + Ok(0) + ); + assert_eq!( + (state.randr.screen_width, state.randr.screen_height), + (w, h) + ); + assert_eq!(state.randr.outputs[0].rotation, RR_ROTATE_180); +} + +#[test] +fn randr_set_screen_config_size_follows_the_clients_randr_version() { + // REQUEST_SIZE_MATCH by RRClientKnowsRates (rrscreen.c:926-933). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let cts = state.randr.config_timestamp; + // Explicit times: CurrentTime is the test clock, behind lastSetTime. + let v10 = screen_config_body(cts, 1000, 0, 1, None); + let v11 = screen_config_body(cts, 1000, 0, 1, Some(0)); + assert_eq!( + randr_set_screen_config(&mut state, &mut backend, &mut peer, &v11), + Err(x11::error::BAD_LENGTH), + "no QueryVersion: the 1.0 size" + ); + assert_eq!( + randr_set_screen_config(&mut state, &mut backend, &mut peer, &v10).map(|r| r.0), + Ok(0) + ); + state.randr_client_versions.insert(ClientId(1), (1, 1)); + assert_eq!( + randr_set_screen_config(&mut state, &mut backend, &mut peer, &v10), + Err(x11::error::BAD_LENGTH), + "measured: a 1.0-sized request from a 1.5 client" + ); + assert_eq!( + randr_set_screen_config(&mut state, &mut backend, &mut peer, &v11).map(|r| r.0), + Ok(0) + ); +} + +#[test] +fn randr_get_screen_info_lists_mode_sizes_and_rates_by_client_version() { + use crate::randr::RR_ROTATE_90; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let output = state.randr.outputs[0].clone(); + state.randr.outputs[0].rotation = RR_ROTATE_90; + let get = |state: &mut ServerState, backend: &mut RecordingBackend, peer: &mut UnixStream| { + handle_randr_request( + state, + backend, + ClientId(1), + SequenceNumber(6), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_SCREEN_INFO, + length_units: 2, + }, + &crate::resources::ROOT_WINDOW.0.to_le_bytes(), + ) + .expect("GetScreenInfo"); + read_all_available(peer) + }; + let u16_at = |b: &[u8], o: usize| u16::from_le_bytes([b[o], b[o + 1]]); + let rate = state.randr.rr10_data().unwrap().rate; + let v10 = get(&mut state, &mut backend, &mut peer); + assert_eq!(v10[1], 0x3f, "setOfRotations"); + assert_eq!(u16_at(&v10, 20), 1, "nSizes"); + assert_eq!(u16_at(&v10, 24), RR_ROTATE_90); + assert_eq!(u16_at(&v10, 26), rate); + assert_eq!(u16_at(&v10, 28), 2, "nrateEnts = nsize + nrefresh"); + assert_eq!(v10.len(), 32 + 8, "no rate lists for a 1.0 client"); + // The mode size, unswapped while rotated (measured). + assert_eq!( + (u16_at(&v10, 32), u16_at(&v10, 34)), + (output.width, output.height) + ); + + state.randr_client_versions.insert(ClientId(1), (1, 5)); + let v11 = get(&mut state, &mut backend, &mut peer); + assert_eq!(v11.len(), 32 + 12); + assert_eq!((u16_at(&v11, 40), u16_at(&v11, 42)), (1, rate)); +} + +#[test] +fn an_asynchronous_crtc_config_applies_the_transform_pending_at_request_time() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].clone(); + let (crtc, mode) = (output.crtc_id, output.mode_id); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = randr_transform_body(crtc, rr_scale(131_072), b""); + assert_eq!(randr_set_crtc_transform(&mut state, &mut peer, &body), None); + backend.pending_crtc_config = Some(CrtcConfigToken(7)); + let config = randr_crtc_config_body(crtc, output.x, output.y, mode, &[output.output_id]); + let RequestOutcome::PendingCrtcConfig(pending) = + randr_set_crtc_config(&mut state, &mut backend, &config).unwrap() + else { + panic!("the enable must park"); + }; + // A new SetCrtcTransform while the enable is in flight stays pending. + let body = randr_transform_body(crtc, rr_scale(32_768), b""); + assert_eq!(randr_set_crtc_transform(&mut state, &mut peer, &body), None); + complete_crtc_config( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + pending.completion, + Ok(true), + ) + .unwrap(); + let output = &state.randr.outputs[0]; + assert_eq!(output.current_transform.matrix, rr_scale(131_072)); + assert_eq!(output.pending_transform.matrix, rr_scale(32_768)); +} + +#[test] +fn randr_set_crtc_config_does_not_bound_a_crtc_by_the_screen() { + // rrcrtc.c:1436 skips the bounds check for transform-capable CRTCs. + let mut state = ServerState::new(); + let output = state.randr.outputs[0].clone(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let x = i16::try_from(state.randr.screen_width).unwrap(); + let body = randr_crtc_config_body(output.crtc_id, x, 0, output.mode_id, &[output.output_id]); + randr_set_crtc_config(&mut state, &mut backend, &body).unwrap(); + let (_, success) = randr_crtc_notifies_and_success(&read_all_available(&mut peer)); + assert!(success, "past the screen edge is not BadValue"); +} + +/// The two 2560×1440 outputs of the muffin capture (spec, "What muffin +/// sends"): CRTC 4 at 0,0 and CRTC 6 at 2560,0, both mode 0x13. +const MUFFIN_MODE: u32 = 0x13; +const MUFFIN_MM: (u32, u32) = (597, 336); + +fn muffin_output(output_id: u32, crtc_id: u32, x: i16) -> crate::randr::RandrOutput { + crate::randr::RandrOutput { + name: format!("DP-{output_id}"), + output_id, + crtc_id, + mode_id: MUFFIN_MODE, + connected: true, + x, + y: 0, + width: 2560, + height: 1440, + vrefresh: 60, + timing: None, + mm_width: MUFFIN_MM.0, + mm_height: MUFFIN_MM.1, + mode_ids: vec![MUFFIN_MODE], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + } +} + +struct MuffinReplay { + state: ServerState, + peer: UnixStream, + backend: RecordingBackend, +} + +type Rect = (i16, i16, u16, u16); + +impl MuffinReplay { + const OUTPUT_4: u32 = 3; + const OUTPUT_6: u32 = 5; + + fn new() -> Self { + let mut state = ServerState::new(); + state.randr = crate::randr::RandrState::from_outputs_with_modes( + 1, + vec![ + muffin_output(Self::OUTPUT_4, 4, 0), + muffin_output(Self::OUTPUT_6, 6, 2560), + ], + vec![crate::randr::RandrMode { + mode_id: MUFFIN_MODE, + width: 2560, + height: 1440, + vrefresh: 60, + timing: None, + }], + ); + let root = state.resources.window_mut(ROOT_WINDOW).unwrap(); + (root.width, root.height) = (5120, 1440); + let peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.apply_crtc_configs = true; + Self { + state, + peer, + backend, + } + } + + fn send(&mut self, minor: u8, body: &[u8]) -> Vec { + handle_randr_request( + &mut self.state, + &mut self.backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + ) + .expect("RANDR request"); + read_all_available(&mut self.peer) + } + + fn set_screen_size(&mut self, w: u16, h: u16, mm_w: u32, mm_h: u32) { + let mut body = ROOT_WINDOW.0.to_le_bytes().to_vec(); + body.extend_from_slice(&w.to_le_bytes()); + body.extend_from_slice(&h.to_le_bytes()); + body.extend_from_slice(&mm_w.to_le_bytes()); + body.extend_from_slice(&mm_h.to_le_bytes()); + let out = self.send(yserver_protocol::x11::randr::RR_SET_SCREEN_SIZE, &body); + assert!( + out.chunks_exact(32).all(|c| c[0] != 0), + "SetScreenSize {w}x{h} failed: {out:02x?}" + ); + } + + /// SetCrtcTransform then SetCrtcConfig, as muffin orders them. + fn configure(&mut self, crtc: u32, output: u32, x: i16, scale: i32, filter: &[u8]) { + let out = self.send( + yserver_protocol::x11::randr::RR_SET_CRTC_TRANSFORM, + &randr_transform_body(crtc, rr_scale(scale), filter), + ); + assert!(out.is_empty(), "SetCrtcTransform crtc {crtc}: {out:02x?}"); + self.set_crtc_config(crtc, x, MUFFIN_MODE, &[output]); + } + + fn set_crtc_config(&mut self, crtc: u32, x: i16, mode: u32, outputs: &[u32]) { + let out = self.send( + yserver_protocol::x11::randr::RR_SET_CRTC_CONFIG, + &randr_crtc_config_body(crtc, x, 0, mode, outputs), + ); + let reply = out.chunks_exact(32).find(|c| c[0] != 0 && c[0] < 2); + assert_eq!( + reply.map(|c| (c[0], c[1])), + Some((1, 0)), + "SetCrtcConfig crtc {crtc} succeeds: {out:02x?}" + ); + } + + fn screen(&self) -> (u16, u16) { + let root = self.state.resources.window(ROOT_WINDOW).unwrap(); + assert_eq!( + (root.width, root.height), + ( + self.state.randr.screen_width, + self.state.randr.screen_height + ), + "root follows the RANDR screen" + ); + (root.width, root.height) + } + + /// GetCrtcInfo's `(x, y, width, height)`. + fn crtc_info(&mut self, crtc: u32) -> Rect { + let mut body = crtc.to_le_bytes().to_vec(); + body.extend_from_slice(&0u32.to_le_bytes()); + let r = self.send(yserver_protocol::x11::randr::RR_GET_CRTC_INFO, &body); + assert_eq!(r[0], 1, "GetCrtcInfo reply"); + let i16_at = |o: usize| i16::from_le_bytes(r[o..o + 2].try_into().unwrap()); + let u16_at = |o: usize| u16::from_le_bytes(r[o..o + 2].try_into().unwrap()); + (i16_at(12), i16_at(14), u16_at(16), u16_at(18)) + } + + /// GetMonitors' `(x, y, width, height)` per monitor; asserts the + /// EDID mm are untouched by any transform. + fn monitors(&mut self) -> Vec { + let mut body = ROOT_WINDOW.0.to_le_bytes().to_vec(); + body.extend_from_slice(&[1, 0, 0, 0]); + let r = self.send(yserver_protocol::x11::randr::RR_GET_MONITORS, &body); + assert_eq!(r[0], 1, "GetMonitors reply"); + let count = u32::from_le_bytes(r[12..16].try_into().unwrap()); + let mut offset = 32; + let mut rects = Vec::new(); + for _ in 0..count { + let m = &r[offset..]; + let n_out = usize::from(u16::from_le_bytes(m[6..8].try_into().unwrap())); + let i16_at = |o: usize| i16::from_le_bytes(m[o..o + 2].try_into().unwrap()); + let u16_at = |o: usize| u16::from_le_bytes(m[o..o + 2].try_into().unwrap()); + let u32_at = |o: usize| u32::from_le_bytes(m[o..o + 4].try_into().unwrap()); + assert_eq!((u32_at(16), u32_at(20)), MUFFIN_MM); + rects.push((i16_at(8), i16_at(10), u16_at(12), u16_at(14))); + offset += 24 + n_out * 4; + } + rects + } + + fn assert_layout(&mut self, screen: (u16, u16), crtc4: Rect, crtc6: Rect, monitors: &[Rect]) { + assert_eq!(self.screen(), screen, "screen"); + assert_eq!(self.crtc_info(4), crtc4, "GetCrtcInfo 4"); + assert_eq!(self.crtc_info(6), crtc6, "GetCrtcInfo 6"); + assert_eq!(self.monitors(), monitors, "GetMonitors"); + } +} + +const MUFFIN_IDENTITY: i32 = 0x0001_0000; +const MUFFIN_1_599991: i32 = 104_857; +const MUFFIN_1_337494: i32 = 87_654; +const MUFFIN_0_5: i32 = 32_768; +const MUFFIN_0_799988: i32 = 52_428; + +#[test] +fn randr_replays_muffin_scale_down_100_125_150() { + let mut r = MuffinReplay::new(); + let left = (0, 0, 2560, 1440); + r.assert_layout( + (5120, 1440), + left, + (2560, 0, 2560, 1440), + &[left, (2560, 0, 2560, 1440)], + ); + + // Each row of the spec table: SetScreenSize, then CRTC 4, then CRTC 6. + for (screen, mm, scale6, crtc6) in [ + ((7680, 2880), (1355, 508), MUFFIN_2_0, (2560, 0, 5120, 2880)), + ( + (6656, 2304), + (1084, 375), + MUFFIN_1_599991, + (2560, 0, 4096, 2304), + ), + ( + (5984, 1926), + (906, 292), + MUFFIN_1_337494, + (2560, 0, 3424, 1926), + ), + ] { + let before6 = r.crtc_info(6); + r.set_screen_size(screen.0, screen.1, mm.0, mm.1); + // A screen may crop the previous scaled footprint for a moment. + r.assert_layout(screen, left, before6, &[left, before6]); + r.configure(4, MuffinReplay::OUTPUT_4, 0, MUFFIN_IDENTITY, b"fast"); + r.assert_layout(screen, left, before6, &[left, before6]); + r.configure(6, MuffinReplay::OUTPUT_6, 2560, scale6, b"good"); + r.assert_layout(screen, left, crtc6, &[left, crtc6]); + } +} + +#[test] +fn randr_replays_muffin_scale_up_125_through_both_crtcs_off() { + let mut r = MuffinReplay::new(); + r.set_crtc_config(4, 0, 0, &[]); + r.assert_layout( + (5120, 1440), + (0, 0, 0, 0), + (2560, 0, 2560, 1440), + &[(2560, 0, 2560, 1440)], + ); + r.set_crtc_config(6, 0, 0, &[]); + r.assert_layout((5120, 1440), (0, 0, 0, 0), (0, 0, 0, 0), &[]); + r.set_screen_size(4608, 1152, 750, 188); + r.assert_layout((4608, 1152), (0, 0, 0, 0), (0, 0, 0, 0), &[]); + // The mode is taller than the screen: this is what went dark. + r.configure(4, MuffinReplay::OUTPUT_4, 0, MUFFIN_0_5, b"nearest"); + let left = (0, 0, 1280, 720); + r.assert_layout((4608, 1152), left, (0, 0, 0, 0), &[left]); + // CRTC 6 stays at 2560 although CRTC 4 is only 1280 wide. + r.configure(6, MuffinReplay::OUTPUT_6, 2560, MUFFIN_0_799988, b"good"); + let right = (2560, 0, 2048, 1152); + r.assert_layout((4608, 1152), left, right, &[left, right]); + assert_eq!( + crate::core_loop::run::enabled_output_bbox(&r.state), + Some((4608, 1152)) + ); +} + +#[test] +fn randr_client_screen_size_survives_a_larger_transformed_bbox() { + let mut r = MuffinReplay::new(); + r.configure(6, MuffinReplay::OUTPUT_6, 2560, MUFFIN_2_0, b"good"); + assert_eq!( + crate::core_loop::run::enabled_output_bbox(&r.state), + Some((7680, 2880)) + ); + let right = (2560, 0, 5120, 2880); + r.assert_layout( + (5120, 1440), + (0, 0, 2560, 1440), + right, + &[(0, 0, 2560, 1440), right], + ); +} + +/// `RRSetCrtcConfig` real handler — validates mode/output/rotation and +/// calls `apply_crtc_config`. Replaces the old no-op-accept test. +/// +/// Cases: +/// The fixture has two outputs with the same connector name. Requests +/// target the second by `(crtc=5, output=4)` so routing cannot fall back +/// to a globally-ambiguous name. +/// +/// 1. valid enable (mode=3, crtc=5, outputs=[4], rotation=RR_Rotate_0) +/// → reply status=0 (Success). +/// 2. disable (mode=0, crtc=2, no outputs) +/// → reply status=0. +/// 3. bad mode (555 not in output's mode_ids) +/// → X11 error BadMatch (type byte = 0). +/// 4. bad rotation (0x41: a bit outside the CRTC's `rotations` 0x3f) +/// → X11 error BadMatch (type byte = 0). +#[test] +fn randr_set_crtc_config_validates_mode_id() { + use crate::randr::{RandrMode, RandrOutput, RandrState}; + + const CLIENT_ID: u32 = 1; + let mode_table = vec![RandrMode { + mode_id: 3, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + }]; + let outputs = vec![ + RandrOutput { + name: "test-0".to_string(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }, + // Equal connector names are legal across different DRM devices. + // Address this second row by CRTC/XID to prove the core never + // re-resolves the request through the ambiguous display name. + RandrOutput { + name: "test-0".to_string(), + output_id: 4, + crtc_id: 5, + mode_id: 3, + connected: true, + x: 1920, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }, + ]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs_with_modes(1, outputs, mode_table); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + + // Body layout: crtc(4) ts(4) cts(4) x(2) y(2) mode(4) rotation(2) + // pad(2) outputs(4*N). + fn build_body(mode: u32, rotation: u16, output_ids: &[u32]) -> Vec { + let mut b = Vec::with_capacity(24 + output_ids.len() * 4); + b.extend_from_slice(&5u32.to_le_bytes()); // target the second same-name CRTC + b.extend_from_slice(&0u32.to_le_bytes()); // timestamp + b.extend_from_slice(&0u32.to_le_bytes()); // config_timestamp + b.extend_from_slice(&0i16.to_le_bytes()); // x + b.extend_from_slice(&0i16.to_le_bytes()); // y + b.extend_from_slice(&mode.to_le_bytes()); // mode + b.extend_from_slice(&rotation.to_le_bytes()); // rotation + b.extend_from_slice(&[0u8; 2]); // pad + for &oid in output_ids { + b.extend_from_slice(&oid.to_le_bytes()); + } + b + } + let header = yserver_protocol::x11::RequestHeader { + opcode: 140, + data: 21, // RR_SET_CRTC_CONFIG + length_units: 7, + }; + + // (1) Valid enable: mode=3, rotation=RR_Rotate_0(1), outputs=[4] → Success reply. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &build_body(3, 1, &[4]), + ) + .expect("valid enable"); + + // (2) Disable: mode=0, no outputs → Success reply. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(2), + header, + &build_body(0, 1, &[]), + ) + .expect("disable"); + + // (3) Bad mode: mode=555 not in output's mode_ids → BadMatch error. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(3), + header, + &build_body(555, 1, &[4]), + ) + .expect("bad mode → error"); + + // (4) Bad rotation: RR_Rotate_0 plus bit 6, which no CRTC + // advertises. validate_set_crtc_config succeeds (mode 3 known), then + // `(~crtc->rotations) & rotation` fires BadMatch (rrcrtc.c:1403). + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(4), + header, + &build_body(3, 0x41, &[4]), + ) + .expect("bad rotation → error"); + + use std::io::Read; + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 1024]; + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + // All 4 responses are 32 bytes. type byte at offset 0: + // 1 = reply, 0 = error. + assert_eq!(wire.len(), 128, "4 × 32-byte packets"); + let type_bytes: Vec = wire.chunks_exact(32).map(|c| c[0]).collect(); + assert_eq!(type_bytes[0], 1, "valid enable → reply"); + let status_enable = wire[1]; // data byte of first reply + assert_eq!(status_enable, 0, "valid enable → status=0 (Success)"); + assert_eq!(type_bytes[1], 1, "disable → reply"); + let status_disable = wire[32 + 1]; + assert_eq!(status_disable, 0, "disable → status=0"); + assert_eq!(type_bytes[2], 0, "bad mode → X11 error (type=0)"); + assert_eq!(type_bytes[3], 0, "bad rotation → X11 error (type=0)"); + + let crtc_calls: Vec<_> = backend + .calls() + .into_iter() + .filter(|call| matches!(call, RecordedCall::ApplyCrtcConfig { .. })) + .collect(); + assert_eq!( + crtc_calls, + vec![ + RecordedCall::ApplyCrtcConfig { + output_id: 4, + connector: "test-0".to_string(), + mode: Some(ModeSpec { + width: 1920, + height: 1080, + vrefresh: 60, + }), + x: 0, + y: 0, + }, + RecordedCall::ApplyCrtcConfig { + output_id: 4, + connector: "test-0".to_string(), + mode: None, + x: 0, + y: 0, + }, + ], + "the second same-name output XID must be carried into backend routing", + ); + + // An asynchronous backend returns a continuation token without + // sending a premature reply. The core loop owns parking and later + // invokes `complete_crtc_config` with the finished result. + let token = CrtcConfigToken(0x1234); + backend.pending_crtc_config = Some(token); + let outcome = handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(5), + header, + &build_body(3, 1, &[4]), + ) + .expect("asynchronous enable begins"); + let RequestOutcome::PendingCrtcConfig(pending) = outcome else { + panic!("asynchronous backend must return a pending continuation"); + }; + assert_eq!(pending.token, token); + assert_eq!(pending.completion.output_id, 4); + assert!( + read_all_available(&mut peer).is_empty(), + "pending request must not receive a reply before completion" + ); +} + +#[test] +fn randr_get_crtc_gamma_size_uses_backend_and_invalid_crtc_is_bad_crtc() { + use crate::randr::{RandrOutput, RandrState}; + use yserver_protocol::x11::randr as x11randr; + + const CLIENT_ID: u32 = 1; + let outputs = vec![RandrOutput { + name: "DP-1".to_string(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(1, outputs); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + + let header = RequestHeader { + opcode: 128, + data: x11randr::RR_GET_CRTC_GAMMA_SIZE, + length_units: 2, + }; + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &2u32.to_le_bytes(), + ) + .expect("valid get gamma size"); + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(2), + header, + &999u32.to_le_bytes(), + ) + .expect("invalid get gamma size"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 64, "reply + error"); + assert_eq!(bytes[0], 1, "valid query replies"); + assert_eq!(&bytes[8..10], &256u16.to_le_bytes(), "gamma size"); + assert_eq!(bytes[32], 0, "invalid crtc emits error packet"); + assert_eq!(bytes[33], RANDR_BAD_CRTC); +} + +#[test] +fn randr_get_crtc_gamma_reports_seeded_identity_ramp() { + use crate::randr::{RandrOutput, RandrState}; + use yserver_protocol::x11::randr as x11randr; + + const CLIENT_ID: u32 = 1; + let outputs = vec![RandrOutput { + name: "DP-1".to_string(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(1, outputs); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: x11randr::RR_GET_CRTC_GAMMA, + length_units: 2, + }, + &2u32.to_le_bytes(), + ) + .expect("get gamma"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32 + 256 * 3 * 2); + assert_eq!(bytes[0], 1); + assert_eq!(&bytes[8..10], &256u16.to_le_bytes()); + assert_eq!(&bytes[32..34], &0u16.to_le_bytes(), "red[0]"); + assert_eq!( + &bytes[32 + 510..32 + 512], + &65535u16.to_le_bytes(), + "red[last]" + ); + assert_eq!(&bytes[32 + 512..32 + 514], &0u16.to_le_bytes(), "green[0]"); + assert_eq!( + &bytes[32 + 1022..32 + 1024], + &65535u16.to_le_bytes(), + "green[last]" + ); + assert_eq!(&bytes[32 + 1024..32 + 1026], &0u16.to_le_bytes(), "blue[0]"); + assert_eq!( + &bytes[32 + 1534..32 + 1536], + &65535u16.to_le_bytes(), + "blue[last]" + ); +} + +#[test] +fn randr_set_crtc_gamma_validates_and_roundtrips() { + use crate::randr::{RandrOutput, RandrState}; + use yserver_protocol::x11::randr as x11randr; + + fn set_gamma_body(crtc: u32, red: &[u16], green: &[u16], blue: &[u16]) -> Vec { + let size = u16::try_from(red.len()).unwrap(); + let mut body = Vec::with_capacity(8 + red.len() * 6); + body.extend_from_slice(&crtc.to_le_bytes()); + body.extend_from_slice(&size.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + for channel in [red, green, blue] { + for &entry in channel { + body.extend_from_slice(&entry.to_le_bytes()); + } + } + body + } + + const CLIENT_ID: u32 = 1; + let outputs = vec![RandrOutput { + name: "DP-1".to_string(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(1, outputs); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + + let red = vec![1u16; 256]; + let green = vec![2u16; 256]; + let blue = vec![3u16; 256]; + let body = set_gamma_body(2, &red, &green, &blue); + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_CRTC_GAMMA, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + ) + .expect("set gamma"); + assert_eq!(backend.get_crtc_gamma(2), (red, green, blue)); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: x11randr::RR_GET_CRTC_GAMMA, + length_units: 2, + }, + &2u32.to_le_bytes(), + ) + .expect("get gamma"); + + let short_body = { + let mut b = Vec::new(); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(&256u16.to_le_bytes()); + b.extend_from_slice(&[0u8; 2]); + b + }; + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(3), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_CRTC_GAMMA, + length_units: 3, + }, + &short_body, + ) + .expect("short set gamma"); + + let red_small = vec![9u16; 128]; + let green_small = vec![8u16; 128]; + let blue_small = vec![7u16; 128]; + let mismatch_body = set_gamma_body(2, &red_small, &green_small, &blue_small); + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(4), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_CRTC_GAMMA, + length_units: u32::try_from(1 + mismatch_body.len().div_ceil(4)).unwrap(), + }, + &mismatch_body, + ) + .expect("size mismatch set gamma"); + + let invalid_body = set_gamma_body(999, &[0u16; 256], &[0u16; 256], &[0u16; 256]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(5), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_CRTC_GAMMA, + length_units: u32::try_from(1 + invalid_body.len().div_ceil(4)).unwrap(), + }, + &invalid_body, + ) + .expect("invalid crtc set gamma"); + + let bytes = read_all_available(&mut peer); + assert_eq!( + bytes.len(), + (32 + 256 * 3 * 2) + (32 * 3), + "one gamma reply + three errors" + ); + let gamma_reply_len = 32 + 256 * 3 * 2; + assert_eq!(bytes[0], 1, "get reply"); + assert_eq!(bytes[gamma_reply_len], 0, "short body => error"); + assert_eq!(bytes[gamma_reply_len + 1], x11::error::BAD_LENGTH); + assert_eq!(bytes[gamma_reply_len + 32], 0, "size mismatch => error"); + assert_eq!(bytes[gamma_reply_len + 33], x11::error::BAD_MATCH); + assert_eq!(bytes[gamma_reply_len + 64], 0, "invalid crtc => error"); + assert_eq!(bytes[gamma_reply_len + 65], RANDR_BAD_CRTC); +} + +/// `RRSetScreenSize` with the cursor stranded off the shrunken screen +/// must trigger a `warp_pointer_root` call that clamps it inside. +/// Also verifies the basic success path and per-dimension errorValue. +#[test] +fn screen_shrink_warps_stranded_cursor_inside() { + use crate::randr::{RandrOutput, RandrState}; + + const CLIENT_ID: u32 = 1; + // One enabled 1920×1080 output at (0,0). + let outputs = vec![RandrOutput { + name: "eDP-1".into(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(0, outputs); + // Park the cursor at (2000, 1500) — valid under the old larger screen. + state.pointer_root = (2000, 1500); + let mut backend = RecordingBackend::new(); + let _peer = install_client(&mut state, CLIENT_ID); + + // Build a SetScreenSize body: window(4) width(2) height(2) + // mm_width(4) mm_height(4). + fn build_body(width: u16, height: u16, mm_w: u32, mm_h: u32) -> Vec { + let mut b = Vec::with_capacity(16); + b.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + b.extend_from_slice(&width.to_le_bytes()); + b.extend_from_slice(&height.to_le_bytes()); + b.extend_from_slice(&mm_w.to_le_bytes()); + b.extend_from_slice(&mm_h.to_le_bytes()); + b + } + + let header = yserver_protocol::x11::RequestHeader { + opcode: 128, // RANDR major opcode + data: yserver_protocol::x11::randr::RR_SET_SCREEN_SIZE, + length_units: 5, + }; + + // Shrink to 1920×1080 (same as output — no crop) with real mm values. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &build_body(1920, 1080, 527, 296), + ) + .expect("valid shrink"); + + // RRSetScreenSize is void — no reply on the wire. + // The cursor at (2000, 1500) is outside 1920×1080, so a warp must fire. + assert_eq!( + backend.warped_to, + Some((1919, 1079)), + "cursor must be warped to (w-1, h-1) when stranded off-screen" + ); + // RandrState must reflect the new logical size. + assert_eq!(state.randr.screen_width, 1920); + assert_eq!(state.randr.screen_height, 1080); + assert_eq!(state.randr.width_mm, 527, "mm verbatim from client"); + assert_eq!(state.randr.height_mm, 296, "mm verbatim from client"); +} + +/// A compositor that renders through the Composite Overlay Window +/// typically backs it with DRI3/Present buffers. `RRSetScreenSize` +/// resizes the root and COW outside the normal `ConfigureWindow` path, +/// so it must still emit both core ConfigureNotify and +/// Present::ConfigureNotify for the materialized COW. Otherwise the +/// compositor can keep presenting its old smaller swap buffers after a +/// shrink-grow cycle, leaving the desktop in the upper-left corner while +/// input/RandR already use the full screen. +#[test] +fn screen_resize_notifies_materialized_cow_present_subscriber() { + use crate::{ + backend::WindowHandle, + randr::{RandrOutput, RandrState}, + resources::COMPOSITE_OVERLAY_WINDOW, + server::PresentEventSelection, + }; + use yserver_protocol::x11::present as x11present; + + const CLIENT_ID: u32 = 1; + const PRESENT_EID: u32 = 0x0010_0042; + + let outputs = vec![RandrOutput { + name: "DP-4".into(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1680, + height: 1050, + vrefresh: 100, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(0, outputs); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state + .resources + .materialize_cow_resource(WindowHandle::from_raw_for_test(COMPOSITE_OVERLAY_WINDOW.0)); + state + .clients + .get_mut(&CLIENT_ID) + .unwrap() + .event_masks + .insert(COMPOSITE_OVERLAY_WINDOW, 0x0002_0000); + state.present_event_selections.insert( + PRESENT_EID, + PresentEventSelection { + owner: ClientId(CLIENT_ID), + window: COMPOSITE_OVERLAY_WINDOW, + event_mask: x11present::EVENT_MASK_CONFIGURE_NOTIFY, + }, + ); + assert_eq!( + crate::core_loop::fanout::subscribers_by_id(&state, COMPOSITE_OVERLAY_WINDOW, 0x0002_0000,), + vec![ClientId(CLIENT_ID)], + "COW StructureNotify subscription visible before resize", + ); + assert_eq!( + state + .present_event_selections + .get(&PRESENT_EID) + .unwrap() + .window, + COMPOSITE_OVERLAY_WINDOW, + "Present Configure subscription visible before resize", + ); + + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&3440u16.to_le_bytes()); + body.extend_from_slice(&1440u16.to_le_bytes()); + body.extend_from_slice(&910u32.to_le_bytes()); + body.extend_from_slice(&381u32.to_le_bytes()); + + let header = yserver_protocol::x11::RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_SET_SCREEN_SIZE, + length_units: 5, + }; + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("RRSetScreenSize grow"); + + assert_eq!(state.randr.screen_width, 3440, "RandR width updated"); + assert_eq!(state.randr.screen_height, 1440, "RandR height updated"); + let cow = state + .resources + .window(COMPOSITE_OVERLAY_WINDOW) + .expect("COW still materialized"); + assert_eq!(cow.width, 3440, "COW width updated"); + assert_eq!(cow.height, 1440, "COW height updated"); + assert_eq!( + crate::core_loop::fanout::subscribers_by_id(&state, COMPOSITE_OVERLAY_WINDOW, 0x0002_0000,), + vec![ClientId(CLIENT_ID)], + "COW StructureNotify subscription still visible after resize", + ); + assert_eq!( + state + .present_event_selections + .get(&PRESENT_EID) + .unwrap() + .window, + COMPOSITE_OVERLAY_WINDOW, + "Present Configure subscription still visible after resize", + ); + assert_eq!( + state.clients.get(&CLIENT_ID).unwrap().outbound.len(), + 0, + "small COW resize notifications should not be stuck in outbound", + ); + + let bytes = read_all_available(&mut peer); + assert_eq!( + bytes.len(), + 32 + 40, + "COW subscriber should receive core ConfigureNotify plus \ + Present::ConfigureNotify only; got {bytes:?}", + ); + + let core = &bytes[..32]; + assert_eq!(core[0] & 0x7f, 22, "first event must be ConfigureNotify"); + assert_eq!( + u32::from_le_bytes(core[4..8].try_into().unwrap()), + COMPOSITE_OVERLAY_WINDOW.0, + "ConfigureNotify event window must be COW", + ); + assert_eq!( + u32::from_le_bytes(core[8..12].try_into().unwrap()), + COMPOSITE_OVERLAY_WINDOW.0, + "ConfigureNotify target window must be COW", + ); + assert_eq!(u16::from_le_bytes(core[20..22].try_into().unwrap()), 3440); + assert_eq!(u16::from_le_bytes(core[22..24].try_into().unwrap()), 1440); + + let present = &bytes[32..]; + assert_eq!(present[0], 35, "second event must be GenericEvent"); + assert_eq!(present[1], 145, "GenericEvent extension must be PRESENT"); + assert_eq!( + u16::from_le_bytes(present[8..10].try_into().unwrap()), + u16::from(x11present::EVENT_CONFIGURE_NOTIFY), + ); + assert_eq!( + u32::from_le_bytes(present[12..16].try_into().unwrap()), + PRESENT_EID, + ); + assert_eq!( + u32::from_le_bytes(present[16..20].try_into().unwrap()), + COMPOSITE_OVERLAY_WINDOW.0, + ); + assert_eq!( + u16::from_le_bytes(present[24..26].try_into().unwrap()), + 3440, + "Present ConfigureNotify width must track the grown COW", + ); + assert_eq!( + u16::from_le_bytes(present[26..28].try_into().unwrap()), + 1440, + "Present ConfigureNotify height must track the grown COW", + ); + assert_eq!( + u16::from_le_bytes(present[32..34].try_into().unwrap()), + 3440, + "Present pixmap width must ask Mesa/KWin to reallocate full-size buffers", + ); + assert_eq!( + u16::from_le_bytes(present[34..36].try_into().unwrap()), + 1440, + "Present pixmap height must ask Mesa/KWin to reallocate full-size buffers", + ); + + crate::core_loop::run::emit_screen_resize_window_notifications_if_outputs_caught_up( + &mut state, + Some((1680, 1050)), + ); + assert!( + read_all_available(&mut peer).is_empty(), + "a stale output bbox must not re-emit full-size configure notifications", + ); + + state.randr.outputs[0].width = 3440; + state.randr.outputs[0].height = 1440; + crate::core_loop::run::emit_screen_resize_window_notifications_if_outputs_caught_up( + &mut state, + Some((1680, 1050)), + ); + let caught_up = read_all_available(&mut peer); + assert_eq!( + caught_up.len(), + 32 + 40, + "matching output bbox must re-emit core and Present COW configure notifications", + ); + assert_eq!(caught_up[0] & 0x7f, 22); + assert_eq!(caught_up[32], 35); + assert_eq!( + u16::from_le_bytes(caught_up[32 + 32..32 + 34].try_into().unwrap()), + 3440, + ); + assert_eq!( + u16::from_le_bytes(caught_up[32 + 34..32 + 36].try_into().unwrap()), + 1440, + ); + + crate::core_loop::run::emit_screen_resize_window_notifications_if_outputs_caught_up( + &mut state, + Some((3440, 1440)), + ); + assert!( + read_all_available(&mut peer).is_empty(), + "an unchanged output bbox must not re-emit configure notifications", + ); +} + +/// `RRSetScreenSize` validation: crop check returns BadMatch; zero-mm +/// returns BadValue; out-of-range width/height each report the offending +/// dimension as errorValue. +#[test] +fn screen_set_size_validation_errors() { + use crate::randr::{RandrOutput, RandrState}; + use yserver_protocol::x11::randr as x11randr; + + const CLIENT_ID: u32 = 1; + let outputs = vec![RandrOutput { + name: "eDP-1".into(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1920, + height: 1080, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(0, outputs); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + + fn build_body(width: u16, height: u16, mm_w: u32, mm_h: u32) -> Vec { + let mut b = Vec::with_capacity(16); + b.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + b.extend_from_slice(&width.to_le_bytes()); + b.extend_from_slice(&height.to_le_bytes()); + b.extend_from_slice(&mm_w.to_le_bytes()); + b.extend_from_slice(&mm_h.to_le_bytes()); + b + } + + let header = yserver_protocol::x11::RequestHeader { + opcode: 128, + data: x11randr::RR_SET_SCREEN_SIZE, + length_units: 5, + }; + + // width=0 → out-of-range (< min=1) → BadValue with errorValue=0. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &build_body(0, 1080, 527, 296), + ) + .unwrap(); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_VALUE, "width=0 → BadValue"); + // errorValue for the offending width is 0 (the bad width). + let ev = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); + assert_eq!(ev, 0u32, "errorValue = offending width"); + + // height=0 → out-of-range → BadValue with errorValue=height. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(2), + header, + &build_body(1920, 0, 527, 296), + ) + .unwrap(); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_VALUE, "height=0 → BadValue"); + let ev = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); + assert_eq!(ev, 0u32, "errorValue = offending height"); + + // Crop: 1280×720 crops the 1920×1080 output → BadMatch. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(3), + header, + &build_body(1280, 720, 527, 296), + ) + .unwrap(); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_MATCH, "crop → BadMatch"); + + // mm_width=0 → BadValue. + handle_randr_request( + &mut state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(4), + header, + &build_body(1920, 1080, 0, 296), + ) + .unwrap(); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_VALUE, "mm_width=0 → BadValue"); +} + +/// `RRSetScreenSize` sends ScreenChangeNotify only when pixel size or mm +/// differ from the current ones (`RRScreenSizeNotify`, rrscreen.c); a +/// repeated size and a rejected crop send nothing, as measured on Xorg +/// 21.1.24 by the xrandr-rotate vng scenario. +#[test] +fn screen_set_size_notifies_only_on_change() { + use crate::randr::{RandrOutput, RandrState}; + use yserver_protocol::x11::randr as x11randr; + + const CLIENT_ID: u32 = 1; + let outputs = vec![RandrOutput { + name: "Virtual-1".into(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 1280, + height: 800, + vrefresh: 60, + timing: None, + mm_width: 0, + mm_height: 0, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }]; + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs(0, outputs); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + state.randr_select_masks.insert( + (CLIENT_ID, ROOT_WINDOW), + x11randr::NOTIFY_MASK_SCREEN_CHANGE, + ); + + let header = yserver_protocol::x11::RequestHeader { + opcode: 128, + data: x11randr::RR_SET_SCREEN_SIZE, + length_units: 5, + }; + let mut set = |state: &mut ServerState, seq: u16, w: u16, h: u16, mm_w: u32, mm_h: u32| { + let mut b = Vec::with_capacity(16); + b.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + b.extend_from_slice(&w.to_le_bytes()); + b.extend_from_slice(&h.to_le_bytes()); + b.extend_from_slice(&mm_w.to_le_bytes()); + b.extend_from_slice(&mm_h.to_le_bytes()); + handle_randr_request( + state, + &mut backend, + ClientId(CLIENT_ID), + SequenceNumber(seq), + header, + &b, + ) + .unwrap(); + }; + // RRScreenChangeNotify is RANDR event base 89 + 0. + let screen_changes = + |bytes: &[u8]| bytes.chunks_exact(32).filter(|e| e[0] & 0x7f == 89).count(); + + set(&mut state, 1, 1280, 800, 300, 200); + assert_eq!( + screen_changes(&read_all_available(&mut peer)), + 1, + "mm changed" + ); + set(&mut state, 2, 1280, 800, 300, 200); + assert_eq!( + screen_changes(&read_all_available(&mut peer)), + 0, + "unchanged" + ); + set(&mut state, 3, 1279, 800, 300, 200); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_MATCH, "crop → BadMatch"); + assert_eq!(screen_changes(&bytes), 0, "rejected crop"); + set(&mut state, 4, 4000, 4000, 300, 200); + assert_eq!(screen_changes(&read_all_available(&mut peer)), 1, "grown"); + set(&mut state, 5, 1280, 800, 300, 200); + assert_eq!( + screen_changes(&read_all_available(&mut peer)), + 1, + "restored" + ); +} + +/// A backend whose CRTCs take neither rotations nor transforms (the +/// surface's window): Xorg's answers for a CRTC left at `RRCrtcCreate`'s +/// defaults, `rotations = RR_Rotate_0` and `transforms = FALSE` +/// (rrcrtc.c:84, calloc). +#[test] +fn randr_fixed_crtc_refuses_rotation_transform_and_overhang_as_xorg() { + use crate::randr::{RR_REFLECT_X, RR_ROTATE_0, RR_ROTATE_90, RandrLimits}; + use yserver_protocol::x11::error::{BAD_MATCH, BAD_VALUE}; + let mut state = ServerState::new(); + state.randr.limits = RandrLimits { + rotations: RR_ROTATE_0, + transforms: false, + min_size: (320, 200), + max_size: (8192, 8192), + }; + let output = state.randr.outputs[0].clone(); + let (crtc, mode) = (output.crtc_id, output.mode_id); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let u16_at = |c: &[u8], o: usize| u16::from_le_bytes(c[o..o + 2].try_into().unwrap()); + let u32_at = |c: &[u8], o: usize| u32::from_le_bytes(c[o..o + 4].try_into().unwrap()); + // `(error code, error value)` of the one error SetCrtcConfig raised. + let mut set = |state: &mut ServerState, x: i16, y: i16, rotation: u16| { + let mut body = randr_crtc_config_body(crtc, x, y, mode, &[output.output_id]); + body[20..22].copy_from_slice(&rotation.to_le_bytes()); + randr_set_crtc_config(state, &mut backend, &body).unwrap(); + let wire = read_all_available(&mut peer); + let error = wire.chunks_exact(32).find(|c| c[0] == 0); + error.map(|c| (c[1], u32_at(c, 4))) + }; + + // `(~crtc->rotations) & rotation` (rrcrtc.c:1403-1410). + assert_eq!( + set(&mut state, 0, 0, RR_ROTATE_90), + Some((BAD_MATCH, u32::from(RR_ROTATE_90))) + ); + assert_eq!( + set(&mut state, 0, 0, RR_ROTATE_0 | RR_REFLECT_X), + Some((BAD_MATCH, u32::from(RR_ROTATE_0 | RR_REFLECT_X))) + ); + // The screen bounds of a CRTC without transforms (rrcrtc.c:1446-1457): + // BadValue carrying x, then y. + assert_eq!(set(&mut state, 8, 0, RR_ROTATE_0), Some((BAD_VALUE, 8))); + assert_eq!(set(&mut state, 0, -1, RR_ROTATE_0), None, "fits: no error"); + assert_eq!(set(&mut state, 0, 4, RR_ROTATE_0), Some((BAD_VALUE, 4))); + state.randr.screen_width = output.width - 1; + assert_eq!(set(&mut state, 0, 0, RR_ROTATE_0), Some((BAD_VALUE, 0))); + + // GetCrtcInfo `rotations` and GetCrtcTransform `hasTransforms`. + let reply = randr_get_crtc_info(&mut state, &mut peer, crtc); + assert_eq!(u16_at(&reply, 26), RR_ROTATE_0); + let reply = randr_get_crtc_transform(&mut state, &mut peer, crtc); + assert_eq!(reply[44], 0, "hasTransforms"); + // RRCrtcTransformSet: `!crtc->transforms` is BadValue (rrcrtc.c:1088). + let body = randr_transform_body(crtc, rr_scale(131_072), b""); + assert_eq!( + randr_set_crtc_transform(&mut state, &mut peer, &body), + Some(BAD_VALUE) + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/randr_output.rs b/crates/yserver-core/src/core_loop/process_request/tests/randr_output.rs new file mode 100644 index 000000000..b3a93910a --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/randr_output.rs @@ -0,0 +1,2384 @@ +use super::*; + +fn randr_panning_body(crtc: u32, width: u16, height: u16) -> Vec { + let mut body = vec![0u8; 32]; + body[0..4].copy_from_slice(&crtc.to_le_bytes()); + body[12..14].copy_from_slice(&width.to_le_bytes()); + body[14..16].copy_from_slice(&height.to_le_bytes()); + body +} + +fn randr_provider(provider_id: u32, capabilities: u32) -> crate::randr::RandrProvider { + crate::randr::RandrProvider { + provider_id, + name: format!("card{provider_id}"), + capabilities, + is_gpu: true, + crtcs: Vec::new(), + outputs: Vec::new(), + associations: Vec::new(), + } +} + +fn randr_provider_request_body(minor: u8, provider: u32) -> Vec { + use yserver_protocol::x11::randr as x11randr; + + let mut body = Vec::new(); + body.extend_from_slice(&provider.to_le_bytes()); + match minor { + x11randr::RR_GET_PROVIDER_INFO => { + body.extend_from_slice(&0u32.to_le_bytes()); + } + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK | x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE => { + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + } + x11randr::RR_LIST_PROVIDER_PROPERTIES => {} + x11randr::RR_QUERY_PROVIDER_PROPERTY | x11randr::RR_DELETE_PROVIDER_PROPERTY => { + body.extend_from_slice(&0u32.to_le_bytes()); + } + x11randr::RR_CONFIGURE_PROVIDER_PROPERTY => { + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&[0u8; 4]); + } + x11randr::RR_CHANGE_PROVIDER_PROPERTY => { + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&[8, 0, 0, 0]); + body.extend_from_slice(&0u32.to_le_bytes()); + } + x11randr::RR_GET_PROVIDER_PROPERTY => { + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&[0u8; 4]); + } + _ => panic!("not a provider request minor: {minor}"), + } + body +} + +fn randr_output_source_body(provider: u32, source_provider: u32, timestamp: u32) -> Vec { + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&provider.to_le_bytes()); + body.extend_from_slice(&source_provider.to_le_bytes()); + body.extend_from_slice(×tamp.to_le_bytes()); + body +} + +#[test] +fn randr_set_panning_accepts_disabled_and_refuses_active_viewport() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let crtc = state.randr.outputs[0].crtc_id; + let timestamp = state.randr.timestamp; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 128, + data: x11randr::RR_SET_PANNING, + length_units: 9, + }; + + let mut disabled = randr_panning_body(crtc, 0, 0); + disabled[8..10].copy_from_slice(&15u16.to_le_bytes()); + disabled[24..26].copy_from_slice(&(-3i16).to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &disabled, + ) + .expect("disabled panning"); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + header, + &randr_panning_body(crtc, 1920, 1080), + ) + .expect("active panning refusal"); + + let replies = read_all_available(&mut peer); + assert_eq!(replies.len(), 64); + assert_eq!(replies[0], 1); + assert_eq!(replies[1], x11randr::SET_CONFIG_SUCCESS); + assert_eq!( + u32::from_le_bytes(replies[8..12].try_into().unwrap()), + timestamp + ); + assert_eq!(replies[32], 1); + assert_eq!(replies[33], x11randr::SET_CONFIG_FAILED); + assert_ne!( + state.randr_unsupported_warned_mask & (1 << x11randr::RR_SET_PANNING), + 0, + ); +} + +#[test] +fn randr_provider_queries_report_sorted_topology_in_both_byte_orders() { + use yserver_protocol::x11::randr as x11randr; + + for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + state.randr.set_providers(vec![ + randr_provider(20, 0), + crate::randr::RandrProvider { + name: "card0".to_string(), + capabilities: x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT, + crtcs: vec![2], + outputs: vec![1], + associations: vec![crate::randr::RandrProviderAssociation { + provider_id: 20, + capability: x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT, + }], + ..randr_provider(10, 0) + }, + ]); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").byte_order = byte_order; + let mut backend = RecordingBackend::new(); + + let mut providers_body = match byte_order { + ClientByteOrder::LittleEndian => ROOT_WINDOW.0.to_le_bytes().to_vec(), + ClientByteOrder::BigEndian => ROOT_WINDOW.0.to_be_bytes().to_vec(), + }; + yserver_protocol::x11::request_swap::swap_request_body( + 128, + x11randr::RR_GET_PROVIDERS, + byte_order, + &mut providers_body, + ); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: x11randr::RR_GET_PROVIDERS, + length_units: 2, + }, + &providers_body, + ) + .expect("get providers"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 40); + match byte_order { + ClientByteOrder::LittleEndian => { + assert_eq!(&bytes[4..8], &2u32.to_le_bytes()); + assert_eq!(&bytes[12..14], &2u16.to_le_bytes()); + assert_eq!(&bytes[32..36], &10u32.to_le_bytes()); + assert_eq!(&bytes[36..40], &20u32.to_le_bytes()); + } + ClientByteOrder::BigEndian => { + assert_eq!(&bytes[4..8], &2u32.to_be_bytes()); + assert_eq!(&bytes[12..14], &2u16.to_be_bytes()); + assert_eq!(&bytes[32..36], &10u32.to_be_bytes()); + assert_eq!(&bytes[36..40], &20u32.to_be_bytes()); + } + } + + let mut info_body = Vec::new(); + match byte_order { + ClientByteOrder::LittleEndian => { + info_body.extend_from_slice(&10u32.to_le_bytes()); + info_body.extend_from_slice(&0u32.to_le_bytes()); + } + ClientByteOrder::BigEndian => { + info_body.extend_from_slice(&10u32.to_be_bytes()); + info_body.extend_from_slice(&0u32.to_be_bytes()); + } + } + yserver_protocol::x11::request_swap::swap_request_body( + 128, + x11randr::RR_GET_PROVIDER_INFO, + byte_order, + &mut info_body, + ); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: x11randr::RR_GET_PROVIDER_INFO, + length_units: 3, + }, + &info_body, + ) + .expect("get provider info"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 56); + assert_eq!(bytes[1], x11randr::SET_CONFIG_SUCCESS); + match byte_order { + ClientByteOrder::LittleEndian => { + assert_eq!(&bytes[4..8], &6u32.to_le_bytes()); + assert_eq!( + &bytes[12..16], + &x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT.to_le_bytes() + ); + assert_eq!(&bytes[16..18], &1u16.to_le_bytes()); + assert_eq!(&bytes[18..20], &1u16.to_le_bytes()); + assert_eq!(&bytes[20..22], &1u16.to_le_bytes()); + assert_eq!(&bytes[32..36], &2u32.to_le_bytes()); + assert_eq!(&bytes[36..40], &1u32.to_le_bytes()); + assert_eq!(&bytes[40..44], &20u32.to_le_bytes()); + assert_eq!( + &bytes[44..48], + &x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT.to_le_bytes() + ); + } + ClientByteOrder::BigEndian => { + assert_eq!(&bytes[4..8], &6u32.to_be_bytes()); + assert_eq!( + &bytes[12..16], + &x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT.to_be_bytes() + ); + assert_eq!(&bytes[16..18], &1u16.to_be_bytes()); + assert_eq!(&bytes[18..20], &1u16.to_be_bytes()); + assert_eq!(&bytes[20..22], &1u16.to_be_bytes()); + assert_eq!(&bytes[32..36], &2u32.to_be_bytes()); + assert_eq!(&bytes[36..40], &1u32.to_be_bytes()); + assert_eq!(&bytes[40..44], &20u32.to_be_bytes()); + assert_eq!( + &bytes[44..48], + &x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT.to_be_bytes() + ); + } + } + assert_eq!(&bytes[48..53], b"card0"); + assert!(bytes[53..].iter().all(|byte| *byte == 0)); + } +} + +#[test] +fn randr_provider_requests_validate_exact_or_minimum_wire_size_first() { + use yserver_protocol::x11::randr as x11randr; + + let mut valid_bodies = vec![( + x11randr::RR_GET_PROVIDERS, + ROOT_WINDOW.0.to_le_bytes().to_vec(), + )]; + valid_bodies + .extend((33..=41).map(|minor| (minor, randr_provider_request_body(minor, 0x00ab_cdef)))); + for (minor, valid) in valid_bodies { + let mut malformed_bodies = vec![valid[..valid.len() - 4].to_vec()]; + if minor != x11randr::RR_CONFIGURE_PROVIDER_PROPERTY { + let mut extra = valid.clone(); + extra.extend_from_slice(&[0; 4]); + malformed_bodies.push(extra); + } + for malformed in malformed_bodies { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(u16::from(minor)), + RequestHeader { + opcode: 128, + data: minor, + length_units: 1 + malformed.len().div_ceil(4) as u32, + }, + &malformed, + ) + .expect("process malformed provider request"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); + assert_eq!(bytes[1], x11::error::BAD_LENGTH, "minor {minor} code"); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 0); + } + } +} + +#[test] +fn randr_unknown_provider_requests_use_valid_shapes_then_bad_provider() { + const PROVIDER: u32 = 0x00ab_cdef; + for minor in 33..=41 { + let body = randr_provider_request_body(minor, PROVIDER); + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(u16::from(minor)), + RequestHeader { + opcode: 128, + data: minor, + length_units: 1 + (body.len() / 4) as u32, + }, + &body, + ) + .expect("process provider request"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); + assert_eq!(bytes[1], RANDR_BAD_PROVIDER, "minor {minor} error"); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + PROVIDER, + "minor {minor} bad provider", + ); + assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); + assert_eq!(bytes[10], 128); + } +} + +#[test] +fn randr_provider_relationships_validate_roles_in_xorg_order() { + use yserver_protocol::x11::randr as x11randr; + + let cases: &[(u8, u32, u32, u8, u32)] = &[ + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 99, + 0, + RANDR_BAD_PROVIDER, + 99, + ), + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 5, + 99, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 1, + 99, + RANDR_BAD_PROVIDER, + 99, + ), + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 1, + 5, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 6, + 99, + RANDR_BAD_PROVIDER, + 99, + ), + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 6, + 2, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + 6, + 0, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 99, + 0, + RANDR_BAD_PROVIDER, + 99, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 5, + 99, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 7, + 99, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 7, + 0, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 3, + 99, + RANDR_BAD_PROVIDER, + 99, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 3, + 5, + x11::error::BAD_VALUE, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 3, + 0, + x11::error::BAD_IMPLEMENTATION, + 0, + ), + ( + x11randr::RR_SET_PROVIDER_OFFLOAD_SINK, + 3, + 4, + x11::error::BAD_IMPLEMENTATION, + 0, + ), + ]; + for &(minor, provider, peer_provider, error_code, error_value) in cases { + let mut state = ServerState::new(); + state.randr.set_providers(vec![ + randr_provider(1, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), + randr_provider(2, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), + randr_provider(3, x11randr::PROVIDER_CAPABILITY_SOURCE_OFFLOAD), + randr_provider(4, x11randr::PROVIDER_CAPABILITY_SINK_OFFLOAD), + randr_provider(5, 0), + crate::randr::RandrProvider { + is_gpu: false, + ..randr_provider(6, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT) + }, + crate::randr::RandrProvider { + is_gpu: false, + ..randr_provider(7, x11randr::PROVIDER_CAPABILITY_SOURCE_OFFLOAD) + }, + ]); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = Vec::new(); + body.extend_from_slice(&provider.to_le_bytes()); + body.extend_from_slice(&peer_provider.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(u16::from(minor)), + RequestHeader { + opcode: 128, + data: minor, + length_units: 4, + }, + &body, + ) + .expect("process provider relationship"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], error_code, "minor={minor} provider={provider}"); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + error_value, + "minor={minor} provider={provider}", + ); + } +} + +#[test] +fn randr_set_provider_output_source_reaches_backend_for_attach_and_detach() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + state.randr.set_providers(vec![ + randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), + randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), + ]); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + for (sequence, source_provider) in [(1, 10), (2, 0)] { + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + length_units: 4, + }, + &randr_output_source_body(11, source_provider, 77), + ) + .expect("set provider output source"); + assert!( + read_all_available(&mut peer).is_empty(), + "successful void requests do not emit a reply" + ); + } + + assert_eq!( + backend.calls(), + vec![ + RecordedCall::SetProviderOutputSource { + provider: 11, + source_provider: Some(10), + }, + RecordedCall::SetProviderOutputSource { + provider: 11, + source_provider: None, + }, + ] + ); +} + +#[test] +fn randr_set_provider_output_source_notifies_in_both_byte_orders() { + use yserver_protocol::x11::randr as x11randr; + + for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + state.randr.timestamp = 0x0102_0304; + state.randr.config_timestamp = 0x0506_0708; + state.randr.set_providers(vec![ + randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), + randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), + ]); + let mut peer = install_client(&mut state, 1); + let client = state.clients.get_mut(&1).expect("test client"); + client.byte_order = byte_order; + client + .last_sequence + .store(14, std::sync::atomic::Ordering::Relaxed); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_PROVIDER_CHANGE); + let mut backend = RecordingBackend::new(); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(14), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + length_units: 4, + }, + &randr_output_source_body(11, 10, 99), + ) + .expect("set provider output source"); + + let event = read_all_available(&mut peer); + let (sequence, timestamp, request_window, provider) = match byte_order { + ClientByteOrder::LittleEndian => ( + 14u16.to_le_bytes(), + 0x0102_0304u32.to_le_bytes(), + ROOT_WINDOW.0.to_le_bytes(), + 11u32.to_le_bytes(), + ), + ClientByteOrder::BigEndian => ( + 14u16.to_be_bytes(), + 0x0102_0304u32.to_be_bytes(), + ROOT_WINDOW.0.to_be_bytes(), + 11u32.to_be_bytes(), + ), + }; + assert_eq!(event.len(), 32); + assert_eq!(event[0], 90, "RANDR Notify event"); + assert_eq!(event[1], x11randr::NOTIFY_PROVIDER_CHANGE); + assert_eq!(&event[2..4], &sequence); + assert_eq!(&event[4..8], ×tamp); + assert_eq!(&event[8..12], &request_window); + assert_eq!(&event[12..16], &provider); + assert_eq!(state.randr.timestamp, 0x0102_0304); + assert_eq!(state.randr.config_timestamp, 0x0506_0708); + } +} + +#[test] +fn randr_idempotent_provider_output_source_skips_notify() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + state.randr.timestamp = 40; + state.randr.config_timestamp = 50; + state.randr.set_providers(vec![ + randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), + randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), + ]); + let mut peer = install_client(&mut state, 1); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_PROVIDER_CHANGE); + let mut backend = RecordingBackend::new(); + backend.provider_output_source_changed = false; + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + length_units: 4, + }, + &randr_output_source_body(11, 10, 99), + ) + .expect("idempotent provider output source"); + + assert!(read_all_available(&mut peer).is_empty()); + assert_eq!(state.randr.timestamp, 40); + assert_eq!(state.randr.config_timestamp, 50); + assert_eq!( + backend.calls(), + vec![RecordedCall::SetProviderOutputSource { + provider: 11, + source_provider: Some(10), + }] + ); +} + +#[test] +fn randr_provider_output_source_maps_backend_errors_by_kind() { + use yserver_protocol::x11::randr as x11randr; + + for (kind, error_code, error_value) in [ + (io::ErrorKind::InvalidInput, x11::error::BAD_MATCH, 11), + (io::ErrorKind::Other, x11::error::BAD_IMPLEMENTATION, 0), + ] { + let mut state = ServerState::new(); + state.randr.set_providers(vec![ + randr_provider(10, x11randr::PROVIDER_CAPABILITY_SOURCE_OUTPUT), + randr_provider(11, x11randr::PROVIDER_CAPABILITY_SINK_OUTPUT), + ]); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + backend.provider_output_source_error = Some(kind); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: x11randr::RR_SET_PROVIDER_OUTPUT_SOURCE, + length_units: 4, + }, + &randr_output_source_body(11, 10, 99), + ) + .expect("backend provider output source error"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], error_code, "backend error kind {kind:?}"); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + error_value, + "backend error kind {kind:?}" + ); + } +} + +#[test] +fn randr_known_provider_property_requests_are_explicitly_unsupported() { + use yserver_protocol::x11::randr as x11randr; + + for minor in x11randr::RR_LIST_PROVIDER_PROPERTIES..=x11randr::RR_GET_PROVIDER_PROPERTY { + let mut body = randr_provider_request_body(minor, 10); + if minor == x11randr::RR_CONFIGURE_PROVIDER_PROPERTY { + // This request is variable-sized: trailing INT32 values are + // part of a valid request shape, not an overlong request. + body.extend_from_slice(&17i32.to_le_bytes()); + } + let mut state = ServerState::new(); + state.randr.set_providers(vec![randr_provider(10, 0)]); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(u16::from(minor)), + RequestHeader { + opcode: 128, + data: minor, + length_units: 1 + (body.len() / 4) as u32, + }, + &body, + ) + .expect("process known provider property request"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_IMPLEMENTATION, "minor {minor}"); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 0); + } +} + +#[test] +fn randr_change_provider_property_pins_xorg_error_precedence() { + use yserver_protocol::x11::randr as x11randr; + + let mut cases = Vec::new(); + let mut bad_mode = randr_provider_request_body(x11randr::RR_CHANGE_PROVIDER_PROPERTY, 99); + bad_mode[13] = 99; + bad_mode[16..20].copy_from_slice(&1u32.to_le_bytes()); + cases.push((bad_mode, x11::error::BAD_VALUE, 99)); + let mut bad_format = randr_provider_request_body(x11randr::RR_CHANGE_PROVIDER_PROPERTY, 99); + bad_format[12] = 7; + bad_format[16..20].copy_from_slice(&1u32.to_le_bytes()); + cases.push((bad_format, x11::error::BAD_VALUE, 7)); + let mut bad_length = randr_provider_request_body(x11randr::RR_CHANGE_PROVIDER_PROPERTY, 99); + bad_length[16..20].copy_from_slice(&1u32.to_le_bytes()); + cases.push((bad_length, x11::error::BAD_LENGTH, 0)); + + for (body, error_code, error_value) in cases { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(39), + RequestHeader { + opcode: 128, + data: x11randr::RR_CHANGE_PROVIDER_PROPERTY, + length_units: 1 + (body.len() / 4) as u32, + }, + &body, + ) + .expect("process malformed ChangeProviderProperty"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], error_code); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + error_value + ); + } +} + +/// RANDR minors 1 (`RROldGetScreenInfo`) and 3 +/// (`RROldScreenChangeSelectInput`) are NULL entries in Xorg's +/// `ProcRandrVector`, and `ProcRRDispatch` treats a NULL slot exactly like +/// an out-of-range minor — `BadRequest`. They previously fell through to +/// the silent "known unsupported" arm and reported success. +#[test] +fn randr_null_dispatch_slots_return_bad_request() { + for minor in [1u8, 3] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(u16::from(minor)), + RequestHeader { + opcode: 128, + data: minor, + length_units: 1, + }, + &[], + ) + .expect("process request"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "minor {minor} must answer"); + assert_eq!(bytes[0], 0, "minor {minor} must be an error, not a reply"); + assert_eq!(bytes[1], x11::error::BAD_REQUEST, "minor {minor} code"); + assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); + assert_eq!(bytes[10], 128); + } +} + +/// Xorg emits plain `BadValue` here, NOT `BadRRLease`: RRLeaseType is +/// created without `SetResourceTypeErrorValue`, so it keeps dix's default +/// errorValue, and `BadRRLease` is referenced nowhere in the Xorg tree. +/// Expected value measured on real Xorg via `tools/randr-probe` +/// (`RRFreeLease(bogus) -> code=2 (BadValue)`), not derived from this +/// implementation. +#[test] +fn randr_free_lease_without_live_lease_returns_bad_value() { + const LEASE: u32 = 0x0012_3456; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(46), + RequestHeader { + opcode: 128, + data: 46, + length_units: 2, + }, + &LEASE.to_le_bytes(), + ) + .expect("process FreeLease"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), LEASE); + assert_eq!(&bytes[8..10], &46u16.to_le_bytes()); + assert_eq!(bytes[10], 128); +} + +/// SetScreenConfig resolves its xid as a DRAWABLE, so a PIXMAP is a legal +/// target and must get a normal reply rather than a resource error. Xorg +/// takes `pDraw->pScreen` from whatever drawable it finds (rrscreen.c). +/// Measured on real Xorg with `tools/randr-probe`: a live pixmap returns +/// Success, while yserver used to answer BadWindow. +#[test] +fn randr_set_screen_config_accepts_a_pixmap_drawable() { + const PIXMAP: u32 = 0x0020_0007; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.resources.create_pixmap( + ClientId(1), + x11::CreatePixmapRequest { + depth: 24, + pixmap: ResourceId(PIXMAP), + drawable: crate::resources::ROOT_WINDOW, + width: 32, + height: 32, + }, + ); + + // A client that never sent QueryVersion: the 1.0 request size. + let mut body = vec![0; 16]; + body[0..4].copy_from_slice(&PIXMAP.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: 2, + length_units: 5, + }, + &body, + ) + .expect("process SetScreenConfig"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "expected a 32-byte reply"); + assert_eq!(bytes[0], 1, "must be a reply (1), not an error (0)"); +} + +#[test] +fn randr_resource_queries_validate_xids_before_replying() { + const MISSING: u32 = 0x00de_ad01; + let cases = [ + // SetScreenConfig takes a DRAWABLE (`dixLookupDrawable`), whose + // BadValue is remapped to BadDrawable — verified on real Xorg with + // `tools/randr-probe` (bogus xid -> code=9). Every other minor here + // takes a window and reports BadWindow. + // 16: the 1.0 size, for a client without QueryVersion. + (2, 16usize, x11::error::BAD_DRAWABLE), + (4, 8, x11::error::BAD_WINDOW), + (5, 4usize, x11::error::BAD_WINDOW), + (6, 4, x11::error::BAD_WINDOW), + (7, 16, x11::error::BAD_WINDOW), + (8, 4, x11::error::BAD_WINDOW), + (25, 4, x11::error::BAD_WINDOW), + (31, 4, x11::error::BAD_WINDOW), + (32, 4, x11::error::BAD_WINDOW), + (42, 8, x11::error::BAD_WINDOW), + (9, 8, RANDR_BAD_OUTPUT), + (10, 4, RANDR_BAD_OUTPUT), + (11, 8, RANDR_BAD_OUTPUT), + (15, 24, RANDR_BAD_OUTPUT), + (20, 8, RANDR_BAD_CRTC), + (22, 4, RANDR_BAD_CRTC), + (23, 4, RANDR_BAD_CRTC), + (24, 8, RANDR_BAD_CRTC), + (26, 44, RANDR_BAD_CRTC), + (27, 4, RANDR_BAD_CRTC), + (28, 4, RANDR_BAD_CRTC), + (29, 32, RANDR_BAD_CRTC), + ]; + + for (minor, body_len, expected_error) in cases { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = vec![0; body_len]; + body[0..4].copy_from_slice(&MISSING.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(u16::from(minor)), + RequestHeader { + opcode: 128, + data: minor, + length_units: u32::try_from(1 + body_len / 4).unwrap(), + }, + &body, + ) + .expect("process RANDR resource request"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "minor {minor} must return an error"); + assert_eq!(bytes[1], expected_error, "minor {minor} error"); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + MISSING, + "minor {minor} bad resource", + ); + assert_eq!(&bytes[8..10], &u16::from(minor).to_le_bytes()); + assert_eq!(bytes[10], 128); + } +} + +/// Xorg treats a primary change as a layout change and fans out +/// ScreenChangeNotify + OutputChangeNotify via `RRTellChanged` +/// (randr/rroutput.c `RRSetPrimaryOutput`). yserver used to just assign the +/// field, so panels never learned the primary moved — they wait for the +/// notify rather than polling GetOutputPrimary. Also pins the idempotent +/// case: re-setting the same output must NOT emit anything. +#[test] +fn randr_set_output_primary_notifies_selecting_clients() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Subscribe to both the screen-change and output-change notifies. + state.randr_select_masks.insert( + (1, ROOT_WINDOW), + x11randr::NOTIFY_MASK_SCREEN_CHANGE | x11randr::NOTIFY_MASK_OUTPUT_CHANGE, + ); + state.randr.timestamp = 41; + state.randr.config_timestamp = 37; + + let request = |target: u32| { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&target.to_le_bytes()); + body + }; + let header = RequestHeader { + opcode: 128, + data: x11randr::RR_SET_OUTPUT_PRIMARY, + length_units: 3, + }; + + // Re-selecting the topology-derived default is wire-idempotent, but + // records that the client now owns this primary choice. + assert!(!state.randr_primary_output_explicit); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(0), + header, + &request(output), + ) + .expect("make default primary explicit"); + assert!(state.randr_primary_output_explicit); + assert!(read_all_available(&mut peer).is_empty()); + + // The first output is primary by default, so clear it first to make the + // set below a real change. (The clear is itself a change and notifies — + // drained here so the assertions below see only the set.) + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &request(0), + ) + .expect("clear primary"); + let _ = read_all_available(&mut peer); + assert_eq!( + (state.randr.timestamp, state.randr.config_timestamp), + (41, 37) + ); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + header, + &request(output), + ) + .expect("set primary"); + + // Two 32-byte events: ScreenChangeNotify then OutputChangeNotify for + // the newly-primary output (the previous primary was None, so it + // contributes nothing). + let events = read_all_available(&mut peer); + assert_eq!(events.len(), 64, "expected ScreenChange + OutputChange"); + const RANDR_FIRST_EVENT: u8 = 89; + assert_eq!(events[0] & 0x7f, RANDR_FIRST_EVENT, "ScreenChangeNotify"); + assert_eq!( + events[32] & 0x7f, + RANDR_FIRST_EVENT + 1, + "RRNotify (OutputChange)" + ); + for event in events.chunks_exact(32) { + assert_eq!(u32::from_le_bytes(event[4..8].try_into().unwrap()), 41); + assert_eq!(u32::from_le_bytes(event[8..12].try_into().unwrap()), 37); + } + assert_eq!( + (state.randr.timestamp, state.randr.config_timestamp), + (41, 37) + ); + + // Setting the same output again changes nothing, so it must be silent. + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + header, + &request(output), + ) + .expect("set same primary"); + assert!( + read_all_available(&mut peer).is_empty(), + "idempotent set must not notify", + ); +} + +#[test] +fn randr_set_output_primary_updates_get_output_primary() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let request = |output: u32| { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&output.to_le_bytes()); + body + }; + let set_header = RequestHeader { + opcode: 128, + data: x11randr::RR_SET_OUTPUT_PRIMARY, + length_units: 3, + }; + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + set_header, + &request(0), + ) + .expect("clear primary"); + assert_eq!(state.randr.primary_output, 0); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + set_header, + &request(output), + ) + .expect("set primary"); + assert_eq!(state.randr.primary_output, output); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 128, + data: x11randr::RR_GET_OUTPUT_PRIMARY, + length_units: 2, + }, + &ROOT_WINDOW.0.to_le_bytes(), + ) + .expect("get primary"); + let reply = read_all_available(&mut peer); + assert_eq!(reply[0], 1); + assert_eq!(u32::from_le_bytes(reply[8..12].try_into().unwrap()), output); + + let missing = 0x00de_ad02; + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(4), + set_header, + &request(missing), + ) + .expect("reject unknown primary"); + let error = read_all_available(&mut peer); + assert_eq!(error[1], RANDR_BAD_OUTPUT); + assert_eq!(u32::from_le_bytes(error[4..8].try_into().unwrap()), missing); + assert_eq!(state.randr.primary_output, output); +} + +fn change_output_property_body( + output: u32, + property: u32, + prop_type: u32, + format: u8, + mode: u8, + data: &[u8], +) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.to_le_bytes()); + body.extend_from_slice(&prop_type.to_le_bytes()); + body.push(format); + body.push(mode); + body.extend_from_slice(&[0, 0]); + let n_units = match format { + 8 => data.len(), + 16 => data.len() / 2, + 32 => data.len() / 4, + _ => 0, + }; + body.extend_from_slice(&(n_units as u32).to_le_bytes()); + body.extend_from_slice(data); + body +} + +fn change_output_property_header(body_len: usize) -> RequestHeader { + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_CHANGE_OUTPUT_PROPERTY, + length_units: u32::try_from(1 + body_len / 4).unwrap(), + } +} + +#[test] +fn randr_change_output_property_creates_and_notifies() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); + + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + let body = + change_output_property_body(output, property.0, prop_type.0, 32, 0, &42u32.to_le_bytes()); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("ChangeOutputProperty"); + + // Void request: no reply bytes, just the notify event. + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "expected exactly one OutputPropertyNotify"); + const RANDR_FIRST_EVENT: u8 = 89; + assert_eq!(bytes[0] & 0x7f, RANDR_FIRST_EVENT + 1, "RRNotify"); + assert_eq!(bytes[1], x11randr::NOTIFY_OUTPUT_PROPERTY); + assert_eq!(u32::from_le_bytes(bytes[8..12].try_into().unwrap()), output); + assert_eq!( + u32::from_le_bytes(bytes[12..16].try_into().unwrap()), + property.0 + ); + assert_eq!(bytes[20], x11randr::PROPERTY_NEW_VALUE); + + let stored = state + .randr_output_properties + .get(&output) + .and_then(|props| props.iter().find(|(atom, _)| *atom == property)) + .map(|(_, p)| p) + .expect("property stored"); + assert_eq!(stored.current.as_ref().unwrap().data, 42u32.to_le_bytes()); + assert_eq!(stored.current.as_ref().unwrap().r#type, prop_type); +} + +/// #185: an output property write must not move lastSetTime/lastConfigTime +/// (Xorg `rrproperty.c`). muffin treats a lastSetTime that no longer +/// matches its own SetCrtcConfig reply as an external reconfiguration and +/// rebuilds its monitor config (Cinnamon then comes back at 200%). +#[test] +fn randr_change_output_property_leaves_randr_timestamps_alone() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.randr.timestamp = 29_342; + state.randr.config_timestamp = 29_133; + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + for (seq, mode) in [(1, 0u8), (2, 2u8)] { + let body = change_output_property_body( + output, + property.0, + prop_type.0, + 32, + mode, + &42u32.to_le_bytes(), + ); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(seq), + change_output_property_header(body.len()), + &body, + ) + .expect("ChangeOutputProperty"); + } + let mut delete = output.to_le_bytes().to_vec(); + delete.extend_from_slice(&property.0.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_DELETE_OUTPUT_PROPERTY, + length_units: 3, + }, + &delete, + ) + .expect("DeleteOutputProperty"); + assert_eq!( + (state.randr.timestamp, state.randr.config_timestamp), + (29_342, 29_133) + ); +} + +#[test] +fn randr_change_output_property_replace_overwrites() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + + for value in [1u32, 2u32] { + let body = change_output_property_body( + output, + property.0, + prop_type.0, + 32, + 0, + &value.to_le_bytes(), + ); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("ChangeOutputProperty"); + } + let _ = read_all_available(&mut peer); + + let stored = &state.randr_output_properties[&output] + .iter() + .find(|(atom, _)| *atom == property) + .unwrap() + .1; + assert_eq!(stored.current.as_ref().unwrap().data, 2u32.to_le_bytes()); +} + +#[test] +fn randr_change_output_property_append_concatenates() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("STRING", false); + + let body = change_output_property_body(output, property.0, prop_type.0, 8, 0, b"hello"); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("replace"); + // mode=2 Append + let body = change_output_property_body(output, property.0, prop_type.0, 8, 2, b" world"); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + change_output_property_header(body.len()), + &body, + ) + .expect("append"); + let _ = read_all_available(&mut peer); + + let stored = &state.randr_output_properties[&output] + .iter() + .find(|(atom, _)| *atom == property) + .unwrap() + .1; + assert_eq!( + stored.current.as_ref().unwrap().data, + b"hello world".to_vec() + ); +} + +#[test] +fn randr_change_output_property_accepts_wire_padded_format8_data() { + // A real X11 client pads the trailing value array to a 4-byte + // boundary (here: 2 real bytes + 2 pad bytes). `nUnits` counts real + // elements only, so the parser must recover exactly "hi", not + // "hi\0\0". + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PADDED_PROP", false); + let prop_type = state.atoms.intern("STRING", false); + + let mut body = change_output_property_body(output, property.0, prop_type.0, 8, 0, b"hi"); + body.extend_from_slice(&[0, 0]); // wire padding to a 4-byte boundary + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("padded change"); + let _ = read_all_available(&mut peer); + + let stored = &state.randr_output_properties[&output] + .iter() + .find(|(atom, _)| *atom == property) + .unwrap() + .1; + assert_eq!(stored.current.as_ref().unwrap().data, b"hi".to_vec()); +} + +#[test] +fn randr_change_output_property_append_type_mismatch_is_bad_match() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let type_a = state.atoms.intern("STRING", false); + let type_b = state.atoms.intern("CARDINAL", false); + + let body = change_output_property_body(output, property.0, type_a.0, 8, 0, b"hi"); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("replace"); + let _ = read_all_available(&mut peer); + + // mode=1 Prepend with a different type -> BadMatch. + let body = change_output_property_body(output, property.0, type_b.0, 8, 1, b"yo"); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + change_output_property_header(body.len()), + &body, + ) + .expect("prepend mismatch"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_MATCH); +} + +#[test] +fn randr_change_output_property_invalid_format_is_bad_value() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + let body = change_output_property_body(output, property.0, prop_type.0, 7, 0, &[]); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("bad format"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_VALUE); +} + +#[test] +fn randr_change_output_property_invalid_mode_is_bad_value() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + let body = change_output_property_body(output, property.0, prop_type.0, 32, 9, &[]); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("bad mode"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_VALUE); +} + +#[test] +fn randr_change_output_property_unknown_output_is_bad_output() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + let missing = 0x00de_ad01; + let body = change_output_property_body(missing, property.0, prop_type.0, 32, 0, &[0; 4]); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("bad output"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], RANDR_BAD_OUTPUT); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), missing); +} + +#[test] +fn randr_change_output_property_unknown_atom_is_bad_atom() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let bogus_atom = 0x00de_ad01; + let prop_type = state.atoms.intern("CARDINAL", false); + let body = change_output_property_body(output, bogus_atom, prop_type.0, 32, 0, &[0; 4]); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("bad atom"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_ATOM); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + bogus_atom + ); +} + +fn configure_output_property_body( + output: u32, + property: u32, + pending: bool, + range: bool, + values: &[i32], +) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.to_le_bytes()); + body.push(u8::from(pending)); + body.push(u8::from(range)); + body.extend_from_slice(&[0, 0]); + for v in values { + body.extend_from_slice(&v.to_le_bytes()); + } + body +} + +fn configure_output_property_header(body_len: usize) -> RequestHeader { + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_CONFIGURE_OUTPUT_PROPERTY, + length_units: u32::try_from(1 + body_len / 4).unwrap(), + } +} + +#[test] +fn randr_configure_output_property_stores_range_and_fires_no_notify() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); + let property = state.atoms.intern("TEST_RANGE_PROP", false); + + let body = configure_output_property_body(output, property.0, false, true, &[0, 100]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + configure_output_property_header(body.len()), + &body, + ) + .expect("ConfigureOutputProperty"); + + assert!( + read_all_available(&mut peer).is_empty(), + "Configure must not notify" + ); + let stored = &state.randr_output_properties[&output] + .iter() + .find(|(atom, _)| *atom == property) + .unwrap() + .1; + assert!(stored.range); + assert!(!stored.is_pending); + assert!(!stored.immutable); + assert_eq!(stored.valid_values, vec![0, 100]); +} + +#[test] +fn randr_configure_output_property_odd_range_values_is_bad_match() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_RANGE_PROP", false); + + let body = configure_output_property_body(output, property.0, false, true, &[0, 50, 100]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + configure_output_property_header(body.len()), + &body, + ) + .expect("odd range values"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_MATCH); +} + +#[test] +fn randr_configure_output_property_leaving_pending_clears_pending_value() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); + let property = state.atoms.intern("TEST_PENDING_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + + // Mark the property pending-capable, then Change it (lands in + // `.pending`, but Xorg's `sendevent` is unconditional in + // `RRChangeOutputProperty` — only the `RRNoticePropertyChange` + // driver hook (unrelated to client notification) is gated on + // `is_pending`, so the wire notify still fires here). + let body = configure_output_property_body(output, property.0, true, false, &[]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + configure_output_property_header(body.len()), + &body, + ) + .expect("configure pending"); + let body = + change_output_property_body(output, property.0, prop_type.0, 32, 0, &7u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + change_output_property_header(body.len()), + &body, + ) + .expect("change pending value"); + let notify = read_all_available(&mut peer); + assert_eq!( + notify.len(), + 32, + "ChangeOutputProperty must notify even when staged as pending" + ); + assert_eq!(notify[20], x11randr::PROPERTY_NEW_VALUE); + assert!( + state.randr_output_properties[&output] + .iter() + .find(|(atom, _)| *atom == property) + .unwrap() + .1 + .pending + .is_some(), + "pending value must be staged" + ); + + // Configure(pending=false) drops the staged pending value (Xorg: + // "Property moving from pending to non-pending loses any pending + // values"). + let body = configure_output_property_body(output, property.0, false, false, &[]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + configure_output_property_header(body.len()), + &body, + ) + .expect("configure non-pending"); + let _ = read_all_available(&mut peer); + let stored = &state.randr_output_properties[&output] + .iter() + .find(|(atom, _)| *atom == property) + .unwrap() + .1; + assert!(!stored.is_pending); + assert!(stored.pending.is_none()); +} + +#[test] +fn randr_configure_output_property_unknown_output_is_bad_output() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_RANGE_PROP", false); + let missing = 0x00de_ad01; + + let body = configure_output_property_body(missing, property.0, false, false, &[]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + configure_output_property_header(body.len()), + &body, + ) + .expect("bad output"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], RANDR_BAD_OUTPUT); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), missing); +} + +fn delete_output_property_header() -> RequestHeader { + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_DELETE_OUTPUT_PROPERTY, + length_units: 3, + } +} + +#[test] +fn randr_delete_output_property_removes_and_notifies() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + + let body = + change_output_property_body(output, property.0, prop_type.0, 32, 0, &1u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("create property"); + let _ = read_all_available(&mut peer); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + delete_output_property_header(), + &body, + ) + .expect("DeleteOutputProperty"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + const RANDR_FIRST_EVENT: u8 = 89; + assert_eq!(bytes[0] & 0x7f, RANDR_FIRST_EVENT + 1); + assert_eq!(bytes[1], x11randr::NOTIFY_OUTPUT_PROPERTY); + assert_eq!(bytes[20], x11randr::PROPERTY_DELETE); + assert!( + !state.randr_output_properties[&output] + .iter() + .any(|(atom, _)| *atom == property), + "property must be removed" + ); +} + +#[test] +fn randr_delete_output_property_unknown_is_bad_name() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let bogus_atom = state.atoms.intern("NEVER_SET_PROP", false); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&bogus_atom.0.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + delete_output_property_header(), + &body, + ) + .expect("delete unknown"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_NAME); +} + +#[test] +fn randr_delete_output_property_unregistered_atom_is_bad_atom() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let never_interned: u32 = 0x00de_ad02; + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&never_interned.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + delete_output_property_header(), + &body, + ) + .expect("delete unregistered atom"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_ATOM); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + never_interned + ); +} + +#[test] +fn randr_delete_output_property_immutable_is_bad_access() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("IMMUTABLE_PROP", false); + state + .randr_output_properties + .entry(output) + .or_default() + .push(( + property, + crate::randr::RandrOutputProperty { + immutable: true, + ..Default::default() + }, + )); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + delete_output_property_header(), + &body, + ) + .expect("delete immutable"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_ACCESS); + assert!( + state.randr_output_properties[&output] + .iter() + .any(|(atom, _)| *atom == property), + "immutable property must not be removed" + ); +} + +#[test] +fn randr_delete_output_property_unknown_output_is_bad_output() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let missing: u32 = 0x00de_ad01; + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&missing.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + delete_output_property_header(), + &body, + ) + .expect("bad output"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], RANDR_BAD_OUTPUT); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), missing); +} + +#[test] +fn randr_query_output_property_reports_stored_metadata() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_RANGE_PROP", false); + + let body = configure_output_property_body(output, property.0, false, true, &[0, 100]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + configure_output_property_header(body.len()), + &body, + ) + .expect("configure"); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_QUERY_OUTPUT_PROPERTY, + length_units: 3, + }, + &body, + ) + .expect("query"); + let reply = read_all_available(&mut peer); + assert_eq!(reply[0], 1, "must be a reply"); + assert_eq!(u32::from_le_bytes(reply[4..8].try_into().unwrap()), 2); // length = num_valid + assert_eq!(reply[8], 0, "pending"); + assert_eq!(reply[9], 1, "range"); + assert_eq!(reply[10], 0, "immutable"); + assert_eq!(i32::from_le_bytes(reply[32..36].try_into().unwrap()), 0); + assert_eq!(i32::from_le_bytes(reply[36..40].try_into().unwrap()), 100); +} + +#[test] +fn randr_query_output_property_unknown_atom_is_bad_name() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let bogus_atom = state.atoms.intern("NEVER_CONFIGURED_PROP", false); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&bogus_atom.0.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_QUERY_OUTPUT_PROPERTY, + length_units: 3, + }, + &body, + ) + .expect("query unknown"); + let reply = read_all_available(&mut peer); + assert_eq!(reply.len(), 32); + assert_eq!(reply[1], x11::error::BAD_NAME); +} + +#[test] +fn randr_get_output_property_round_trips_changed_value() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + + let body = + change_output_property_body(output, property.0, prop_type.0, 32, 0, &99u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("change"); + let _ = read_all_available(&mut peer); + + // RRGetOutputProperty(output, property, AnyPropertyType, 0, 1, false, false) + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // AnyPropertyType + body.extend_from_slice(&0u32.to_le_bytes()); // long_offset + body.extend_from_slice(&1u32.to_le_bytes()); // long_length + body.push(0); // delete + body.push(0); // pending + body.extend_from_slice(&[0, 0]); // pad + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, + length_units: 6, + }, + &body, + ) + .expect("get"); + let reply = read_all_available(&mut peer); + assert_eq!(reply[0], 1); + assert_eq!(reply[1], 32, "format"); + assert_eq!( + u32::from_le_bytes(reply[8..12].try_into().unwrap()), + prop_type.0 + ); + assert_eq!(u32::from_le_bytes(reply[12..16].try_into().unwrap()), 0); // bytes_after + assert_eq!(u32::from_le_bytes(reply[16..20].try_into().unwrap()), 1); // nItems + assert_eq!(&reply[32..36], &99u32.to_le_bytes()); +} + +#[test] +fn randr_get_output_property_type_mismatch_returns_metadata_only() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let real_type = state.atoms.intern("CARDINAL", false); + let other_type = state.atoms.intern("STRING", false); + + // Two format-32 elements (8 bytes) so byte-count vs element-count + // diverge: Xorg's `bytesAfter` for a type mismatch is + // `prop_value->size`, an ELEMENT count (`rrproperty.c` + // `RRChangeOutputProperty`: `new_value.size = total_len` where + // `total_len` is `nUnits`, not a byte length), not `full.len()`. + let mut value = Vec::new(); + value.extend_from_slice(&1u32.to_le_bytes()); + value.extend_from_slice(&2u32.to_le_bytes()); + let body = change_output_property_body(output, property.0, real_type.0, 32, 0, &value); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("change"); + let _ = read_all_available(&mut peer); + + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + body.extend_from_slice(&other_type.0.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + body.push(0); + body.push(0); + body.extend_from_slice(&[0, 0]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, + length_units: 6, + }, + &body, + ) + .expect("get mismatched type"); + let reply = read_all_available(&mut peer); + assert_eq!( + u32::from_le_bytes(reply[8..12].try_into().unwrap()), + real_type.0, + "propertyType must be the real type" + ); + assert_eq!( + u32::from_le_bytes(reply[12..16].try_into().unwrap()), + 2, + "bytes_after is an ELEMENT count (2 x format-32), not a byte count (8)" + ); + assert_eq!(u32::from_le_bytes(reply[16..20].try_into().unwrap()), 0); // nItems +} + +#[test] +fn randr_get_output_property_unregistered_property_atom_is_bad_atom() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let never_interned: u32 = 0x00de_ad03; + + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&never_interned.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + body.extend_from_slice(&[0, 0, 0, 0]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, + length_units: 6, + }, + &body, + ) + .expect("get unregistered property atom"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_ATOM); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + never_interned + ); +} + +#[test] +fn randr_get_output_property_unregistered_type_atom_is_bad_atom() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let never_interned: u32 = 0x00de_ad04; + + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + body.extend_from_slice(&never_interned.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + body.extend_from_slice(&[0, 0, 0, 0]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, + length_units: 6, + }, + &body, + ) + .expect("get unregistered type atom"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_ATOM); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + never_interned + ); +} + +#[test] +fn randr_get_output_property_invalid_delete_byte_is_bad_value() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + body.push(2); // delete: neither xTrue(1) nor xFalse(0) + body.push(0); + body.extend_from_slice(&[0, 0]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, + length_units: 6, + }, + &body, + ) + .expect("get invalid delete byte"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 2); +} + +#[test] +fn randr_get_output_property_delete_removes_and_notifies() { + use yserver_protocol::x11::randr as x11randr; + + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + + let body = + change_output_property_body(output, property.0, prop_type.0, 32, 0, &1u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("change"); + let _ = read_all_available(&mut peer); + state + .randr_select_masks + .insert((1, ROOT_WINDOW), x11randr::NOTIFY_MASK_OUTPUT_PROPERTY); + + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&output.to_le_bytes()); + body.extend_from_slice(&property.0.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // AnyPropertyType + body.extend_from_slice(&0u32.to_le_bytes()); // long_offset + body.extend_from_slice(&1u32.to_le_bytes()); // long_length + body.push(1); // delete = true + body.push(0); + body.extend_from_slice(&[0, 0]); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_GET_OUTPUT_PROPERTY, + length_units: 6, + }, + &body, + ) + .expect("get with delete"); + + let bytes = read_all_available(&mut peer); + // One 32-byte OutputPropertyNotify(state=Delete) followed by the + // 36-byte reply (32-byte header + the just-deleted 4-byte value: + // Xorg reads the value before removing the property). + assert_eq!(bytes.len(), 68); + const RANDR_FIRST_EVENT: u8 = 89; + assert_eq!(bytes[0] & 0x7f, RANDR_FIRST_EVENT + 1, "RRNotify"); + assert_eq!(bytes[20], x11randr::PROPERTY_DELETE); + assert_eq!(bytes[32], 1, "reply type"); + assert!( + !state.randr_output_properties[&output] + .iter() + .any(|(atom, _)| *atom == property), + "property must be removed after delete=true read" + ); +} + +#[test] +fn randr_list_output_properties_includes_stored_atoms() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let property = state.atoms.intern("TEST_PROP", false); + let prop_type = state.atoms.intern("CARDINAL", false); + + let body = + change_output_property_body(output, property.0, prop_type.0, 32, 0, &1u32.to_le_bytes()); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("change"); + let _ = read_all_available(&mut peer); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_LIST_OUTPUT_PROPERTIES, + length_units: 2, + }, + &output.to_le_bytes(), + ) + .expect("list"); + let reply = read_all_available(&mut peer); + assert_eq!(reply[0], 1); + let n_atoms = u16::from_le_bytes(reply[8..10].try_into().unwrap()); + assert_eq!(n_atoms, 1); + assert_eq!( + u32::from_le_bytes(reply[32..36].try_into().unwrap()), + property.0 + ); +} + +#[test] +fn randr_list_output_properties_orders_newest_first() { + let mut state = ServerState::new(); + let output = state.randr.outputs[0].output_id; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let prop_type = state.atoms.intern("CARDINAL", false); + let first = state.atoms.intern("FIRST_PROP", false); + let second = state.atoms.intern("SECOND_PROP", false); + + for property in [first, second] { + let body = change_output_property_body( + output, + property.0, + prop_type.0, + 32, + 0, + &1u32.to_le_bytes(), + ); + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + change_output_property_header(body.len()), + &body, + ) + .expect("change"); + } + let _ = read_all_available(&mut peer); + + handle_randr_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 128, + data: yserver_protocol::x11::randr::RR_LIST_OUTPUT_PROPERTIES, + length_units: 2, + }, + &output.to_le_bytes(), + ) + .expect("list"); + let reply = read_all_available(&mut peer); + let n_atoms = u16::from_le_bytes(reply[8..10].try_into().unwrap()); + assert_eq!(n_atoms, 2); + // Xorg's RRCreateOutputProperty prepends onto a linked list, so + // ListOutputProperties enumerates newest-first. + assert_eq!( + u32::from_le_bytes(reply[32..36].try_into().unwrap()), + second.0, + "most recently created property must list first" + ); + assert_eq!( + u32::from_le_bytes(reply[36..40].try_into().unwrap()), + first.0 + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/region_probe.rs b/crates/yserver-core/src/core_loop/process_request/tests/region_probe.rs new file mode 100644 index 000000000..62b453628 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/region_probe.rs @@ -0,0 +1,720 @@ +//! `tools/xfixes-region-probe.c` replayed through the dispatcher, its +//! output compared line by line with the Xephyr run kept next to it +//! (`tools/xfixes-region-probe.xephyr.txt`). Every expected value here is +//! that Xorg output; nothing is derived from this server. + +use super::*; + +const GOLDEN: &str = include_str!("../../../../../../tools/xfixes-region-probe.xephyr.txt"); + +/// Golden lines this server does not reproduce, by tag, with the reason. +const KNOWN_DIVERGENT: &[&str] = &[ + // RegionExtents of an empty region: Xorg's `RegionReset` leaves a + // region whose one box has no area, which FetchRegion reports as one + // 0x0 rect; a canonical empty region has none. + "extents.empty ", + // The default Input shape: Xorg's is the bounding default, border + // included (`CreateBoundingShape` for ShapeInput); ours excludes the + // border, which nested.rs's + // `the_default_shape_region_includes_the_border_for_bounding_only` + // pins. A Subtract on an unset Input shape starts from it. + "fresh.subtract.on2.k2 ", + "input.sub.k2 ", + "offset.c.k2 ", + "mask.none.k2 ", + // A translation that puts an edge exactly on the 16-bit limit: pixman + // keeps the box with no area, `Region::translate_clipped` drops it. + "edge.exact ", +]; + +type R = (i16, i16, u16, u16); + +const V_ADJ: &[R] = &[(0, 0, 10, 5), (0, 5, 10, 5)]; +const OVL: &[R] = &[(0, 0, 10, 10), (0, 5, 10, 10)]; +const MULTI: &[R] = &[ + (20, 20, 10, 10), + (0, 0, 10, 10), + (5, 5, 10, 10), + (25, 0, 5, 30), +]; +const ZERO: &[R] = &[(0, 0, 0, 10), (5, 5, 10, 0), (1, 1, 2, 2)]; +const NEG: &[R] = &[(-10, -10, 15, 15), (-5, 0, 5, 5)]; +const H_ADJ: &[R] = &[(0, 0, 5, 5), (5, 0, 5, 5)]; +const ELL: &[R] = &[(0, 0, 20, 5), (0, 5, 5, 15)]; +const BIG: &[R] = &[(0, 0, 30, 30)]; +const HOLE: &[R] = &[(10, 10, 10, 10)]; +const CLAMP: &[R] = &[(32760, 32760, 100, 100)]; +const STRIPES: &[R] = &[(0, 0, 30, 2), (0, 4, 30, 2), (0, 8, 30, 2)]; +const COLS: &[R] = &[(0, 0, 2, 10), (4, 0, 2, 10), (8, 0, 2, 10)]; +const FRESH: &[R] = &[(10, 10, 10, 10), (90, 70, 20, 20)]; +const EDGE: &[R] = &[(32760, 0, 7, 10)]; +const EDGE_Y: &[R] = &[(0, 32760, 10, 7)]; +const LOW: &[R] = &[(-32768, 0, 10, 10)]; +const BANDS: &[R] = &[(0, 0, 10, 10), (32760, 0, 7, 10), (0, 10, 10, 10)]; +const DIAG: &[R] = &[(32000, 0, 767, 10), (0, 32000, 10, 767)]; +const CORNER: &[R] = &[(-10, -10, 30, 30)]; +const DOT: &[R] = &[(0, 0, 1, 1)]; +const FULL: &[R] = &[(-32768, -32768, 65535, 65535)]; + +const SHAPE_MAJOR: u8 = 141; + +fn xfixes_u32s(values: &[u32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +struct Twin { + state: ServerState, + backend: RecordingBackend, + peer: UnixStream, + out: Vec, + next: u32, +} + +fn rect_bytes(rects: &[R]) -> Vec { + let mut b = Vec::with_capacity(rects.len() * 8); + for &(x, y, w, h) in rects { + b.extend_from_slice(&x.to_le_bytes()); + b.extend_from_slice(&y.to_le_bytes()); + b.extend_from_slice(&w.to_le_bytes()); + b.extend_from_slice(&h.to_le_bytes()); + } + b +} + +fn fmt_rects(bytes: &[u8]) -> String { + let mut s = format!(" n={}", bytes.len() / 8); + for r in bytes.chunks_exact(8) { + let i = |at: usize| i16::from_le_bytes([r[at], r[at + 1]]); + let u = |at: usize| u16::from_le_bytes([r[at], r[at + 1]]); + s.push_str(&format!(" [{},{} {}x{}]", i(0), i(2), u(4), u(6))); + } + s +} + +impl Twin { + fn new() -> Self { + let mut state = ServerState::new(); + let peer = install_client(&mut state, 1); + state.xfixes_client_major.insert(1, 5); + Self { + state, + backend: RecordingBackend::new(), + peer, + out: Vec::new(), + next: 0x0020_0000, + } + } + + fn id(&mut self) -> u32 { + self.next += 1; + self.next + } + + /// Run one request; returns the replies (header + data) it produced + /// and prints any error the way the probe's `check` does. + fn req(&mut self, what: &str, major: u8, minor: u8, body: &[u8]) -> Vec> { + process_request( + &mut self.state, + &mut self.backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: major, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("request"); + let bytes = read_all_or_buffered(&mut self.state, 1, &mut self.peer); + let mut replies = Vec::new(); + let mut at = 0; + while at + 32 <= bytes.len() { + let p = &bytes[at..]; + let len = if p[0] == 1 { + 32 + 4 * le_u32(p, 4) as usize + } else { + 32 + }; + match p[0] { + 0 => self.out.push(format!( + "{what} ERR code={} minor={}", + p[1], + u16::from_le_bytes([p[8], p[9]]) + )), + 1 => replies.push(p[..len].to_vec()), + _ => {} + } + at += len; + } + replies + } + + fn xf(&mut self, what: &str, minor: u8, body: &[u8]) -> Vec> { + self.req(what, XFIXES_MAJOR_OPCODE, minor, body) + } + + fn mk(&mut self, rects: &[R]) -> u32 { + let id = self.id(); + let mut body = id.to_le_bytes().to_vec(); + body.extend(rect_bytes(rects)); + self.xf("create", x11xfixes::CREATE_REGION, &body); + id + } + + fn destroy(&mut self, region: u32) { + self.xf("destroy", x11xfixes::DESTROY_REGION, ®ion.to_le_bytes()); + } + + fn fetch(&mut self, tag: &str, region: u32) { + let replies = self.xf(tag, x11xfixes::FETCH_REGION, ®ion.to_le_bytes()); + let Some(r) = replies.first() else { + self.out.push(format!("{tag} fetch ERR")); + return; + }; + let e = &r[8..16]; + let i = |at: usize| i16::from_le_bytes([e[at], e[at + 1]]); + let u = |at: usize| u16::from_le_bytes([e[at], e[at + 1]]); + self.out.push(format!( + "{tag} ext=[{},{} {}x{}] {}", + i(0), + i(2), + u(4), + u(6), + fmt_rects(&r[32..]) + )); + } + + fn op3(&mut self, what: &str, minor: u8, a: u32, b: u32, d: u32) { + let body = xfixes_u32s(&[a, b, d]); + self.xf(what, minor, &body); + } + + fn mkwin(&mut self) -> u32 { + let id = self.id(); + self.state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(id), + parent: ROOT_WINDOW, + x: 10, + y: 10, + width: 100, + height: 80, + border_width: 3, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + id + } + + fn get_shape(&mut self, tag: &str, w: u32, kind: u8) { + let mut body = w.to_le_bytes().to_vec(); + body.extend_from_slice(&[kind, 0, 0, 0]); + let replies = self.req(tag, SHAPE_MAJOR, x11shape::GET_RECTANGLES, &body); + let Some(r) = replies.first() else { + self.out.push(format!("{tag} get ERR")); + return; + }; + let n = le_u32(r, 8) as usize; + self.out.push(format!( + "{tag}.k{kind} ordering={}{}", + r[1], + fmt_rects(&r[32..32 + 8 * n]) + )); + } + + fn get_all(&mut self, tag: &str, w: u32) { + for k in 0..=2 { + self.get_shape(tag, w, k); + } + let replies = self.req(tag, SHAPE_MAJOR, x11shape::QUERY_EXTENTS, &w.to_le_bytes()); + let r = &replies[0]; + let i = |at: usize| i16::from_le_bytes([r[at], r[at + 1]]); + let u = |at: usize| u16::from_le_bytes([r[at], r[at + 1]]); + self.out.push(format!( + "{tag}.extents bshaped={} cshaped={} b=[{},{} {}x{}] c=[{},{} {}x{}]", + r[8], + r[9], + i(12), + i(14), + u(16), + u(18), + i(20), + i(22), + u(24), + u(26) + )); + } + + #[allow(clippy::too_many_arguments)] + fn rects( + &mut self, + what: &str, + w: u32, + op: u8, + kind: u8, + ordering: u8, + off: (i16, i16), + r: &[R], + ) { + let mut body = vec![op, kind, ordering, 0]; + body.extend_from_slice(&w.to_le_bytes()); + body.extend_from_slice(&off.0.to_le_bytes()); + body.extend_from_slice(&off.1.to_le_bytes()); + body.extend(rect_bytes(r)); + self.req(what, SHAPE_MAJOR, x11shape::RECTANGLES, &body); + } + + fn offset(&mut self, what: &str, kind: u8, w: u32, dx: i16, dy: i16) { + let mut body = vec![kind, 0, 0, 0]; + body.extend_from_slice(&w.to_le_bytes()); + body.extend_from_slice(&dx.to_le_bytes()); + body.extend_from_slice(&dy.to_le_bytes()); + self.req(what, SHAPE_MAJOR, x11shape::OFFSET, &body); + } + + #[allow(clippy::too_many_arguments)] + fn combine( + &mut self, + what: &str, + op: u8, + dkind: u8, + skind: u8, + dest: u32, + off: (i16, i16), + src: u32, + ) { + let mut body = vec![op, dkind, skind, 0]; + body.extend_from_slice(&dest.to_le_bytes()); + body.extend_from_slice(&off.0.to_le_bytes()); + body.extend_from_slice(&off.1.to_le_bytes()); + body.extend_from_slice(&src.to_le_bytes()); + self.req(what, SHAPE_MAJOR, x11shape::COMBINE, &body); + } + + fn mask_none(&mut self, what: &str, kind: u8, w: u32) { + let mut body = vec![x11shape::OP_SET, kind, 0, 0]; + body.extend_from_slice(&w.to_le_bytes()); + body.extend_from_slice(&[0; 8]); + self.req(what, SHAPE_MAJOR, x11shape::MASK, &body); + } + + fn translate(&mut self, region: u32, dx: i16, dy: i16) { + let mut body = region.to_le_bytes().to_vec(); + body.extend_from_slice(&dx.to_le_bytes()); + body.extend_from_slice(&dy.to_le_bytes()); + self.xf("translate", x11xfixes::TRANSLATE_REGION, &body); + } + + /// Fetch `region` united with `HOLE`: an emptied region's extents are + /// stale in Xorg, the union's are not. + fn fetch_union_hole(&mut self, tag: &str, region: u32) { + let (h, d) = (self.mk(HOLE), self.mk(&[])); + self.op3("union", x11xfixes::UNION_REGION, region, h, d); + self.fetch(tag, d); + self.destroy(h); + self.destroy(d); + } + + fn region_from_window(&mut self, tag: &str, w: u32, kind: u8) { + let d = self.id(); + let mut body = xfixes_u32s(&[d, w]); + body.extend_from_slice(&[kind, 0, 0, 0]); + self.xf("from_window", x11xfixes::CREATE_REGION_FROM_WINDOW, &body); + self.fetch(tag, d); + self.destroy(d); + } +} + +use yserver_protocol::x11::{shape as x11shape, xfixes as x11xfixes}; + +fn xfixes_section(t: &mut Twin) { + t.out.push("== xfixes create/fetch".into()); + let inputs: &[(&str, &[R])] = &[ + ("v_adj", V_ADJ), + ("ovl", OVL), + ("multi", MULTI), + ("empty", &[]), + ("zero", ZERO), + ("neg", NEG), + ("h_adj", H_ADJ), + ("ell", ELL), + ("clamp", CLAMP), + ("stripes", STRIPES), + ("cols", COLS), + ]; + for (name, rects) in inputs { + let r = t.mk(rects); + t.fetch(&format!("create.{name}"), r); + t.destroy(r); + } + + t.out.push("== xfixes ops".into()); + let pairs: &[(&str, &[R], &[R])] = &[ + ("vadj_halves", &V_ADJ[..1], &V_ADJ[1..]), + ("big_hole", BIG, HOLE), + ("multi_ovl", MULTI, OVL), + ("multi_neg", MULTI, NEG), + ("ell_big", ELL, BIG), + ("stripes_cols", STRIPES, COLS), + ("empty_big", &[], BIG), + ("hadj_halves", &H_ADJ[..1], &H_ADJ[1..]), + ]; + for (name, a, b) in pairs { + let (a, b, d) = (t.mk(a), t.mk(b), t.mk(&[])); + t.op3("union", x11xfixes::UNION_REGION, a, b, d); + t.fetch(&format!("union.{name}"), d); + t.op3("intersect", x11xfixes::INTERSECT_REGION, a, b, d); + t.fetch(&format!("intersect.{name}"), d); + t.op3("subtract", x11xfixes::SUBTRACT_REGION, a, b, d); + t.fetch(&format!("subtract.{name}"), d); + t.op3("subtract", x11xfixes::SUBTRACT_REGION, b, a, d); + t.fetch(&format!("subtract_rev.{name}"), d); + for r in [a, b, d] { + t.destroy(r); + } + } + + let (a, b) = (t.mk(BIG), t.mk(HOLE)); + t.op3("subtract_inplace", x11xfixes::SUBTRACT_REGION, a, b, a); + t.fetch("subtract_inplace.big_hole", a); + t.op3("union_inplace", x11xfixes::UNION_REGION, a, b, a); + t.fetch("union_inplace.back", a); + t.destroy(a); + t.destroy(b); + + let inv: &[(&str, &[R], R)] = &[ + ("multi", MULTI, (0, 0, 40, 40)), + ("neg", NEG, (-20, -20, 30, 30)), + ("empty", &[], (5, 5, 10, 10)), + ("hole", HOLE, (0, 0, 30, 30)), + ("clamp", BIG, (32000, 32000, 2000, 2000)), + ("outside", HOLE, (100, 100, 5, 5)), + ]; + for (name, rects, bounds) in inv { + let (a, d) = (t.mk(rects), t.mk(&[])); + let mut body = a.to_le_bytes().to_vec(); + body.extend(rect_bytes(&[*bounds])); + body.extend_from_slice(&d.to_le_bytes()); + t.xf("invert", x11xfixes::INVERT_REGION, &body); + t.fetch(&format!("invert.{name}"), d); + t.destroy(a); + t.destroy(d); + } + + let a = t.mk(MULTI); + let translate = |t: &mut Twin, dx: i16, dy: i16| { + let mut body = a.to_le_bytes().to_vec(); + body.extend_from_slice(&dx.to_le_bytes()); + body.extend_from_slice(&dy.to_le_bytes()); + t.xf("translate", x11xfixes::TRANSLATE_REGION, &body); + }; + translate(t, 3, -4); + t.fetch("translate.multi", a); + translate(t, -30, -30); + t.fetch("translate.multi_neg", a); + let d = t.mk(&[]); + t.xf("extents", x11xfixes::REGION_EXTENTS, &xfixes_u32s(&[a, d])); + t.fetch("extents.multi", d); + t.destroy(a); + let a = t.mk(&[]); + t.xf("extents", x11xfixes::REGION_EXTENTS, &xfixes_u32s(&[a, d])); + t.fetch("extents.empty", d); + t.destroy(a); + let a = t.mk(V_ADJ); + t.xf("copy", x11xfixes::COPY_REGION, &xfixes_u32s(&[a, d])); + t.fetch("copy.v_adj", d); + let mut body = d.to_le_bytes().to_vec(); + body.extend(rect_bytes(OVL)); + t.xf("set", x11xfixes::SET_REGION, &body); + t.fetch("set.ovl", d); + t.destroy(a); + t.destroy(d); +} + +#[allow(clippy::too_many_lines)] +fn shape_section(t: &mut Twin) { + use x11shape::{ + KIND_BOUNDING as B, KIND_CLIP as C, KIND_INPUT as I, OP_INTERSECT, OP_INVERT, OP_SET, + OP_SUBTRACT, OP_UNION, ORDERING_UNSORTED as U, ORDERING_Y_SORTED as YS, + ORDERING_YX_BANDED as BAND, ORDERING_YX_SORTED as YX, + }; + t.out.push("== shape unshaped".into()); + let w = t.mkwin(); + t.get_all("unshaped", w); + t.region_from_window("fromwin.unshaped.b", w, B); + t.region_from_window("fromwin.unshaped.c", w, C); + + t.out.push("== shape ops on unshaped windows".into()); + for (name, op) in [ + ("set", OP_SET), + ("union", OP_UNION), + ("intersect", OP_INTERSECT), + ("subtract", OP_SUBTRACT), + ("invert", OP_INVERT), + ] { + for k in 0..=2 { + let v = t.mkwin(); + let tag = format!("fresh.{name}.on{k}"); + t.rects(&tag, v, op, k, U, (0, 0), FRESH); + t.get_all(&tag, v); + } + } + + t.out.push("== shape set orderings".into()); + t.rects("set.multi", w, OP_SET, B, U, (0, 0), MULTI); + t.get_all("set.multi", w); + t.region_from_window("fromwin.multi.b", w, B); + t.rects("set.v_adj.unsorted", w, OP_SET, B, U, (0, 0), V_ADJ); + t.get_shape("set.v_adj.unsorted", w, B); + t.rects("set.v_adj.banded", w, OP_SET, B, BAND, (0, 0), V_ADJ); + t.get_shape("set.v_adj.banded", w, B); + t.region_from_window("fromwin.v_adj.banded", w, B); + t.rects("set.h_adj.banded", w, OP_SET, B, BAND, (0, 0), H_ADJ); + t.get_shape("set.h_adj.banded", w, B); + t.rects("set.h_adj.yxsorted", w, OP_SET, B, YX, (0, 0), H_ADJ); + t.get_shape("set.h_adj.yxsorted", w, B); + t.rects("set.multi.yxsorted_bad", w, OP_SET, B, YX, (0, 0), MULTI); + t.rects("set.ovl.banded_bad", w, OP_SET, B, BAND, (0, 0), OVL); + t.rects("set.ovl.ysorted", w, OP_SET, B, YS, (0, 0), OVL); + t.get_shape("set.ovl.ysorted", w, B); + t.rects("set.zero", w, OP_SET, B, U, (0, 0), ZERO); + t.get_shape("set.zero", w, B); + t.rects("set.empty", w, OP_SET, B, U, (0, 0), &[]); + t.get_all("set.empty", w); + t.rects("set.neg.off", w, OP_SET, B, U, (7, -3), NEG); + t.get_shape("set.neg.off", w, B); + + t.out.push("== shape ops on a shaped window".into()); + t.rects("big", w, OP_SET, B, U, (0, 0), BIG); + t.rects("sub.hole", w, OP_SUBTRACT, B, U, (0, 0), HOLE); + t.get_shape("sub.hole", w, B); + t.rects("union.hole", w, OP_UNION, B, U, (0, 0), HOLE); + t.get_shape("union.hole", w, B); + t.rects("union.multi", w, OP_UNION, B, U, (5, 5), MULTI); + t.get_shape("union.multi", w, B); + t.rects("intersect.stripes", w, OP_INTERSECT, B, U, (0, 0), STRIPES); + t.get_shape("intersect.stripes", w, B); + t.rects("union.stripes_gaps", w, OP_UNION, B, U, (0, 2), STRIPES); + t.get_shape("union.stripes_gaps", w, B); + t.rects("invert.big", w, OP_INVERT, B, U, (0, 0), BIG); + t.get_shape("invert.big", w, B); + t.rects("invert.ell", w, OP_INVERT, B, U, (0, 0), ELL); + t.get_shape("invert.ell", w, B); + t.rects("sub.all", w, OP_SUBTRACT, B, U, (-100, -100), BIG); + t.get_shape("sub.all_offscreen", w, B); + t.offset("offset", B, w, -4, 6); + t.get_shape("offset.b", w, B); + t.get_all("offset.all", w); + + t.out.push("== clip and input kinds".into()); + t.rects("clip.set", w, OP_SET, C, U, (0, 0), MULTI); + t.rects("clip.sub", w, OP_SUBTRACT, C, U, (0, 0), HOLE); + t.get_shape("clip.sub", w, C); + t.region_from_window("fromwin.clip", w, C); + t.rects("input.union_unshaped", w, OP_UNION, I, U, (0, 0), HOLE); + t.get_shape("input.union_unshaped", w, I); + t.rects("input.sub", w, OP_SUBTRACT, I, U, (0, 0), HOLE); + t.get_shape("input.sub", w, I); + t.offset("offset.c", C, w, 2, 2); + t.get_all("offset.c", w); + + t.out.push("== combine from another window".into()); + let src = t.mkwin(); + t.rects("src.set", src, OP_SET, B, U, (0, 0), ELL); + t.combine("combine.union", OP_UNION, B, B, w, (1, 1), src); + t.get_shape("combine.union", w, B); + let unshaped = t.mkwin(); + t.combine("combine.set_unshaped", OP_SET, B, C, w, (0, 0), unshaped); + t.get_shape("combine.set_unshaped_clip", w, B); + t.mask_none("mask.none", B, w); + t.get_all("mask.none", w); +} + +#[allow(clippy::too_many_lines)] +fn translate_section(t: &mut Twin) { + use x11shape::{KIND_BOUNDING as B, OP_SET, ORDERING_UNSORTED as U}; + t.out.push("== translate limits".into()); + let a = t.mk(EDGE); + t.translate(a, 5, 0); + t.fetch("edge.right", a); + t.translate(a, -5, 0); + t.fetch("edge.right.back", a); + t.destroy(a); + let a = t.mk(EDGE_Y); + t.translate(a, 0, 5); + t.fetch("edge.down", a); + t.destroy(a); + let a = t.mk(LOW); + t.translate(a, -5, 0); + t.fetch("edge.left", a); + t.translate(a, 5, 0); + t.fetch("edge.left.back", a); + t.destroy(a); + let a = t.mk(EDGE); + t.translate(a, 7, 0); + t.fetch("edge.exact", a); + t.destroy(a); + let a = t.mk(EDGE); + t.translate(a, 8, 0); + t.fetch_union_hole("edge.gone", a); + t.destroy(a); + let a = t.mk(BANDS); + t.fetch("bands", a); + t.translate(a, 8, 0); + t.fetch("bands.right", a); + t.destroy(a); + let a = t.mk(DIAG); + t.translate(a, 1000, 1000); + t.fetch_union_hole("diag.gone", a); + t.destroy(a); + let a = t.mk(CORNER); + t.translate(a, -32760, -32760); + t.fetch("corner.low", a); + t.translate(a, 32760, 32760); + t.fetch("corner.low.back", a); + t.destroy(a); + let a = t.mk(DOT); + for _ in 0..65540 { + t.translate(a, 32767, 0); + } + t.fetch_union_hole("repeat.right", a); + t.destroy(a); + let a = t.mk(FULL); + t.fetch("full", a); + for _ in 0..4 { + t.translate(a, -32768, -32768); + } + t.fetch_union_hole("repeat.full", a); + t.destroy(a); + + t.out.push("== shape offsets at the limits".into()); + let w = t.mkwin(); + t.rects("rect.off", w, OP_SET, B, U, (32760, 0), BIG); + t.get_shape("rect.off", w, B); + t.offset("offset", B, w, -32760, 0); + t.get_shape("offset.back", w, B); + t.offset("offset", B, w, 32765, 0); + t.get_shape("offset.clip", w, B); + t.offset("offset", B, w, 5, 0); + t.get_shape("offset.gone", w, B); + let src = t.mkwin(); + t.rects("src.set", src, OP_SET, B, U, (0, 0), ELL); + t.combine("combine.off", OP_SET, B, B, w, (32760, 32760), src); + t.get_shape("combine.off", w, B); + let a = t.mk(CORNER); + let mut body = w.to_le_bytes().to_vec(); + body.extend_from_slice(&[B, 0, 0, 0]); + body.extend_from_slice(&(-32760i16).to_le_bytes()); + body.extend_from_slice(&(-32760i16).to_le_bytes()); + body.extend_from_slice(&a.to_le_bytes()); + t.xf( + "xfixes_shape.off", + x11xfixes::SET_WINDOW_SHAPE_REGION, + &body, + ); + t.get_shape("xfixes_shape.off", w, B); + t.destroy(a); + // A 30x30 depth-1 pixmap, all set in the probe; without a pixmap + // mirror the dispatcher takes its bounds, the same region. + let p = t.id(); + t.state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: ResourceId(p), + drawable: ROOT_WINDOW, + width: 30, + height: 30, + depth: 1, + }, + ); + let mut body = vec![OP_SET, B, 0, 0]; + body.extend_from_slice(&w.to_le_bytes()); + body.extend_from_slice(&32760i16.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + body.extend_from_slice(&p.to_le_bytes()); + t.req("mask.off", SHAPE_MAJOR, x11shape::MASK, &body); + t.get_shape("mask.off", w, B); +} + +/// Compare `out` with the golden lines up to (not including) the line +/// `until`, skipping [`KNOWN_DIVERGENT`] tags. +fn compare(out: &[String], until: Option<&str>) { + let golden: Vec<&str> = GOLDEN + .lines() + .take_while(|l| until.is_none_or(|u| *l != u)) + .collect(); + let skip = |l: &str| KNOWN_DIVERGENT.iter().any(|t| l.starts_with(t)); + let mut diffs = Vec::new(); + for (i, g) in golden.iter().enumerate() { + let ours = out.get(i).map_or("", String::as_str); + if ours != *g && !skip(g) { + diffs.push(format!("line {}:\n xephyr {g}\n yserver {ours}", i + 1)); + } + } + if out.len() > golden.len() { + diffs.push(format!( + "extra lines from {}: {}", + golden.len() + 1, + out[golden.len()] + )); + } + assert!( + diffs.is_empty(), + "{} divergences:\n{}", + diffs.len(), + diffs.join("\n") + ); +} + +#[test] +fn xfixes_regions_match_xephyr() { + let mut t = Twin::new(); + xfixes_section(&mut t); + compare(&t.out, Some("== shape unshaped")); +} + +#[test] +fn shape_regions_match_xephyr() { + let mut t = Twin::new(); + xfixes_section(&mut t); + shape_section(&mut t); + compare(&t.out, Some("== translate limits")); +} + +#[test] +fn translations_at_the_limits_match_xephyr() { + let mut t = Twin::new(); + xfixes_section(&mut t); + shape_section(&mut t); + translate_section(&mut t); + compare(&t.out, None); +} + +/// Repeated translations by the largest offset end in the empty region +/// (pixman drops what leaves the 16-bit range) and cannot overflow. +#[test] +fn repeated_translation_cannot_overflow() { + let mut t = Twin::new(); + let a = t.mk(DOT); + for _ in 0..65540 { + t.translate(a, 32767, 0); + } + assert!(t.state.xfixes_regions[&a].region.is_empty()); +} + +/// TranslateRegion clips at the 16-bit limit, as `pixman_region_translate` +/// does (`edge.right` in the golden). +#[test] +fn translate_clips_at_the_16_bit_limit() { + let mut t = Twin::new(); + let a = t.mk(EDGE); + t.translate(a, 5, 0); + t.fetch("clipped", a); + assert_eq!(t.out, ["clipped ext=[32765,0 2x10] n=1 [32765,0 2x10]"]); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/render.rs b/crates/yserver-core/src/core_loop/process_request/tests/render.rs new file mode 100644 index 000000000..1218724e9 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/render.rs @@ -0,0 +1,1327 @@ +use super::*; +use crate::core_loop::process_request::render::render_picture_damage_drawable; + +fn render_damage_fixture( + render_return_region: Vec, +) -> (ServerState, RecordingBackend) { + use crate::{ + backend::PictureHandle, + resources::{PictureKind, PictureState}, + server::DamageObject, + }; + use yserver_protocol::x11::CreateWindowRequest; + + const COMPOSITOR: u32 = 7; + const WIN_XID: u32 = 0x0020_0001; + const SRC_PIC_XID: u32 = 0x0020_0010; + const DST_PIC_XID: u32 = 0x0020_0011; + const DAMAGE_XID: u32 = 0x0020_0020; + const HOST_SRC: u32 = 0xAA01; + const HOST_DST: u32 = 0xAA02; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + backend.render_return_region = render_return_region; + let _peer = install_client(&mut state, COMPOSITOR); + + state.resources.create_window( + ClientId(COMPOSITOR), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + state.resources.create_picture( + ResourceId(SRC_PIC_XID), + PictureState { + client: ClientId(COMPOSITOR), + host_picture_xid: Some(PictureHandle::from_raw_for_test(HOST_SRC)), + host_owned_pixmap: None, + kind: PictureKind::Drawable, + drawable: Some(ResourceId(WIN_XID)), + window: None, + }, + ); + state.resources.create_picture( + ResourceId(DST_PIC_XID), + PictureState { + client: ClientId(COMPOSITOR), + host_picture_xid: Some(PictureHandle::from_raw_for_test(HOST_DST)), + host_owned_pixmap: None, + kind: PictureKind::Drawable, + drawable: Some(ResourceId(WIN_XID)), + window: None, + }, + ); + // The dst window must be MAPPED for these tests to describe a real + // situation. Damage is gated on viewability (issue #97): Xorg's + // `checkPictureDamage` requires `RegionNotEmpty(pCompositeClip)` + // (miext/damage/damage.c:474) and an unmapped window's clip is empty, + // so a RENDER op into it damages nothing there either. Leaving the + // window unmapped made these tests assert damage that Xorg would not + // produce; mapping it keeps each test's real subject — "the render op + // damages exactly the backend-returned region" — intact. + let _ = state.resources.map_window(ResourceId(WIN_XID)); + + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(COMPOSITOR), + drawable: ResourceId(WIN_XID), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + (state, backend) +} + +fn assert_damage_rects_exact( + state: &ServerState, + expected: &[(i16, i16, u16, u16)], + message: &str, +) { + const DAMAGE_XID: u32 = 0x0020_0020; + let damage = state.damage_objects.get(&DAMAGE_XID).unwrap(); + let got: Vec<(i16, i16, u16, u16)> = damage + .rects + .iter() + .map(|r| (r.x, r.y, r.width, r.height)) + .collect(); + assert_eq!(got, expected, "{message}"); +} + +/// RENDER Composite must damage exactly the backend-returned region on +/// the dst picture's underlying drawable. +#[test] +fn render_composite_emits_damage_on_dst_drawable() { + const COMPOSITOR: u32 = 7; + const SRC_PIC_XID: u32 = 0x0020_0010; + const DST_PIC_XID: u32 = 0x0020_0011; + let (mut state, mut backend) = + render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 80, + }]); + + // RENDER Composite body (minor=8, total 32 bytes): + // op(1) + pad(3) + src(4) + mask(4) + dst(4) + src_xy(4) + + // mask_xy(4) + dst_xy(4) + size(4) + let mut body = vec![0u8; 32]; + body[0] = 3; // PictOpOver + body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); + body[8..12].copy_from_slice(&0u32.to_le_bytes()); // no mask + body[12..16].copy_from_slice(&DST_PIC_XID.to_le_bytes()); + body[28..30].copy_from_slice(&100u16.to_le_bytes()); // width + body[30..32].copy_from_slice(&80u16.to_le_bytes()); // height + + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, // RENDER major opcode + data: 8, // minor: Composite + length_units: u32::try_from(1 + 32 / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + + assert_damage_rects_exact( + &state, + &[(0, 0, 100, 80)], + "render_composite must damage exactly the backend-returned region", + ); +} + +#[test] +fn render_trapezoids_damages_returned_region() { + const COMPOSITOR: u32 = 7; + const DST_PIC_XID: u32 = 0x0020_0011; + const SRC_PIC_XID: u32 = 0x0020_0010; + let (mut state, mut backend) = + render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { + x: 3, + y: 4, + width: 20, + height: 30, + }]); + + let mut body = vec![0u8; 60]; + body[0] = 3; + body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); + body[8..12].copy_from_slice(&DST_PIC_XID.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, + data: 10, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + assert_damage_rects_exact( + &state, + &[(3, 4, 20, 30)], + "render_trapezoids must damage exactly the backend-returned region", + ); + + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, + data: 10, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + assert_damage_rects_exact(&state, &[], "empty trapezoid region must not damage"); +} + +#[test] +fn render_triangles_damages_returned_region() { + const COMPOSITOR: u32 = 7; + const DST_PIC_XID: u32 = 0x0020_0011; + const SRC_PIC_XID: u32 = 0x0020_0010; + let (mut state, mut backend) = + render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { + x: 7, + y: 8, + width: 11, + height: 12, + }]); + + let mut body = vec![0u8; 44]; + body[0] = 3; + body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); + body[8..12].copy_from_slice(&DST_PIC_XID.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, + data: 11, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + assert_damage_rects_exact( + &state, + &[(7, 8, 11, 12)], + "render_triangles must damage exactly the backend-returned region", + ); + + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, + data: 11, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + assert_damage_rects_exact(&state, &[], "empty triangle region must not damage"); +} + +#[test] +fn render_composite_glyphs_damages_returned_region() { + const COMPOSITOR: u32 = 7; + const DST_PIC_XID: u32 = 0x0020_0011; + const SRC_PIC_XID: u32 = 0x0020_0010; + const GLYPHSET_XID: u32 = 0x0020_0030; + const HOST_GS: u32 = 0xAA03; + let (mut state, mut backend) = + render_damage_fixture(vec![yserver_protocol::x11::xfixes::RegionRect { + x: 9, + y: 10, + width: 13, + height: 14, + }]); + state.resources.create_glyphset( + ResourceId(GLYPHSET_XID), + crate::resources::GlyphSetState { + client: ClientId(COMPOSITOR), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_GS), + }, + ); + + let mut body = vec![0u8; 28]; + body[0] = 3; + body[4..8].copy_from_slice(&SRC_PIC_XID.to_le_bytes()); + body[8..12].copy_from_slice(&DST_PIC_XID.to_le_bytes()); + body[16..20].copy_from_slice(&GLYPHSET_XID.to_le_bytes()); + body[20..28].copy_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0]); + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, + data: 23, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + assert_damage_rects_exact( + &state, + &[(9, 10, 13, 14)], + "render_composite_glyphs must damage exactly the backend-returned region", + ); + + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + state.resources.create_glyphset( + ResourceId(GLYPHSET_XID), + crate::resources::GlyphSetState { + client: ClientId(COMPOSITOR), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_GS), + }, + ); + process_request( + &mut state, + &mut backend, + ClientId(COMPOSITOR), + SequenceNumber(1), + RequestHeader { + opcode: 133, + data: 23, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .unwrap(); + assert_damage_rects_exact(&state, &[], "empty glyph region must not damage"); +} + +#[test] +fn render_picture_damage_drawable_prefers_named_window_pixmap_owner() { + use crate::{backend::PixmapHandle, resources::NamedCompositePixmap}; + use yserver_protocol::x11::CreateWindowRequest; + + const CLIENT: u32 = 7; + const WINDOW_XID: u32 = 0x0030_0001; + const ALIAS_PIXMAP_XID: u32 = 0x0030_0002; + const ALIAS_PIXMAP_HOST: u32 = 0x0050_0102; + const ORDINARY_PIXMAP_XID: u32 = 0x0030_0003; + + let mut state = ServerState::new(); + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 100, + y: 200, + width: 800, + height: 600, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let window = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window"); + window.composite_named_pixmaps.push(NamedCompositePixmap { + client_pixmap: ResourceId(ALIAS_PIXMAP_XID), + host_pixmap: PixmapHandle::from_raw_for_test(ALIAS_PIXMAP_HOST), + width: 800, + height: 600, + }); + } + assert!( + render_picture_damage_drawable(&state, ResourceId(ALIAS_PIXMAP_XID)) + == ResourceId(WINDOW_XID), + "RENDER pictures created on a NameWindowPixmap alias must route later damage to the \ + owning window XID so XDamageCreate(window) subscriptions wake", + ); + assert!( + render_picture_damage_drawable(&state, ResourceId(ORDINARY_PIXMAP_XID)) + == ResourceId(ORDINARY_PIXMAP_XID), + "ordinary pixmaps must keep their own drawable identity; only Composite aliases \ + remap to the owner window", + ); +} + +// ── RENDER::CreateAnimCursor (opcode 133 / minor 31) helpers ───────────── + +fn anim_cursor_body(cid: u32, elts: &[(u32, u32)]) -> Vec { + let mut b = cid.to_le_bytes().to_vec(); + for (cur, delay) in elts { + b.extend_from_slice(&cur.to_le_bytes()); + b.extend_from_slice(&delay.to_le_bytes()); + } + b +} + +fn seed_cursor(state: &mut ServerState, raw: u32, host: u32) { + state.resources.create_cursor(ClientId(1), ResourceId(raw)); + state.resources.set_cursor_host_xid( + ResourceId(raw), + crate::backend::CursorHandle::from_raw(host).unwrap(), + ); +} + +fn send_anim_cursor( + state: &mut ServerState, + backend: &mut RecordingBackend, + seq: u16, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(1), + SequenceNumber(seq), + RequestHeader { + opcode: 133, + data: 31, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("process_request"); +} + +#[test] +fn create_anim_cursor_empty_list_returns_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = anim_cursor_body(0x4000, &[]); + send_anim_cursor(&mut state, &mut backend, 1, &body); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "expected error reply, got {bytes:02x?}"); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert_eq!(&bytes[8..10], &31u16.to_le_bytes()); + assert_eq!(bytes[10], 133); + assert!(!state.resources.cursor_exists(ResourceId(0x4000))); +} + +#[test] +fn create_anim_cursor_odd_pairs_returns_bad_length() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_cursor(&mut state, 0x3000, 0x77); + // One full pair + 4 trailing bytes = not a multiple of 8. + let mut body = anim_cursor_body(0x4000, &[(0x3000, 50)]); + body.extend_from_slice(&0x3000u32.to_le_bytes()); + send_anim_cursor(&mut state, &mut backend, 1, &body); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32); + assert_eq!(bytes[1], x11::error::BAD_LENGTH); + assert_eq!(&bytes[8..10], &31u16.to_le_bytes()); + assert_eq!(bytes[10], 133); + assert!(!state.resources.cursor_exists(ResourceId(0x4000))); +} + +#[test] +fn create_anim_cursor_nested_anim_returns_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_cursor(&mut state, 0x3000, 0x77); + // First anim cursor (fallback path on RecordingBackend). + let body = anim_cursor_body(0x4000, &[(0x3000, 50)]); + send_anim_cursor(&mut state, &mut backend, 1, &body); + let _ = read_all_available(&mut peer); // no error expected + assert!(state.resources.cursor_is_anim(ResourceId(0x4000))); + // Second anim cursor referencing the first → BadMatch. + let body2 = anim_cursor_body(0x4001, &[(0x4000, 50)]); + send_anim_cursor(&mut state, &mut backend, 2, &body2); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32); + assert_eq!(bytes[1], x11::error::BAD_MATCH); + // Xorg's AnimCursorCreate returns BadMatch without setting + // client->errorValue → value field must be zero. + assert_eq!(&bytes[4..8], &0u32.to_le_bytes()); + assert_eq!(&bytes[8..10], &31u16.to_le_bytes()); + assert_eq!(bytes[10], 133); + assert!(!state.resources.cursor_exists(ResourceId(0x4001))); +} + +#[test] +fn create_anim_cursor_fallback_aliases_first_frame_and_sets_anim() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_cursor(&mut state, 0x3000, 0x77); + seed_cursor(&mut state, 0x3001, 0x78); + let body = anim_cursor_body(0x4000, &[(0x3000, 50), (0x3001, 75)]); + send_anim_cursor(&mut state, &mut backend, 1, &body); + let bytes = read_all_available(&mut peer); + assert!(bytes.is_empty(), "no error expected, got {bytes:02x?}"); + assert_eq!( + state.resources.cursor_host_xid(ResourceId(0x4000)), + Some(0x77) + ); + assert!(state.resources.cursor_is_anim(ResourceId(0x4000))); +} + +// ── Step 3 (window-storage lifecycle): Pictures on windows ────────── + +const PIC_A: u32 = 0x0030_0000; +const PIC_B: u32 = 0x0040_0000; +const PIC_WIN: u32 = PIC_A | 1; +const PIC_WIN_HOST: u32 = 0x00E0_0001; +const PIC_ON_WIN: u32 = PIC_B | 1; +const PIC_PIXMAP: u32 = PIC_B | 2; +const PIC_ON_PIXMAP: u32 = PIC_B | 3; + +fn picture_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + opcode: u8, + data: u8, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(client), + SequenceNumber(1), + RequestHeader { + opcode, + data, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .unwrap(); +} + +/// `(error code, bad value)` of every error queued on `peer`. +fn drain_errors(peer: &mut UnixStream) -> Vec<(u8, u32)> { + peer.set_nonblocking(true).unwrap(); + let mut out = Vec::new(); + let mut buf = [0u8; 32]; + while peer.read_exact(&mut buf).is_ok() { + if buf[0] == 0 { + out.push((buf[1], u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]))); + } + } + out +} + +fn drain_error_details(peer: &mut UnixStream) -> Vec<(u8, u32, u16, u8)> { + peer.set_nonblocking(true).unwrap(); + let mut out = Vec::new(); + let mut buf = [0u8; 32]; + while peer.read_exact(&mut buf).is_ok() { + if buf[0] == 0 { + out.push(( + buf[1], + u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]), + u16::from_le_bytes([buf[8], buf[9]]), + buf[10], + )); + } + } + out +} + +fn create_render_picture( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + pic: u32, + drawable: u32, +) { + let mut body = Vec::new(); + for v in [pic, drawable, 0, 0] { + body.extend_from_slice(&v.to_le_bytes()); + } + picture_request(state, backend, client, 133, 4, &body); +} + +fn render_fill(state: &mut ServerState, backend: &mut RecordingBackend, client: u32, dst: u32) { + let mut body = vec![1u8, 0, 0, 0]; + body.extend_from_slice(&dst.to_le_bytes()); + body.extend_from_slice(&[0xff; 8]); + for v in [0i16, 0] { + body.extend_from_slice(&v.to_le_bytes()); + } + for v in [8u16, 8] { + body.extend_from_slice(&v.to_le_bytes()); + } + picture_request(state, backend, client, 133, 26, &body); +} + +fn render_composite_pics( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + src: u32, + dst: u32, +) { + let mut body = vec![0u8; 32]; + body[0] = 3; + body[4..8].copy_from_slice(&src.to_le_bytes()); + body[12..16].copy_from_slice(&dst.to_le_bytes()); + body[28..30].copy_from_slice(&8u16.to_le_bytes()); + body[30..32].copy_from_slice(&8u16.to_le_bytes()); + picture_request(state, backend, client, 133, 8, &body); +} + +fn render_free(state: &mut ServerState, backend: &mut RecordingBackend, client: u32, pic: u32) { + picture_request(state, backend, client, 133, 7, &pic.to_le_bytes()); +} + +fn host_pic_of(state: &ServerState, pic: u32) -> u32 { + state + .resources + .picture(ResourceId(pic)) + .expect("picture exists") + .host_picture_xid + .expect("backed picture") + .as_raw() +} + +fn render_paints(backend: &RecordingBackend) -> Vec { + backend + .calls() + .into_iter() + .filter(|c| { + matches!( + c, + RecordedCall::RenderComposite { .. } | RecordedCall::RenderFillRectangles { .. } + ) + }) + .collect() +} + +fn composite_glyph_items_with_switch(minor: u8, glyphset: u32) -> (Vec, usize) { + let id_size = match minor { + 23 => 1, + 24 => 2, + 25 => 4, + _ => unreachable!(), + }; + let mut items = vec![2, 0, 0, 0, 0, 0, 0, 0]; + let payload_bytes = 2 * id_size; + items.extend((0..payload_bytes).map(|n| u8::try_from(n).unwrap())); + items.resize(items.len() + ((4 - payload_bytes % 4) % 4), 0); + + let switch_offset = items.len(); + items.extend_from_slice(&yserver_protocol::x11::render_composite_glyphset_switch( + glyphset, + )); + items.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0]); + items.extend(std::iter::repeat_n(0, id_size)); + items.resize(items.len() + ((4 - id_size % 4) % 4), 0); + (items, switch_offset) +} + +fn dispatch_composite_glyphs( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + minor: u8, + glyphset: u32, + items: &[u8], +) { + const SRC_PIC: u32 = 0x0020_0010; + const DST_PIC: u32 = 0x0020_0011; + let mut body = vec![0u8; 24]; + body[0] = 3; + body[4..8].copy_from_slice(&SRC_PIC.to_le_bytes()); + body[8..12].copy_from_slice(&DST_PIC.to_le_bytes()); + body[16..20].copy_from_slice(&glyphset.to_le_bytes()); + body.extend_from_slice(items); + picture_request(state, backend, client, 133, minor, &body); +} + +fn create_render_picture_with_values( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + picture: u32, + drawable: u32, + value_mask: u32, + values: &[u8], +) { + let mut body = Vec::with_capacity(16 + values.len()); + for value in [picture, drawable, 0, value_mask] { + body.extend_from_slice(&value.to_le_bytes()); + } + body.extend_from_slice(values); + picture_request(state, backend, client, 133, 4, &body); +} + +#[test] +fn composite_glyphs_switch_is_translated_to_backend_handle() { + // Mutation: forward the item bytes unchanged. + const CLIENT: u32 = 7; + const G1: u32 = 0x0020_0030; + const G2: u32 = 0x0020_0031; + const HOST_G1: u32 = 0xAA03; + const HOST_G2: u32 = 0xAA04; + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + for (xid, host) in [(G1, HOST_G1), (G2, HOST_G2)] { + state.resources.create_glyphset( + ResourceId(xid), + crate::resources::GlyphSetState { + client: ClientId(CLIENT), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(host), + }, + ); + } + + for (minor, switch_offset) in [(23, 12), (24, 12), (25, 16)] { + let (items, actual_switch_offset) = composite_glyph_items_with_switch(minor, G2); + assert_eq!(actual_switch_offset, switch_offset); + dispatch_composite_glyphs(&mut state, &mut backend, CLIENT, minor, G1, &items); + + let calls = backend.calls(); + let call = calls.iter().find_map(|call| match call { + RecordedCall::RenderCompositeGlyphs { + minor: got_minor, + host_gs, + items, + .. + } if *got_minor == minor => Some((*host_gs, items)), + _ => None, + }); + let (host_gs, forwarded_items) = call.expect("backend composite glyph call"); + assert_eq!(host_gs, HOST_G1); + assert_eq!( + u32::from_le_bytes( + forwarded_items[switch_offset + 8..switch_offset + 12] + .try_into() + .unwrap() + ), + HOST_G2, + "minor {minor} switch item must carry G2's backend handle", + ); + backend.calls.lock().unwrap().clear(); + } +} + +#[test] +fn composite_glyphs_switch_to_non_glyphset_is_bad_glyphset() { + // Mutation: forward an unknown switch as backend handle 0 instead of returning BadGlyphSet. + const CLIENT: u32 = 7; + const OTHER_CLIENT: u32 = 8; + const G1: u32 = 0x0020_0030; + const OTHER_GLYPHSET: u32 = 0x0030_0030; + const HOST_G1: u32 = 0xAA03; + const OTHER_HOST_GLYPHSET: u32 = 0xAA04; + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + let mut peer = install_client(&mut state, CLIENT); + let _other_peer = install_client(&mut state, OTHER_CLIENT); + state.resources.create_glyphset( + ResourceId(G1), + crate::resources::GlyphSetState { + client: ClientId(CLIENT), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_G1), + }, + ); + state.resources.create_glyphset( + ResourceId(OTHER_GLYPHSET), + crate::resources::GlyphSetState { + client: ClientId(OTHER_CLIENT), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test( + OTHER_HOST_GLYPHSET, + ), + }, + ); + assert!( + state + .resources + .glyphset(ResourceId(OTHER_HOST_GLYPHSET)) + .is_none() + ); + for minor in [23, 24, 25] { + backend.calls.lock().unwrap().clear(); + let (items, _) = composite_glyph_items_with_switch(minor, OTHER_HOST_GLYPHSET); + + dispatch_composite_glyphs(&mut state, &mut backend, CLIENT, minor, G1, &items); + + assert_eq!( + drain_error_details(&mut peer), + vec![( + crate::nested::RENDER_BAD_GLYPHSET_ERROR, + OTHER_HOST_GLYPHSET, + u16::from(minor), + 133, + )], + "minor {minor} must report the invalid client glyphset XID", + ); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::RenderCompositeGlyphs { .. })), + "minor {minor} must reject the entire request before forwarding", + ); + } +} + +#[test] +fn composite_glyphs_bad_switch_after_good_glyphs_draws_nothing() { + // Mutation: validate the switch only after forwarding the preceding glyph run. + const CLIENT: u32 = 7; + const G1: u32 = 0x0020_0030; + const BAD_GLYPHSET: u32 = 0xDEAD_BEEF; + const HOST_G1: u32 = 0xAA03; + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + let mut peer = install_client(&mut state, CLIENT); + state.resources.create_glyphset( + ResourceId(G1), + crate::resources::GlyphSetState { + client: ClientId(CLIENT), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_G1), + }, + ); + backend.calls.lock().unwrap().clear(); + + let mut items = vec![1, 0, 0, 0, 0, 0, 0, 0, 0x10, 0, 0, 0]; + items.extend_from_slice(&yserver_protocol::x11::render_composite_glyphset_switch( + BAD_GLYPHSET, + )); + items.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0x20, 0, 0, 0]); + + dispatch_composite_glyphs(&mut state, &mut backend, CLIENT, 23, G1, &items); + + assert_eq!( + drain_error_details(&mut peer), + vec![( + crate::nested::RENDER_BAD_GLYPHSET_ERROR, + BAD_GLYPHSET, + 23, + 133, + )], + ); + assert!( + backend + .calls() + .iter() + .all(|call| !matches!(call, RecordedCall::RenderCompositeGlyphs { .. })), + "a later bad switch rejects earlier glyphs too", + ); +} + +#[test] +fn composite_glyphs_switch_at_stream_end_is_not_checked() { + // Mutation: use `<=` for Xorg's strict switch lookup boundary. + const CLIENT: u32 = 7; + const G1: u32 = 0x0020_0030; + const FINAL_UNKNOWN_GLYPHSET: u32 = 0xDEAD_BEEF; + const HOST_G1: u32 = 0xAA03; + let (mut state, mut backend) = render_damage_fixture(Vec::new()); + let mut peer = install_client(&mut state, CLIENT); + state.resources.create_glyphset( + ResourceId(G1), + crate::resources::GlyphSetState { + client: ClientId(CLIENT), + host_glyphset_xid: crate::backend::GlyphSetHandle::from_raw_for_test(HOST_G1), + }, + ); + backend.calls.lock().unwrap().clear(); + let items = yserver_protocol::x11::render_composite_glyphset_switch(FINAL_UNKNOWN_GLYPHSET); + + dispatch_composite_glyphs(&mut state, &mut backend, CLIENT, 23, G1, &items); + + assert!(drain_error_details(&mut peer).is_empty()); + assert!(backend.calls().iter().any(|call| matches!( + call, + RecordedCall::RenderCompositeGlyphs { items: forwarded, .. } + if forwarded == &items + ))); +} + +#[test] +fn create_picture_alpha_map_and_clip_mask_are_translated() { + // Mutation: pass req.values unchanged. + const PICTURE: u32 = PIC_B | 14; + const VALUE_MASK: u32 = (1 << 0) | (1 << 1) | (1 << 6); + let (mut state, mut backend, _peer_a, _peer_b) = cross_client_picture_fixture(); + let alpha_map = host_pic_of(&state, PIC_ON_WIN); + const CLIP_MASK: u32 = 0x00E0_0100; + assert_ne!(alpha_map, PIC_ON_WIN); + assert_ne!(CLIP_MASK, PIC_PIXMAP); + backend.calls.lock().unwrap().clear(); + + let mut values = Vec::new(); + for value in [1u32, PIC_ON_WIN, PIC_PIXMAP] { + values.extend_from_slice(&value.to_le_bytes()); + } + create_render_picture_with_values( + &mut state, + &mut backend, + 2, + PICTURE, + PIC_PIXMAP, + VALUE_MASK, + &values, + ); + + let call = backend.calls().into_iter().find_map(|call| match call { + RecordedCall::RenderCreatePicture { + value_mask, values, .. + } => Some((value_mask, values)), + _ => None, + }); + let (value_mask, got_values) = call.expect("backend create picture call"); + assert_eq!(value_mask, VALUE_MASK); + let mut expected_values = Vec::new(); + for value in [1u32, alpha_map, CLIP_MASK] { + expected_values.extend_from_slice(&value.to_le_bytes()); + } + assert_eq!(got_values, expected_values); +} + +#[test] +fn create_picture_unresolved_alpha_map_still_registers_picture() { + // Mutation: drop the request as ChangePicture does. + const PICTURE: u32 = PIC_B | 15; + const UNKNOWN_PICTURE: u32 = PIC_B | 16; + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + backend.calls.lock().unwrap().clear(); + + let mut values = Vec::new(); + values.extend_from_slice(&1u32.to_le_bytes()); // CPRepeat remains scalar. + values.extend_from_slice(&UNKNOWN_PICTURE.to_le_bytes()); // unresolved CPAlphaMap. + create_render_picture_with_values( + &mut state, + &mut backend, + 2, + PICTURE, + PIC_PIXMAP, + (1 << 0) | (1 << 1), + &values, + ); + + assert!(state.resources.picture(ResourceId(PICTURE)).is_some()); + let call = backend.calls().into_iter().find_map(|call| match call { + RecordedCall::RenderCreatePicture { values, .. } => Some(values), + _ => None, + }); + let mut expected_values = Vec::new(); + expected_values.extend_from_slice(&1u32.to_le_bytes()); + expected_values.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(call.expect("backend create picture call"), expected_values); + + let mut transform = vec![0u8; 40]; + transform[..4].copy_from_slice(&PICTURE.to_le_bytes()); + picture_request(&mut state, &mut backend, 2, 133, 28, &transform); + assert!(drain_errors(&mut peer_b).is_empty()); +} + +#[test] +fn change_picture_unresolved_alpha_map_still_drops_request() { + // Mutation: forward 0 as CreatePicture does. + const UNKNOWN_PICTURE: u32 = PIC_B | 17; + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + backend.calls.lock().unwrap().clear(); + let mut body = Vec::new(); + let value_mask: u32 = (1 << 0) | (1 << 1); + body.extend_from_slice(&PIC_ON_WIN.to_le_bytes()); + body.extend_from_slice(&value_mask.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); // CPRepeat scalar. + body.extend_from_slice(&UNKNOWN_PICTURE.to_le_bytes()); // unresolved CPAlphaMap. + + picture_request(&mut state, &mut backend, 2, 133, 5, &body); + + assert!(drain_errors(&mut peer_b).is_empty()); + assert!( + backend + .calls() + .iter() + .all(|call| { !matches!(call, RecordedCall::RenderChangePicture { .. }) }) + ); +} + +/// Client A owns a mapped top-level `PIC_WIN`; client B holds a Picture on it and +/// one on its own pixmap. +fn cross_client_picture_fixture() -> (ServerState, RecordingBackend, UnixStream, UnixStream) { + let mut state = ServerState::new(); + let peer_a = install_client(&mut state, 1); + let peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + create_pic_test_window(&mut state, PIC_WIN, PIC_WIN_HOST); + state.resources.create_pixmap( + ClientId(2), + CreatePixmapRequest { + pixmap: ResourceId(PIC_PIXMAP), + drawable: ROOT_WINDOW, + width: 16, + height: 16, + depth: 24, + }, + ); + assert!(state.resources.set_pixmap_host_xid( + ResourceId(PIC_PIXMAP), + crate::backend::PixmapHandle::from_raw_for_test(0x00E0_0100), + )); + create_render_picture(&mut state, &mut backend, 2, PIC_ON_WIN, PIC_WIN); + create_render_picture(&mut state, &mut backend, 2, PIC_ON_PIXMAP, PIC_PIXMAP); + (state, backend, peer_a, peer_b) +} + +fn create_pic_test_window(state: &mut ServerState, xid: u32, host: u32) { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + width: 64, + height: 64, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(xid)) + .unwrap() + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(host)); + let _ = state.resources.map_window(ResourceId(xid)); +} + +/// B's Picture on A's window is dead once the window is gone: every use and +/// its FreePicture are BadPicture, its pixmap Picture is untouched, and a new +/// window on the same xid and host storage does not revive it. +fn assert_window_picture_dead_after(destroy: impl FnOnce(&mut ServerState, &mut RecordingBackend)) { + let bad_picture = crate::nested::RENDER_FIRST_ERROR + 1; + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + let host_on_win = host_pic_of(&state, PIC_ON_WIN); + let host_on_pixmap = host_pic_of(&state, PIC_ON_PIXMAP); + + destroy(&mut state, &mut backend); + + assert!(state.resources.picture(ResourceId(PIC_ON_WIN)).is_none()); + let freed: Vec = backend + .calls() + .into_iter() + .filter_map(|c| match c { + RecordedCall::RenderFreePicture { host_pic } => Some(host_pic), + _ => None, + }) + .collect(); + assert_eq!( + freed, + vec![host_on_win], + "only the window Picture's backend record is freed" + ); + assert_eq!(host_pic_of(&state, PIC_ON_PIXMAP), host_on_pixmap); + backend.calls.lock().unwrap().clear(); + + create_pic_test_window(&mut state, PIC_WIN, PIC_WIN_HOST); + render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); + render_composite_pics(&mut state, &mut backend, 2, PIC_ON_WIN, PIC_ON_PIXMAP); + render_free(&mut state, &mut backend, 2, PIC_ON_WIN); + assert_eq!( + drain_errors(&mut peer_b), + vec![(bad_picture, PIC_ON_WIN); 3], + "FillRectangles, Composite and FreePicture on the dead Picture", + ); + assert!(render_paints(&backend).is_empty()); + assert!( + !backend + .calls() + .iter() + .any(|c| matches!(c, RecordedCall::RenderFreePicture { .. })) + ); + + render_fill(&mut state, &mut backend, 2, PIC_ON_PIXMAP); + assert_eq!( + render_paints(&backend), + vec![RecordedCall::RenderFillRectangles { + host_dst: host_on_pixmap + }], + ); + assert!(drain_errors(&mut peer_b).is_empty()); +} + +#[test] +fn destroy_window_frees_other_clients_pictures_on_it() { + assert_window_picture_dead_after(|state, backend| { + picture_request(state, backend, 1, 4, 0, &PIC_WIN.to_le_bytes()); + }); +} + +#[test] +fn owner_disconnect_frees_other_clients_pictures_on_its_windows() { + assert_window_picture_dead_after(|state, backend| { + crate::core_loop::process_disconnect::process_disconnect(state, backend, ClientId(1)); + let _peer = install_client(state, 1); + }); +} + +#[test] +fn destroying_a_parent_frees_pictures_on_its_descendants() { + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + const CHILD: u32 = PIC_A | 2; + const PIC_ON_CHILD: u32 = PIC_B | 4; + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD), + parent: ResourceId(PIC_WIN), + width: 8, + height: 8, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(CHILD)) + .unwrap() + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(0x00E0_0002)); + create_render_picture(&mut state, &mut backend, 2, PIC_ON_CHILD, CHILD); + assert!(state.resources.picture(ResourceId(PIC_ON_CHILD)).is_some()); + + picture_request(&mut state, &mut backend, 1, 4, 0, &PIC_WIN.to_le_bytes()); + + assert!(state.resources.picture(ResourceId(PIC_ON_CHILD)).is_none()); + assert!(state.resources.picture(ResourceId(PIC_ON_WIN)).is_none()); + assert!(state.resources.picture(ResourceId(PIC_ON_PIXMAP)).is_some()); + assert!(drain_errors(&mut peer_b).is_empty()); +} + +/// Xorg: an unviewable window's clipList is empty, so a Picture on it as the +/// destination draws nothing; the same Picture draws again after remap. +#[test] +fn window_picture_draws_nothing_while_unmapped_and_again_after_remap() { + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + let host_on_win = host_pic_of(&state, PIC_ON_WIN); + let host_on_pixmap = host_pic_of(&state, PIC_ON_PIXMAP); + let fill = RecordedCall::RenderFillRectangles { + host_dst: host_on_win, + }; + + render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); + assert_eq!(render_paints(&backend), vec![fill.clone()]); + backend.calls.lock().unwrap().clear(); + + picture_request(&mut state, &mut backend, 1, 10, 0, &PIC_WIN.to_le_bytes()); + render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); + render_composite_pics(&mut state, &mut backend, 2, PIC_ON_PIXMAP, PIC_ON_WIN); + assert!( + render_paints(&backend).is_empty(), + "unmapped: nothing drawn" + ); + // As a source the hidden window's contents are undefined, not an error. + render_composite_pics(&mut state, &mut backend, 2, PIC_ON_WIN, PIC_ON_PIXMAP); + assert_eq!( + render_paints(&backend), + vec![RecordedCall::RenderComposite { + host_src: host_on_win, + host_dst: host_on_pixmap, + }], + ); + backend.calls.lock().unwrap().clear(); + + picture_request(&mut state, &mut backend, 1, 8, 0, &PIC_WIN.to_le_bytes()); + render_fill(&mut state, &mut backend, 2, PIC_ON_WIN); + assert_eq!(render_paints(&backend), vec![fill]); + assert!(drain_errors(&mut peer_b).is_empty()); +} + +/// A Picture on a redirected window names the window, not the backing it +/// has at creation time, so it follows backing rotations. +#[test] +fn create_picture_on_redirected_window_names_the_window() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + create_pic_test_window(&mut state, PIC_WIN, PIC_WIN_HOST); + state + .resources + .window_mut(ResourceId(PIC_WIN)) + .unwrap() + .redirected_backing = Some(crate::resources::RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(0x00E0_0200), + width: 64, + height: 64, + depth: 24, + }); + create_render_picture(&mut state, &mut backend, 1, PIC_A | 5, PIC_WIN); + let host_drawables: Vec = backend + .calls() + .into_iter() + .filter_map(|c| match c { + RecordedCall::RenderCreatePicture { host_drawable, .. } => Some(host_drawable), + _ => None, + }) + .collect(); + assert_eq!( + host_drawables, + vec![crate::backend::AnyHandle::Window( + crate::backend::WindowHandle::from_raw_for_test(PIC_WIN_HOST) + )], + ); + assert_eq!( + state + .resources + .picture(ResourceId(PIC_A | 5)) + .unwrap() + .window, + Some(ResourceId(PIC_WIN)), + ); +} + +/// Xorg `compDestroyOverlayWindow` frees the overlay through DeleteWindow, so +/// Pictures on it are freed with it (`composite/compoverlay.c:167-172`). +#[test] +fn overlay_release_frees_pictures_on_the_overlay() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut body = vec![0u8; 4]; + body[0..4].copy_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 1, + yserver_protocol::x11::composite::GET_OVERLAY_WINDOW, + &body, + ); + drain_errors(&mut peer); + create_render_picture(&mut state, &mut backend, 1, PIC_A | 6, cow.0); + assert!(state.resources.picture(ResourceId(PIC_A | 6)).is_some()); + body[0..4].copy_from_slice(&cow.0.to_le_bytes()); + dispatch_composite_minor( + &mut state, + &mut backend, + ClientId(1), + 2, + yserver_protocol::x11::composite::RELEASE_OVERLAY_WINDOW, + &body, + ); + assert!(state.resources.window(cow).is_none()); + assert!(state.resources.picture(ResourceId(PIC_A | 6)).is_none()); +} + +/// CreateConicalGradient registers a Picture: usable as a source without an +/// error (drawing with it stays unimplemented) and freeable. +#[test] +fn conical_gradient_picture_is_usable_as_source_and_freeable() { + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + const CONICAL: u32 = PIC_B | 9; + let mut body = Vec::new(); + body.extend_from_slice(&CONICAL.to_le_bytes()); + body.extend_from_slice(&[0u8; 16]); // center, angle, nstops = 0 + picture_request(&mut state, &mut backend, 2, 133, 36, &body); + assert!(state.resources.picture(ResourceId(CONICAL)).is_some()); + backend.calls.lock().unwrap().clear(); + render_composite_pics(&mut state, &mut backend, 2, CONICAL, PIC_ON_PIXMAP); + assert!( + render_paints(&backend).is_empty(), + "unbacked source draws nothing" + ); + render_free(&mut state, &mut backend, 2, CONICAL); + assert!(state.resources.picture(ResourceId(CONICAL)).is_none()); + assert!(drain_errors(&mut peer_b).is_empty()); +} + +/// A CreatePicture the backend could not back still succeeds at protocol level: +/// ops on the Picture are silent no-ops and FreePicture is valid. An id that was +/// never created is still BadPicture. +#[test] +fn unbacked_picture_ops_are_silent_no_ops() { + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + const UNBACKED: u32 = PIC_B | 10; + backend.render_create_picture_fails = true; + create_render_picture(&mut state, &mut backend, 2, UNBACKED, PIC_PIXMAP); + backend.render_create_picture_fails = false; + let st = state + .resources + .picture(ResourceId(UNBACKED)) + .expect("registered"); + assert!(st.host_picture_xid.is_none()); + backend.calls.lock().unwrap().clear(); + + render_fill(&mut state, &mut backend, 2, UNBACKED); + render_composite_pics(&mut state, &mut backend, 2, UNBACKED, PIC_ON_PIXMAP); + render_composite_pics(&mut state, &mut backend, 2, PIC_ON_PIXMAP, UNBACKED); + render_free(&mut state, &mut backend, 2, UNBACKED); + assert!(drain_errors(&mut peer_b).is_empty()); + assert!(state.resources.picture(ResourceId(UNBACKED)).is_none()); + assert!(backend.calls().iter().all(|c| !matches!( + c, + RecordedCall::RenderComposite { .. } + | RecordedCall::RenderFillRectangles { .. } + | RecordedCall::RenderFreePicture { .. } + ))); + + const NEVER: u32 = PIC_B | 11; + render_fill(&mut state, &mut backend, 2, NEVER); + assert_eq!( + drain_errors(&mut peer_b), + vec![(crate::nested::RENDER_FIRST_ERROR + 1, NEVER)], + ); +} + +/// Xorg dixLookupDrawable: CreatePicture on an unknown drawable is BadDrawable +/// and registers nothing. +#[test] +fn create_picture_on_unknown_drawable_is_bad_drawable() { + let (mut state, mut backend, _peer_a, mut peer_b) = cross_client_picture_fixture(); + const PIC: u32 = PIC_B | 12; + create_render_picture(&mut state, &mut backend, 2, PIC, 0x00DE_AD00); + assert_eq!( + drain_errors(&mut peer_b), + vec![(x11::error::BAD_DRAWABLE, 0x00DE_AD00)], + ); + assert!(state.resources.picture(ResourceId(PIC)).is_none()); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/saver_dpms.rs b/crates/yserver-core/src/core_loop/process_request/tests/saver_dpms.rs new file mode 100644 index 000000000..e83183bb0 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/saver_dpms.rs @@ -0,0 +1,1107 @@ +use super::*; +use crate::resources::MapState; + +struct DenyAllAccessPolicy; + +impl crate::access::AccessPolicy for DenyAllAccessPolicy { + fn resource( + &self, + _ctx: &crate::access::AccessContext<'_>, + _client: ClientId, + _target: &crate::access::ResourceTarget, + _mode: crate::access::AccessMode, + ) -> crate::access::Decision { + crate::access::Decision::Deny(crate::access::DenyError { + code: x11::error::BAD_ACCESS, + value: 0, + }) + } +} + +#[test] +fn dpms_force_level_rejects_when_disabled() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = false; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 134, + data: 6, + length_units: 2, + }; + let body = [3u8, 0, 0, 0]; // level=Off + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + let calls = backend.calls(); + assert!( + !calls + .iter() + .any(|c| matches!(c, RecordedCall::SetDpmsPower(_))), + "ForceLevel must not call backend when !enabled" + ); + assert_eq!(state.dpms.power_level, 0, "state unchanged on BadMatch"); + // Error reply: byte 0 == 0 (Error), byte 1 == x11::error::BAD_MATCH. + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0, "reply is an X11 error"); + assert_eq!(bytes[1], x11::error::BAD_MATCH); +} + +#[test] +fn dpms_force_level_changes_state_and_notifies() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.selected_by.insert(ClientId(1)); + let header = RequestHeader { + opcode: 134, + data: 6, + length_units: 2, + }; + let body = [3u8, 0, 0, 0]; // level=Off + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + assert_eq!(state.dpms.power_level, 3); + assert!( + backend + .calls() + .iter() + .any(|c| matches!(c, RecordedCall::SetDpmsPower(3))) + ); + // GenericEvent tag = 35 should appear exactly once in this client's stream. + let bytes = read_all_available(&mut peer); + let notifies = bytes.iter().filter(|&&b| b == 35).count(); + assert_eq!(notifies, 1, "ForceLevel(Off) from On: exactly one notify"); +} + +#[test] +fn dpms_disable_from_off_emits_two_notifies() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + state.dpms.power_level = 3; // Off + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.selected_by.insert(ClientId(1)); + let header = RequestHeader { + opcode: 134, + data: 5, + length_units: 1, + }; // Disable + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[], + ); + // First notify: Off→On (level change). Second: enabled true→false. + let bytes = read_all_available(&mut peer); + let notifies = bytes.iter().filter(|&&b| b == 35).count(); + assert_eq!(notifies, 2, "Disable from Off must emit two XGE notifies"); + assert!(!state.dpms.enabled); + assert_eq!(state.dpms.power_level, 0); + // Verify ordering: byte 18 of each event is the `state` + // (enabled) field. The first event fires from + // apply_dpms_transition before `enabled` is cleared, so it + // should show enabled=1; the second event fires after the + // enable flip, so it should show enabled=0. + assert_eq!( + bytes[18], 1, + "first notify is the level-change notify; enabled still true" + ); + assert_eq!( + bytes[32 + 18], + 0, + "second notify is the enable-change notify; enabled now false" + ); +} + +#[test] +fn dpms_disable_from_on_emits_one_notify() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.selected_by.insert(ClientId(1)); + let header = RequestHeader { + opcode: 134, + data: 5, + length_units: 1, + }; + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[], + ); + let bytes = read_all_available(&mut peer); + let notifies = bytes.iter().filter(|&&b| b == 35).count(); + assert_eq!( + notifies, 1, + "Disable from On: only the enable-change notify fires" + ); + assert!(!state.dpms.enabled); +} + +#[test] +fn dpms_enable_when_already_enabled_emits_no_notify() { + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.selected_by.insert(ClientId(1)); + let header = RequestHeader { + opcode: 134, + data: 4, + length_units: 1, + }; // Enable + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[], + ); + let bytes = read_all_available(&mut peer); + assert!(!bytes.contains(&35), "no notify when state didn't change"); +} + +#[test] +fn dpms_set_timeouts_rejects_inverted_ordering() { + // off=10 but suspend=20 violates the non-zero + // off >= suspend ordering — must produce BadValue. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 134, + data: 3, + length_units: 2, + }; // SetTimeouts + // Body: standby=30, suspend=20, off=10, pad=0 — clearly out of order. + let body = [30u8, 0, 20, 0, 10, 0, 0, 0]; + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0, "reply is an X11 error"); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + // Timeouts must NOT have been stored. + assert_eq!(state.dpms.standby_ms, 600_000); + assert_eq!(state.dpms.suspend_ms, 600_000); + assert_eq!(state.dpms.off_ms, 600_000); +} + +#[test] +fn dpms_select_input_zero_removes_subscriber() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Pre-seed: client is already subscribed. + state.dpms.selected_by.insert(ClientId(1)); + assert!(state.dpms.selected_by.contains(&ClientId(1))); + + let header = RequestHeader { + opcode: 134, + data: 8, + length_units: 2, + }; // SelectInput + let body = [0u8, 0, 0, 0]; // mask = 0 → unsubscribe + let _ = handle_dpms_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + assert!( + !state.dpms.selected_by.contains(&ClientId(1)), + "mask=0 must remove the client from selected_by" + ); +} + +#[test] +fn dpms_off_drives_screensaver_on_with_forced_true() { + // Xorg dpms.c:269-279 — DPMS Non-On + SS Off → + // dixSaveScreens(SCREEN_SAVER_FORCER, ScreenSaverActive) + // → SendScreenSaverNotify(... forced=true). + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + let mut peer = install_client(&mut state, 1); + state + .screensaver + .selected_by + .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); + let mut backend = RecordingBackend::new(); + + apply_dpms_transition(&mut state, &mut backend, 3); // Off + + assert_eq!(state.screensaver.active, ScreenSaverActive::On); + assert!(state.screensaver.forced); + + let bytes = read_all_available(&mut peer); + // Sequential event tag is first_event + 0 = 92. + let idx = bytes + .iter() + .position(|&b| b == 92) + .expect("ScreenSaverNotify must be present"); + assert_eq!(bytes[idx + 1], x11screensaver::SCREEN_SAVER_ON, "state=On"); + assert_eq!(bytes[idx + 17], 1, "forced byte = 1"); +} + +#[test] +fn dpms_on_drives_screensaver_off_with_forced_false_and_no_activity_reset() { + // Xorg dpms.c:275-278 + window.c:3187-3193 — DPMS On + SS On + // takes the SCREEN_SAVER_OFF (not FORCER) path, so forced=0. + // NoticeTime only fires on the FORCER+Reset combination, so + // last_activity must NOT be touched by the coupling itself. + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + state.dpms.power_level = 3; + state.screensaver.active = ScreenSaverActive::On; + let prior = state.dpms.last_activity; + + let mut peer = install_client(&mut state, 1); + state + .screensaver + .selected_by + .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); + let mut backend = RecordingBackend::new(); + + apply_dpms_transition(&mut state, &mut backend, 0); + + assert_eq!(state.screensaver.active, ScreenSaverActive::Off); + assert!( + !state.screensaver.forced, + "DPMS-On→SS-Off is non-FORCER path" + ); + assert_eq!(state.dpms.last_activity, prior, "coupling must NOT reset"); + + let bytes = read_all_available(&mut peer); + let idx = bytes.iter().position(|&b| b == 92).unwrap(); + assert_eq!(bytes[idx + 1], x11screensaver::SCREEN_SAVER_OFF); + assert_eq!(bytes[idx + 17], 0, "forced byte = 0"); +} + +#[test] +fn dpms_coupling_emits_screensaver_notify_before_dpms_notify() { + // SS notify (sequential event tag 92) must appear at a lower + // wire offset than the DPMS XGE notify (GenericEvent tag 35) + // — matches Xorg ordering in DPMSSet (dpms.c:262-293). + let mut state = ServerState::new(); + state.dpms.kms_capable = true; + state.dpms.enabled = true; + let mut peer = install_client(&mut state, 1); + state.dpms.selected_by.insert(ClientId(1)); + state + .screensaver + .selected_by + .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); + let mut backend = RecordingBackend::new(); + + apply_dpms_transition(&mut state, &mut backend, 3); + + let bytes = read_all_available(&mut peer); + let ss_pos = bytes.iter().position(|&b| b == 92).unwrap(); + let dpms_pos = bytes.iter().position(|&b| b == 35).unwrap(); + assert!( + ss_pos < dpms_pos, + "SS notify (offset {ss_pos}) must precede DPMS notify (offset {dpms_pos})" + ); +} + +#[test] +fn force_screen_saver_activate_emits_notify_with_forced_true() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state + .screensaver + .selected_by + .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); + let mut backend = RecordingBackend::new(); + + apply_screen_saver_transition( + &mut state, + &mut backend, + ScreenSaverActive::On, + /*forced=*/ true, + ); + + let bytes = read_all_available(&mut peer); + let idx = bytes.iter().position(|&b| b == 92).unwrap(); + assert_eq!(bytes[idx + 1], x11screensaver::SCREEN_SAVER_ON); + assert_eq!(bytes[idx + 17], 1, "forced=1"); +} + +#[test] +fn apply_screen_saver_transition_does_not_touch_last_activity() { + // last_activity update is the *handler's* responsibility + // (FORCER+Reset path runs Xorg's NoticeTime, window.c:3187-3193). + // The pure helper must NOT touch last_activity — otherwise the + // input-fanout SS-only sibling check (Task 3 step 5) would + // double-bump it, and the DPMS coupling would too. + let mut state = ServerState::new(); + state.screensaver.active = ScreenSaverActive::On; + let prior = state.dpms.last_activity; + let mut backend = RecordingBackend::new(); + + apply_screen_saver_transition( + &mut state, + &mut backend, + ScreenSaverActive::Off, + /*forced=*/ true, + ); + + assert_eq!(state.screensaver.active, ScreenSaverActive::Off); + assert_eq!( + state.dpms.last_activity, prior, + "helper alone must not touch last_activity" + ); +} + +#[test] +fn force_screen_saver_invalid_mode_returns_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 115, + data: 2, // mode=2 — only 0 (Reset) and 1 (Activate) are valid + length_units: 1, + }; + let _ = handle_force_screen_saver( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0, "error reply tag"); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + // bad_value at offset 4 = 2 + assert_eq!( + u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), + 2 + ); +} + +#[test] +fn force_screen_saver_activate_via_handler_transitions_to_on() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 115, + data: 1, + length_units: 1, + }; // mode=1 (Activate) + + let _ = handle_force_screen_saver( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + ); + + assert_eq!(state.screensaver.active, ScreenSaverActive::On); + assert!( + state.screensaver.forced, + "Activate is the FORCER path → forced=true" + ); +} + +#[test] +fn force_screen_saver_reset_via_handler_advances_last_activity() { + // Reset is the FORCER+Reset path Xorg runs NoticeTime on + // (window.c:3187-3193) — the handler must bump last_activity. + use std::time::Duration; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state.screensaver.active = ScreenSaverActive::On; + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); + let stale = state.dpms.last_activity; + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 115, + data: 0, + length_units: 1, + }; // mode=0 (Reset) + + let _ = handle_force_screen_saver( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + ); + + assert_eq!(state.screensaver.active, ScreenSaverActive::Off); + assert!( + state.dpms.last_activity > stale, + "handler must bump last_activity on Reset" + ); +} + +#[test] +fn set_screen_saver_stores_fields() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let header = RequestHeader { + opcode: 107, + data: 0, + length_units: 3, + }; + // timeout=300, interval=900, prefer_blanking=0 (no), + // allow_exposures=1 (yes), pad:u16 + let body = [ + 44, 1, // 300 (LE) + 132, 3, // 900 (LE) + 0, // prefer_blanking + 1, // allow_exposures + 0, 0, // pad + ]; + let _ = handle_set_screen_saver(&mut state, ClientId(1), SequenceNumber(1), header, &body); + assert_eq!(state.screensaver.timeout_ms, 300_000); + assert_eq!(state.screensaver.interval_ms, 900_000); + assert!(!state.screensaver.prefer_blanking); + assert!(state.screensaver.allow_exposures); +} + +#[test] +fn set_screen_saver_minus_one_restores_default() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state.screensaver.timeout_ms = 12_345; + state.screensaver.interval_ms = 67_890; + let header = RequestHeader { + opcode: 107, + data: 0, + length_units: 3, + }; + // -1 (0xffff), -1, default(2), default(2), pad + let body = [0xff, 0xff, 0xff, 0xff, 2, 2, 0, 0]; + let _ = handle_set_screen_saver(&mut state, ClientId(1), SequenceNumber(1), header, &body); + // defaults: timeout=600s, interval=600s, prefer=true, allow=true + assert_eq!(state.screensaver.timeout_ms, 600_000); + assert_eq!(state.screensaver.interval_ms, 600_000); + assert!(state.screensaver.prefer_blanking); + assert!(state.screensaver.allow_exposures); +} + +#[test] +fn set_screen_saver_invalid_prefer_blanking_returns_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let header = RequestHeader { + opcode: 107, + data: 0, + length_units: 3, + }; + // prefer_blanking=3 is invalid (only 0/1/2 valid). + let body = [60, 0, 60, 0, 3, 1, 0, 0]; + let _ = handle_set_screen_saver(&mut state, ClientId(1), SequenceNumber(1), header, &body); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert_eq!( + u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), + 3 + ); +} + +#[test] +fn get_screen_saver_reflects_current_state() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.screensaver.timeout_ms = 120_000; + state.screensaver.interval_ms = 240_000; + state.screensaver.prefer_blanking = false; + state.screensaver.allow_exposures = true; + let _ = handle_get_screen_saver(&mut state, ClientId(1), SequenceNumber(1)); + let bytes = read_all_available(&mut peer); + // Reply layout: tag(0) data(1) seq(2-3) length(4-7) timeout(8-9) + // interval(10-11) prefer(12) allow(13) pad to 32. + assert_eq!(bytes[0], 1, "reply tag"); + assert_eq!( + u16::from_le_bytes([bytes[8], bytes[9]]), + 120, + "timeout in s" + ); + assert_eq!( + u16::from_le_bytes([bytes[10], bytes[11]]), + 240, + "interval in s" + ); + assert_eq!(bytes[12], 0, "prefer_blanking = false"); + assert_eq!(bytes[13], 1, "allow_exposures = true"); +} + +#[test] +fn suspend_per_client_refcount_stacks() { + // Two Suspend(true) from the same client stacks the refcount. + // It takes two Suspend(false) calls to drain. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let true_body = [1u8, 0, 0, 0]; + let false_body = [0u8, 0, 0, 0]; + let header = RequestHeader { + opcode: 150, + data: x11screensaver::SUSPEND, + length_units: 2, + }; + + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &true_body, + ); + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + header, + &true_body, + ); + assert!(state.screensaver_idle_deadline().is_none(), "suspended"); + assert_eq!( + state.screensaver.suspend_counts.get(&ClientId(1)).copied(), + Some(2) + ); + + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + header, + &false_body, + ); + assert!( + state.screensaver_idle_deadline().is_none(), + "still suspended" + ); + + state.screensaver.timeout_ms = 60_000; // arm the timer + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(4), + header, + &false_body, + ); + assert!(state.screensaver_idle_deadline().is_some(), "drained"); + assert!(!state.screensaver.suspend_counts.contains_key(&ClientId(1))); +} + +#[test] +fn suspend_release_last_resets_last_activity_when_screensaver_off_and_dpms_on() { + use std::time::Duration; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state.screensaver.timeout_ms = 60_000; + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); + let stale = state.dpms.last_activity; + state.screensaver.suspend_counts.insert(ClientId(1), 1); + let mut backend = RecordingBackend::new(); + + let header = RequestHeader { + opcode: 150, + data: x11screensaver::SUSPEND, + length_units: 2, + }; + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[0u8, 0, 0, 0], + ); + + assert!( + state.dpms.last_activity > stale, + "last_activity must advance" + ); +} + +#[test] +fn force_screen_saver_activate_still_works_while_suspended() { + // Xorg saver.c: "suspending it (by design) doesn't prevent it + // from being forcibly activated". + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state.screensaver.suspend_counts.insert(ClientId(2), 1); + let mut backend = RecordingBackend::new(); + + let header = RequestHeader { + opcode: 115, + data: 1, + length_units: 1, + }; // Activate + let _ = handle_force_screen_saver( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + ); + + assert_eq!(state.screensaver.active, ScreenSaverActive::On); +} + +#[test] +fn screen_saver_query_version_returns_one_one() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 150, + data: x11screensaver::QUERY_VERSION, + length_units: 2, + }; + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[1, 1, 0, 0], + ); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 1, "reply tag"); + assert_eq!( + u16::from_le_bytes([bytes[8], bytes[9]]), + x11screensaver::SERVER_MAJOR_VERSION + ); + assert_eq!( + u16::from_le_bytes([bytes[10], bytes[11]]), + x11screensaver::SERVER_MINOR_VERSION + ); +} + +#[test] +fn screen_saver_query_info_returns_disabled_when_timeout_zero() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.screensaver.timeout_ms = 0; + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 150, + data: x11screensaver::QUERY_INFO, + length_units: 2, + }; + let drawable = ROOT_WINDOW.0.to_le_bytes(); + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &drawable, + ); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11screensaver::SCREEN_SAVER_DISABLED); + assert_eq!( + u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]), + crate::resources::SCREEN_SAVER_WINDOW.0, + "the screen's saver window id, set or not (`Xext/saver.c:665`)" + ); + assert_eq!( + u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]), + 0, + "til_or_since = 0 in Disabled" + ); + assert_eq!( + bytes[24], + x11screensaver::SCREEN_SAVER_BLANKED, + "kind = Blanked (prefer_blanking default true)" + ); +} + +#[test] +fn screen_saver_query_info_off_carries_til_remaining_and_caller_mask() { + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let _ = install_client(&mut state, 2); // other subscriber; must not influence reply + state.screensaver.timeout_ms = 60_000; + state.dpms.last_activity = std::time::Instant::now() - Duration::from_millis(20_000); + state + .screensaver + .selected_by + .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); + state + .screensaver + .selected_by + .insert(ClientId(2), x11screensaver::SCREEN_SAVER_CYCLE_MASK); + let mut backend = RecordingBackend::new(); + + let header = RequestHeader { + opcode: 150, + data: x11screensaver::QUERY_INFO, + length_units: 2, + }; + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &ROOT_WINDOW.0.to_le_bytes(), + ); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11screensaver::SCREEN_SAVER_OFF, "state Off"); + let til = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + assert!( + til > 30_000 && til <= 40_000, + "til_remaining ≈ 60_000 - idle(~20_000); got {til}" + ); + let idle = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]); + assert!( + (19_000..=30_000).contains(&idle), + "idle≈20_000ms (slack for test scheduling); got {idle}" + ); + let mask = u32::from_le_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]); + assert_eq!( + mask, + x11screensaver::SCREEN_SAVER_NOTIFY_MASK, + "event_mask is caller's only, not union with client 2" + ); +} + +#[test] +fn screen_saver_query_info_on_state_uses_til_since_underflow_when_idle_lt_timeout() { + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.screensaver.active = ScreenSaverActive::On; + state.screensaver.timeout_ms = 60_000; + state.dpms.last_activity = std::time::Instant::now() - Duration::from_millis(5_000); + let mut backend = RecordingBackend::new(); + + let header = RequestHeader { + opcode: 150, + data: x11screensaver::QUERY_INFO, + length_units: 2, + }; + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &ROOT_WINDOW.0.to_le_bytes(), + ); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11screensaver::SCREEN_SAVER_ON); + let til = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + assert!( + til > 0xff00_0000, + "underflow wrap expected when idle < timeout; got 0x{til:08x}" + ); +} + +#[test] +fn screen_saver_query_info_kind_reflects_prefer_blanking() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.screensaver.prefer_blanking = false; + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 150, + data: x11screensaver::QUERY_INFO, + length_units: 2, + }; + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &ROOT_WINDOW.0.to_le_bytes(), + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[24], x11screensaver::SCREEN_SAVER_INTERNAL); +} + +#[test] +fn screen_saver_select_input_accepts_unknown_mask_bits() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 150, + data: x11screensaver::SELECT_INPUT, + length_units: 3, + }; + let mut body = Vec::new(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&0x0000_0004u32.to_le_bytes()); + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let bytes = read_all_available(&mut peer); + assert!(bytes.is_empty(), "SelectInput has no reply on success"); + assert_eq!( + state.screensaver.selected_by.get(&ClientId(1)).copied(), + Some(0x04) + ); + + apply_screen_saver_transition( + &mut state, + &mut backend, + ScreenSaverActive::On, + /*forced=*/ false, + ); + let bytes2 = read_all_available(&mut peer); + assert!( + !bytes2.contains(&92), + "client without NOTIFY_MASK bit must not receive notify" + ); +} + +/// `ScreenSaverSetAttributes` (`Xext/saver.c:840-845`): the first +/// client gets the attributes, another BadAccess until the first +/// unsets them; activation then creates and maps the server's saver +/// window, override-redirect, and deactivation destroys it +/// (`CreateSaverWindow` / `DestroySaverWindow`). dtsession sets +/// 1x1 InputOutput, mask 0, and exits on BadAccess. +#[test] +fn screen_saver_set_attributes_belongs_to_one_client_and_shows_a_window() { + let mut state = ServerState::new(); + let mut peer1 = install_client(&mut state, 1); + let mut peer2 = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let mut body = ROOT_WINDOW.0.to_le_bytes().to_vec(); + for v in [0u16, 0, 1, 1, 0] { + body.extend_from_slice(&v.to_le_bytes()); + } + body.extend_from_slice(&[0, 0]); // CopyFromParent class and depth + body.extend_from_slice(&0u32.to_le_bytes()); // visual + body.extend_from_slice(&0u32.to_le_bytes()); // mask + let request = + |state: &mut ServerState, backend: &mut RecordingBackend, client, minor, body: &[u8]| { + let header = RequestHeader { + opcode: 150, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }; + let _ = handle_screen_saver_request( + state, + backend, + ClientId(client), + SequenceNumber(1), + header, + body, + ); + }; + request( + &mut state, + &mut backend, + 1, + x11screensaver::SET_ATTRIBUTES, + &body, + ); + assert!( + read_all_available(&mut peer1).is_empty(), + "client 1: no error" + ); + request( + &mut state, + &mut backend, + 2, + x11screensaver::SET_ATTRIBUTES, + &body, + ); + let bytes = read_all_available(&mut peer2); + assert_eq!((bytes[0], bytes[1]), (0, x11::error::BAD_ACCESS)); + + // Mutation: remove the SERVER_OWNER fast path; the saver CreateWindow must stay authorized. + state.install_access_policy(Arc::new(DenyAllAccessPolicy)); + let saver = crate::resources::SCREEN_SAVER_WINDOW; + apply_screen_saver_transition(&mut state, &mut backend, ScreenSaverActive::On, true); + let w = state.resources.window(saver).expect("saver window"); + assert_eq!((w.width, w.height, w.parent), (1, 1, ROOT_WINDOW)); + assert!(w.override_redirect); + assert_eq!(w.map_state, MapState::Viewable); + apply_screen_saver_transition(&mut state, &mut backend, ScreenSaverActive::Off, true); + assert!(state.resources.window(saver).is_none()); + + request( + &mut state, + &mut backend, + 1, + x11screensaver::UNSET_ATTRIBUTES, + &ROOT_WINDOW.0.to_le_bytes(), + ); + request( + &mut state, + &mut backend, + 2, + x11screensaver::SET_ATTRIBUTES, + &body, + ); + assert!( + read_all_available(&mut peer2).is_empty(), + "client 2 after the unset" + ); +} + +#[test] +fn screen_saver_unset_attributes_returns_success_noop() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 150, + data: x11screensaver::UNSET_ATTRIBUTES, + length_units: 2, + }; + let drawable = ROOT_WINDOW.0.to_le_bytes(); + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &drawable, + ); + + let bytes = read_all_available(&mut peer); + assert!(bytes.is_empty(), "UnsetAttributes must be a silent no-op"); +} + +#[test] +fn cycle_event_delivered_only_to_cycle_mask_subscribers() { + // Two clients: A subscribed with NOTIFY_MASK, B with CYCLE_MASK. + // After SS goes Active and we fire a Cycle event, only B sees it. + let mut state = ServerState::new(); + let mut peer_a = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + state + .screensaver + .selected_by + .insert(ClientId(1), x11screensaver::SCREEN_SAVER_NOTIFY_MASK); + state + .screensaver + .selected_by + .insert(ClientId(2), x11screensaver::SCREEN_SAVER_CYCLE_MASK); + let mut backend = RecordingBackend::new(); + + apply_screen_saver_transition( + &mut state, + &mut backend, + ScreenSaverActive::On, + /*forced=*/ false, + ); + // A received the activation Notify; drain so the next read is clean. + let _ = read_all_available(&mut peer_a); + // B was NOT a NOTIFY subscriber; it should have received nothing yet. + assert!(read_all_available(&mut peer_b).is_empty()); + + emit_screen_saver_notify(&mut state, ScreenSaverActive::Cycle, /*forced=*/ false); + assert!( + read_all_available(&mut peer_a).is_empty(), + "Cycle must NOT deliver to NOTIFY_MASK subscriber" + ); + let b = read_all_available(&mut peer_b); + let idx = b.iter().position(|&x| x == 92).expect("B receives Cycle"); + assert_eq!(b[idx + 1], x11screensaver::SCREEN_SAVER_CYCLE); +} + +#[test] +fn suspend_release_resets_idletime_last_evaluated_and_per_device_baselines() { + use std::time::Duration; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Pre-seed: stale idletime cache from before suspend. + state + .idletime_last_evaluated + .insert(x11sync::IDLETIME_COUNTER, 999_999); + state + .per_device_last_activity + .insert(3, std::time::Instant::now() - Duration::from_secs(120)); + + // Insert a suspending client, then drain via Suspend(false). + state.screensaver.suspend_counts.insert(ClientId(1), 1); + let header = RequestHeader { + opcode: 150, + data: x11screensaver::SUSPEND, + length_units: 2, + }; + let _ = handle_screen_saver_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &[0u8, 0, 0, 0], + ); + + // The drain hit the (drained && empty && SS=Off && DPMS=On) guard + // and must have reset both IDLETIME bookkeeping fields. + assert!( + state.idletime_last_evaluated.is_empty(), + "idletime_last_evaluated must be cleared on suspend release" + ); + let vck_baseline = state + .per_device_last_activity + .get(&3) + .copied() + .expect("per_device_last_activity[3] still present"); + let elapsed = std::time::Instant::now().duration_since(vck_baseline); + assert!( + elapsed < Duration::from_millis(100), + "per_device_last_activity[3] must be reset to ~now; got elapsed {elapsed:?}" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/selection.rs b/crates/yserver-core/src/core_loop/process_request/tests/selection.rs new file mode 100644 index 000000000..a37376456 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/selection.rs @@ -0,0 +1,1604 @@ +use super::*; +use crate::access::RequestOpcodes; +use yserver_protocol::x11::AtomId; + +const SET_SELECTION_OWNER_REQUEST: RequestOpcodes = RequestOpcodes { + major: 22, + minor: 0, +}; +const CONVERT_SELECTION_REQUEST: RequestOpcodes = RequestOpcodes { + major: 24, + minor: 0, +}; + +/// Audit #9 (`docs/protocol-audit-2026-05-19.md`): when a client +/// takes ownership of a selection via core `SetSelectionOwner`, the +/// server must fire `XFixesSelectionNotify(SetSelectionOwner)` to +/// every client that has subscribed via `SelectSelectionInput` with +/// the matching mask bit. Without this, every clipboard manager +/// (klipper, copyq, gpaste, gnome-shell clipboard indicator) wedges +/// waiting for the event that says "the clipboard contents +/// changed". Xorg's `xfixes/select.c:158-210` `XFixesSelectionCallback` +/// is the reference. +#[test] +fn set_selection_owner_emits_xfixes_set_owner_notify_to_subscribers() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + + const CLIPBOARD_MGR: u32 = 7; + const APP: u32 = 9; + const SUBSCRIBER_WIN: u32 = 0x0070_0001; + const OWNER_WIN: u32 = 0x0090_0001; + const PRIMARY: u32 = 1; // X11 atom PRIMARY + + let mut state = ServerState::new(); + // Clipboard manager: subscribes; we'll inspect its peer socket. + let mut peer = install_client(&mut state, CLIPBOARD_MGR); + // App: issues SetSelectionOwner (no peer needed). + let _app_peer = install_client(&mut state, APP); + + // OWNER_WIN must exist for the SetSelectionOwner window + // validation gate (`dix/selection.c:169-173`). + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(OWNER_WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + // Subscribe clipboard mgr to PRIMARY's set-owner events on + // SUBSCRIBER_WIN. This is what `SelectSelectionInput` writes. + state.xfixes_selection_masks.insert( + (CLIPBOARD_MGR, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_SET_OWNER, + ); + + // SetSelectionOwner(window=OWNER_WIN, selection=PRIMARY, time=0). + // time=0 is X11's `CurrentTime` which Xorg's + // `ClientTimeToServerTime` resolves to the server's + // currentTime — guaranteed to clear both the future-shift + // (`time > currentTime`) and stale (`time < lastTimeChanged`) + // checks at `dix/selection.c:166,192`. + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&OWNER_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + handle_set_selection_owner( + &mut state, + ClientId(APP), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + // Drain clipboard mgr's socket and locate the XFixesSelectionNotify. + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let evt: [u8; 32] = all + .chunks_exact(32) + .find(|evt| evt[0] == crate::nested::XFIXES_FIRST_EVENT) + .map(|s| { + let mut a = [0u8; 32]; + a.copy_from_slice(s); + a + }) + .unwrap_or_else(|| { + panic!( + "expected XFixesSelectionNotify (type={}) in clipboard manager's stream; \ + got {} bytes: {:02x?}", + crate::nested::XFIXES_FIRST_EVENT, + all.len(), + all, + ) + }); + assert_eq!( + evt[1], + x11xfixes::SELECTION_NOTIFY_SET_OWNER, + "subtype must be SetSelectionOwnerNotify (0)", + ); + // Skip the 2-byte sequence and verify the payload (windows / + // selection / timestamps). + assert_eq!( + u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]), + SUBSCRIBER_WIN, + "window field must be the subscriber's window", + ); + assert_eq!( + u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]), + OWNER_WIN, + "owner field must be the new selection-owner window", + ); + assert_eq!( + u32::from_le_bytes([evt[12], evt[13], evt[14], evt[15]]), + PRIMARY, + "selection field must be the selection atom", + ); + // `timestamp` is Xorg's `currentTime.milliseconds` + // (`xfixes/select.c:88`) — NOT the request's `time` arg as + // the pre-fix code assumed. `selection_timestamp` is the + // freshly-updated `lastTimeChanged`. With request `time=0` + // resolving to `currentTime`, both should reflect server + // uptime at the moment of the call. The window/owner/selection + // fields above are the load-bearing identity assertions; the + // timestamp wire encoding is covered by the destroy/close + // tests where the prior `lastTimeChanged` is seeded directly. +} + +/// Audit #9: when the window currently owning a selection is +/// destroyed, the server must fire +/// `XFixesSelectionNotify(SelectionWindowDestroy)` to every +/// subscribing client whose mask includes the WindowDestroy bit, +/// and clear the selection ownership in `state.selections`. +/// Reference: Xorg `xfixes/select.c:158-210` + the +/// `SelectionCallback`'s `SelectionWindowDestroy` branch. +#[test] +fn destroy_window_owning_selection_fires_window_destroy_notify_and_clears_ownership() { + use std::io::Read; + use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; + const SUBSCRIBER_ID: u32 = 8; + const OWNER_ID: u32 = 10; + const SUBSCRIBER_WIN: u32 = 0x0080_0001; + const OWNER_WIN: u32 = 0x00a0_0001; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER_ID); + let _ = install_client(&mut state, OWNER_ID); + + // Create the owner window so DestroyWindow can find it. + state.resources.create_window( + ClientId(OWNER_ID), + CreateWindowRequest { + depth: 24, + window: ResourceId(OWNER_WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + // PRIMARY currently owned by OWNER_WIN. + state.selections.insert( + AtomId(PRIMARY), + crate::server::SelectionOwner { + window: ResourceId(OWNER_WIN), + last_time_changed: 0, + client: Some(ClientId(OWNER_ID)), + }, + ); + + // Subscriber registered with WindowDestroy bit. + state.xfixes_selection_masks.insert( + (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_WINDOW_DESTROY, + ); + + // Destroy OWNER_WIN — should fire WindowDestroy notify + clear. + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&OWNER_WIN.to_le_bytes()); + let mut backend = RecordingBackend::new(); + handle_destroy_window( + &mut state, + &mut backend, + None, + ClientId(OWNER_ID), + SequenceNumber(1), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &body, + ) + .expect("handle_destroy_window"); + + // Verify selection ownership cleared; the record keeps its time. + assert_eq!( + state.selections.get(&AtomId(PRIMARY)).copied(), + Some(crate::server::SelectionOwner { + window: ResourceId(0), + last_time_changed: 0, + client: None, + }), + "destroying the owning window must release state.selections[PRIMARY]", + ); + + // Verify subscriber received the event. + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let evt: [u8; 32] = all + .chunks_exact(32) + .find(|evt| { + evt[0] == crate::nested::XFIXES_FIRST_EVENT + && evt[1] == x11xfixes::SELECTION_NOTIFY_WINDOW_DESTROY + }) + .map(|s| { + let mut a = [0u8; 32]; + a.copy_from_slice(s); + a + }) + .unwrap_or_else(|| { + panic!( + "expected XFixesSelectionNotify(WindowDestroy) on subscriber; \ + got {} bytes: {:02x?}", + all.len(), + all, + ) + }); + assert_eq!( + u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]), + SUBSCRIBER_WIN, + "window field must be the subscriber's window", + ); + assert_eq!( + u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]), + 0, + "owner field must be None (0) after window-destroy", + ); + assert_eq!( + u32::from_le_bytes([evt[12], evt[13], evt[14], evt[15]]), + PRIMARY, + "selection field must be the cleared selection atom", + ); +} + +/// Audit #9: when a client disconnects while owning a selection, +/// the server must fire +/// `XFixesSelectionNotify(SelectionClientClose)` to every subscriber +/// whose mask includes the ClientClose bit, and drop the selection +/// ownership entry. Reference: Xorg +/// `xfixes/select.c:158-210`'s `SelectionClientClose` branch. +#[test] +fn client_disconnect_owning_selection_fires_client_close_notify_and_clears_ownership() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + const SUBSCRIBER_ID: u32 = 11; + const OWNER_ID: u32 = 12; + const SUBSCRIBER_WIN: u32 = 0x00b0_0001; + const OWNER_WIN: u32 = 0x00c0_0001; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER_ID); + let _ = install_client(&mut state, OWNER_ID); + + // OWNER_ID creates OWNER_WIN and sets the selection on it. + state.resources.create_window( + ClientId(OWNER_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(OWNER_WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.selections.insert( + AtomId(PRIMARY), + crate::server::SelectionOwner { + window: ResourceId(OWNER_WIN), + last_time_changed: 0, + client: Some(ClientId(OWNER_ID)), + }, + ); + state.xfixes_selection_masks.insert( + (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_CLIENT_CLOSE, + ); + + // Simulate client disconnect cleanup for OWNER_ID's selections. + fanout_xfixes_selection_client_close_for_client(&mut state, ClientId(OWNER_ID)); + + assert_eq!( + state.selections.get(&AtomId(PRIMARY)).copied(), + Some(crate::server::SelectionOwner { + window: ResourceId(0), + last_time_changed: 0, + client: None, + }), + "client disconnect must release selections it set", + ); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let evt: [u8; 32] = all + .chunks_exact(32) + .find(|evt| { + evt[0] == crate::nested::XFIXES_FIRST_EVENT + && evt[1] == x11xfixes::SELECTION_NOTIFY_CLIENT_CLOSE + }) + .map(|s| { + let mut a = [0u8; 32]; + a.copy_from_slice(s); + a + }) + .unwrap_or_else(|| { + panic!( + "expected XFixesSelectionNotify(ClientClose); \ + got {} bytes: {:02x?}", + all.len(), + all, + ) + }); + assert_eq!( + u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]), + SUBSCRIBER_WIN, + "window field = subscriber", + ); + assert_eq!( + u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]), + 0, + "owner field = None on client-close", + ); + assert_eq!( + u32::from_le_bytes([evt[12], evt[13], evt[14], evt[15]]), + PRIMARY, + "selection field", + ); +} + +/// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` +/// (`dix/selection.c:194`) gates SelectionClear on the previous +/// OWNER's client identity, not on the window identity: +/// `if (pSel->client && (!pWin || (pSel->client != client)))` +/// A single client moving its own selection between two of its +/// own windows must NOT receive a spurious SelectionClear. Pre-fix +/// yserver gated on `old_window != new_window`, which over-fires. +#[test] +fn set_selection_owner_no_clear_when_same_client_moves_between_own_windows() { + use std::io::Read; + use yserver_protocol::x11::CreateWindowRequest; + const APP: u32 = 50; + const WIN_A: u32 = 0x0050_0001; + const WIN_B: u32 = 0x0050_0002; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + // Both windows owned by the same client. + for win in [WIN_A, WIN_B] { + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + // Seed prior ownership directly so we isolate the second-call + // path. Owner = WIN_A (belongs to APP). + state.selections.insert( + AtomId(PRIMARY), + crate::server::SelectionOwner { + window: ResourceId(WIN_A), + last_time_changed: 0, + client: Some(ClientId(APP)), + }, + ); + + // Same client takes ownership at WIN_B. + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&WIN_B.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time=CurrentTime + handle_set_selection_owner( + &mut state, + ClientId(APP), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + // SelectionClear has event type 29 (X11 core). + assert!( + !all.chunks_exact(32).any(|e| e[0] == 29), + "no SelectionClear must be sent when the same client \ + moves selection between its own windows; got {} bytes: \ + {:02x?}", + all.len(), + all, + ); +} + +/// Audit #9 (code-review follow-up): Xorg encodes the resolved +/// server time (post-`ClientTimeToServerTime`, so CurrentTime/0 +/// becomes the actual `currentTime`) into the SelectionClear +/// event's time field at `dix/selection.c:196`. Pre-fix yserver +/// encoded the raw `time_val`, so a client sending `time=0` made +/// the SelectionClear carry `time=0` (the CurrentTime sentinel). +#[test] +fn set_selection_owner_clear_event_uses_resolved_time_when_client_sends_zero() { + use std::{io::Read, thread, time::Duration}; + use yserver_protocol::x11::CreateWindowRequest; + const PRIOR_OWNER: u32 = 51; + const NEW_OWNER: u32 = 52; + const PRIOR_WIN: u32 = 0x0051_0001; + const NEW_WIN: u32 = 0x0052_0001; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, PRIOR_OWNER); + let _ = install_client(&mut state, NEW_OWNER); + for (owner, win) in &[(PRIOR_OWNER, PRIOR_WIN), (NEW_OWNER, NEW_WIN)] { + state.resources.create_window( + ClientId(*owner), + CreateWindowRequest { + depth: 24, + window: ResourceId(*win), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + // Seed prior ownership with lastTimeChanged=0 so the stale + // check at the new call never trips. + state.selections.insert( + AtomId(PRIMARY), + crate::server::SelectionOwner { + window: ResourceId(PRIOR_WIN), + last_time_changed: 0, + client: Some(ClientId(PRIOR_OWNER)), + }, + ); + + // Sleep so `state.timestamp_now()` is non-zero when the new + // request runs — pre-fix the SelectionClear's `time` field + // carries the raw `time_val=0` (CurrentTime sentinel), so + // pinning `>= ts_before` after a sleep distinguishes the + // resolved-time encoding from the raw-passthrough encoding. + thread::sleep(Duration::from_millis(2)); + let ts_before = state.timestamp_now(); + assert!(ts_before > 0, "sanity: sleep advanced server time"); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&NEW_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time=CurrentTime + handle_set_selection_owner( + &mut state, + ClientId(NEW_OWNER), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let clear: [u8; 32] = all + .chunks_exact(32) + .find(|e| e[0] == 29) + .map(|s| { + let mut a = [0u8; 32]; + a.copy_from_slice(s); + a + }) + .unwrap_or_else(|| { + panic!( + "expected SelectionClear (event type 29) on prior \ + owner's stream; got {} bytes: {:02x?}", + all.len(), + all, + ); + }); + let clear_time = u32::from_le_bytes([clear[4], clear[5], clear[6], clear[7]]); + assert!( + clear_time >= ts_before, + "SelectionClear.time must be the resolved server time \ + (>= ts_before={ts_before}), not the raw time_val=0 the \ + client sent; got {clear_time}", + ); +} + +/// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` +/// (`dix/selection.c:169-173`) returns BadWindow when `window` is +/// non-`None` and `dixLookupWindow` fails. Pre-fix yserver +/// silently stored an unknown window xid as the new owner and +/// fired XFixesSelectionNotify as if it were valid. +#[test] +fn set_selection_owner_with_unknown_window_returns_bad_window() { + use std::io::Read; + const APP: u32 = 40; + const UNKNOWN_WIN: u32 = 0x0040_dead; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&UNKNOWN_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: 22, // core SetSelectionOwner + data: 0, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!(buf[0], 0, "first byte = error class"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_WINDOW, + "expected BadWindow (3) for unknown window xid; got {}", + buf[1], + ); + // SetSelectionOwner is core opcode 22; the error reply's + // major_opcode field (byte 10) MUST reflect that, or + // clients that key on major_opcode see a malformed error. + assert_eq!( + buf[10], 22, + "BadWindow reply must carry SetSelectionOwner's major opcode (22); got {}", + buf[10], + ); + assert!( + !state.selections.contains_key(&AtomId(PRIMARY)), + "no ownership must be recorded on BadWindow; got {:?}", + state.selections.get(&AtomId(PRIMARY)), + ); +} + +/// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` +/// (`dix/selection.c:175-178`) returns BadAtom for an unknown +/// selection atom. window=None bypasses the BadWindow gate so the +/// BadAtom path is isolated. +#[test] +fn set_selection_owner_with_invalid_atom_returns_bad_atom() { + use std::io::Read; + const APP: u32 = 41; + const BOGUS_ATOM: u32 = 0xdead_beef; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&0u32.to_le_bytes()); // window=None + body.extend_from_slice(&BOGUS_ATOM.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time=CurrentTime + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: 22, // core SetSelectionOwner + data: 0, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!(buf[0], 0, "first byte = error class"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_ATOM, + "expected BadAtom (5) for an unknown selection atom; got {}", + buf[1], + ); + assert_eq!( + buf[10], 22, + "BadAtom reply must carry SetSelectionOwner's major opcode (22); got {}", + buf[10], + ); + assert!( + !state.selections.contains_key(&AtomId(BOGUS_ATOM)), + "no ownership must be recorded on BadAtom", + ); +} + +/// Audit #9 (code-review follow-up): Xorg's +/// `dixSetSelectionOwner` (`dix/selection.c:164-167`) silently +/// ignores a request whose timestamp is in the future relative +/// to the server's currentTime, returning Success without +/// changing ownership and without firing any callbacks. Pre-fix +/// yserver accepted any timestamp, which lets a misbehaving +/// client jump the ownership queue past a well-behaved one. +#[test] +fn set_selection_owner_with_future_time_is_silently_ignored() { + use std::io::Read; + use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; + const SUBSCRIBER_ID: u32 = 30; + const OWNER_ID: u32 = 31; + const SUBSCRIBER_WIN: u32 = 0x0030_0001; + const OWNER_WIN: u32 = 0x0031_0001; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER_ID); + let _ = install_client(&mut state, OWNER_ID); + state.resources.create_window( + ClientId(OWNER_ID), + CreateWindowRequest { + depth: 24, + window: ResourceId(OWNER_WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.xfixes_selection_masks.insert( + (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_SET_OWNER, + ); + + // u32::MAX is guaranteed > state.timestamp_now() during the + // test (≈49 days post-start would be needed to reach it). + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&OWNER_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&u32::MAX.to_le_bytes()); + handle_set_selection_owner( + &mut state, + ClientId(OWNER_ID), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + assert!( + !state.selections.contains_key(&AtomId(PRIMARY)), + "future-timestamp request must not update ownership; \ + got {:?}", + state.selections.get(&AtomId(PRIMARY)), + ); + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + assert!( + !all.chunks_exact(32) + .any(|e| e[0] == crate::nested::XFIXES_FIRST_EVENT), + "no XFixesSelectionNotify must fire on silent-ignore; \ + got {} bytes: {:02x?}", + all.len(), + all, + ); +} + +/// Audit #9 (code-review follow-up): Xorg's `dixSetSelectionOwner` +/// (`dix/selection.c:188-193`) silently ignores a request whose +/// timestamp predates the selection's current `lastTimeChanged`, +/// preserving the existing ownership. Pre-fix yserver accepted +/// the stale request and overwrote the newer ownership. +#[test] +fn set_selection_owner_with_stale_time_is_silently_ignored() { + use std::io::Read; + use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; + const SUBSCRIBER_ID: u32 = 32; + const PRIOR_OWNER_ID: u32 = 33; + const NEW_OWNER_ID: u32 = 34; + const SUBSCRIBER_WIN: u32 = 0x0032_0001; + const PRIOR_OWNER_WIN: u32 = 0x0033_0001; + const NEW_OWNER_WIN: u32 = 0x0034_0001; + const PRIMARY: u32 = 1; + const PRIOR_LAST_TIME: u32 = 1000; + const STALE_TIME: u32 = 500; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER_ID); + let _ = install_client(&mut state, PRIOR_OWNER_ID); + let _ = install_client(&mut state, NEW_OWNER_ID); + for (owner, win) in &[ + (PRIOR_OWNER_ID, PRIOR_OWNER_WIN), + (NEW_OWNER_ID, NEW_OWNER_WIN), + ] { + state.resources.create_window( + ClientId(*owner), + CreateWindowRequest { + depth: 24, + window: ResourceId(*win), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + // Seed prior ownership with lastTimeChanged = 1000. + state.selections.insert( + AtomId(PRIMARY), + crate::server::SelectionOwner { + window: ResourceId(PRIOR_OWNER_WIN), + last_time_changed: PRIOR_LAST_TIME, + client: Some(ClientId(PRIOR_OWNER_ID)), + }, + ); + state.xfixes_selection_masks.insert( + (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_SET_OWNER, + ); + + // Attempt to take ownership at time=500 (before + // prior_last_time=1000). + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&NEW_OWNER_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&STALE_TIME.to_le_bytes()); + handle_set_selection_owner( + &mut state, + ClientId(NEW_OWNER_ID), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + let preserved = state + .selections + .get(&AtomId(PRIMARY)) + .map(|owner| (owner.window, owner.last_time_changed)); + assert_eq!( + preserved, + Some((ResourceId(PRIOR_OWNER_WIN), PRIOR_LAST_TIME)), + "stale-timestamp request must NOT overwrite a newer \ + ownership; got {preserved:?}", + ); + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + assert!( + !all.chunks_exact(32) + .any(|e| e[0] == crate::nested::XFIXES_FIRST_EVENT), + "no XFixesSelectionNotify must fire on stale-ignore; \ + got {} bytes: {:02x?}", + all.len(), + all, + ); +} + +/// Audit #9 (code-review follow-up): Xorg's +/// `ProcXFixesSelectSelectionInput` (`xfixes/select.c:189-192`) +/// runs `dixLookupWindow` first and propagates its return code +/// (`BadWindow` for an unknown xid). Before the fix yserver +/// silently stored the subscription, accepting illegal records. +#[test] +fn select_selection_input_with_invalid_window_returns_bad_window() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + + const CLIENT: u32 = 21; + const UNKNOWN_WIN: u32 = 0x00ff_eeee; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&UNKNOWN_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&x11xfixes::SELECTION_MASK_SET_OWNER.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(CLIENT, 5); + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::SELECT_SELECTION_INPUT, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!(buf[0], 0, "first byte = error class"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_WINDOW, + "expected BadWindow (3) for unknown window xid; got {}", + buf[1], + ); + assert!( + state.xfixes_selection_masks.is_empty(), + "the subscription must NOT be recorded on BadWindow; got {:?}", + state.xfixes_selection_masks, + ); +} + +/// Audit #9 (code-review follow-up): Xorg's +/// `ProcXFixesSelectSelectionInput` (`xfixes/select.c:193-196`) +/// returns BadValue when `eventMask & ~SelectionAllEvents` is +/// non-zero. Before the fix yserver stored arbitrary mask bits. +#[test] +fn select_selection_input_with_mask_outside_known_bits_returns_bad_value() { + use std::io::Read; + use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; + + const CLIENT: u32 = 22; + const WIN: u32 = 0x0150_0001; + const PRIMARY: u32 = 1; + const ILLEGAL_MASK: u32 = 1 << 8; // outside SelectionAllEvents + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + // Window must exist for the window-validation step to pass, + // so we cleanly isolate the mask-validation path. + state.resources.create_window( + ClientId(CLIENT), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&ILLEGAL_MASK.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(CLIENT, 5); + process_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::SELECT_SELECTION_INPUT, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!(buf[0], 0, "first byte = error class"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_VALUE, + "expected BadValue (2) for mask with bits outside \ + SelectionAllEvents (0b111); got {}", + buf[1], + ); + assert!( + state.xfixes_selection_masks.is_empty(), + "the subscription must NOT be recorded on BadValue; got {:?}", + state.xfixes_selection_masks, + ); +} + +/// Audit #9 (code-review follow-up): the destroy/close path +/// must emit the notify BEFORE clearing the selection (matching +/// Xorg's `DeleteWindowFromAnySelections` order at +/// `dix/selection.c:131-138`) so the wire payload carries the +/// stored `selection_timestamp` — `selection->lastTimeChanged` +/// in Xorg's `xfixes/select.c:89`. yserver tracks +/// `lastTimeChanged` as the second element of the +/// `state.selections` tuple, stamped by SetSelectionOwner with +/// the request's `time` arg. +#[test] +fn destroy_window_owning_selection_carries_prior_last_time_changed_in_selection_timestamp() { + use std::io::Read; + use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; + const SUBSCRIBER_ID: u32 = 15; + const OWNER_ID: u32 = 16; + const SUBSCRIBER_WIN: u32 = 0x00f0_0001; + const OWNER_WIN: u32 = 0x0100_0001; + const PRIMARY: u32 = 1; + const SET_OWNER_TIME: u32 = 0x0a0b_0c0d; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER_ID); + let _ = install_client(&mut state, OWNER_ID); + + state.resources.create_window( + ClientId(OWNER_ID), + CreateWindowRequest { + depth: 24, + window: ResourceId(OWNER_WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.xfixes_selection_masks.insert( + (SUBSCRIBER_ID, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_WINDOW_DESTROY, + ); + + // Seed ownership directly with a known `lastTimeChanged`. + // This decouples the destroy-path assertion from + // `handle_set_selection_owner`'s time-resolution logic + // (future/stale checks, ClientTime → ServerTime conversion); + // we only care here that whatever value is in the second + // tuple slot flows through to the notify wire payload. + state.selections.insert( + AtomId(PRIMARY), + crate::server::SelectionOwner { + window: ResourceId(OWNER_WIN), + last_time_changed: SET_OWNER_TIME, + client: Some(ClientId(OWNER_ID)), + }, + ); + + let mut destroy_body = Vec::with_capacity(4); + destroy_body.extend_from_slice(&OWNER_WIN.to_le_bytes()); + let mut backend = RecordingBackend::new(); + handle_destroy_window( + &mut state, + &mut backend, + None, + ClientId(OWNER_ID), + SequenceNumber(2), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &destroy_body, + ) + .expect("handle_destroy_window"); + peer.set_nonblocking(true).unwrap(); + + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let evt: [u8; 32] = all + .chunks_exact(32) + .find(|e| { + e[0] == crate::nested::XFIXES_FIRST_EVENT + && e[1] == x11xfixes::SELECTION_NOTIFY_WINDOW_DESTROY + }) + .map(|s| { + let mut a = [0u8; 32]; + a.copy_from_slice(s); + a + }) + .expect("WindowDestroy notify in stream"); + + assert_eq!( + u32::from_le_bytes([evt[20], evt[21], evt[22], evt[23]]), + SET_OWNER_TIME, + "selection_timestamp must carry the prior SetSelectionOwner \ + time arg (Xorg `selection->lastTimeChanged`); pre-fix the \ + payload was zeroed", + ); + // The `timestamp` field is `state.timestamp_now()` (Xorg's + // `currentTime.milliseconds` equivalent); not asserted here + // because in a sub-millisecond test it's legitimately 0 — which + // matches Xorg behavior (`UpdateCurrentTimeIf` snapshots + // `GetTimeInMillis()` with no floor). The + // `selection_timestamp` assertion above is the load-bearing + // spec-compliance check. +} + +/// Audit #9 (code-review follow-up): Xorg's +/// `XFixesSelectionCallback` (`xfixes/select.c:79-91`) walks +/// every matching subscription record and emits one event per +/// `(client, window, selection)` tuple. A single client that +/// has two windows subscribed to the same selection must +/// receive TWO events whose `window` fields are the two +/// distinct subscriber windows — not one collapsed event nor +/// two events with the same window field. +/// +/// `fanout_event_to_clients` deduplicates by ClientId *within +/// one call* via a freshly-allocated `seen` set, so calling it +/// once per subscription with a single-element slice is the +/// correct shape; the closure captures the per-iteration +/// subscriber window. This test pins that invariant against +/// future refactors. +#[test] +fn set_selection_owner_emits_one_event_per_subscription_when_client_has_two_windows() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + const SUBSCRIBER: u32 = 13; + const APP: u32 = 14; + const WIN_A: u32 = 0x00d0_0001; + const WIN_B: u32 = 0x00d0_0002; + const OWNER_WIN: u32 = 0x00e0_0001; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER); + let _ = install_client(&mut state, APP); + + // OWNER_WIN must exist for SetSelectionOwner's window + // validation gate. + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(OWNER_WIN), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + // Same client, two subscription records on the same selection. + state.xfixes_selection_masks.insert( + (SUBSCRIBER, ResourceId(WIN_A), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_SET_OWNER, + ); + state.xfixes_selection_masks.insert( + (SUBSCRIBER, ResourceId(WIN_B), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_SET_OWNER, + ); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&OWNER_WIN.to_le_bytes()); + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + handle_set_selection_owner( + &mut state, + ClientId(APP), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + let mut subscriber_windows: Vec = all + .chunks_exact(32) + .filter(|e| { + e[0] == crate::nested::XFIXES_FIRST_EVENT + && e[1] == x11xfixes::SELECTION_NOTIFY_SET_OWNER + }) + .map(|e| u32::from_le_bytes([e[4], e[5], e[6], e[7]])) + .collect(); + subscriber_windows.sort_unstable(); + assert_eq!( + subscriber_windows, + vec![WIN_A, WIN_B], + "must get one event per (client, window, selection) subscription \ + record with distinct `window` fields; got {} bytes total: {:02x?}", + all.len(), + all, + ); +} + +/// Audit #9: subscribing with mask=0 then re-subscribing with the +/// set-owner bit, the FIRST owner-change must still emit (verifies +/// the mask-bit gate, not the presence of the subscription key). +#[test] +fn set_selection_owner_skips_subscribers_whose_mask_excludes_set_owner() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + + const SUBSCRIBER: u32 = 5; + const APP: u32 = 6; + const SUBSCRIBER_WIN: u32 = 0x0050_0001; + const PRIMARY: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, SUBSCRIBER); + let _ = install_client(&mut state, APP); + + // Subscribe with a mask that does NOT include SET_OWNER — + // only WINDOW_DESTROY. SetSelectionOwner must NOT fire for + // this subscription. + state.xfixes_selection_masks.insert( + (SUBSCRIBER, ResourceId(SUBSCRIBER_WIN), AtomId(PRIMARY)), + x11xfixes::SELECTION_MASK_WINDOW_DESTROY, + ); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&0x0090_0001u32.to_le_bytes()); // owner window + body.extend_from_slice(&PRIMARY.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time + handle_set_selection_owner( + &mut state, + ClientId(APP), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); + + peer.set_nonblocking(true).unwrap(); + let mut all = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => all.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + assert!( + !all.chunks_exact(32) + .any(|evt| evt[0] == crate::nested::XFIXES_FIRST_EVENT), + "no XFixesSelectionNotify expected when subscriber's mask excludes \ + SET_OWNER; got {} bytes: {:02x?}", + all.len(), + all, + ); +} + +// ── tools/selection-record-probe.c: `a` owns window A, `b` owns window B ── + +const REC_A: u32 = 40; +const REC_B: u32 = 41; +const REC_WIN_A: u32 = 0x0040_0001; +const REC_WIN_B: u32 = 0x0041_0001; +const REC_SELECTION: &str = "SELECTION_RECORD_PROBE"; + +/// Clients `a` and `b`, each with its window, and the probe's selection +/// atom. The clock is ten seconds in, so `now - 10` is a valid timestamp. +fn selection_record_fixture() -> (ServerState, UnixStream, UnixStream, AtomId, u32) { + let mut state = ServerState::new(); + state.start_instant -= std::time::Duration::from_secs(10); + let a = install_client(&mut state, REC_A); + let b = install_client(&mut state, REC_B); + for (client, window) in [(REC_A, REC_WIN_A), (REC_B, REC_WIN_B)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent: crate::resources::ROOT_WINDOW, + width: 10, + height: 10, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + let selection = state.atoms.intern(REC_SELECTION, false); + let now = state.timestamp_now(); + (state, a, b, selection, now) +} + +fn record_set_owner( + state: &mut ServerState, + client: u32, + window: u32, + selection: AtomId, + time: u32, +) { + let mut body = Vec::with_capacity(12); + for word in [window, selection.0, time] { + body.extend_from_slice(&word.to_le_bytes()); + } + handle_set_selection_owner( + state, + ClientId(client), + SequenceNumber(1), + SET_SELECTION_OWNER_REQUEST, + &body, + ) + .expect("handle_set_selection_owner"); +} + +/// GetSelectionOwner as `b` issues it. +fn record_owner(state: &mut ServerState, b: &mut UnixStream, selection: AtomId) -> u32 { + let _ = read_all_or_buffered(state, REC_B, b); + crate::core_loop::process_request::selection::handle_get_selection_owner( + state, + ClientId(REC_B), + SequenceNumber(2), + &selection.0.to_le_bytes(), + ) + .expect("handle_get_selection_owner"); + let reply = read_all_or_buffered(state, REC_B, b); + assert_eq!(reply.len(), 32, "one GetSelectionOwner reply"); + u32::from_le_bytes([reply[8], reply[9], reply[10], reply[11]]) +} + +/// `(type, requestor, property)` of every core event a client received. +fn record_events( + state: &mut ServerState, + client: u32, + peer: &mut UnixStream, +) -> Vec<(u8, u32, u32)> { + read_all_or_buffered(state, client, peer) + .chunks_exact(32) + .map(|e| { + let word = |i: usize| u32::from_le_bytes([e[i], e[i + 1], e[i + 2], e[i + 3]]); + (e[0] & 0x7f, word(8), word(20)) + }) + .collect() +} + +fn record_convert(state: &mut ServerState, client: u32, requestor: u32, selection: AtomId) { + let mut body = Vec::with_capacity(20); + for word in [requestor, selection.0, 31, 31, 0] { + body.extend_from_slice(&word.to_le_bytes()); + } + crate::core_loop::process_request::selection::handle_convert_selection( + state, + ClientId(client), + SequenceNumber(3), + CONVERT_SELECTION_REQUEST, + &body, + ) + .expect("handle_convert_selection"); +} + +/// `tools/selection-record-probe convert`, measured on Xephyr: +/// +/// ```text +/// b ConvertSelection requestor=A (never owned) +/// b: SelectionNotify(requestor=A property=0) +/// a SetSelectionOwner A, then None +/// a: SelectionClear(owner=A) +/// selection owner: None +/// b ConvertSelection requestor=A (released) +/// b: SelectionNotify(requestor=A property=0) +/// ``` +/// +/// With no owner, `ProcConvertSelection` writes the SelectionNotify to the +/// client that issued the request (`dix/selection.c:304-311`), not to the +/// creator of the requestor window. +#[test] +fn convert_selection_without_an_owner_notifies_the_requesting_client() { + let (mut state, mut a, mut b, selection, now) = selection_record_fixture(); + const SELECTION_NOTIFY: u8 = 31; + + record_convert(&mut state, REC_B, REC_WIN_A, selection); + assert!(record_events(&mut state, REC_A, &mut a).is_empty()); + assert_eq!( + record_events(&mut state, REC_B, &mut b), + [(SELECTION_NOTIFY, REC_WIN_A, 0)] + ); + + record_set_owner(&mut state, REC_A, REC_WIN_A, selection, now); + record_set_owner(&mut state, REC_A, 0, selection, now); + let _ = record_events(&mut state, REC_A, &mut a); + assert_eq!(record_owner(&mut state, &mut b, selection), 0); + + record_convert(&mut state, REC_B, REC_WIN_A, selection); + assert!(record_events(&mut state, REC_A, &mut a).is_empty()); + assert_eq!( + record_events(&mut state, REC_B, &mut b), + [(SELECTION_NOTIFY, REC_WIN_A, 0)] + ); +} + +/// `ProcConvertSelection` checks the requestor (BadWindow) and then the +/// atoms (BadAtom, whose value is the property whichever atom is bad) before +/// anything is sent (`dix/selection.c:271-280`). +#[test] +fn convert_selection_with_a_bad_requestor_or_atom_is_an_error_and_sends_nothing() { + let (mut state, mut a, mut b, selection, _now) = selection_record_fixture(); + const BOGUS: u32 = 0x00ee_0000; + let convert = |state: &mut ServerState, requestor: u32, target: u32, property: u32| { + let mut body = Vec::with_capacity(20); + for word in [requestor, selection.0, target, property, 0] { + body.extend_from_slice(&word.to_le_bytes()); + } + crate::core_loop::process_request::selection::handle_convert_selection( + state, + ClientId(REC_B), + SequenceNumber(3), + CONVERT_SELECTION_REQUEST, + &body, + ) + .expect("handle_convert_selection"); + }; + // (code, bad value, major opcode) of each error `b` reads. + let errors = |state: &mut ServerState, peer: &mut UnixStream| -> Vec<(u8, u32, u8)> { + read_all_or_buffered(state, REC_B, peer) + .chunks_exact(32) + .map(|e| { + assert_eq!(e[0], 0, "only errors expected, got event {}", e[0]); + (e[1], u32::from_le_bytes([e[4], e[5], e[6], e[7]]), e[10]) + }) + .collect() + }; + + convert(&mut state, BOGUS, 31, 31); + assert_eq!( + errors(&mut state, &mut b), + [(yserver_protocol::x11::error::BAD_WINDOW, BOGUS, 24)] + ); + convert(&mut state, REC_WIN_A, BOGUS, 31); + assert_eq!( + errors(&mut state, &mut b), + [(yserver_protocol::x11::error::BAD_ATOM, 31, 24)] + ); + convert(&mut state, REC_WIN_A, 31, BOGUS); + assert_eq!( + errors(&mut state, &mut b), + [(yserver_protocol::x11::error::BAD_ATOM, BOGUS, 24)] + ); + assert!(record_events(&mut state, REC_A, &mut a).is_empty()); +} + +/// How `a` gives up the selection it set on A at `now`. +#[derive(Clone, Copy)] +enum RecordRelease { + /// `a` sets None at `now` (`ProcSetSelectionOwner`, `dix/selection.c:204-207`). + SetNone, + /// `a` disconnects (`DeleteClientFromAnySelections`, `dix/selection.c:128-139`). + Close, + /// `a` destroys A (`DeleteWindowFromAnySelections`, `dix/selection.c:113-125`). + Destroy, +} + +/// `b`'s SetSelectionOwner(B) after the release: at `now - 10` it is older +/// than the kept `lastTimeChanged` and ignored (`dix/selection.c:192-193`), +/// at `now` it takes the selection with no SelectionClear, since the record's +/// client is NullClient (`:194`). +fn assert_stale_set_after_release_is_ignored(release: RecordRelease) { + let (mut state, mut a, mut b, selection, now) = selection_record_fixture(); + record_set_owner(&mut state, REC_A, REC_WIN_A, selection, now); + assert_eq!(record_owner(&mut state, &mut b, selection), REC_WIN_A); + match release { + RecordRelease::SetNone => record_set_owner(&mut state, REC_A, 0, selection, now), + RecordRelease::Close => { + fanout_xfixes_selection_client_close_for_client(&mut state, ClientId(REC_A)); + } + RecordRelease::Destroy => { + let mut backend = RecordingBackend::new(); + handle_destroy_window( + &mut state, + &mut backend, + None, + ClientId(REC_A), + SequenceNumber(4), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &REC_WIN_A.to_le_bytes(), + ) + .expect("handle_destroy_window"); + } + } + assert_eq!(record_owner(&mut state, &mut b, selection), 0); + let _ = record_events(&mut state, REC_A, &mut a); + + record_set_owner(&mut state, REC_B, REC_WIN_B, selection, now - 10); + assert_eq!(record_owner(&mut state, &mut b, selection), 0); + record_set_owner(&mut state, REC_B, REC_WIN_B, selection, now); + assert_eq!(record_owner(&mut state, &mut b, selection), REC_WIN_B); + assert!(record_events(&mut state, REC_A, &mut a).is_empty()); + assert!(record_events(&mut state, REC_B, &mut b).is_empty()); +} + +/// `tools/selection-record-probe none`, measured on Xephyr: +/// +/// ```text +/// a SetSelectionOwner A at now +/// selection owner: A +/// a SetSelectionOwner None at now +/// a: SelectionClear(owner=A) +/// selection owner: None +/// b SetSelectionOwner B at now-10 +/// selection owner: None +/// b SetSelectionOwner B at now +/// selection owner: B +/// ``` +#[test] +fn released_selection_keeps_its_last_time_changed_after_set_none() { + assert_stale_set_after_release_is_ignored(RecordRelease::SetNone); +} + +/// `tools/selection-record-probe close`, measured on Xephyr: +/// +/// ```text +/// a SetSelectionOwner A at now +/// selection owner: A +/// a disconnects +/// selection owner: None +/// b SetSelectionOwner B at now-10 +/// selection owner: None +/// b SetSelectionOwner B at now +/// selection owner: B +/// ``` +#[test] +fn released_selection_keeps_its_last_time_changed_after_setter_disconnect() { + assert_stale_set_after_release_is_ignored(RecordRelease::Close); +} + +/// `tools/selection-record-probe destroy`, measured on Xephyr: +/// +/// ```text +/// a SetSelectionOwner A at now +/// selection owner: A +/// a DestroyWindow A +/// selection owner: None +/// b SetSelectionOwner B at now-10 +/// selection owner: None +/// b SetSelectionOwner B at now +/// selection owner: B +/// ``` +#[test] +fn released_selection_keeps_its_last_time_changed_after_owner_window_destroy() { + assert_stale_set_after_release_is_ignored(RecordRelease::Destroy); +} + +/// `tools/selection-record-probe fresh`, measured on Xephyr: releasing a +/// selection nobody owned creates its record (`dix/selection.c:196-213`) +/// with `lastTimeChanged` = the request's time. +/// +/// ```text +/// a SetSelectionOwner None (never owned) at now +/// selection owner: None +/// b SetSelectionOwner B at now-10 +/// selection owner: None +/// b SetSelectionOwner B at now +/// selection owner: B +/// ``` +#[test] +fn releasing_a_never_owned_selection_records_its_time() { + let (mut state, mut a, mut b, selection, now) = selection_record_fixture(); + record_set_owner(&mut state, REC_A, 0, selection, now); + assert_eq!(record_owner(&mut state, &mut b, selection), 0); + record_set_owner(&mut state, REC_B, REC_WIN_B, selection, now - 10); + assert_eq!(record_owner(&mut state, &mut b, selection), 0); + record_set_owner(&mut state, REC_B, REC_WIN_B, selection, now); + assert_eq!(record_owner(&mut state, &mut b, selection), REC_WIN_B); + assert!(record_events(&mut state, REC_A, &mut a).is_empty()); + assert!(record_events(&mut state, REC_B, &mut b).is_empty()); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/sync.rs b/crates/yserver-core/src/core_loop/process_request/tests/sync.rs new file mode 100644 index 000000000..b70f9b3ba --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/sync.rs @@ -0,0 +1,2142 @@ +use super::*; + +fn sync_header(minor: u8) -> RequestHeader { + RequestHeader { + opcode: 142, + data: minor, + length_units: 0, + } +} + +fn counter_value_body(counter: u32, value: i64) -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(&counter.to_le_bytes()); + b.extend_from_slice(&xsync_i64(value)); + b +} + +// The exact CreateAlarm muffin issues under Cinnamon: Relative +// value 1, PositiveComparison, delta 1, events true, watching +// counter 0x02600006. +fn muffin_alarm_body() -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(&0x01e0_0019u32.to_le_bytes()); + let mask = x11sync::CA_COUNTER + | x11sync::CA_VALUE_TYPE + | x11sync::CA_VALUE + | x11sync::CA_TEST_TYPE + | x11sync::CA_DELTA + | x11sync::CA_EVENTS; + b.extend_from_slice(&mask.to_le_bytes()); + b.extend_from_slice(&0x0260_0006u32.to_le_bytes()); + b.extend_from_slice(&x11sync::VALUE_TYPE_RELATIVE.to_le_bytes()); + b.extend_from_slice(&0i32.to_le_bytes()); // value hi + b.extend_from_slice(&1u32.to_le_bytes()); // value lo + b.extend_from_slice(&x11sync::TEST_POSITIVE_COMPARISON.to_le_bytes()); + b.extend_from_slice(&0i32.to_le_bytes()); // delta hi + b.extend_from_slice(&1u32.to_le_bytes()); // delta lo + b.push(1); // events = true + b.extend_from_slice(&[0u8; 3]); + b +} + +// Reproduces the Cinnamon frame-sync deadlock: muffin arms a SYNC +// alarm on a GTK client's _NET_WM_SYNC_REQUEST_COUNTER and depends +// on AlarmNotify to learn the client finished a frame. Before the +// fix, SetCounter never evaluated alarms and no AlarmNotify was +// ever sent, so muffin never composited and clients froze. +#[test] +fn sync_alarm_fires_alarmnotify_on_watched_counter_crossing() { + let mut state = ServerState::new(); + let mut muffin = install_client(&mut state, 1); + let mut gtk = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + // GTK client (2) creates its frame-sync counter at 0. + handle_sync_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(1), + sync_header(2), // CREATE_COUNTER + &counter_value_body(0x0260_0006, 0), + ) + .unwrap(); + + // muffin (1) arms the alarm. wait_value = counter(0) + 1 = 1, + // so the create-time test (0 >= 1) does not fire. + handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + sync_header(8), // CREATE_ALARM + &muffin_alarm_body(), + ) + .unwrap(); + assert!( + read_all_available(&mut muffin).is_empty(), + "alarm must not fire at creation when wait_value exceeds the counter" + ); + + // GTK client finishes a frame: counter 0 -> 2, crossing 1. + handle_sync_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(2), + sync_header(3), // SET_COUNTER + &counter_value_body(0x0260_0006, 2), + ) + .unwrap(); + + let evt = read_all_available(&mut muffin); + assert_eq!(evt.len(), 32, "exactly one AlarmNotify to the alarm owner"); + assert_eq!(evt[0], 84, "type = SYNC first-event(83) + AlarmNotify(1)"); + assert_eq!(evt[1], 1, "kind = AlarmNotify"); + assert_eq!( + u32::from_le_bytes(evt[4..8].try_into().unwrap()), + 0x01e0_0019, + "alarm id" + ); + assert_eq!( + u32::from_le_bytes(evt[12..16].try_into().unwrap()), + 2, + "counter value carried on the event" + ); + assert_eq!( + u32::from_le_bytes(evt[20..24].try_into().unwrap()), + 1, + "alarm (wait) value that triggered" + ); + assert_eq!(evt[28], 0, "non-zero delta re-arms -> state Active"); + assert!( + read_all_available(&mut gtk).is_empty(), + "AlarmNotify goes to the alarm owner, not the counter setter" + ); + + // Re-arm proof: the next frame (2 -> 4) must fire again. Without + // re-arm the muffin frame loop would stall after one frame. + handle_sync_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(3), + sync_header(3), + &counter_value_body(0x0260_0006, 4), + ) + .unwrap(); + let evt2 = read_all_available(&mut muffin); + assert_eq!( + evt2.len(), + 32, + "second crossing fires again (alarm re-armed)" + ); + assert_eq!( + u32::from_le_bytes(evt2[12..16].try_into().unwrap()), + 4, + "second event carries the new counter value" + ); +} + +#[test] +fn sync_create_trigger_query_fence_round_trip() { + let mut state = ServerState::new(); + let peer_a = install_client(&mut state, 1); + let mut peer_b = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + + // Client A: CreateFence(fence=0x42, initially_triggered=false). + let mut create_body = vec![0u8; 12]; + create_body[0..4].copy_from_slice(&0u32.to_le_bytes()); // drawable=0 + create_body[4..8].copy_from_slice(&0x42u32.to_le_bytes()); + create_body[8] = 0; + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 142, + data: 14, // CREATE_FENCE + length_units: 4, + }, + &create_body, + None, + ) + .unwrap(); + + // Client B: QueryFence -> triggered=false initially. + let mut q_body = vec![0u8; 4]; + q_body[0..4].copy_from_slice(&0x42u32.to_le_bytes()); + process_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(1), + RequestHeader { + opcode: 142, + data: 18, // QUERY_FENCE + length_units: 2, + }, + &q_body, + None, + ) + .unwrap(); + peer_b.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer_b.read_exact(&mut buf).unwrap(); + assert_eq!(buf[0], 1); // Reply + assert_eq!(buf[8], 0, "fence not yet triggered"); + + // Client A: TriggerFence. + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 142, + data: 15, // TRIGGER_FENCE + length_units: 2, + }, + &q_body, + None, + ) + .unwrap(); + + // Client B: QueryFence -> triggered=true now. + process_request( + &mut state, + &mut backend, + ClientId(2), + SequenceNumber(2), + RequestHeader { + opcode: 142, + data: 18, // QUERY_FENCE + length_units: 2, + }, + &q_body, + None, + ) + .unwrap(); + let mut buf2 = [0u8; 32]; + peer_b.read_exact(&mut buf2).unwrap(); + assert_eq!(buf2[8], 1, "fence triggered after Client A's trigger"); + + // Stash peer_a so it doesn't drop and close the writer mid-test. + let _ = peer_a; +} + +// ── SYNC Await / AwaitFence ───────────────────────────────────── +// Ground truth for every expectation below: Xorg 21.1.24 Xvfb driven +// by a two-connection xcb probe (client A changes counters and fences, +// client B awaits and then sends GetInputFocus; "suspended" means B's +// reply had not arrived after A's round trip). + +fn sync_req( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + minor: u8, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(client), + SequenceNumber(1), + RequestHeader { + opcode: 142, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("sync request"); +} + +fn sync_i64(v: i64) -> [u8; 8] { + let mut out = [0u8; 8]; + #[allow(clippy::cast_possible_truncation)] + out[..4].copy_from_slice(&((v >> 32) as i32).to_le_bytes()); + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + out[4..].copy_from_slice(&(v as u32).to_le_bytes()); + out +} + +fn sync_counter_body(counter: u32, value: i64) -> Vec { + let mut body = counter.to_le_bytes().to_vec(); + body.extend_from_slice(&sync_i64(value)); + body +} + +/// One `WAITCONDITION`: counter, value type, wait value, test type, +/// event threshold. +fn sync_wait(counter: u32, value_type: u32, wait: i64, test_type: u32, threshold: i64) -> Vec { + let mut body = counter.to_le_bytes().to_vec(); + body.extend_from_slice(&value_type.to_le_bytes()); + body.extend_from_slice(&sync_i64(wait)); + body.extend_from_slice(&test_type.to_le_bytes()); + body.extend_from_slice(&sync_i64(threshold)); + body +} + +/// CounterNotify → (counter, wait value, counter value, count, destroyed). +fn counter_notify_fields(p: &[u8; 32]) -> (u32, i64, i64, u16, bool) { + assert_eq!(p[0], crate::nested::SYNC_FIRST_EVENT, "CounterNotify type"); + assert_eq!(p[1], 0, "kind CounterNotify"); + let i64_at = |at: usize| { + #[allow(clippy::cast_possible_wrap)] + let hi = le_u32(p, at) as i32; + (i64::from(hi) << 32) | i64::from(le_u32(p, at + 4)) + }; + ( + le_u32(p, 4), + i64_at(8), + i64_at(16), + u16::from_le_bytes([p[28], p[29]]), + p[30] != 0, + ) +} + +struct SyncFixture { + state: ServerState, + backend: RecordingBackend, + _peer_a: UnixStream, + peer_b: UnixStream, +} + +const SYNC_A: u32 = 1; +const SYNC_B: u32 = 2; +const SYNC_C1: u32 = 0x0010_0001; +const SYNC_C2: u32 = 0x0010_0002; + +fn sync_fixture() -> SyncFixture { + let mut state = ServerState::new(); + let peer_a = install_client(&mut state, SYNC_A); + let peer_b = install_client(&mut state, SYNC_B); + SyncFixture { + state, + backend: RecordingBackend::new(), + _peer_a: peer_a, + peer_b, + } +} + +impl SyncFixture { + fn a(&mut self, minor: u8, body: &[u8]) { + sync_req(&mut self.state, &mut self.backend, SYNC_A, minor, body); + } + fn b(&mut self, minor: u8, body: &[u8]) { + sync_req(&mut self.state, &mut self.backend, SYNC_B, minor, body); + } + fn suspended(&self) -> bool { + crate::core_loop::sync_await::client_is_suspended(&self.state, ClientId(SYNC_B)) + } + fn b_packets(&mut self) -> Vec<[u8; 32]> { + wire_packets(&mut self.peer_b) + } + fn a_packets(&mut self) -> Vec<[u8; 32]> { + wire_packets(&mut self._peer_a) + } +} + +/// Xvfb: B awaits c1 >= 5 (PositiveComparison); A sets 3 → B stays +/// suspended; A sets 7 → B resumes with CounterNotify(c1, wait 5, +/// value 7, count 0, not destroyed). +#[test] +fn sync_await_suspends_until_the_counter_condition_holds() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 5, + s::TEST_POSITIVE_COMPARISON, + 0, + ), + ); + assert!(f.suspended()); + assert!(f.b_packets().is_empty()); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 3)); + assert!(f.suspended(), "3 < 5"); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 7)); + assert!(!f.suspended()); + let events = f.b_packets(); + assert_eq!(events.len(), 1); + assert_eq!(counter_notify_fields(&events[0]), (SYNC_C1, 5, 7, 0, false)); + + // Already satisfied at request time: no suspension, the event + // still goes out (Xvfb: reply arrives with CounterNotify wait 5 + // value 7). + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 5, + s::TEST_POSITIVE_COMPARISON, + 0, + ), + ); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (SYNC_C1, 5, 7, 0, false) + ); +} + +/// Transitions need a crossing and events respect the threshold, per +/// Xvfb: PositiveTransition 10 thr 2 from 7 → set 9 (no), set 12 → +/// event value 12; from 12, PositiveTransition 10 → set 1 does not +/// fire (no upward crossing); from 1, PositiveTransition 10 → 5 (no), +/// 11 → event; PositiveTransition 0 thr 5 from -5 → set 1 resumes the +/// client without an event (diff 1 < 5). +#[test] +fn sync_await_transitions_and_event_threshold() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 7)); + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 10, + s::TEST_POSITIVE_TRANSITION, + 2, + ), + ); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 9)); + assert!(f.suspended()); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 12)); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (SYNC_C1, 10, 12, 0, false) + ); + + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 10, + s::TEST_POSITIVE_TRANSITION, + 100, + ), + ); + assert!(f.suspended(), "12 >= 10 but no transition yet"); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 1)); + assert!(f.suspended()); + f.state.sync_awaits.remove(&SYNC_B); + + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 10, + s::TEST_POSITIVE_TRANSITION, + 0, + ), + ); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 5)); + assert!(f.suspended()); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 11)); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (SYNC_C1, 10, 11, 0, false) + ); + + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, -5)); + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 0, + s::TEST_POSITIVE_TRANSITION, + 5, + ), + ); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 1)); + assert!(!f.suspended()); + assert!(f.b_packets().is_empty(), "diff below threshold: no event"); +} + +/// Xvfb: c1=11, c2=100; B awaits [c1 >= 1000 thr -2000, c2 <= 45 thr +/// 0]; A sets c2 50 (suspended) then 40 → both conditions report, in +/// order, count 1 then 0. Relative waits add to the counter (c1=11, +/// +3 → wait 14); NegativeTransition -3 fires on the way down. +#[test] +fn sync_await_multi_condition_relative_and_negative() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 11)); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 100)); + let mut body = sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 1000, + s::TEST_POSITIVE_COMPARISON, + -2000, + ); + body.extend(sync_wait( + SYNC_C2, + s::VALUE_TYPE_ABSOLUTE, + 45, + s::TEST_NEGATIVE_COMPARISON, + 0, + )); + f.b(s::AWAIT, &body); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C2, 50)); + assert!(f.suspended()); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C2, 40)); + assert!(!f.suspended()); + let events = f.b_packets(); + assert_eq!(events.len(), 2); + assert_eq!( + counter_notify_fields(&events[0]), + (SYNC_C1, 1000, 11, 1, false) + ); + assert_eq!( + counter_notify_fields(&events[1]), + (SYNC_C2, 45, 40, 0, false) + ); + + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_RELATIVE, + 3, + s::TEST_POSITIVE_COMPARISON, + 0, + ), + ); + f.a(s::CHANGE_COUNTER, &sync_counter_body(SYNC_C1, 2)); + assert!(f.suspended()); + f.a(s::CHANGE_COUNTER, &sync_counter_body(SYNC_C1, 1)); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (SYNC_C1, 14, 14, 0, false) + ); + + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + -3, + s::TEST_NEGATIVE_TRANSITION, + 0, + ), + ); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, -5)); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (SYNC_C1, -3, -5, 0, false) + ); +} + +/// Xvfb: destroying an awaited counter resumes the client with a +/// destroyed event carrying its last value, plus threshold events for +/// the other conditions; an alarm on it goes Inactive with an +/// AlarmNotify. A counter owner disconnecting does the same (value 0). +#[test] +fn sync_await_fires_destroyed_when_the_counter_goes_away() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, -5)); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 40)); + let mut body = sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 1000, + s::TEST_POSITIVE_COMPARISON, + 0, + ); + body.extend(sync_wait( + SYNC_C2, + s::VALUE_TYPE_ABSOLUTE, + 1000, + s::TEST_POSITIVE_COMPARISON, + -2000, + )); + f.b(s::AWAIT, &body); + f.state.sync_alarms.insert( + 0x0020_0009, + crate::server::SyncAlarm { + owner: ClientId(SYNC_B), + counter: SYNC_C1, + wait_value: 1000, + delta: 1, + test_type: s::TEST_POSITIVE_COMPARISON, + events: true, + state: s::ALARM_STATE_ACTIVE, + event_clients: Vec::new(), + value_type: 0, + raw_wait: 1000, + check_type: s::TEST_POSITIVE_COMPARISON, + }, + ); + f.a(s::DESTROY_COUNTER, &SYNC_C1.to_le_bytes()); + assert!(!f.suspended()); + let packets = f.b_packets(); + let notifies: Vec<_> = packets + .iter() + .filter(|p| p[0] == crate::nested::SYNC_FIRST_EVENT) + .map(counter_notify_fields) + .collect(); + assert_eq!( + notifies, + vec![(SYNC_C1, 1000, -5, 1, true), (SYNC_C2, 1000, 40, 0, false)] + ); + let alarm = packets + .iter() + .find(|p| p[0] == crate::nested::SYNC_FIRST_EVENT + 1) + .expect("AlarmNotify for the alarm on the destroyed counter"); + assert_eq!(alarm[28], s::ALARM_STATE_INACTIVE); + assert_eq!( + f.state.sync_alarms[&0x0020_0009].state, + s::ALARM_STATE_INACTIVE + ); + assert_eq!(f.state.sync_alarms[&0x0020_0009].counter, 0); + + // Owner disconnect: Xvfb sends destroyed, wait 10, value 0. + const C3: u32 = 0x0030_0001; + let _peer_c = install_client(&mut f.state, 3); + sync_req( + &mut f.state, + &mut f.backend, + 3, + s::CREATE_COUNTER, + &sync_counter_body(C3, 0), + ); + f.b( + s::AWAIT, + &sync_wait( + C3, + s::VALUE_TYPE_ABSOLUTE, + 10, + s::TEST_POSITIVE_COMPARISON, + 0, + ), + ); + assert!(f.suspended()); + crate::core_loop::process_disconnect::process_disconnect( + &mut f.state, + &mut f.backend, + ClientId(3), + ); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (C3, 10, 0, 0, true) + ); +} + +/// Xvfb: Initialize with client 3.1 / 3.0 / 2.0 / 4.0 always replies 3.1. +#[test] +fn sync_initialize_always_answers_the_server_version() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + for (major, minor) in [(3u8, 1u8), (3, 0), (2, 0), (4, 0)] { + f.b(s::INITIALIZE, &[major, minor, 0, 0]); + let reply = f.b_packets(); + assert_eq!(reply[0][0], 1); + assert_eq!((reply[0][8], reply[0][9]), (3, 1), "client {major}.{minor}"); + } +} + +/// Xvfb error table for Await and the counter requests. +#[test] +fn sync_await_and_counter_errors_match_xvfb() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + let bad_counter = crate::nested::SYNC_FIRST_ERROR + s::BAD_COUNTER; + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 100)); + let cases: [(Vec, u8, u32); 6] = [ + (Vec::new(), x11::error::BAD_VALUE, 0), + (sync_wait(0, 0, 1, 2, 0), bad_counter, 0), + (sync_wait(0x0bad_bad0, 0, 1, 2, 0), bad_counter, 0x0bad_bad0), + (sync_wait(SYNC_C2, 7, 1, 2, 0), x11::error::BAD_VALUE, 7), + (sync_wait(SYNC_C2, 0, 1, 9, 0), x11::error::BAD_VALUE, 9), + ( + sync_wait(SYNC_C2, 1, i64::MAX, 2, 0), + x11::error::BAD_VALUE, + 0x7fff_ffff, + ), + ]; + for (body, code, value) in cases { + f.b(s::AWAIT, &body); + assert!(!f.suspended(), "an erroring Await never suspends"); + assert_eq!( + error_fields(&f.b_packets()[0]), + (code, value, u16::from(s::AWAIT), 142) + ); + } + let mut peer_a = std::mem::replace(&mut f._peer_a, UnixStream::pair().unwrap().0); + let st = s::SERVERTIME_COUNTER; + let a_cases: [(u8, Vec, u8, u32); 5] = [ + ( + s::SET_COUNTER, + sync_counter_body(st, 1), + x11::error::BAD_ACCESS, + st, + ), + ( + s::SET_COUNTER, + sync_counter_body(0x0bad_bad0, 1), + bad_counter, + 0x0bad_bad0, + ), + ( + s::CHANGE_COUNTER, + sync_counter_body(SYNC_C2, i64::MAX), + x11::error::BAD_VALUE, + 0x7fff_ffff, + ), + ( + s::DESTROY_COUNTER, + st.to_le_bytes().to_vec(), + x11::error::BAD_ACCESS, + st, + ), + ( + s::DESTROY_COUNTER, + 0x0bad_bad0u32.to_le_bytes().to_vec(), + bad_counter, + 0x0bad_bad0, + ), + ]; + for (minor, body, code, value) in a_cases { + f.a(minor, &body); + assert_eq!( + error_fields(&wire_packets(&mut peer_a)[0]), + (code, value, u16::from(minor), 142) + ); + } + assert_eq!( + f.state.sync_counters[&SYNC_C2].value, 100, + "overflow left it alone" + ); +} + +/// Xvfb: AwaitFence on an untriggered fence suspends until TriggerFence +/// (no events); on a triggered fence it returns at once; destroying the +/// fence resumes with CounterNotify(counter = fence, 0, 0, destroyed). +/// Errors: empty → BadValue, None / unknown → BadFence; ResetFence of an +/// untriggered fence → BadMatch naming it. +#[test] +fn sync_await_fence_suspends_until_triggered() { + use yserver_protocol::x11::sync as s; + const F1: u32 = 0x0010_0010; + const F2: u32 = 0x0010_0011; + let mut f = sync_fixture(); + let fence_body = |fence: u32, triggered: bool| { + let mut body = ROOT_WINDOW.0.to_le_bytes().to_vec(); + body.extend_from_slice(&fence.to_le_bytes()); + body.extend_from_slice(&[u8::from(triggered), 0, 0, 0]); + body + }; + f.a(s::CREATE_FENCE, &fence_body(F1, false)); + f.a(s::CREATE_FENCE, &fence_body(F2, true)); + + f.b(s::AWAIT_FENCE, &F1.to_le_bytes()); + assert!(f.suspended()); + f.a(s::TRIGGER_FENCE, &F1.to_le_bytes()); + assert!(!f.suspended()); + assert!( + f.b_packets().is_empty(), + "fences send no events when triggered" + ); + + f.b(s::AWAIT_FENCE, &F2.to_le_bytes()); + assert!(!f.suspended(), "already triggered"); + + f.a(s::RESET_FENCE, &F1.to_le_bytes()); + f.b(s::AWAIT_FENCE, &F1.to_le_bytes()); + assert!(f.suspended()); + f.a(s::DESTROY_FENCE, &F1.to_le_bytes()); + assert!(!f.suspended()); + assert_eq!( + counter_notify_fields(&f.b_packets()[0]), + (F1, 0, 0, 0, true) + ); + + let bad_fence = crate::nested::SYNC_FIRST_ERROR + s::BAD_FENCE; + for (body, code, value) in [ + (Vec::new(), x11::error::BAD_VALUE, 0), + (0u32.to_le_bytes().to_vec(), bad_fence, 0), + ( + 0x0bad_bad0u32.to_le_bytes().to_vec(), + bad_fence, + 0x0bad_bad0, + ), + ] { + f.b(s::AWAIT_FENCE, &body); + assert!(!f.suspended()); + assert_eq!( + error_fields(&f.b_packets()[0]), + (code, value, u16::from(s::AWAIT_FENCE), 142) + ); + } + f.b(s::RESET_FENCE, &F2.to_le_bytes()); + f.b(s::RESET_FENCE, &F2.to_le_bytes()); + assert_eq!( + error_fields(&f.b_packets()[0]), + (x11::error::BAD_MATCH, F2, u16::from(s::RESET_FENCE), 142) + ); +} + +/// A Present idle fence triggered by the server wakes an AwaitFence on +/// it. A deliberate difference from Xorg: `present_fence_set_triggered` +/// only calls the fence's `SetTriggered`, not `miSyncTriggerFence`, so +/// on Xorg such an await is only re-checked by a TriggerFence request +/// or the fence's destruction and would otherwise stay suspended. +#[test] +fn sync_await_fence_wakes_on_server_side_trigger() { + use yserver_protocol::x11::sync as s; + const F1: u32 = 0x0010_0020; + let mut f = sync_fixture(); + f.state.sync_fences.insert( + F1, + crate::server::SyncFence { + owner: ClientId(SYNC_A), + triggered: false, + }, + ); + f.b(s::AWAIT_FENCE, &F1.to_le_bytes()); + assert!(f.suspended()); + crate::core_loop::sync_await::fence_triggered(&mut f.state, F1); + assert!(!f.suspended()); + assert!(f.state.sync_fences[&F1].triggered); +} + +/// A ChangeAlarm body: alarm, value mask, value list. +fn sync_alarm_body(alarm: u32, mask: u32, values: &[u32]) -> Vec { + let mut body = alarm.to_le_bytes().to_vec(); + body.extend_from_slice(&mask.to_le_bytes()); + for v in values { + body.extend_from_slice(&v.to_le_bytes()); + } + body +} + +/// Xvfb: ChangeAlarm / QueryAlarm / DestroyAlarm on an alarm that +/// does not exist (unknown, None, or destroyed) answer BadAlarm (SYNC +/// error base + 1) naming it. Xorg's order: QueryAlarm and DestroyAlarm +/// check the exact request size first (BadLength), ChangeAlarm checks +/// the minimum size, then looks the alarm up, and only then matches the +/// value list against the mask (BadLength naming the alarm). +#[test] +fn sync_alarm_requests_on_a_missing_alarm_answer_bad_alarm() { + use yserver_protocol::x11::sync as s; + const ALARM: u32 = 0x0010_0030; + const GONE: u32 = 0x0010_0031; + const UNKNOWN: u32 = 0x0bad_bad0; + let bad_alarm = crate::nested::SYNC_FIRST_ERROR + s::BAD_ALARM; + let bad_length = x11::error::BAD_LENGTH; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); + f.a( + s::CREATE_ALARM, + &sync_alarm_body(ALARM, s::CA_COUNTER, &[SYNC_C1]), + ); + f.a( + s::CREATE_ALARM, + &sync_alarm_body(GONE, s::CA_COUNTER, &[SYNC_C1]), + ); + f.a(s::DESTROY_ALARM, &GONE.to_le_bytes()); + let _ = f.b_packets(); + let long = sync_alarm_body(UNKNOWN, s::CA_EVENTS, &[]); + let cases: Vec<(u8, Vec, u8, u32)> = vec![ + ( + s::QUERY_ALARM, + UNKNOWN.to_le_bytes().to_vec(), + bad_alarm, + UNKNOWN, + ), + (s::QUERY_ALARM, 0u32.to_le_bytes().to_vec(), bad_alarm, 0), + (s::QUERY_ALARM, GONE.to_le_bytes().to_vec(), bad_alarm, GONE), + ( + s::CHANGE_ALARM, + sync_alarm_body(UNKNOWN, 0, &[]), + bad_alarm, + UNKNOWN, + ), + ( + s::CHANGE_ALARM, + sync_alarm_body(GONE, 0, &[]), + bad_alarm, + GONE, + ), + (s::CHANGE_ALARM, long.clone(), bad_alarm, UNKNOWN), + ( + s::DESTROY_ALARM, + UNKNOWN.to_le_bytes().to_vec(), + bad_alarm, + UNKNOWN, + ), + ( + s::DESTROY_ALARM, + GONE.to_le_bytes().to_vec(), + bad_alarm, + GONE, + ), + (s::QUERY_ALARM, long.clone(), bad_length, 0), + (s::DESTROY_ALARM, long, bad_length, 0), + ( + s::CHANGE_ALARM, + UNKNOWN.to_le_bytes().to_vec(), + bad_length, + 0, + ), + ( + s::CHANGE_ALARM, + sync_alarm_body(ALARM, s::CA_EVENTS, &[]), + bad_length, + ALARM, + ), + ( + s::CHANGE_ALARM, + sync_alarm_body(ALARM, s::CA_VALUE, &[0]), + bad_length, + ALARM, + ), + ]; + for (minor, body, code, value) in cases { + f.b(minor, &body); + let packets = f.b_packets(); + assert!( + !packets.is_empty(), + "minor {minor} body {body:x?}: no error" + ); + assert_eq!( + error_fields(&packets[0]), + (code, value, u16::from(minor), 142), + "minor {minor} body {body:x?}" + ); + } + assert!(f.state.sync_alarms.contains_key(&ALARM)); +} + +/// QueryAlarm → (counter, value type, wait value, test type, delta, +/// events, state), per `xSyncQueryAlarmReply`. +fn query_alarm_fields(f: &mut SyncFixture, alarm: u32) -> (u32, u32, i64, u32, i64, u8, u8) { + use yserver_protocol::x11::sync as s; + f.b(s::QUERY_ALARM, &alarm.to_le_bytes()); + let r = read_all_available(&mut f.peer_b); + assert_eq!((r.len(), r[0]), (40, 1), "QueryAlarm reply"); + let i64_at = |at: usize| { + #[allow(clippy::cast_possible_wrap)] + let hi = le_u32(&r, at) as i32; + (i64::from(hi) << 32) | i64::from(le_u32(&r, at + 4)) + }; + ( + le_u32(&r, 8), + le_u32(&r, 12), + i64_at(16), + le_u32(&r, 24), + i64_at(28), + r[36], + r[37], + ) +} + +/// Xvfb: QueryAlarm reports the alarm's test type (a fresh alarm's +/// default is PositiveComparison, 2) and, as Xorg's +/// `ProcSyncQueryAlarm`, always value type Absolute with the resolved +/// wait value. +#[test] +fn sync_query_alarm_reports_the_test_type() { + use yserver_protocol::x11::sync as s; + const AL: u32 = 0x0010_0080; + const AN: u32 = 0x0010_0081; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); + f.a( + s::CREATE_ALARM, + &sync_alarm_body(AL, s::CA_COUNTER | s::CA_VALUE, &[SYNC_C1, 0, 10]), + ); + assert_eq!( + query_alarm_fields(&mut f, AL), + ( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 10, + s::TEST_POSITIVE_COMPARISON, + 1, + 1, + s::ALARM_STATE_ACTIVE + ) + ); + f.a(s::CREATE_ALARM, &sync_alarm_body(AN, s::CA_VALUE, &[0, 5])); + assert_eq!( + query_alarm_fields(&mut f, AN), + ( + 0, + s::VALUE_TYPE_ABSOLUTE, + 5, + s::TEST_POSITIVE_COMPARISON, + 1, + 1, + s::ALARM_STATE_INACTIVE + ) + ); +} + +/// Xvfb ("CreateAlarm attribute errors"): Xorg's checks, in its order — +/// the value list in mask-bit order (`events` not True/False, unknown +/// bits naming the bits above), the delta sign against the test type +/// (the default delta 1 counts), then the trigger: unknown counter, +/// value type, Relative without a counter, INT64 overflow (naming the +/// value's high word), test type. BadMatch names the alarm. A failing +/// CreateAlarm creates nothing. +#[test] +fn sync_create_alarm_attribute_errors_match_xvfb() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 14)); + let bad_counter = crate::nested::SYNC_FIRST_ERROR + s::BAD_COUNTER; + let (value, matchh) = (x11::error::BAD_VALUE, x11::error::BAD_MATCH); + let c = SYNC_C1; + let unknown = 0x0bad_bad0; + // (mask, values, expected error (code, value; None = the alarm id)). + type Case = (u32, Vec, Option<(u8, Option)>); + let cases: Vec = vec![ + ( + s::CA_COUNTER | s::CA_TEST_TYPE, + vec![c, 9], + Some((value, Some(9))), + ), + ( + s::CA_COUNTER | s::CA_VALUE_TYPE, + vec![c, 7], + Some((value, Some(7))), + ), + ( + s::CA_COUNTER | s::CA_EVENTS, + vec![c, 2], + Some((value, Some(2))), + ), + ( + s::CA_COUNTER, + vec![unknown], + Some((bad_counter, Some(unknown))), + ), + ( + s::CA_VALUE_TYPE, + vec![s::VALUE_TYPE_RELATIVE], + Some((matchh, None)), + ), + ( + s::CA_COUNTER | s::CA_TEST_TYPE | s::CA_DELTA, + vec![c, s::TEST_POSITIVE_COMPARISON, u32::MAX, u32::MAX], + Some((matchh, None)), + ), + ( + s::CA_COUNTER | s::CA_TEST_TYPE, + vec![c, s::TEST_NEGATIVE_COMPARISON], + Some((matchh, None)), + ), + ( + s::CA_COUNTER | s::CA_TEST_TYPE | s::CA_DELTA, + vec![c, s::TEST_NEGATIVE_COMPARISON, 0, 0], + None, + ), + ( + s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE, + vec![c, s::VALUE_TYPE_RELATIVE, 0x7fff_ffff, u32::MAX], + Some((value, Some(0x7fff_ffff))), + ), + ( + s::CA_COUNTER | s::CA_TEST_TYPE, + vec![unknown, 9], + Some((bad_counter, Some(unknown))), + ), + ( + s::CA_VALUE_TYPE | s::CA_TEST_TYPE, + vec![7, 9], + Some((value, Some(7))), + ), + (1 << 6, vec![0], Some((value, Some(0)))), + (s::CA_EVENTS | 1 << 6, vec![2, 0], Some((value, Some(2)))), + ]; + for (index, (mask, values, expect)) in cases.into_iter().enumerate() { + let alarm = 0x0020_0100 + u32::try_from(index).unwrap(); + f.b(s::CREATE_ALARM, &sync_alarm_body(alarm, mask, &values)); + let packets = f.b_packets(); + match expect { + Some((code, bad)) => { + assert_eq!( + error_fields(&packets[0]), + (code, bad.unwrap_or(alarm), u16::from(s::CREATE_ALARM), 142), + "case {index}" + ); + assert!(!f.state.sync_alarms.contains_key(&alarm), "case {index}"); + } + None => { + assert!(packets.is_empty(), "case {index}"); + assert!(f.state.sync_alarms.contains_key(&alarm), "case {index}"); + } + } + } +} + +/// Xvfb ("ChangeAlarm attribute errors: what sticks"): a failing +/// ChangeAlarm keeps what Xorg's `SyncChangeAlarmAttributes` stored +/// before `SyncInitTrigger` failed — delta, value type, value and the +/// test type — while the counter, the resolved wait value (except an +/// overflowing Relative sum, which is stored wrapped), the test the +/// trigger runs and the state stay. A stored bad value type makes a +/// later value-only change Relative; a stored bad test type is what +/// QueryAlarm reports, passes the delta-sign check, and the alarm keeps +/// firing on its old PositiveComparison. +#[test] +fn sync_change_alarm_failures_keep_what_xorg_keeps() { + use yserver_protocol::x11::sync as s; + const X: u32 = 0x0010_0090; + let mut f = sync_fixture(); + let bad_counter = crate::nested::SYNC_FIRST_ERROR + s::BAD_COUNTER; + let (value, matchh) = (x11::error::BAD_VALUE, x11::error::BAD_MATCH); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 20)); + f.a( + s::CREATE_ALARM, + &sync_alarm_body( + X, + s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE | s::CA_TEST_TYPE | s::CA_DELTA, + &[SYNC_C1, 0, 0, 30, s::TEST_POSITIVE_COMPARISON, 0, 1], + ), + ); + let q = |f: &mut SyncFixture| query_alarm_fields(f, X); + let pc = s::TEST_POSITIVE_COMPARISON; + assert_eq!(q(&mut f), (SYNC_C1, 0, 30, pc, 1, 1, 0)); + let change = |f: &mut SyncFixture, mask: u32, values: &[u32]| { + f.a(s::CHANGE_ALARM, &sync_alarm_body(X, mask, values)); + f.a_packets() + .first() + .map(error_fields) + .map(|(code, bad, minor, _)| { + assert_eq!(minor, u16::from(s::CHANGE_ALARM)); + (code, bad) + }) + }; + let m = u32::MAX; + assert_eq!( + change(&mut f, s::CA_VALUE_TYPE | s::CA_VALUE, &[7, 0, 50]), + Some((value, 7)) + ); + assert_eq!(q(&mut f), (SYNC_C1, 0, 30, pc, 1, 1, 0)); + assert_eq!(change(&mut f, s::CA_VALUE, &[0, 5]), None); + assert_eq!( + q(&mut f), + (SYNC_C1, 0, 25, pc, 1, 1, 0), + "stored type 7 acts Relative" + ); + assert_eq!( + change( + &mut f, + s::CA_COUNTER | s::CA_VALUE | s::CA_DELTA, + &[0x0bad_bad0, 0, 70, 0, 3] + ), + Some((bad_counter, 0x0bad_bad0)) + ); + assert_eq!(q(&mut f), (SYNC_C1, 0, 25, pc, 3, 1, 0), "delta sticks"); + assert_eq!(change(&mut f, s::CA_DELTA, &[m, m]), Some((matchh, X))); + assert_eq!( + change( + &mut f, + s::CA_VALUE_TYPE | s::CA_VALUE | s::CA_TEST_TYPE, + &[0, 0, 100, s::TEST_NEGATIVE_TRANSITION] + ), + Some((matchh, X)) + ); + assert_eq!(q(&mut f), (SYNC_C1, 0, 25, pc, 3, 1, 0)); + assert_eq!(change(&mut f, s::CA_TEST_TYPE, &[9]), Some((value, 9))); + assert_eq!(q(&mut f), (SYNC_C1, 0, 25, 9, 3, 1, 0)); + assert_eq!( + change(&mut f, s::CA_DELTA, &[m, m]), + None, + "no sign for test type 9" + ); + assert_eq!(q(&mut f), (SYNC_C1, 0, 25, 9, -1, 1, 0)); + assert_eq!(change(&mut f, s::CA_DELTA, &[0, 1]), None); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 25)); + assert_eq!( + alarm_notifies(&f.a_packets()), + vec![(X, 25, 25, s::ALARM_STATE_ACTIVE)] + ); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 21)); + assert!(f.a_packets().is_empty()); + assert_eq!(q(&mut f), (SYNC_C1, 0, 26, 9, 1, 1, 0)); + f.a(s::CHANGE_ALARM, &sync_alarm_body(X, s::CA_COUNTER, &[0])); + assert_eq!( + alarm_notifies(&f.a_packets()), + vec![(X, 0, 26, s::ALARM_STATE_INACTIVE)] + ); + assert_eq!( + change(&mut f, s::CA_VALUE_TYPE, &[s::VALUE_TYPE_RELATIVE]), + Some((matchh, X)) + ); + assert_eq!(q(&mut f), (0, 0, 26, 9, 1, 1, s::ALARM_STATE_INACTIVE)); + assert_eq!( + change( + &mut f, + s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE, + &[SYNC_C1, s::VALUE_TYPE_RELATIVE, 0x7fff_ffff, m] + ), + Some((value, 0x7fff_ffff)) + ); + let wrapped = 21i64.wrapping_add(i64::MAX); + assert_eq!(q(&mut f), (0, 0, wrapped, 9, 1, 1, s::ALARM_STATE_INACTIVE)); + assert_eq!(change(&mut f, 1 << 6, &[0]), Some((value, 0))); + f.a(s::DESTROY_ALARM, &X.to_le_bytes()); + assert_eq!( + alarm_notifies(&f.a_packets()), + vec![(X, 0, wrapped, s::ALARM_STATE_DESTROYED)] + ); +} + +/// Xvfb (the "bad test type" line of "AlarmNotify selection"): B's +/// ChangeAlarm {test type 9, events True} on A's alarm is BadValue(9), +/// yet B is selected (the selection precedes the check) and the alarm, +/// still running PositiveComparison, notifies B when the counter +/// reaches it; QueryAlarm reports test type 9. +#[test] +fn sync_alarm_bad_test_type_still_selects_and_fires() { + use yserver_protocol::x11::sync as s; + const AL: u32 = 0x0010_00a0; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 13)); + f.a( + s::CREATE_ALARM, + &sync_alarm_body( + AL, + s::CA_COUNTER | s::CA_VALUE | s::CA_EVENTS, + &[SYNC_C1, 0, 14, 0], + ), + ); + f.b( + s::CHANGE_ALARM, + &sync_alarm_body(AL, s::CA_TEST_TYPE | s::CA_EVENTS, &[9, 1]), + ); + assert_eq!( + error_fields(&f.b_packets()[0]), + (x11::error::BAD_VALUE, 9, u16::from(s::CHANGE_ALARM), 142) + ); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 14)); + assert_eq!( + alarm_notifies(&f.b_packets()), + vec![(AL, 14, 14, s::ALARM_STATE_ACTIVE)] + ); + assert!(f.a_packets().is_empty()); + assert_eq!(query_alarm_fields(&mut f, AL), (SYNC_C1, 0, 15, 9, 1, 0, 0)); +} + +/// Every AlarmNotify in `packets` → (alarm, counter value, alarm +/// value, state). +fn alarm_notifies(packets: &[[u8; 32]]) -> Vec<(u32, i64, i64, u8)> { + let i64_at = |p: &[u8; 32], at: usize| { + #[allow(clippy::cast_possible_wrap)] + let hi = le_u32(p, at) as i32; + (i64::from(hi) << 32) | i64::from(le_u32(p, at + 4)) + }; + packets + .iter() + .filter(|p| p[0] == crate::nested::SYNC_FIRST_EVENT + 1) + .map(|p| { + assert_eq!(p[1], 1, "kind AlarmNotify"); + (le_u32(p, 4), i64_at(p, 8), i64_at(p, 16), p[28]) + }) + .collect() +} + +fn sync_events_body(alarm: u32, on: u32) -> Vec { + use yserver_protocol::x11::sync as s; + sync_alarm_body(alarm, s::CA_EVENTS, &[on]) +} + +/// Xvfb (tools/sync-await-probe.c, "AlarmNotify selection"): an alarm +/// owned by A (c >= 10, delta 1, events). B and D select AlarmNotify +/// with ChangeAlarm(events=True) — any client may — and every firing +/// reaches the owner (while its own flag is set) and each selecting +/// client once. events=False by B removes B; by A clears only the +/// owner's flag (what QueryAlarm reports). A selecting client that +/// disconnects drops off the list. A non-owner may change other +/// attributes too. DestroyAlarm sends a Destroyed notify to the +/// selecting clients. An `events` value other than True/False is +/// BadValue naming it and selects nothing. +#[test] +fn sync_alarm_notify_reaches_every_client_that_selected_it() { + use yserver_protocol::x11::sync as s; + const AL: u32 = 0x0010_0040; + const D: u32 = 3; + let mut f = sync_fixture(); + let mut peer_d = install_client(&mut f.state, D); + let d_req = |f: &mut SyncFixture, minor: u8, body: &[u8]| { + sync_req(&mut f.state, &mut f.backend, D, minor, body); + }; + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); + let mut create = AL.to_le_bytes().to_vec(); + create.extend_from_slice( + &(s::CA_COUNTER + | s::CA_VALUE_TYPE + | s::CA_VALUE + | s::CA_TEST_TYPE + | s::CA_DELTA + | s::CA_EVENTS) + .to_le_bytes(), + ); + for v in [ + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 0, + 10, + s::TEST_POSITIVE_COMPARISON, + 0, + 1, + 1, + ] { + create.extend_from_slice(&v.to_le_bytes()); + } + f.a(s::CREATE_ALARM, &create); + f.b(s::CHANGE_ALARM, &sync_events_body(AL, 1)); + d_req(&mut f, s::CHANGE_ALARM, &sync_events_body(AL, 1)); + f.b(s::CHANGE_ALARM, &sync_events_body(AL, 1)); + assert!(f.b_packets().is_empty(), "selecting sends nothing"); + assert!(f.state.sync_alarms[&AL].events, "owner flag untouched"); + assert!(f.a_packets().is_empty()); + + let set = |f: &mut SyncFixture, v: i64| f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, v)); + set(&mut f, 10); + let fired = |v: i64| vec![(AL, v, v, s::ALARM_STATE_ACTIVE)]; + assert_eq!(alarm_notifies(&f.a_packets()), fired(10)); + assert_eq!(alarm_notifies(&f.b_packets()), fired(10), "B once"); + assert_eq!(alarm_notifies(&wire_packets(&mut peer_d)), fired(10)); + + f.b(s::CHANGE_ALARM, &sync_events_body(AL, 0)); + set(&mut f, 11); + assert_eq!(alarm_notifies(&f.a_packets()), fired(11)); + assert!(f.b_packets().is_empty(), "B deselected"); + assert_eq!(alarm_notifies(&wire_packets(&mut peer_d)), fired(11)); + + f.a(s::CHANGE_ALARM, &sync_events_body(AL, 0)); + set(&mut f, 12); + assert!(f.a_packets().is_empty(), "owner flag off"); + assert!(!f.state.sync_alarms[&AL].events); + assert_eq!(alarm_notifies(&wire_packets(&mut peer_d)), fired(12)); + + crate::core_loop::process_disconnect::process_disconnect( + &mut f.state, + &mut f.backend, + ClientId(D), + ); + assert!(f.state.sync_alarms[&AL].event_clients.is_empty()); + set(&mut f, 13); + assert!(f.a_packets().is_empty() && f.b_packets().is_empty()); + + f.b(s::CHANGE_ALARM, &sync_events_body(AL, 9)); + assert_eq!( + error_fields(&f.b_packets()[0]), + (x11::error::BAD_VALUE, 9, u16::from(s::CHANGE_ALARM), 142) + ); + assert!(f.state.sync_alarms[&AL].event_clients.is_empty()); + + f.b(s::CHANGE_ALARM, &sync_events_body(AL, 1)); + set(&mut f, 14); + assert_eq!(alarm_notifies(&f.b_packets()), fired(14)); + f.b( + s::CHANGE_ALARM, + &sync_alarm_body(AL, s::CA_VALUE, &[0, 100]), + ); + assert!(f.b_packets().is_empty(), "a non-owner may change the value"); + assert_eq!(f.state.sync_alarms[&AL].wait_value, 100); + + f.a(s::DESTROY_ALARM, &AL.to_le_bytes()); + assert!(f.a_packets().is_empty()); + assert_eq!( + alarm_notifies(&f.b_packets()), + vec![(AL, 14, 100, s::ALARM_STATE_DESTROYED)] + ); +} + +/// Xvfb: a non-owner may DestroyAlarm (owner and selecting clients get +/// the Destroyed notify); the owner's disconnect destroys its alarms, +/// and the clients that selected them get the Destroyed notify with +/// the counter's value. A destroyed counter deactivates the alarm with +/// an Inactive notify to them as well. +#[test] +fn sync_alarm_destruction_notifies_every_selecting_client() { + use yserver_protocol::x11::sync as s; + const E: u32 = 3; + const CE: u32 = 0x0030_0001; + const AE1: u32 = 0x0030_0002; + const AE2: u32 = 0x0030_0003; + const A2: u32 = 0x0010_0050; + let mut f = sync_fixture(); + let mut peer_e = install_client(&mut f.state, E); + let e_req = |f: &mut SyncFixture, minor: u8, body: &[u8]| { + sync_req(&mut f.state, &mut f.backend, E, minor, body); + }; + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 14)); + e_req(&mut f, s::CREATE_COUNTER, &sync_counter_body(CE, 0)); + e_req( + &mut f, + s::CREATE_ALARM, + &sync_alarm_body(AE1, s::CA_COUNTER | s::CA_VALUE, &[CE, 0, 50]), + ); + e_req( + &mut f, + s::CREATE_ALARM, + &sync_alarm_body(AE2, s::CA_COUNTER | s::CA_VALUE, &[SYNC_C1, 0, 50]), + ); + f.b(s::CHANGE_ALARM, &sync_events_body(AE1, 1)); + f.b(s::CHANGE_ALARM, &sync_events_body(AE2, 1)); + f.b(s::DESTROY_ALARM, &AE1.to_le_bytes()); + let destroyed = vec![(AE1, 0, 50, s::ALARM_STATE_DESTROYED)]; + assert_eq!(alarm_notifies(&wire_packets(&mut peer_e)), destroyed); + assert_eq!(alarm_notifies(&f.b_packets()), destroyed); + assert!(!f.state.sync_alarms.contains_key(&AE1)); + + crate::core_loop::process_disconnect::process_disconnect( + &mut f.state, + &mut f.backend, + ClientId(E), + ); + assert_eq!( + alarm_notifies(&f.b_packets()), + vec![(AE2, 14, 50, s::ALARM_STATE_DESTROYED)] + ); + assert!(!f.state.sync_alarms.contains_key(&AE2)); + + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C2, 3)); + f.a( + s::CREATE_ALARM, + &sync_alarm_body(A2, s::CA_COUNTER | s::CA_VALUE, &[SYNC_C2, 0, 50]), + ); + f.b(s::CHANGE_ALARM, &sync_events_body(A2, 1)); + f.a(s::DESTROY_COUNTER, &SYNC_C2.to_le_bytes()); + let inactive = vec![(A2, 3, 50, s::ALARM_STATE_INACTIVE)]; + assert_eq!(alarm_notifies(&f.a_packets()), inactive); + assert_eq!(alarm_notifies(&f.b_packets()), inactive); + f.a(s::DESTROY_ALARM, &A2.to_le_bytes()); + let destroyed = vec![(A2, 0, 50, s::ALARM_STATE_DESTROYED)]; + assert_eq!(alarm_notifies(&f.a_packets()), destroyed); + assert_eq!(alarm_notifies(&f.b_packets()), destroyed); +} + +/// Xvfb: CreateAlarm defaults are Xorg's (PositiveComparison, value 0, +/// delta 1, events): on a counter at 0 it fires at once and re-arms to +/// a wait value of 1. Without a counter the alarm starts Inactive and +/// silent; a ChangeAlarm on it then fires Inactive with counter value +/// 0 ("NULL counter WILL trigger in ChangeAlarm"). +#[test] +fn sync_alarm_defaults_and_counterless_alarms_match_xvfb() { + use yserver_protocol::x11::sync as s; + const GONE: u32 = 0x0010_0060; + const AN: u32 = 0x0020_0060; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); + f.a( + s::CREATE_ALARM, + &sync_alarm_body(GONE, s::CA_COUNTER, &[SYNC_C1]), + ); + assert_eq!( + alarm_notifies(&f.a_packets()), + vec![(GONE, 0, 0, s::ALARM_STATE_ACTIVE)] + ); + f.a(s::DESTROY_ALARM, &GONE.to_le_bytes()); + assert_eq!( + alarm_notifies(&f.a_packets()), + vec![(GONE, 0, 1, s::ALARM_STATE_DESTROYED)] + ); + + f.b(s::CREATE_ALARM, &sync_alarm_body(AN, s::CA_VALUE, &[0, 5])); + assert!(f.b_packets().is_empty()); + assert_eq!(f.state.sync_alarms[&AN].state, s::ALARM_STATE_INACTIVE); + f.b(s::CHANGE_ALARM, &sync_events_body(AN, 1)); + assert_eq!( + alarm_notifies(&f.b_packets()), + vec![(AN, 0, 5, s::ALARM_STATE_INACTIVE)] + ); + f.b(s::DESTROY_ALARM, &AN.to_le_bytes()); + assert_eq!( + alarm_notifies(&f.b_packets()), + vec![(AN, 0, 5, s::ALARM_STATE_DESTROYED)] + ); +} + +/// A DRI3 FenceFromFD xshmfence keeps its state in memory the client +/// can trigger and reset itself (`xshmfence_trigger` / +/// `xshmfence_reset`). Xorg's shm fence (`misyncshm.c`) answers every +/// `CheckTriggered` from that memory — QueryFence, the AwaitFence +/// epilogue, ResetFence's BadMatch test, and `miSyncTriggerFence`'s +/// re-check — and never from the server's own bit; ResetFence resets +/// the memory and DestroyFence triggers it before unmapping. Nothing in +/// Xorg watches the memory, so an AwaitFence already suspended stays +/// suspended when the client triggers it in memory, until a +/// TriggerFence request or the fence's destruction. Xvfb has no DRI3, +/// so this follows the source (`miSyncShmFenceCheckTriggered`, +/// `miSyncShmFenceReset`, `miSyncShmScreenDestroyFence`, +/// `SyncAwaitEpilogue`, `miSyncTriggerFence`). +#[test] +fn sync_shm_fence_state_is_read_from_shared_memory() { + use yserver_protocol::x11::sync as s; + const F: u32 = 0x0010_0070; + const G: u32 = 0x0010_0071; + let mut f = sync_fixture(); + for fence in [F, G] { + f.state.sync_fences.insert( + fence, + crate::server::SyncFence { + owner: ClientId(SYNC_A), + triggered: false, + }, + ); + f.backend.shm_fences.insert(fence, false); + } + let query = |f: &mut SyncFixture| { + f.b(s::QUERY_FENCE, &F.to_le_bytes()); + let reply = f.b_packets(); + assert_eq!(reply[0][0], 1, "QueryFence reply"); + reply[0][8] != 0 + }; + + // The client triggers it in memory: QueryFence sees it and an + // AwaitFence returns at once. + f.backend.shm_fences.insert(F, true); + assert!(query(&mut f)); + f.b(s::AWAIT_FENCE, &F.to_le_bytes()); + assert!(!f.suspended()); + + // The client resets it in memory after the server triggered it: + // the memory wins over the server's bit. + f.a(s::TRIGGER_FENCE, &F.to_le_bytes()); + assert!(f.state.sync_fences[&F].triggered); + f.backend.shm_fences.insert(F, false); + assert!(!query(&mut f)); + f.b(s::RESET_FENCE, &F.to_le_bytes()); + assert_eq!( + error_fields(&f.b_packets()[0]), + (x11::error::BAD_MATCH, F, u16::from(s::RESET_FENCE), 142), + "untriggered in memory" + ); + f.b(s::AWAIT_FENCE, &F.to_le_bytes()); + assert!(f.suspended(), "untriggered in memory"); + + // A trigger in memory alone wakes nothing (Xorg never looks); + // a TriggerFence request does. + f.backend.shm_fences.insert(F, true); + assert!(f.suspended()); + f.a(s::TRIGGER_FENCE, &F.to_le_bytes()); + assert!(!f.suspended()); + + // ResetFence of a fence triggered in memory resets the memory. + f.b(s::RESET_FENCE, &F.to_le_bytes()); + assert!(f.b_packets().is_empty()); + assert_eq!(f.backend.shm_fences.get(&F), Some(&false)); + assert!(!query(&mut f)); + + // DestroyFence triggers the memory (releasing client waiters) and + // unmaps it; so does the owner's disconnect. + f.a(s::DESTROY_FENCE, &F.to_le_bytes()); + assert_eq!(f.backend.destroyed_shm_fences, vec![(F, true)]); + assert!(!f.backend.shm_fences.contains_key(&F)); + crate::core_loop::process_disconnect::process_disconnect( + &mut f.state, + &mut f.backend, + ClientId(SYNC_A), + ); + assert_eq!(f.backend.destroyed_shm_fences, vec![(F, true), (G, true)]); + assert!(f.backend.shm_fences.is_empty()); +} + +/// SERVERTIME awaits wake when the clock reaches the value (Xvfb: an +/// absolute now+300 PositiveComparison blocked ~300 ms and reported +/// wait == value), and the loop gets a deadline for it. +#[test] +fn sync_await_on_servertime_fires_when_the_clock_gets_there() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + let now = i64::from(f.state.timestamp_now()); + f.b( + s::AWAIT, + &sync_wait( + s::SERVERTIME_COUNTER, + s::VALUE_TYPE_ABSOLUTE, + now + 300, + s::TEST_POSITIVE_COMPARISON, + 0, + ), + ); + assert!(f.suspended()); + let deadline = crate::core_loop::sync_await::system_counter_deadline(&f.state) + .expect("a SERVERTIME deadline"); + let wait = deadline.saturating_duration_since(std::time::Instant::now()); + assert!( + wait > std::time::Duration::from_millis(200) + && wait <= std::time::Duration::from_millis(300), + "deadline ~300 ms out, got {wait:?}" + ); + crate::core_loop::sync_await::evaluate_servertime(&mut f.state); + assert!(f.suspended(), "not there yet"); + // Let 400 ms of server time pass. Until the loop evaluates it, the + // passed value must read as due now — never as "no deadline", or + // an idle loop would block past it. + f.state.start_instant -= std::time::Duration::from_millis(400); + let due = crate::core_loop::sync_await::system_counter_deadline(&f.state) + .expect("still pending until evaluated"); + assert!(due <= std::time::Instant::now()); + crate::core_loop::sync_await::evaluate_servertime(&mut f.state); + assert!(!f.suspended()); + let (counter, wait_value, value, count, destroyed) = counter_notify_fields(&f.b_packets()[0]); + assert_eq!( + (counter, wait_value, count, destroyed), + (s::SERVERTIME_COUNTER, now + 300, 0, false) + ); + assert!(value >= now + 300); + assert!(crate::core_loop::sync_await::system_counter_deadline(&f.state).is_none()); +} + +/// SERVERTIME alarms fire too (Xvfb: an absolute now+200 +/// PositiveComparison alarm with delta 0 sent AlarmNotify after ~200 ms +/// with state Inactive and counter >= alarm value). +#[test] +fn sync_alarm_on_servertime_fires_when_the_clock_gets_there() { + use yserver_protocol::x11::sync as s; + const ALARM: u32 = 0x0010_0030; + let mut f = sync_fixture(); + let now = i64::from(f.state.timestamp_now()); + let mut body = ALARM.to_le_bytes().to_vec(); + let mask = s::CA_COUNTER | s::CA_VALUE_TYPE | s::CA_VALUE | s::CA_TEST_TYPE | s::CA_DELTA; + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&s::SERVERTIME_COUNTER.to_le_bytes()); + body.extend_from_slice(&s::VALUE_TYPE_ABSOLUTE.to_le_bytes()); + body.extend_from_slice(&sync_i64(now + 200)); + body.extend_from_slice(&s::TEST_POSITIVE_COMPARISON.to_le_bytes()); + body.extend_from_slice(&sync_i64(0)); + f.b(s::CREATE_ALARM, &body); + assert!(f.b_packets().is_empty(), "not due yet"); + assert!(crate::core_loop::sync_await::system_counter_deadline(&f.state).is_some()); + f.state.start_instant -= std::time::Duration::from_millis(300); + crate::core_loop::sync_await::evaluate_servertime(&mut f.state); + let packets = f.b_packets(); + assert_eq!(packets.len(), 1); + assert_eq!( + packets[0][0], + crate::nested::SYNC_FIRST_EVENT + 1, + "AlarmNotify" + ); + assert_eq!(packets[0][28], s::ALARM_STATE_INACTIVE); + assert_eq!(f.state.sync_alarms[&ALARM].state, s::ALARM_STATE_INACTIVE); +} + +/// IDLETIME awaits: a positive test wakes when idle time reaches it; a +/// negative transition wakes on input (idle drops to 0). +#[test] +fn sync_await_on_idletime_fires_on_idle_and_on_input() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.state.dpms.last_activity = std::time::Instant::now(); + f.b( + s::AWAIT, + &sync_wait( + s::IDLETIME_COUNTER, + s::VALUE_TYPE_ABSOLUTE, + 5_000, + s::TEST_POSITIVE_TRANSITION, + 0, + ), + ); + assert!(f.suspended()); + assert!(crate::core_loop::sync_await::system_counter_deadline(&f.state).is_some()); + f.state.dpms.last_activity -= std::time::Duration::from_secs(6); + crate::core_loop::run::evaluate_idletime_alarms_post_poll(&mut f.state, &mut f.backend); + assert!(!f.suspended()); + let (counter, wait_value, _, _, _) = counter_notify_fields(&f.b_packets()[0]); + assert_eq!((counter, wait_value), (s::IDLETIME_COUNTER, 5_000)); + + f.b( + s::AWAIT, + &sync_wait( + s::IDLETIME_COUNTER, + s::VALUE_TYPE_ABSOLUTE, + 1_000, + s::TEST_NEGATIVE_TRANSITION, + 0, + ), + ); + assert!(f.suspended(), "idle is ~6 s, no downward crossing yet"); + evaluate_idletime_negative_alarms_on_input_wake(&mut f.state, 2, 6_000, 6_000); + assert!(!f.suspended()); +} + +/// The awaiting client's own disconnect drops its await. +#[test] +fn sync_await_dies_with_its_client() { + use yserver_protocol::x11::sync as s; + let mut f = sync_fixture(); + f.a(s::CREATE_COUNTER, &sync_counter_body(SYNC_C1, 0)); + f.b( + s::AWAIT, + &sync_wait( + SYNC_C1, + s::VALUE_TYPE_ABSOLUTE, + 5, + s::TEST_POSITIVE_COMPARISON, + 0, + ), + ); + assert!(f.suspended()); + crate::core_loop::process_disconnect::process_disconnect( + &mut f.state, + &mut f.backend, + ClientId(SYNC_B), + ); + assert!(f.state.sync_awaits.is_empty()); + f.a(s::SET_COUNTER, &sync_counter_body(SYNC_C1, 9)); + assert!(f.state.sync_counters.contains_key(&SYNC_C1)); +} + +/// Read the XSync i64 counter value from a QueryCounter reply. +/// Protocol encoding: hi(INT32 LE at bytes[8..12]) || lo(CARD32 LE at +/// bytes[12..16]) — NOT a raw 8-byte little-endian integer. +fn read_query_counter_reply_value(bytes: &[u8]) -> i64 { + let hi = i32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]); + let lo = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + (i64::from(hi) << 32) | i64::from(lo) +} + +#[test] +fn query_counter_idletime_returns_elapsed_since_last_activity_not_uptime() { + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(30); + + let header = RequestHeader { + opcode: 142, + data: x11sync::QUERY_COUNTER, + length_units: 2, + }; + let body = x11sync::IDLETIME_COUNTER.to_le_bytes(); + let _ = handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let bytes = read_all_available(&mut peer); + // QueryCounter reply: tag(1) data(1) seq(2) length(4) value:i64(8) pad(16) + assert_eq!(bytes[0], 1, "reply tag"); + let value = read_query_counter_reply_value(&bytes); + assert!( + (29_000..=35_000).contains(&value), + "IDLETIME ≈ 30_000ms ± scheduling slack; got {value}" + ); +} + +#[test] +fn query_counter_idletime_device_vcp_uses_per_device_baseline() { + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Global was idle 60s ago, but the pointer device is fresh. + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(60); + state.per_device_last_activity.insert( + 2, /* VCP */ + std::time::Instant::now() - Duration::from_millis(500), + ); + + let header = RequestHeader { + opcode: 142, + data: x11sync::QUERY_COUNTER, + length_units: 2, + }; + let body = x11sync::IDLETIME_DEVICE_VCP.to_le_bytes(); + let _ = handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let bytes = read_all_available(&mut peer); + let value = read_query_counter_reply_value(&bytes); + assert!( + (400..=5_000).contains(&value), + "VCP IDLETIME ≈ 500ms; got {value}" + ); +} + +#[test] +fn query_counter_idletime_device_vck_uses_per_device_baseline() { + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(60); + state.per_device_last_activity.insert( + 3, /* VCK */ + std::time::Instant::now() - Duration::from_millis(200), + ); + + let header = RequestHeader { + opcode: 142, + data: x11sync::QUERY_COUNTER, + length_units: 2, + }; + let body = x11sync::IDLETIME_DEVICE_VCK.to_le_bytes(); + let _ = handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let bytes = read_all_available(&mut peer); + let value = read_query_counter_reply_value(&bytes); + assert!( + (100..=3_000).contains(&value), + "VCK IDLETIME ≈ 200ms; got {value}" + ); +} + +#[test] +fn evaluate_alarms_positive_transition_with_delta_zero_stays_active() { + // Regression: Xorg sync.c:548-555 — only delta=0 + Comparison + // goes Inactive. Transitions with delta=0 must stay Active so + // the next crossing re-fires. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let counter = 0x1000; + state.sync_counters.insert( + counter, + crate::server::SyncCounter { + owner: ClientId(1), + value: 0, + }, + ); + let alarm_id = 0x2000; + state.sync_alarms.insert( + alarm_id, + crate::server::SyncAlarm { + owner: ClientId(1), + counter, + wait_value: 100, + delta: 0, + test_type: x11sync::TEST_POSITIVE_TRANSITION, + events: true, + state: x11sync::ALARM_STATE_ACTIVE, + event_clients: Vec::new(), + value_type: 0, + raw_wait: 100, + check_type: x11sync::TEST_POSITIVE_TRANSITION, + }, + ); + + // Counter transition from 50 → 150 crosses the trigger. + evaluate_alarms_for_counter(&mut state, counter, 50, 150); + + let after = &state.sync_alarms[&alarm_id]; + assert_eq!( + after.state, + x11sync::ALARM_STATE_ACTIVE, + "PositiveTransition + delta=0 must stay Active (Xorg sync.c:548-555)" + ); + assert_eq!( + after.wait_value, 100, + "wait_value unchanged for delta=0 Transition" + ); +} + +#[test] +fn evaluate_alarms_positive_comparison_with_delta_zero_goes_inactive() { + // Companion test: PositiveComparison + delta=0 SHOULD go Inactive. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let counter = 0x1000; + state.sync_counters.insert( + counter, + crate::server::SyncCounter { + owner: ClientId(1), + value: 0, + }, + ); + let alarm_id = 0x2000; + state.sync_alarms.insert( + alarm_id, + crate::server::SyncAlarm { + owner: ClientId(1), + counter, + wait_value: 100, + delta: 0, + test_type: x11sync::TEST_POSITIVE_COMPARISON, + events: true, + state: x11sync::ALARM_STATE_ACTIVE, + event_clients: Vec::new(), + value_type: 0, + raw_wait: 100, + check_type: x11sync::TEST_POSITIVE_COMPARISON, + }, + ); + + evaluate_alarms_for_counter(&mut state, counter, 50, 150); + + let after = &state.sync_alarms[&alarm_id]; + assert_eq!(after.state, x11sync::ALARM_STATE_INACTIVE); +} + +#[test] +fn evaluate_alarms_re_arm_overflow_transitions_alarm_to_inactive() { + // Xorg sync.c:589-597 — re-arm overflow on i64::checked_add + // must transition the alarm to Inactive and leave wait_value + // unchanged. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let counter = 0x1000; + state.sync_counters.insert( + counter, + crate::server::SyncCounter { + owner: ClientId(1), + value: 0, + }, + ); + let alarm_id = 0x2000; + // Start near i64::MAX so adding delta overflows on the very + // first re-arm step. Use PositiveTransition so the trigger fires + // when new >= wait_value. + let near_max = i64::MAX - 10; + state.sync_alarms.insert( + alarm_id, + crate::server::SyncAlarm { + owner: ClientId(1), + counter, + wait_value: near_max, + delta: 100, // would overflow on first add + test_type: x11sync::TEST_POSITIVE_TRANSITION, + events: true, + state: x11sync::ALARM_STATE_ACTIVE, + event_clients: Vec::new(), + value_type: 0, + raw_wait: near_max, + check_type: x11sync::TEST_POSITIVE_TRANSITION, + }, + ); + + // Crossing: old < wait_value, new >= wait_value → trigger fires. + evaluate_alarms_for_counter(&mut state, counter, near_max - 1, near_max + 5); + + let after = &state.sync_alarms[&alarm_id]; + assert_eq!( + after.state, + x11sync::ALARM_STATE_INACTIVE, + "overflow on re-arm → Inactive" + ); + assert_eq!( + after.wait_value, near_max, + "wait_value unchanged on overflow (Xorg sync.c:589-597)" + ); +} + +/// Encode an INT64 value in XSync wire format: hi(INT32 LE) || lo(CARD32 LE). +/// This is NOT the same as `i64::to_le_bytes()` (which is lo-first). +fn xsync_i64(v: i64) -> [u8; 8] { + #[allow(clippy::cast_possible_truncation)] + let hi = (v >> 32) as i32; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let lo = v as u32; + let mut out = [0u8; 8]; + out[..4].copy_from_slice(&hi.to_le_bytes()); + out[4..].copy_from_slice(&lo.to_le_bytes()); + out +} + +#[test] +fn relative_alarm_value_on_idletime_resolves_against_current_idle() { + use std::time::Duration; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Pre-condition: already idle 5s. + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(5); + + // CreateAlarm relative-value=10_000 → wait_value should resolve + // to current_idle (~5_000) + 10_000 = ~15_000. + let alarm_id: u32 = 0x2000_0002; + let mut body = Vec::new(); + body.extend_from_slice(&alarm_id.to_le_bytes()); + let mask: u32 = x11sync::CA_COUNTER + | x11sync::CA_VALUE_TYPE + | x11sync::CA_VALUE + | x11sync::CA_TEST_TYPE + | x11sync::CA_DELTA + | x11sync::CA_EVENTS; + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&x11sync::IDLETIME_COUNTER.to_le_bytes()); + body.extend_from_slice(&x11sync::VALUE_TYPE_RELATIVE.to_le_bytes()); // u32 + body.extend_from_slice(&xsync_i64(10_000)); // value = 10_000 relative + body.extend_from_slice(&x11sync::TEST_POSITIVE_TRANSITION.to_le_bytes()); + body.extend_from_slice(&xsync_i64(0)); // delta = 0 + body.push(1); // events = true + body.extend_from_slice(&[0u8; 3]); + + let header = RequestHeader { + opcode: 142, + data: x11sync::CREATE_ALARM, + length_units: u32::try_from(2 + body.len() / 4).unwrap(), + }; + let _ = handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let alarm = state.sync_alarms.get(&alarm_id).expect("alarm exists"); + assert!( + alarm.wait_value >= 14_500 && alarm.wait_value <= 16_000, + "wait_value ≈ current_idle(5000) + 10000 = 15000; got {}", + alarm.wait_value + ); +} + +#[test] +fn create_alarm_on_idletime_with_comparison_already_true_fires_immediately() { + // Xorg sync.c:1772-1775 — create-time trigger eval passes + // (old=current, new=current). PositiveTransition requires + // `old < wait <= new` so it cannot fire on a same-value pair; + // only Comparison test types can fire at create time. + // PositiveComparison fires when `new >= wait`, which is + // exactly the "client opens an alarm while user is already + // idle past the threshold" smoke we want to verify. + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Pre-condition: already idle past the alarm threshold. + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); + + let alarm_id: u32 = 0x2000_0001; + let mut body = Vec::new(); + body.extend_from_slice(&alarm_id.to_le_bytes()); + let mask: u32 = x11sync::CA_COUNTER + | x11sync::CA_VALUE_TYPE + | x11sync::CA_VALUE + | x11sync::CA_TEST_TYPE + | x11sync::CA_DELTA + | x11sync::CA_EVENTS; + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&x11sync::IDLETIME_COUNTER.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // value_type = Absolute + body.extend_from_slice(&xsync_i64(60_000)); // value = 60_000 + body.extend_from_slice(&x11sync::TEST_POSITIVE_COMPARISON.to_le_bytes()); + body.extend_from_slice(&xsync_i64(0)); // delta = 0 → goes Inactive on fire + body.push(1); // events = true + body.extend_from_slice(&[0u8; 3]); + + let header = RequestHeader { + opcode: 142, + data: x11sync::CREATE_ALARM, + length_units: u32::try_from(2 + body.len() / 4).unwrap(), + }; + let _ = handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let bytes = read_all_available(&mut peer); + // AlarmNotify event: type = SYNC_FIRST_EVENT(83) + ALARM_NOTIFY_KIND(1) = 84 + assert!( + bytes.contains(&84), + "AlarmNotify must fire at create-time for an already-idle PositiveComparison alarm; got {:?}", + bytes + ); + // Comparison + delta=0 transitions to Inactive on fire. + assert_eq!( + state.sync_alarms[&alarm_id].state, + x11sync::ALARM_STATE_INACTIVE + ); +} + +#[test] +fn create_alarm_on_idletime_with_pos_transition_does_not_fire_at_create() { + // Companion test: PositiveTransition cannot fire at create-time + // (Xorg sync.c:1772-1775 — old==new). The alarm sits Active + // waiting for the post-poll evaluator or input wake to drive + // the (old, new) pair across the threshold. + use std::time::Duration; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.dpms.last_activity = std::time::Instant::now() - Duration::from_secs(120); + + let alarm_id: u32 = 0x2000_0003; + let mut body = Vec::new(); + body.extend_from_slice(&alarm_id.to_le_bytes()); + let mask: u32 = x11sync::CA_COUNTER + | x11sync::CA_VALUE_TYPE + | x11sync::CA_VALUE + | x11sync::CA_TEST_TYPE + | x11sync::CA_DELTA + | x11sync::CA_EVENTS; + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&x11sync::IDLETIME_COUNTER.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&xsync_i64(60_000)); + body.extend_from_slice(&x11sync::TEST_POSITIVE_TRANSITION.to_le_bytes()); + body.extend_from_slice(&xsync_i64(0)); + body.push(1); + body.extend_from_slice(&[0u8; 3]); + + let header = RequestHeader { + opcode: 142, + data: x11sync::CREATE_ALARM, + length_units: u32::try_from(2 + body.len() / 4).unwrap(), + }; + let _ = handle_sync_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + header, + &body, + ); + + let bytes = read_all_available(&mut peer); + assert!( + !bytes.contains(&84), + "PositiveTransition with old==new at create-time must not fire" + ); + assert_eq!( + state.sync_alarms[&alarm_id].state, + x11sync::ALARM_STATE_ACTIVE, + "alarm stays Active, waiting for evaluator/input to drive the transition" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/vidmode.rs b/crates/yserver-core/src/core_loop/process_request/tests/vidmode.rs new file mode 100644 index 000000000..12c8ae5b6 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/vidmode.rs @@ -0,0 +1,1167 @@ +use super::*; +#[cfg(test)] +use crate::core_loop::process_request::vidmode::current_vidmode_mode_line; +use crate::core_loop::process_request::vidmode::{ + current_vidmode_output, vidmode_monitor_identity, +}; + +#[test] +fn xf86vidmode_v2_mode_line_round_trips_current_randr_timing() { + use crate::randr::{ModeTiming, RandrOutput, RandrState}; + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + state.randr = RandrState::from_outputs( + 1, + vec![RandrOutput { + name: "DP-1".to_string(), + output_id: 1, + crtc_id: 2, + mode_id: 3, + connected: true, + x: 0, + y: 0, + width: 2560, + height: 1440, + vrefresh: 60, + timing: Some(ModeTiming { + clock_khz: 241_500, + hsync_start: 2608, + hsync_end: 2640, + htotal: 2720, + vsync_start: 1443, + vsync_end: 1448, + vtotal: 1481, + mode_flags: 5, + }), + mm_width: 600, + mm_height: 340, + mode_ids: vec![3], + num_preferred: 1, + pending_transform: Default::default(), + current_transform: Default::default(), + rotation: crate::randr::RR_ROTATE_0, + }], + ); + let expected = current_vidmode_mode_line(&state).expect("active RandR mode"); + assert_eq!( + expected, + x11vm::ModeLine { + dot_clock: 241_500, + hdisplay: 2560, + hsync_start: 2608, + hsync_end: 2640, + htotal: 2720, + hskew: 0, + vdisplay: 1440, + vsync_start: 1443, + vsync_end: 1448, + vtotal: 1481, + flags: 5, + } + ); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::QUERY_VERSION, + length_units: 1, + }, + &[], + None, + ) + .expect("QueryVersion"); + let version = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(version.len(), 32); + assert_eq!(&version[8..12], &[2, 0, 2, 0]); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::SET_CLIENT_VERSION, + length_units: 2, + }, + &[2, 0, 2, 0], + None, + ) + .expect("SetClientVersion"); + assert!(read_all_or_buffered(&mut state, 1, &mut peer).is_empty()); + assert_eq!( + state.vidmode_client_versions.get(&ClientId(1)), + Some(&(2, 2)) + ); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::GET_MODE_LINE, + length_units: 2, + }, + &[0; 4], + None, + ) + .expect("GetModeLine"); + let mode = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(mode.len(), 52); + assert_eq!(u32::from_le_bytes(mode[4..8].try_into().unwrap()), 5); + assert_eq!( + u32::from_le_bytes(mode[8..12].try_into().unwrap()), + expected.dot_clock + ); + assert_eq!( + u16::from_le_bytes(mode[12..14].try_into().unwrap()), + expected.hdisplay + ); + assert_eq!( + u16::from_le_bytes(mode[18..20].try_into().unwrap()), + expected.htotal + ); + assert_eq!( + u16::from_le_bytes(mode[22..24].try_into().unwrap()), + expected.vdisplay + ); + assert_eq!( + u16::from_le_bytes(mode[28..30].try_into().unwrap()), + expected.vtotal + ); + assert_eq!( + u32::from_le_bytes(mode[32..36].try_into().unwrap()), + expected.flags + ); + assert_eq!(&mode[36..52], &[0; 16]); +} + +#[test] +fn xf86vidmode_defaults_to_legacy_reply_and_rejects_unknown_screen() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::GET_MODE_LINE, + length_units: 2, + }, + &[0; 4], + None, + ) + .expect("legacy GetModeLine"); + let legacy = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(legacy.len(), 36); + assert_eq!(u32::from_le_bytes(legacy[4..8].try_into().unwrap()), 1); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::GET_MODE_LINE, + length_units: 2, + }, + &[1, 0, 0, 0], + None, + ) + .expect("bad-screen GetModeLine"); + let error = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!(error.len(), 32); + assert_eq!(error[0], 0); + assert_eq!(error[1], x11::error::BAD_VALUE); + assert_eq!(u32::from_le_bytes(error[4..8].try_into().unwrap()), 1); + assert_eq!( + u16::from_le_bytes(error[8..10].try_into().unwrap()), + u16::from(x11vm::GET_MODE_LINE) + ); + assert_eq!(error[10], crate::nested::XF86VIDMODE_MAJOR_OPCODE); +} + +/// Drive one VidMode request and return whatever went back to the client. +fn dispatch_vidmode( + state: &mut ServerState, + peer: &mut UnixStream, + sequence: u16, + minor: u8, + body: &[u8], +) -> Vec { + let mut backend = RecordingBackend::new(); + dispatch_vidmode_with_backend(state, &mut backend, peer, sequence, minor, body) +} + +fn dispatch_vidmode_with_backend( + state: &mut ServerState, + backend: &mut dyn Backend, + peer: &mut UnixStream, + sequence: u16, + minor: u8, + body: &[u8], +) -> Vec { + let length_units = u32::try_from(4 + body.len()).expect("test body") / 4; + process_request( + state, + backend, + ClientId(1), + SequenceNumber(sequence), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: minor, + length_units, + }, + body, + None, + ) + .expect("vidmode dispatch"); + read_all_or_buffered(state, 1, peer) +} + +fn assert_vidmode_error(reply: &[u8], code: u8, minor: u8) { + assert_eq!(reply.len(), 32, "X errors are always 32 bytes"); + assert_eq!(reply[0], 0, "error, not a reply"); + assert_eq!(reply[1], code); + assert_eq!( + u16::from_le_bytes(reply[8..10].try_into().unwrap()), + u16::from(minor) + ); + assert_eq!(reply[10], crate::nested::XF86VIDMODE_MAJOR_OPCODE); +} + +fn validate_mode_line_body( + mode: yserver_protocol::x11::xf86vidmode::ModeLine, + version_2: bool, + byte_order: ClientByteOrder, +) -> Vec { + fn put_u16(body: &mut [u8], offset: usize, value: u16, order: ClientByteOrder) { + let bytes = match order { + ClientByteOrder::LittleEndian => value.to_le_bytes(), + ClientByteOrder::BigEndian => value.to_be_bytes(), + }; + body[offset..offset + 2].copy_from_slice(&bytes); + } + + fn put_u32(body: &mut [u8], offset: usize, value: u32, order: ClientByteOrder) { + let bytes = match order { + ClientByteOrder::LittleEndian => value.to_le_bytes(), + ClientByteOrder::BigEndian => value.to_be_bytes(), + }; + body[offset..offset + 4].copy_from_slice(&bytes); + } + + let mut body = vec![0; if version_2 { 48 } else { 32 }]; + put_u32(&mut body, 4, mode.dot_clock, byte_order); + put_u16(&mut body, 8, mode.hdisplay, byte_order); + put_u16(&mut body, 10, mode.hsync_start, byte_order); + put_u16(&mut body, 12, mode.hsync_end, byte_order); + put_u16(&mut body, 14, mode.htotal, byte_order); + if version_2 { + put_u16(&mut body, 16, mode.hskew, byte_order); + put_u16(&mut body, 18, mode.vdisplay, byte_order); + put_u16(&mut body, 20, mode.vsync_start, byte_order); + put_u16(&mut body, 22, mode.vsync_end, byte_order); + put_u16(&mut body, 24, mode.vtotal, byte_order); + put_u32(&mut body, 28, mode.flags, byte_order); + } else { + put_u16(&mut body, 16, mode.vdisplay, byte_order); + put_u16(&mut body, 18, mode.vsync_start, byte_order); + put_u16(&mut body, 20, mode.vsync_end, byte_order); + put_u16(&mut body, 22, mode.vtotal, byte_order); + put_u32(&mut body, 24, mode.flags, byte_order); + } + body +} + +/// Known writes must use the same Xorg non-local branch advertised by +/// GetPermissions; truly unknown minors remain BadRequest. +#[test] +fn xf86vidmode_rejects_writes_with_client_not_local() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").is_local = false; + + for (seq, minor) in [2u8, 3, 5, 7, 8, 10, 12, 15, 18].into_iter().enumerate() { + #[allow(clippy::cast_possible_truncation)] + let seq = seq as u16 + 1; + // The locality gate runs before per-request length parsing in Xorg. + let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[]); + assert_vidmode_error( + &reply, + crate::nested::XF86VIDMODE_FIRST_ERROR + + yserver_protocol::x11::xf86vidmode::CLIENT_NOT_LOCAL, + minor, + ); + } + + for (seq, minor) in [21u8, 255].into_iter().enumerate() { + #[allow(clippy::cast_possible_truncation)] + let seq = seq as u16 + 20; + let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[]); + assert_vidmode_error(&reply, x11::error::BAD_REQUEST, minor); + } +} + +#[test] +fn xf86vidmode_permissions_follow_client_locality() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let local = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_PERMISSIONS, &[0; 4]); + assert_eq!(local[0], 1); + assert_eq!( + u32::from_le_bytes(local[8..12].try_into().unwrap()), + x11vm::PERMISSION_READ | 2, + "local clients receive XF86VM_WRITE_PERMISSION" + ); + + state.clients.get_mut(&1).expect("test client").is_local = false; + let remote = dispatch_vidmode(&mut state, &mut peer, 2, x11vm::GET_PERMISSIONS, &[0; 4]); + assert_eq!(remote[0], 1); + assert_eq!( + u32::from_le_bytes(remote[8..12].try_into().unwrap()), + x11vm::PERMISSION_READ, + "remote clients remain read-only" + ); +} + +#[test] +fn xf86vidmode_rejects_malformed_bodies_with_bad_length() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").is_local = false; + + // QueryVersion takes no body at all. + let reply = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::QUERY_VERSION, &[0; 4]); + assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::QUERY_VERSION); + + // The screen-scoped requests need exactly `screen + pad`. + for (seq, minor) in [ + x11vm::GET_MODE_LINE, + x11vm::GET_MONITOR, + x11vm::GET_ALL_MODE_LINES, + x11vm::GET_VIEW_PORT, + x11vm::GET_DOT_CLOCKS, + x11vm::GET_GAMMA_RAMP_SIZE, + x11vm::GET_PERMISSIONS, + ] + .into_iter() + .enumerate() + { + #[allow(clippy::cast_possible_truncation)] + let seq = seq as u16 + 2; + let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[0; 8]); + assert_vidmode_error(&reply, x11::error::BAD_LENGTH, minor); + } + + // The legacy gamma scalar request is padded to 32 bytes total. + let reply = dispatch_vidmode(&mut state, &mut peer, 12, x11vm::GET_GAMMA, &[0; 4]); + assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::GET_GAMMA); + + // GetGammaRamp carries exactly screen + requested size. + let reply = dispatch_vidmode(&mut state, &mut peer, 13, x11vm::GET_GAMMA_RAMP, &[0; 8]); + assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::GET_GAMMA_RAMP); + + // A legacy ValidateModeLine body is 32 bytes after the X header. + let reply = dispatch_vidmode( + &mut state, + &mut peer, + 14, + x11vm::VALIDATE_MODE_LINE, + &[0; 4], + ); + assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::VALIDATE_MODE_LINE); + + // SetClientVersion needs exactly `major + minor`. + let reply = dispatch_vidmode( + &mut state, + &mut peer, + 15, + x11vm::SET_CLIENT_VERSION, + &[2, 0], + ); + assert_vidmode_error(&reply, x11::error::BAD_LENGTH, x11vm::SET_CLIENT_VERSION); + assert!( + !state.vidmode_client_versions.contains_key(&ClientId(1)), + "a rejected SetClientVersion must not record a version" + ); +} + +#[test] +fn xf86vidmode_gamma_ramp_is_the_vidmode_table_not_the_randr_crtc() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let crtc = current_vidmode_output(&state) + .expect("active output") + .crtc_id; + let mut backend = RecordingBackend::new(); + + let mut red = vec![0u16; 256]; + let mut green = vec![0u16; 256]; + let mut blue = vec![0u16; 256]; + red[0] = 0x1111; + green[0] = 0x2222; + blue[0] = 0x3333; + red[255] = 0xaaaa; + green[255] = 0xbbbb; + blue[255] = 0xcccc; + backend + .set_crtc_gamma(crtc, &red, &green, &blue) + .expect("seed selected CRTC gamma"); + + let perms = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 1, + x11vm::GET_PERMISSIONS, + &[0; 4], + ); + assert_eq!(perms.len(), 32); + assert_eq!(perms[0], 1, "reply, not an error"); + assert_eq!( + u32::from_le_bytes(perms[8..12].try_into().unwrap()), + x11vm::PERMISSION_READ | x11vm::PERMISSION_WRITE, + "local clients receive Xorg's WRITE permission" + ); + + let size = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 2, + x11vm::GET_GAMMA_RAMP_SIZE, + &[0; 4], + ); + assert_eq!(size.len(), 32); + assert_eq!(size[0], 1); + assert_eq!( + u16::from_le_bytes(size[8..10].try_into().unwrap()), + 1024, + "the table's size, not the CRTC's 256" + ); + + let gamma = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 3, + x11vm::GET_GAMMA, + &[0; 28], + ); + assert_eq!(gamma.len(), 32); + for offset in [8usize, 12, 16] { + assert_eq!( + u32::from_le_bytes(gamma[offset..offset + 4].try_into().unwrap()), + 10_000, + "GetGamma is the independent per-screen 1.0 scalar" + ); + } + + let ramp = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 4, + x11vm::GET_GAMMA_RAMP, + &[0, 0, 0, 4], // screen=0, size=1024 + ); + assert_eq!(ramp.len(), 32 + 1024 * 3 * 2); + assert_eq!( + u32::from_le_bytes(ramp[4..8].try_into().unwrap()), + 1024 * 3 * 2 / 4 + ); + assert_eq!(u16::from_le_bytes(ramp[8..10].try_into().unwrap()), 1024); + let entry = |at: usize| u16::from_le_bytes(ramp[at..at + 2].try_into().unwrap()); + // The identity table widened (xf86GetGammaRamp), not the seeded + // 0x1111/0x2222/0x3333 of the CRTC's RANDR ramp. + assert_eq!((entry(32), entry(34), entry(32 + 1023 * 2)), (0, 64, 65535)); + assert_eq!(entry(32 + 2048), 0, "green starts at 0"); + assert_eq!(entry(32 + 4096 + 1023 * 2), 65535, "blue ends at 65535"); + assert_eq!( + backend.get_crtc_gamma(crtc).0[0], + 0x1111, + "the RANDR ramp is untouched" + ); + + let wrong_size = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 5, + x11vm::GET_GAMMA_RAMP, + &[0, 0, 0, 1], + ); + assert_vidmode_error(&wrong_size, x11::error::BAD_VALUE, x11vm::GET_GAMMA_RAMP); +} + +#[test] +fn xf86vidmode_monitor_viewport_dotclocks_and_validation_are_readable() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let current = current_vidmode_output(&state).expect("active output"); + let connector = current.connector.clone(); + let mut peer = install_client(&mut state, 1); + + let monitor = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_MONITOR, &[0; 4]); + assert_eq!(monitor[0], 1); + assert_eq!(monitor[8], 0, "no synthetic EDID vendor"); + assert_eq!(usize::from(monitor[9]), connector.len()); + assert_eq!(monitor[10], 1, "one active hsync range"); + assert_eq!(monitor[11], 1, "one active vsync range"); + assert_eq!(&monitor[40..40 + connector.len()], connector.as_bytes()); + + let viewport = dispatch_vidmode(&mut state, &mut peer, 2, x11vm::GET_VIEW_PORT, &[0; 4]); + assert_eq!(viewport.len(), 32); + assert_eq!(&viewport[8..16], &[0; 8]); + + let clocks = dispatch_vidmode(&mut state, &mut peer, 3, x11vm::GET_DOT_CLOCKS, &[0; 4]); + assert_eq!(clocks.len(), 32); + assert_eq!( + u32::from_le_bytes(clocks[8..12].try_into().unwrap()), + x11vm::CLOCK_FLAG_PROGRAMMABLE + ); + assert_eq!(u32::from_le_bytes(clocks[12..16].try_into().unwrap()), 0); + assert_eq!( + u32::from_le_bytes(clocks[16..20].try_into().unwrap()), + x11vm::MAX_CLOCKS + ); + + let legacy_body = validate_mode_line_body(current.mode, false, ClientByteOrder::LittleEndian); + let legacy_validate = dispatch_vidmode( + &mut state, + &mut peer, + 4, + x11vm::VALIDATE_MODE_LINE, + &legacy_body, + ); + assert_eq!(legacy_validate.len(), 32); + assert_eq!( + u32::from_le_bytes(legacy_validate[8..12].try_into().unwrap()), + x11vm::MODE_OK + ); + + let invalid_validate = dispatch_vidmode( + &mut state, + &mut peer, + 5, + x11vm::VALIDATE_MODE_LINE, + &[0; 32], + ); + assert_eq!( + u32::from_le_bytes(invalid_validate[8..12].try_into().unwrap()), + x11vm::MODE_BAD + ); + + let mut inverted_mode = current.mode; + inverted_mode.hsync_start = inverted_mode.hdisplay - 1; + let inverted_body = + validate_mode_line_body(inverted_mode, false, ClientByteOrder::LittleEndian); + let inverted_validate = dispatch_vidmode( + &mut state, + &mut peer, + 6, + x11vm::VALIDATE_MODE_LINE, + &inverted_body, + ); + assert_eq!( + u32::from_le_bytes(inverted_validate[8..12].try_into().unwrap()), + x11vm::MODE_BAD + ); + + dispatch_vidmode( + &mut state, + &mut peer, + 7, + x11vm::SET_CLIENT_VERSION, + &[2, 0, 2, 0], + ); + let v2_body = validate_mode_line_body(current.mode, true, ClientByteOrder::LittleEndian); + let v2_validate = dispatch_vidmode( + &mut state, + &mut peer, + 8, + x11vm::VALIDATE_MODE_LINE, + &v2_body, + ); + assert_eq!(v2_validate.len(), 32); + assert_eq!( + u32::from_le_bytes(v2_validate[8..12].try_into().unwrap()), + x11vm::MODE_OK + ); + + let mut other_mode = current.mode; + other_mode.dot_clock += 1; + let other_body = validate_mode_line_body(other_mode, true, ClientByteOrder::LittleEndian); + let other_validate = dispatch_vidmode( + &mut state, + &mut peer, + 9, + x11vm::VALIDATE_MODE_LINE, + &other_body, + ); + assert_eq!( + u32::from_le_bytes(other_validate[8..12].try_into().unwrap()), + x11vm::MODE_BAD + ); +} + +#[test] +fn xf86vidmode_dotclocks_reports_programmable_clock_when_headless() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + state.randr.outputs.clear(); + let mut peer = install_client(&mut state, 1); + + // Xorg's modesetting driver advertises a programmable clock even + // without an active output; the active dot clock belongs to + // GetModeLine rather than the legacy fixed-clock table. + let clocks = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_DOT_CLOCKS, &[0; 4]); + assert_eq!(clocks.len(), 32); + assert_eq!( + u32::from_le_bytes(clocks[8..12].try_into().unwrap()), + x11vm::CLOCK_FLAG_PROGRAMMABLE + ); + assert_eq!(u32::from_le_bytes(clocks[12..16].try_into().unwrap()), 0); + assert_eq!( + u32::from_le_bytes(clocks[16..20].try_into().unwrap()), + x11vm::MAX_CLOCKS + ); +} + +#[test] +fn xf86vidmode_monitor_identity_decodes_edid_and_falls_back_to_connector() { + let mut edid = vec![0u8; 128]; + // DEL manufacturer code: D=4, E=5, L=12. + edid[8..10].copy_from_slice(&0x10ac_u16.to_be_bytes()); + edid[54..59].copy_from_slice(&[0, 0, 0, 0xfc, 0]); + edid[59..72].copy_from_slice(b"U2723QE\n "); + assert_eq!( + vidmode_monitor_identity(&edid, "DP-1"), + (b"DEL".to_vec(), b"U2723QE".to_vec()) + ); + assert_eq!( + vidmode_monitor_identity(&[], "Virtual-1"), + (Vec::new(), b"Virtual-1".to_vec()) + ); +} + +#[test] +fn xf86vidmode_get_all_mode_lines_reports_only_the_active_mode() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + // Legacy client: 32-byte header + one 28-byte xXF86OldVidModeModeInfo. + let legacy = dispatch_vidmode(&mut state, &mut peer, 1, x11vm::GET_ALL_MODE_LINES, &[0; 4]); + assert_eq!(legacy.len(), 60); + assert_eq!(u32::from_le_bytes(legacy[8..12].try_into().unwrap()), 1); + + dispatch_vidmode( + &mut state, + &mut peer, + 2, + x11vm::SET_CLIENT_VERSION, + &[2, 0, 2, 0], + ); + + // v2 client: 32-byte header + one 48-byte xXF86VidModeModeInfo. + let v2 = dispatch_vidmode(&mut state, &mut peer, 3, x11vm::GET_ALL_MODE_LINES, &[0; 4]); + assert_eq!(v2.len(), 80); + assert_eq!(u32::from_le_bytes(v2[4..8].try_into().unwrap()), 12); + assert_eq!(u32::from_le_bytes(v2[8..12].try_into().unwrap()), 1); + // Same active mode GetModeLine reports. + let expected = current_vidmode_mode_line(&state).expect("active mode"); + assert_eq!( + u32::from_le_bytes(v2[32..36].try_into().unwrap()), + expected.dot_clock + ); + assert_eq!( + u16::from_le_bytes(v2[42..44].try_into().unwrap()), + expected.htotal + ); +} + +#[test] +fn xf86vidmode_v2_mode_list_keeps_the_core_stream_aligned() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::SET_CLIENT_VERSION, + length_units: 2, + }, + &[2, 0, 2, 0], + None, + ) + .expect("SetClientVersion"); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: crate::nested::XF86VIDMODE_MAJOR_OPCODE, + data: x11vm::GET_ALL_MODE_LINES, + length_units: 2, + }, + &[0; 4], + None, + ) + .expect("GetAllModeLines"); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 43, // GetInputFocus + data: 0, + length_units: 1, + }, + &[], + None, + ) + .expect("GetInputFocus"); + + let stream = read_all_or_buffered(&mut state, 1, &mut peer); + assert_eq!( + stream.len(), + 80 + 32, + "complete VidMode reply followed by core reply" + ); + + assert_eq!(stream[0], 1); + assert_eq!(u16::from_le_bytes(stream[2..4].try_into().unwrap()), 2); + assert_eq!(u32::from_le_bytes(stream[4..8].try_into().unwrap()), 12); + assert_eq!(u32::from_le_bytes(stream[8..12].try_into().unwrap()), 1); + + let focus = &stream[80..]; + assert_eq!(focus[0], 1); + assert_eq!(u16::from_le_bytes(focus[2..4].try_into().unwrap()), 3); + assert_eq!(u32::from_le_bytes(focus[4..8].try_into().unwrap()), 0); +} + +/// `client_reader` swaps ordinary request bodies before dispatch. +/// ValidateModeLine remains in original client order for its +/// version-dependent parser; replies and errors always use client order. +#[test] +fn xf86vidmode_big_endian_client_gets_a_byte_swapped_reply() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.clients.get_mut(&1).expect("test client").byte_order = ClientByteOrder::BigEndian; + + // Bodies arrive already in host order — as `swap_request_body` left + // them — so this is still a little-endian `2.2`. + dispatch_vidmode( + &mut state, + &mut peer, + 1, + x11vm::SET_CLIENT_VERSION, + &[2, 0, 2, 0], + ); + assert_eq!( + state.vidmode_client_versions.get(&ClientId(1)), + Some(&(2, 2)), + "the swapped body must parse as 2.2, not 512.512" + ); + + let expected = current_vidmode_mode_line(&state).expect("active mode"); + let reply = dispatch_vidmode(&mut state, &mut peer, 0x1234, x11vm::GET_MODE_LINE, &[0; 4]); + assert_eq!(reply.len(), 52); + assert_eq!(&reply[2..4], &0x1234_u16.to_be_bytes()); + assert_eq!(&reply[4..8], &5_u32.to_be_bytes()); + assert_eq!(&reply[8..12], &expected.dot_clock.to_be_bytes()); + assert_eq!(&reply[18..20], &expected.htotal.to_be_bytes()); + assert_eq!(&reply[28..30], &expected.vtotal.to_be_bytes()); + + // Errors follow the client's byte order too. `screen = 1` is still + // spelled little-endian in the already-swapped body. + let error = dispatch_vidmode( + &mut state, + &mut peer, + 5, + x11vm::GET_MODE_LINE, + &[1, 0, 0, 0], + ); + assert_eq!(error[0], 0); + assert_eq!(error[1], x11::error::BAD_VALUE); + assert_eq!(&error[4..8], &1_u32.to_be_bytes()); + + let validate = validate_mode_line_body(expected, true, ClientByteOrder::BigEndian); + let validated = dispatch_vidmode( + &mut state, + &mut peer, + 6, + x11vm::VALIDATE_MODE_LINE, + &validate, + ); + assert_eq!(validated.len(), 32); + assert_eq!(&validated[2..4], &6u16.to_be_bytes()); + assert_eq!(&validated[8..12], &x11vm::MODE_OK.to_be_bytes()); +} + +/// The VidMode mode line and RANDR's `ModeInfo` describe the same +/// hardware mode; they must agree on blanking, and their pixel clocks +/// must agree once RANDR's Hz is reduced to VidMode's kHz. +#[test] +fn xf86vidmode_mode_line_agrees_with_randr_mode_info() { + let state = ServerState::new(); + let mode = current_vidmode_mode_line(&state).expect("active mode"); + let resources = state.randr.screen_resources_current(); + let info = resources + .modes + .iter() + .find(|m| m.width == mode.hdisplay && m.height == mode.vdisplay) + .expect("matching RANDR mode"); + + assert_eq!(mode.htotal, info.htotal); + assert_eq!(mode.vtotal, info.vtotal); + assert_eq!(mode.hsync_start, info.hsync_start); + assert_eq!(mode.hsync_end, info.hsync_end); + assert_eq!(mode.vsync_start, info.vsync_start); + assert_eq!(mode.vsync_end, info.vsync_end); + assert_eq!(mode.flags, info.mode_flags); + assert_eq!(mode.dot_clock, (info.dot_clock + 500) / 1000); +} + +/// A `SetGamma` body: screen 0 and the three values times 10000. +fn set_gamma_body(red: u32, green: u32, blue: u32) -> Vec { + let mut body = vec![0u8; 28]; + for (at, value) in [(4, red), (8, green), (12, blue)] { + body[at..at + 4].copy_from_slice(&value.to_le_bytes()); + } + body +} + +/// GetGamma's three values. +fn get_gamma( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, +) -> [u32; 3] { + let reply = dispatch_vidmode_with_backend( + state, + backend, + peer, + 90, + yserver_protocol::x11::xf86vidmode::GET_GAMMA, + &[0; 28], + ); + assert_eq!(reply[0], 1, "GetGamma replies"); + [8usize, 12, 16].map(|at| u32::from_le_bytes(reply[at..at + 4].try_into().unwrap())) +} + +/// GetGammaRamp's three channels, for a 1024-entry ramp. +fn get_gamma_ramp( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, +) -> (Vec, Vec, Vec) { + let reply = dispatch_vidmode_with_backend( + state, + backend, + peer, + 91, + yserver_protocol::x11::xf86vidmode::GET_GAMMA_RAMP, + &[0, 0, 0, 4], + ); + assert_eq!(reply[0], 1, "GetGammaRamp replies"); + let channel = |index: usize| -> Vec { + let start = 32 + index * 2048; + reply[start..start + 2048] + .chunks_exact(2) + .map(|w| u16::from_le_bytes([w[0], w[1]])) + .collect() + }; + (channel(0), channel(1), channel(2)) +} + +/// A local client's SetGamma stores the values GetGamma reads back and +/// builds the screen's table with Xorg's `ComputeGamma` (values printed by +/// Xorg's own function), which the backend gets to load under every +/// CRTC's RANDR ramp; the RANDR ramp itself is untouched. +#[test] +fn xf86vidmode_local_set_gamma_builds_the_vidmode_table() { + use crate::backend::gamma::{VidModeGammaTable, identity_ramp}; + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let crtc = current_vidmode_output(&state) + .expect("active output") + .crtc_id; + let mut backend = RecordingBackend::new(); + + let reply = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 1, + x11vm::SET_GAMMA, + &set_gamma_body(20_000, 10_000, 5_000), + ); + assert!(reply.is_empty(), "SetGamma has no reply: {reply:?}"); + assert_eq!( + get_gamma(&mut state, &mut backend, &mut peer), + [20_000, 10_000, 5_000] + ); + let table = backend + .vidmode_gamma + .clone() + .expect("the backend got the table"); + assert_eq!(table, VidModeGammaTable::from_gamma([2.0, 1.0, 0.5])); + assert_eq!((table.red[1], table.green[1], table.blue[1]), (32, 1, 0)); + assert_eq!( + (table.red[512], table.green[512], table.blue[512]), + (724, 512, 256) + ); + let ramp = get_gamma_ramp(&mut state, &mut backend, &mut peer); + assert_eq!( + (ramp.0[1], ramp.1[1], ramp.2[1]), + (32 << 6 | 32 >> 4, 64, 0), + "GetGammaRamp reads the table back" + ); + let identity = identity_ramp(256); + assert_eq!( + backend.get_crtc_gamma(crtc), + (identity.clone(), identity.clone(), identity), + "the CRTC's RANDR ramp is untouched" + ); +} + +/// Xorg's CMapChangeGamma takes each value in [0.1, 10] and answers +/// anything else with BadValue, storing nothing. +#[test] +fn xf86vidmode_set_gamma_out_of_range_is_bad_value() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + for (seq, (red, green, blue)) in [ + (5_000, 0, 0), + (999, 10_000, 10_000), + (10_000, 100_001, 10_000), + ] + .into_iter() + .enumerate() + { + #[allow(clippy::cast_possible_truncation)] + let seq = seq as u16 + 1; + let reply = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + seq, + x11vm::SET_GAMMA, + &set_gamma_body(red, green, blue), + ); + assert_vidmode_error(&reply, x11::error::BAD_VALUE, x11vm::SET_GAMMA); + } + assert_eq!( + get_gamma(&mut state, &mut backend, &mut peer), + [10_000; 3], + "a refused SetGamma stores nothing" + ); + + let edges = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 10, + x11vm::SET_GAMMA, + &set_gamma_body(1_000, 100_000, 10_000), + ); + assert!(edges.is_empty(), "0.1 and 10 are in range: {edges:?}"); + assert_eq!( + get_gamma(&mut state, &mut backend, &mut peer), + [1_000, 100_000, 10_000] + ); + + let short = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 11, + x11vm::SET_GAMMA, + &[0; 4], + ); + assert_vidmode_error(&short, x11::error::BAD_LENGTH, x11vm::SET_GAMMA); +} + +/// SetGammaRamp takes exactly the table's size, GetGammaRampSize's 1024, +/// as a request of exactly that many entries, and makes the ramp the table +/// (`ComputeGammaRamp`, values printed by Xorg's own function) without +/// touching GetGamma's values or the CRTC's RANDR ramp. +#[test] +fn xf86vidmode_local_set_gamma_ramp_replaces_the_vidmode_table() { + use crate::backend::gamma::identity_ramp; + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let crtc = current_vidmode_output(&state) + .expect("active output") + .crtc_id; + let mut backend = RecordingBackend::new(); + + let wrong_size = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 1, + x11vm::SET_GAMMA_RAMP, + &[0, 0, 0, 1], // the CRTC's 256, not the table's 1024 + ); + assert_vidmode_error(&wrong_size, x11::error::BAD_VALUE, x11vm::SET_GAMMA_RAMP); + + let mut body = vec![0, 0, 0, 4]; // screen 0, size 1024 + let truncated = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 2, + x11vm::SET_GAMMA_RAMP, + &body, + ); + assert_vidmode_error(&truncated, x11::error::BAD_LENGTH, x11vm::SET_GAMMA_RAMP); + + let channels: [Vec; 3] = [ + (0..1024).map(|i| 65535 - i * 64).collect(), + (0..1024).map(|i| i * 64 + 63).collect(), + (0..1024u32).map(|i| (i * 37) as u16).collect(), + ]; + for channel in &channels { + for entry in channel { + body.extend_from_slice(&entry.to_le_bytes()); + } + } + let reply = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 3, + x11vm::SET_GAMMA_RAMP, + &body, + ); + assert!(reply.is_empty(), "SetGammaRamp has no reply: {reply:?}"); + let table = backend + .vidmode_gamma + .clone() + .expect("the backend got the table"); + assert_eq!( + (table.red[0], table.red[1], table.blue[1023]), + (1023, 1022, 591) + ); + let ramp = get_gamma_ramp(&mut state, &mut backend, &mut peer); + assert_eq!((ramp.0[0], ramp.1[0], ramp.2[0]), (65535, 0, 0)); + assert_eq!((ramp.0[1], ramp.1[1], ramp.2[1]), (65471, 64, 0)); + assert_eq!( + (ramp.0[1023], ramp.1[1023], ramp.2[1023]), + (0, 65535, 37860) + ); + assert_eq!( + get_gamma(&mut state, &mut backend, &mut peer), + [10_000; 3], + "SetGammaRamp leaves GetGamma's values" + ); + let identity = identity_ramp(256); + assert_eq!( + backend.get_crtc_gamma(crtc), + (identity.clone(), identity.clone(), identity), + "the CRTC's RANDR ramp is untouched" + ); + + let short = dispatch_vidmode_with_backend( + &mut state, + &mut backend, + &mut peer, + 4, + x11vm::SET_GAMMA_RAMP, + &[0, 0], + ); + assert_vidmode_error(&short, x11::error::BAD_LENGTH, x11vm::SET_GAMMA_RAMP); +} + +/// LockModeSwitch succeeds for a local client; mode setting stays RANDR's +/// and keeps ClientNotLocal. +#[test] +fn xf86vidmode_local_lock_succeeds_and_mode_setting_stays_refused() { + use yserver_protocol::x11::xf86vidmode as x11vm; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + let lock = dispatch_vidmode( + &mut state, + &mut peer, + 1, + x11vm::LOCK_MODE_SWITCH, + &[0, 0, 1, 0], + ); + assert!(lock.is_empty(), "LockModeSwitch has no reply: {lock:?}"); + let other_screen = dispatch_vidmode( + &mut state, + &mut peer, + 2, + x11vm::LOCK_MODE_SWITCH, + &[1, 0, 1, 0], + ); + assert_vidmode_error( + &other_screen, + x11::error::BAD_VALUE, + x11vm::LOCK_MODE_SWITCH, + ); + let short = dispatch_vidmode(&mut state, &mut peer, 3, x11vm::LOCK_MODE_SWITCH, &[0, 0]); + assert_vidmode_error(&short, x11::error::BAD_LENGTH, x11vm::LOCK_MODE_SWITCH); + + for (seq, minor) in [2u8, 3, 7, 8, 10, 12].into_iter().enumerate() { + #[allow(clippy::cast_possible_truncation)] + let seq = seq as u16 + 10; + let reply = dispatch_vidmode(&mut state, &mut peer, seq, minor, &[]); + assert_vidmode_error( + &reply, + crate::nested::XF86VIDMODE_FIRST_ERROR + x11vm::CLIENT_NOT_LOCAL, + minor, + ); + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/window.rs b/crates/yserver-core/src/core_loop/process_request/tests/window.rs new file mode 100644 index 000000000..3e4f8e0f0 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/window.rs @@ -0,0 +1,4925 @@ +use super::*; +use crate::resources::{COMPOSITE_OVERLAY_WINDOW, MapState}; + +fn count_configure_notifies(bytes: &[u8]) -> usize { + // X11 events are 32 bytes; ConfigureNotify event code is 22. + bytes.chunks(32).filter(|e| e[0] & 0x7f == 22).count() +} + +#[test] +fn configure_window_noop_restack_emits_no_configure_notify() { + // Regression (Enlightenment e27 restack war): a stacking-only + // ConfigureWindow that does NOT change the child order must emit + // zero ConfigureNotify, matching Xorg dix/window.c. A spurious + // notify makes the WM re-restack forever (~8000 req/s observed), + // pegging the desktop so clicks never get processed. + let (mut state, mut peer) = two_children_under_root(); + // 0x300 was created last → already on top. Subscribe to its + // StructureNotify, then drain any setup traffic. + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(ResourceId(0x300), 0x0002_0000); + let _ = read_all_available(&mut peer); + + // Raise the already-top window to the top: a positional no-op. + let body = cw_restack_body(0x300, 0x0040, &[0]); // CWStackMode=Above + let mut backend = RecordingBackend::new(); + handle_configure_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &body, + ) + .expect("handle_configure_window"); + + let out = read_all_available(&mut peer); + assert_eq!( + count_configure_notifies(&out), + 0, + "no-op restack must not emit ConfigureNotify (got {} bytes)", + out.len() + ); +} + +#[test] +fn configure_window_real_restack_emits_one_configure_notify() { + // Guard against over-suppression: a restack that DOES reorder the + // children must still emit exactly one ConfigureNotify. + let (mut state, mut peer) = two_children_under_root(); + // 0x200 was created first → currently at the bottom. + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(ResourceId(0x200), 0x0002_0000); + let _ = read_all_available(&mut peer); + + // Raise 0x200 to the top: a real reorder. + let body = cw_restack_body(0x200, 0x0040, &[0]); // CWStackMode=Above + let mut backend = RecordingBackend::new(); + handle_configure_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &body, + ) + .expect("handle_configure_window"); + + let out = read_all_available(&mut peer); + assert_eq!( + count_configure_notifies(&out), + 1, + "a real restack must emit exactly one ConfigureNotify" + ); +} + +// ── #143 — a resize must report the window exposed, either way ── +// +// Xorg's `miResizeWindow` copies the NEW clip list wholesale into +// `after.exposed` — "the entire window is trashed unless bitGravity +// recovers portions of it" (`mi/miwindow.c:466-472`) — and only a +// non-Forget `bitGravity` subtracts the bits it actually moved +// (`:596-599`). There is no grow/shrink branch: under the default +// ForgetGravity the full window is reported in both directions. +// Nor does the background gate the EVENT — `miWindowExposures` +// paints, then sends (`mi/miexpose.c:387-389`), and the +// background-None early-out is inside the paint (`:438-440`). +// +// We emitted this for a grow only. On HW that is the #143 xterm: +// awesome retiles it smaller, the leaf is re-tiled from the +// window's black background, and with no Expose nothing asks xterm +// to repaint its static banner rows — they stay black while the +// prompt line, which xterm redraws unprompted, comes back. + +/// One viewable, Expose-selecting child of root at `w`x`h`, plus +/// client 1's already-drained peer socket. `background_pixel` picks +/// the two shapes that matter here: `Some` is the xterm case (the +/// resize re-tiles the leaf and destroys the content), `None` is the +/// background-None case (the content survives). +fn one_viewable_expose_child( + w: u16, + h: u16, + background_pixel: Option, +) -> (ServerState, UnixStream) { + const XID: u32 = 0x400; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(XID), + parent: ROOT_WINDOW, + width: w, + height: h, + background_pixel, + ..Default::default() + }, + ); + assert_eq!( + state + .resources + .window(ResourceId(XID)) + .map(|win| win.background_none), + Some(background_pixel.is_none()), + "harness sanity: the background shape under test", + ); + state + .resources + .window_mut(ResourceId(XID)) + .expect("child installed") + .map_state = crate::resources::MapState::Viewable; + state + .clients + .get_mut(&1) + .expect("test client") + .event_masks + .insert(ResourceId(XID), 0x0000_8000); // ExposureMask + let _ = read_all_available(&mut peer); + (state, peer) +} + +/// Every Expose in `bytes` for `window`, as `(x, y, width, height)`. +fn expose_rects(bytes: &[u8], window: u32) -> Vec<(u16, u16, u16, u16)> { + bytes + .chunks(32) + .filter(|e| { + e.len() == 32 + && e[0] & 0x7f == 12 + && u32::from_le_bytes([e[4], e[5], e[6], e[7]]) == window + }) + .map(|e| { + ( + u16::from_le_bytes([e[8], e[9]]), + u16::from_le_bytes([e[10], e[11]]), + u16::from_le_bytes([e[12], e[13]]), + u16::from_le_bytes([e[14], e[15]]), + ) + }) + .collect() +} + +/// Resize `window` to `w`x`h` (CWWidth|CWHeight) and return whatever +/// reached the client. +fn resize_and_read( + state: &mut ServerState, + peer: &mut UnixStream, + window: u32, + w: u32, + h: u32, +) -> Vec { + let body = cw_restack_body(window, 0x000C, &[w, h]); + let mut backend = RecordingBackend::new(); + handle_configure_window( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &body, + ) + .expect("handle_configure_window"); + read_all_available(peer) +} + +#[test] +fn configure_window_shrink_exposes_the_whole_window() { + // The #143 case. `configure_subwindow` re-tiles the leaf from + // the window's background on a shrink, so without this Expose + // the discarded pixels are unrecoverable. + let (mut state, mut peer) = one_viewable_expose_child(200, 100, Some(0x0000_0000)); + let out = resize_and_read(&mut state, &mut peer, 0x400, 100, 60); + assert_eq!( + expose_rects(&out, 0x400), + vec![(0, 0, 100, 60)], + "a shrink must report the whole NEW window exposed, exactly once \ + (`mi/miwindow.c:466-472`); emitting none leaves an idle client \ + showing the background fill forever (#143)", + ); +} + +#[test] +fn configure_window_grow_exposes_the_whole_window() { + // Over-suppression guard: the grow path predates the shrink one + // and must keep its single full-window Expose. + let (mut state, mut peer) = one_viewable_expose_child(100, 60, Some(0x0000_0000)); + let out = resize_and_read(&mut state, &mut peer, 0x400, 200, 100); + assert_eq!( + expose_rects(&out, 0x400), + vec![(0, 0, 200, 100)], + "a grow must still report exactly one full-window Expose", + ); +} + +#[test] +fn configure_window_shrink_exposes_a_background_none_window_too() { + // A background-None window keeps its pixels across the resize + // (`mi/miexpose.c:438-440` returns before painting) but STILL + // gets the Expose: `miWindowExposures` calls `PaintWindow` and + // `miSendExposures` in sequence and only the paint is skipped + // (`mi/miexpose.c:387-389`). Nothing on this path may start + // reading the background state to suppress the event. + let (mut state, mut peer) = one_viewable_expose_child(200, 100, None); + let out = resize_and_read(&mut state, &mut peer, 0x400, 100, 60); + assert_eq!( + expose_rects(&out, 0x400), + vec![(0, 0, 100, 60)], + "a background-None window is not painted but is still told what \ + was exposed", + ); +} + +#[test] +fn configure_window_pure_move_emits_no_expose() { + // Under-suppression guard: `after.exposed` is seeded from the + // clip list only when the size changes; a pure move of an + // unobscured window exposes nothing of the window itself. + let (mut state, mut peer) = one_viewable_expose_child(200, 100, Some(0x0000_0000)); + let body = cw_restack_body(0x400, 0x0003, &[37, 41]); // CWX|CWY + let mut backend = RecordingBackend::new(); + handle_configure_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &body, + ) + .expect("handle_configure_window"); + let out = read_all_available(&mut peer); + assert_eq!( + expose_rects(&out, 0x400), + Vec::new(), + "a move is not a resize and must not expose the window", + ); +} + +/// ProcTranslateCoords applies child input shapes. The Composite Overlay +/// Window is the top root child and, like Xorg's, starts unshaped, so it +/// is the `child` over a popup until the compositor empties its input +/// region; then the popup below it is (measured on Xvfb 21.1, +/// tools/vng-scenarios/cow-input-shape). +#[test] +fn translate_coordinates_skips_empty_input_shaped_cow() { + use crate::{backend::WindowHandle, resources::COMPOSITE_OVERLAY_WINDOW}; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let popup = ResourceId(0x200); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: popup, + parent: ROOT_WINDOW, + x: 715, + y: 327, + width: 132, + height: 165, + ..Default::default() + }, + ); + let _ = state.resources.map_window(popup); + state + .resources + .materialize_cow_resource(WindowHandle::from_raw_for_test(COMPOSITE_OVERLAY_WINDOW.0)); + let _ = read_all_available(&mut peer); + + let mut translate = |state: &mut ServerState| { + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&715i16.to_le_bytes()); + body.extend_from_slice(&327i16.to_le_bytes()); + handle_translate_coordinates( + state, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 40, + minor: 0, + }, + &body, + ) + .expect("handle_translate_coordinates"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32); + assert_eq!(bytes[0], 1, "reply"); + assert_eq!(i16::from_le_bytes(bytes[12..14].try_into().unwrap()), 715); + assert_eq!(i16::from_le_bytes(bytes[14..16].try_into().unwrap()), 327); + u32::from_le_bytes(bytes[8..12].try_into().unwrap()) + }; + assert_eq!( + translate(&mut state), + COMPOSITE_OVERLAY_WINDOW.0, + "an unshaped COW is the child over the popup", + ); + state + .shape_windows + .entry(COMPOSITE_OVERLAY_WINDOW) + .or_default() + .set_rects(yserver_protocol::x11::shape::KIND_INPUT, Some(Vec::new())); + assert_eq!( + translate(&mut state), + popup.0, + "empty-input COW must not hide the popup child", + ); +} + +#[test] +fn configure_window_resize_applies_win_gravity_and_emits_gravity_notify() { + // X11 window gravity: growing a parent moves a South-gravity child + // down by the height delta and delivers a GravityNotify (Xorg + // ResizeChildrenWinSize). fvwm's window-shade relies on exactly + // this to reveal a client it parked above the fold. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let parent = ResourceId(0x400); + let child = ResourceId(0x401); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: parent, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + ..Default::default() + }, + ); + let _ = state.resources.map_window(parent); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: child, + parent, + x: 10, + y: -100, + width: 100, + height: 100, + win_gravity: Some(8), // South + ..Default::default() + }, + ); + let _ = state.resources.map_window(child); + state + .clients + .get_mut(&1) + .unwrap() + .event_masks + .insert(child, 0x0002_0000); // StructureNotify + let _ = read_all_available(&mut peer); + + // Grow the parent 100×100 → 100×200 (dh=+100): CWWidth|CWHeight. + let body = cw_restack_body(0x400, 0x000C, &[100, 200]); + let mut backend = RecordingBackend::new(); + handle_configure_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &body, + ) + .expect("handle_configure_window"); + + // South gravity: child.y += 100 → (10, 0). + let c = state.resources.window(child).expect("child"); + assert_eq!( + (c.x, c.y), + (10, 0), + "South-gravity child follows the parent's height growth", + ); + + // Exactly one GravityNotify (type 24) delivered to the child. + let out = read_all_available(&mut peer); + let gravity: Vec<&[u8]> = out + .chunks(32) + .filter(|e| e.len() == 32 && e[0] & 0x7f == 24) + .collect(); + assert_eq!(gravity.len(), 1, "exactly one GravityNotify to the child"); + let g = gravity[0]; + assert_eq!(&g[4..8], &child.0.to_le_bytes(), "event window = child"); + assert_eq!(&g[8..12], &child.0.to_le_bytes(), "reported window = child"); + assert_eq!(i16::from_le_bytes([g[12], g[13]]), 10, "GravityNotify x"); + assert_eq!(i16::from_le_bytes([g[14], g[15]]), 0, "GravityNotify y"); +} + +/// Per X11 protocol spec: "If the window is already mapped, this +/// request has no effect." brisk-menu (Ubuntu MATE's standalone +/// applications popup) pounds `MapWindow` at ~50 Hz on its +/// already-viewable override-redirect popup via GTK3's +/// `gtk_window_present`/`XMapRaised` loop. Pre-fix every redundant +/// MapWindow re-emitted MapNotify → Expose → full-extent damage, +/// triggering Marco to issue `COMPOSITE::NameWindowPixmap` and a +/// full recomposite of the popup ~50× per second — visible as +/// menu flicker on the COW-authoritative KMS scene path. +#[test] +fn map_window_on_already_mapped_window_is_no_op() { + use crate::server::DamageObject; + use std::io::Read; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0014; + const HOST_XID: u32 = 0x0040_0014; + const DAMAGE_ID: u32 = 0x0080_0014; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + background_pixel: Some(0x0080_8080), + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + + // Marco-like subscriber: SubstructureNotify on root + + // XDamageCreate on the new window. + state + .clients + .get_mut(&CLIENT_ID) + .unwrap() + .event_masks + .insert(ROOT_WINDOW, 0x0008_0000); + state.damage_objects.insert( + DAMAGE_ID, + DamageObject { + owner: ClientId(CLIENT_ID), + drawable: ResourceId(WINDOW_XID), + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + + // First map: genuine transition Unmapped → Viewable. Should + // emit MapNotify + accumulate damage. + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window first"); + + peer.set_nonblocking(true).unwrap(); + let mut tmp = [0u8; 1024]; + let mut first_wire = Vec::new(); + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => first_wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + let first_map_notifies = first_wire + .chunks_exact(32) + .filter(|chunk| chunk[0] & 0x7f == 19) + .count(); + assert!( + first_map_notifies >= 1, + "first MapWindow on an unmapped window must emit MapNotify", + ); + let first_rect_count = state + .damage_objects + .get(&DAMAGE_ID) + .expect("damage object") + .rects + .len(); + assert!( + first_rect_count > 0, + "first MapWindow must accumulate damage on the window extent", + ); + + // Second map on the now-already-Viewable window. Per spec this + // is a no-op: no MapNotify, no extra damage rects. + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(2), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window second"); + + let mut second_wire = Vec::new(); + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => second_wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + let second_map_notifies = second_wire + .chunks_exact(32) + .filter(|chunk| chunk[0] & 0x7f == 19) + .count(); + assert_eq!( + second_map_notifies, 0, + "MapWindow on an already-mapped window must NOT re-emit \ + MapNotify — repeated MapNotifies cause Marco to re-issue \ + COMPOSITE::NameWindowPixmap and full recomposite on every \ + redundant map (visible as brisk-menu flicker on KMS).", + ); + let second_rect_count = state + .damage_objects + .get(&DAMAGE_ID) + .expect("damage object") + .rects + .len(); + assert_eq!( + second_rect_count, first_rect_count, + "MapWindow on an already-mapped window must NOT accumulate \ + additional damage — full-extent damage on every redundant \ + call is what drives the recompositing flicker storm.", + ); +} + +/// Per X11 protocol (Xorg `dix/window.c:2661`): `if (pWin->mapped) +/// return Success;` — `MapWindow` on an already-mapped window is a +/// no-op BEFORE any MapRequest dispatch. The root window is always +/// mapped (initialised `Viewable` at `resources.rs:204`) AND in +/// yserver root's `parent` field points to itself +/// (`resources.rs:194`), so a client calling `MapWindow(root)` +/// pre-fix matched the SubstructureRedirect-on-parent path: the +/// requester wasn't the WM, marco had SubstructureRedirect +/// (`0x0010_0000`) on root, so yserver dispatched a phantom +/// MapRequest event with `parent=root, window=root` to marco. +/// Marco's response (seen on hardware via xtrace seq `0x35e5a` +/// during a mate-screensaver activation): GrabServer → +/// ChangeWindowAttributes(root, event_mask=...) DROPPING +/// SubstructureNotify+SubstructureRedirect → UngrabServer. After +/// that marco no longer receives MapNotify for new top-levels → +/// no `COMPOSITE::NameWindowPixmap` → newly-mapped windows +/// (mate-screensaver overlay, dialogs) are invisible while the +/// cursor still moves. Match Xorg: hoist the "already mapped" +/// short-circuit above the MapRequest emission. +#[test] +fn map_window_on_root_does_not_emit_phantom_map_request() { + use std::io::Read; + + const WM_ID: u32 = 1; + const SAVER_ID: u32 = 2; + + let mut state = ServerState::new(); + let mut wm_peer = install_client(&mut state, WM_ID); + let _saver_peer = install_client(&mut state, SAVER_ID); + let mut backend = RecordingBackend::new(); + + // Marco-like WM: SubstructureRedirect (0x0010_0000) on root. + state + .clients + .get_mut(&WM_ID) + .unwrap() + .event_masks + .insert(ROOT_WINDOW, 0x0010_0000); + + // mate-screensaver-like activation: client 2 calls + // `MapWindow(root)`. Per X11 spec this must be a silent + // no-op (root is always mapped). + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(SAVER_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window root"); + + wm_peer.set_nonblocking(true).unwrap(); + let mut tmp = [0u8; 1024]; + let mut wm_wire = Vec::new(); + loop { + match wm_peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wm_wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + let map_requests = wm_wire + .chunks_exact(32) + .filter(|chunk| chunk[0] & 0x7f == 20) + .count(); + assert_eq!( + map_requests, 0, + "MapWindow(root) must NOT generate a phantom MapRequest \ + event to the WM. Pre-fix yserver dispatched a bogus \ + MapRequest(parent=root, window=root) because root's parent \ + field points to itself; marco reacted by dropping its \ + SubstructureRedirect subscription, which broke compositing \ + of every subsequent top-level (mate-screensaver overlay \ + and dialogs went invisible while cursor still moved).", + ); +} + +/// Per X11 protocol: `cursor = None` (resource id 0) on +/// ChangeWindowAttributes(CWCursor) means "clear this window's +/// cursor so the effective cursor inherits from the parent +/// chain". Pre-fix the handler short-circuited because +/// `resources.cursor_host_xid(ResourceId(0))` returns `None` and +/// the `(Some, Some)` match below dropped the call — marco +/// resets its frame's cursor via `XDefineCursor(frame, None)` +/// when the pointer moves off the resize edge into the frame +/// interior, and that reset never propagated to the backend +/// (resize cursor sprite stayed visible until the pointer left +/// the top-level frame entirely). Matches Xorg +/// `dix/window.c:1487-1491`. +#[test] +fn cwa_cursor_none_propagates_define_cursor_zero_to_backend() { + use crate::backend::recording::RecordedCall; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0020; + const HOST_XID: u32 = 0x0040_0020; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + + // CWA body: window xid (4) + value_mask (4) + values. + // CWCursor is bit 14 (mask = 0x4000); value = 0 means + // X11 None. + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body.extend_from_slice(&0x4000u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + + handle_change_window_attributes( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + RequestHeader { + opcode: 2, + data: 0, + length_units: 4, + }, + &body, + ) + .expect("handle_change_window_attributes"); + + let define_cursor_calls: Vec<_> = backend + .calls() + .into_iter() + .filter(|c| matches!(c, RecordedCall::DefineCursor { .. })) + .collect(); + assert_eq!( + define_cursor_calls, + vec![RecordedCall::DefineCursor { + host_window_xid: HOST_XID, + cursor_host_xid: 0, + }], + "CWA with CWCursor + value=0 must invoke \ + `backend.define_cursor(window, 0)` so the backend clears \ + its per-window cursor slot and refreshes the effective \ + cursor. Pre-fix this dropped silently, leaving stale \ + cursor state (marco's resize-frame XDefineCursor(frame, \ + None) reset on edge→interior transitions had no effect).", + ); +} + +/// A `ChangeWindowAttributes` that only changes the cursor (or any +/// other non-event-mask attribute) must NOT move the input focus. +/// In X11 focus changes only via `SetInputFocus` / grabs, never CWA. +/// +/// Regression (the evince / GTK4 titlebar-drag freeze): during a +/// `_NET_WM_MOVERESIZE` move, muffin sets the "fleur" move cursor on +/// its guard window via a cursor-only CWA. The handler promoted +/// keyboard focus to any "focus-wanting" (viewable + key-selecting) +/// window on *any* CWA, so focus was stolen to the guard window. The +/// app's next `SetInputFocus` to its own child was then computed from +/// that unrelated prev focus -> `FocusOut(detail=Nonlinear)` -> GTK4 +/// backdrop (greyed CSD buttons) and the drag collapsed. +#[test] +fn cursor_only_cwa_does_not_steal_keyboard_focus() { + const CLIENT_ID: u32 = 1; + const GUARD_XID: u32 = 0x0010_0011; // muffin's guard window + const FOCUSED_XID: u32 = 0x0010_0007; // the real focus window + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + for xid in [GUARD_XID, FOCUSED_XID] { + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(xid)); + } + // Guard window is viewable and selects key events, so + // `window_wants_keyboard_focus` would return true for it. + state + .clients + .get_mut(&CLIENT_ID) + .expect("client") + .event_masks + .insert(ResourceId(GUARD_XID), 0x1); // KeyPress + + // Establish the real focus on FOCUSED_XID before the CWA. + state.core_focus.raw = FOCUSED_XID; + for c in state.clients.values_mut() { + c.focused_window = ResourceId(FOCUSED_XID); + } + + // Cursor-only CWA on the guard window: CWCursor (bit 14 = + // 0x4000), value 0 = None. No event-mask change. + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&GUARD_XID.to_le_bytes()); + body.extend_from_slice(&0x4000u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + + handle_change_window_attributes( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + RequestHeader { + opcode: 2, + data: 0, + length_units: 4, + }, + &body, + ) + .expect("handle_change_window_attributes"); + + assert_eq!( + state + .clients + .get(&CLIENT_ID) + .expect("client") + .focused_window, + ResourceId(FOCUSED_XID), + "a cursor-only ChangeWindowAttributes must not promote keyboard \ + focus to the target window; focus must stay where SetInputFocus \ + put it", + ); +} + +/// F{ A{ A1 }, B{ B1 }, C }: F viewable, A and B unmapped with their +/// child mapped (Unviewable), C mapped. +fn subwindows_delta_fixture(state: &mut ServerState) -> [ResourceId; 6] { + let [f, a, a1, b, b1, c] = [ + 0x0010_0200, + 0x0010_0201, + 0x0010_0202, + 0x0010_0203, + 0x0010_0204, + 0x0010_0205, + ] + .map(ResourceId); + for (id, parent) in [(f, ROOT_WINDOW), (a, f), (a1, a), (b, f), (b1, b), (c, f)] { + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: id, + parent, + x: 0, + y: 0, + width: 40, + height: 40, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + for w in [a1, b1, f, c] { + let _ = state.resources.map_window(w); + } + [f, a, a1, b, b1, c] +} + +/// Window storage follows the delta: realize parent first, release child first, never the COW. +#[test] +fn window_storage_follows_viewability_delta_in_order() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let [f, a, a1, b, b1, c] = subwindows_delta_fixture(&mut state); + for w in [f, a, a1, b, b1, c] { + state.resources.window_mut(w).expect("window").host_xid = + Some(crate::backend::WindowHandle::from_raw_for_test(w.0)); + } + let _ = state.resources.map_window(a); + let _ = state.resources.map_window(b); + let storage_calls = |backend: &RecordingBackend, from: usize| -> Vec { + backend + .calls() + .into_iter() + .skip(from) + .filter(|c| { + matches!( + c, + RecordedCall::RealizeWindowStorage(_) | RecordedCall::ReleaseWindowStorage(_) + ) + }) + .collect() + }; + let unmap = |state: &mut ServerState, backend: &mut RecordingBackend, w: ResourceId| { + handle_unmap_window( + state, + backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 10, + minor: 0, + }, + &w.0.to_le_bytes(), + ) + .expect("UnmapWindow"); + }; + let map = |state: &mut ServerState, backend: &mut RecordingBackend, w: ResourceId| { + handle_map_window( + state, + backend, + None, + ClientId(1), + SequenceNumber(2), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &w.0.to_le_bytes(), + ) + .expect("MapWindow"); + }; + + unmap(&mut state, &mut backend, f); + assert_eq!( + storage_calls(&backend, 0), + [a1, a, b1, b, c, f].map(|w| RecordedCall::ReleaseWindowStorage(w.0)), + "the whole subtree releases, child first", + ); + let from = backend.calls().len(); + map(&mut state, &mut backend, f); + assert_eq!( + storage_calls(&backend, from), + [f, a, a1, b, b1, c].map(|w| RecordedCall::RealizeWindowStorage(w.0)), + "the whole subtree realizes, parent first", + ); + let realize_at = backend + .calls() + .iter() + .skip(from) + .position(|c| matches!(c, RecordedCall::RealizeWindowStorage(_))) + .expect("realize recorded"); + let map_at = backend + .calls() + .iter() + .skip(from) + .position(|c| matches!(c, RecordedCall::MapSubwindow(_))) + .expect("map recorded"); + assert!( + map_at < realize_at, + "map_subwindow flips `mapped` before realize reads it" + ); + + // A mapped window under an unmapped parent gets nothing; the root and the COW never do. + unmap(&mut state, &mut backend, a); + let _ = state.resources.unmap_window(a1); + let from = backend.calls().len(); + map(&mut state, &mut backend, a1); + assert!( + storage_calls(&backend, from).is_empty(), + "Unmapped -> Unviewable is no transition" + ); + state + .resources + .materialize_cow_resource(crate::backend::WindowHandle::from_raw_for_test( + COMPOSITE_OVERLAY_WINDOW.0, + )); + let from = backend.calls().len(); + unmap(&mut state, &mut backend, COMPOSITE_OVERLAY_WINDOW); + map(&mut state, &mut backend, COMPOSITE_OVERLAY_WINDOW); + assert!( + storage_calls(&backend, from).is_empty(), + "the COW is outside the lifecycle" + ); + assert_eq!(storage_lifecycle_host_xid(&state, ROOT_WINDOW), None); + assert_eq!( + storage_lifecycle_host_xid(&state, COMPOSITE_OVERLAY_WINDOW), + None + ); +} + +#[test] +fn map_subwindows_delta_includes_promoted_grandchildren() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let [f, a, a1, b, b1, _c] = subwindows_delta_fixture(&mut state); + + let (_, delta) = map_subwindows_with_delta( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 9, minor: 0 }, + &f.0.to_le_bytes(), + ) + .expect("MapSubwindows"); + // C was already viewable; B then A (top-most first, `dix/window.c:2739`), + // each bringing its grandchild. + assert_eq!(delta.became_viewable, vec![b, b1, a, a1]); + assert!(delta.became_unviewable.is_empty()); +} + +#[test] +fn unmap_subwindows_delta_is_union_in_post_order() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let [f, a, a1, b, b1, c] = subwindows_delta_fixture(&mut state); + let _ = state.resources.map_window(a); + let _ = state.resources.map_window(b); + + let (_, delta) = unmap_subwindows_with_delta( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + &f.0.to_le_bytes(), + None, + ) + .expect("UnmapSubwindows"); + assert!(delta.became_viewable.is_empty()); + assert_eq!(delta.became_unviewable, vec![a1, a, b1, b, c]); +} + +#[test] +fn query_tree_of_the_root_hides_the_overlay_window() { + // Xorg CompositeRealChildHead (composite/compwindow.c:762), measured + // on Xvfb 21.1 (tools/vng-scenarios/composite-reredirect). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let child = ResourceId(0x0010_0001); + create_root_child(&mut state, child.0); + state + .resources + .materialize_cow_resource(crate::backend::WindowHandle::from_raw_for_test(0xC0C0)); + handle_query_tree( + &mut state, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 15, + minor: 0, + }, + &ROOT_WINDOW.0.to_le_bytes(), + ) + .expect("QueryTree"); + let reply = read_all_available(&mut peer); + let listed: Vec = reply[32..] + .chunks_exact(4) + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + assert_eq!(u16::from_le_bytes([reply[16], reply[17]]), 1); + assert_eq!(listed, vec![child.0]); +} + +#[test] +fn unmap_subwindows_of_the_root_leaves_the_overlay_window_mapped() { + // dix/window.c:2897 stops at RealChildHead; measured on Xvfb 21.1. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let child = ResourceId(0x0010_0001); + create_root_child(&mut state, child.0); + let _ = state.resources.map_window(child); + state + .resources + .materialize_cow_resource(crate::backend::WindowHandle::from_raw_for_test(0xC0C0)); + let (_, delta) = unmap_subwindows_with_delta( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + &ROOT_WINDOW.0.to_le_bytes(), + None, + ) + .expect("UnmapSubwindows"); + assert_eq!(delta.became_unviewable, vec![child]); + assert_eq!( + state + .resources + .window(COMPOSITE_OVERLAY_WINDOW) + .map(|w| w.map_state), + Some(MapState::Viewable) + ); +} + +#[test] +fn map_and_unmap_under_unmapped_parent_still_send_notify() { + const STRUCTURE_NOTIFY: u32 = 0x0002_0000; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let [_f, _a, a1, ..] = subwindows_delta_fixture(&mut state); + let _ = state.resources.unmap_window(a1); + state + .clients + .get_mut(&1) + .expect("client") + .event_masks + .insert(a1, STRUCTURE_NOTIFY); + let notified = |bytes: &[u8], code: u8| { + bytes.chunks_exact(32).any(|evt| { + evt[0] == code && u32::from_le_bytes([evt[8], evt[9], evt[10], evt[11]]) == a1.0 + }) + }; + + // A1 under unmapped A: Unmapped -> Unviewable, still MapNotify. + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &a1.0.to_le_bytes(), + ) + .expect("MapWindow"); + assert_eq!( + state.resources.window(a1).map(|w| w.map_state), + Some(MapState::Unviewable) + ); + assert!(notified(&read_all_available(&mut peer), 19), "MapNotify"); + + // Unviewable -> Unmapped, still UnmapNotify. + handle_unmap_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 10, + minor: 0, + }, + &a1.0.to_le_bytes(), + ) + .expect("UnmapWindow"); + assert_eq!( + state.resources.window(a1).map(|w| w.map_state), + Some(MapState::Unmapped) + ); + assert!(notified(&read_all_available(&mut peer), 18), "UnmapNotify"); +} + +#[test] +fn map_subwindows_exposes_grandchild_promoted_by_viewability_cascade() { + // MapSubwindows(parent) maps parent's direct children. When a + // child transitions Unmapped -> Viewable, the viewability cascade + // (map_window) also promotes any of the + // child's descendants that were sitting Unviewable (mapped while + // their ancestor was unmapped) to Viewable. Xorg fires Expose on + // every newly-viewable window, not just the directly-mapped child. + // handle_map_subwindows previously emitted Expose only for the + // direct children, so a promoted grandchild never got its Expose + // and never painted its first frame (docs/known-issues.md). + const CLIENT_ID: u32 = 1; + const PARENT_XID: u32 = 0x0010_0032; + const CHILD_XID: u32 = 0x0010_0033; + const CHILD_HOST_XID: u32 = 0x0040_0033; + const GRANDCHILD_XID: u32 = 0x0010_0034; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(PARENT_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 400, + height: 300, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_XID), + parent: ResourceId(PARENT_XID), + x: 20, + y: 30, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRANDCHILD_XID), + parent: ResourceId(CHILD_XID), + x: 5, + y: 5, + width: 100, + height: 40, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + // Parent already viewable; child unmapped so MapSubwindows maps it; + // grandchild mapped-but-Unviewable so the cascade promotes it. + state + .resources + .window_mut(ResourceId(PARENT_XID)) + .expect("parent installed") + .map_state = crate::resources::MapState::Viewable; + { + let child = state + .resources + .window_mut(ResourceId(CHILD_XID)) + .expect("child installed"); + child.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + CHILD_HOST_XID, + )); + child.map_state = crate::resources::MapState::Unmapped; + } + state + .resources + .window_mut(ResourceId(GRANDCHILD_XID)) + .expect("grandchild installed") + .map_state = crate::resources::MapState::Unviewable; + + // Client selects ExposureMask (0x8000) on both child and grandchild. + let client = state.clients.get_mut(&CLIENT_ID).expect("client"); + client + .event_masks + .insert(ResourceId(CHILD_XID), 0x0000_8000); + client + .event_masks + .insert(ResourceId(GRANDCHILD_XID), 0x0000_8000); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&PARENT_XID.to_le_bytes()); + handle_map_subwindows( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 9, minor: 0 }, + &body, + ) + .expect("handle_map_subwindows"); + + // Grandchild is now Viewable (cascade worked)... + assert_eq!( + state + .resources + .window(ResourceId(GRANDCHILD_XID)) + .map(|w| w.map_state), + Some(crate::resources::MapState::Viewable), + "the viewability cascade must promote the grandchild" + ); + + let bytes = read_all_available(&mut peer); + let exposed = |xid: u32| { + bytes + .chunks_exact(32) + .any(|evt| evt[0] == 12 && u32::from_le_bytes([evt[4], evt[5], evt[6], evt[7]]) == xid) + }; + assert!( + exposed(CHILD_XID), + "the directly-mapped child must receive Expose (harness sanity)" + ); + assert!( + exposed(GRANDCHILD_XID), + "a grandchild promoted Unviewable->Viewable by MapSubwindows must \ + also receive Expose, else it never paints its first frame" + ); +} + +// X11 wire-event ordering on map. Verified divergence vs Xorg: +// +// - **Xorg** (mate-xorg.xtrace lines 5164→5173 around mate-panel-top +// map): MapNotify(event=root) first, then DAMAGE-Notify. +// - **yserver pre-fix** (mate.xtrace lines 4938→4940): DAMAGE-Notify +// first, then MapNotify(event=root). +// +// Marco's compositor relies on MapNotify(SubstructureNotify on root) +// to register a window in its compositor tree, and on the *next* +// DAMAGE-Notify on that window to trigger NameWindowPixmap. When +// damage arrives first, marco's tree doesn't know about the window +// yet and the damage is silently discarded. Marco then never sees +// the audit-#11 initial-paint damage and never Names the window; +// the panel renders blank until a *later* damage event arrives +// (typically the post-resize damage), by which point the icon-paint +// CopyAreas have already missed their compositor pickup window. +// +// The audit-#11 fix (`accumulate_damage_full_to_state` inside +// `handle_map_window`) is structurally correct but was placed +// before the MapNotify emissions — inverting the spec-correct +// order. This test pins MapNotify-before-DAMAGE on the wire. +#[test] +fn map_window_emits_map_notify_before_damage_notify() { + use crate::server::DamageObject; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0011; + const HOST_XID: u32 = 0x0040_0011; + const DAMAGE_ID: u32 = 0x0080_0011; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + background_pixel: Some(0x0080_8080), + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + + // Compositor-like subscription: SubstructureNotify on root + // (0x0008_0000) — gets MapNotify(event=root) when a child of + // root maps. Plus an `XDamageCreate(window)` subscription — + // gets DAMAGE-Notify on the new window. + state + .clients + .get_mut(&CLIENT_ID) + .unwrap() + .event_masks + .insert(ROOT_WINDOW, 0x0008_0000); + state.damage_objects.insert( + DAMAGE_ID, + DamageObject { + owner: ClientId(CLIENT_ID), + drawable: ResourceId(WINDOW_XID), + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window"); + + // Drain everything emitted to the client. Each X11 event is + // 32 bytes — read until WouldBlock and walk event-by-event. + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 1024]; + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + + // First occurrence of MapNotify(opcode 19, event=ROOT) and + // DAMAGE-Notify(opcode 91) by 32-byte event index. MapNotify's + // `event` field is at offset 4..8 (after response_type, pad, + // sequence_number_lo, sequence_number_hi). + let mut map_root_idx: Option = None; + let mut damage_idx: Option = None; + for (i, chunk) in wire.chunks_exact(32).enumerate() { + let opcode = chunk[0] & 0x7f; // top bit is SendEvent flag + if opcode == 19 && map_root_idx.is_none() { + let event_xid = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); + if event_xid == ROOT_WINDOW.0 { + map_root_idx = Some(i); + } + } else if opcode == 91 && damage_idx.is_none() { + damage_idx = Some(i); + } + } + + let m = map_root_idx + .expect("MapNotify(event=root) must be emitted to a SubstructureNotify-on-root listener"); + let d = damage_idx.expect("DAMAGE-Notify must be emitted to a subscribed damage object"); + assert!( + m < d, + "MapNotify(event=root, idx={m}) must precede DAMAGE-Notify(idx={d}) on the \ + wire — pre-fix the audit-#11 damage emission inside `handle_map_window` ran \ + before the MapNotify emissions, so marco's compositor saw the damage on a \ + window that hadn't yet entered its compositor tree, silently discarded it, \ + and never NameWindowPixmap'd the freshly-mapped window. \ + See mate.xtrace lines 4938→4940 vs mate-xorg.xtrace lines 5164→5173.", + ); +} + +/// Mapping a viewable window emits `VisibilityNotify(Unobscured)` +/// (event type 15, state 0) to clients selecting +/// `VisibilityChangeMask` (0x10000). Without it, GTK3 suppresses +/// all frame-clock paints after the first expose-driven frame — +/// the cinnamon-settings "title updates but content never +/// repaints" freeze, confirmed by diffing the Xorg vs yserver +/// wire traces (Xorg sends Unobscured; yserver previously sent +/// nothing). +#[test] +fn map_window_emits_visibility_notify_unobscured() { + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0021; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + // Client selects VisibilityChangeMask on its own window. + state + .clients + .get_mut(&CLIENT_ID) + .unwrap() + .event_masks + .insert(ResourceId(WINDOW_XID), 0x0001_0000); + + let mut body = Vec::with_capacity(4); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &body, + ) + .expect("handle_map_window"); + + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 1024]; + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + + let vis = wire.chunks_exact(32).find(|chunk| chunk[0] & 0x7f == 15); + let vis = vis.expect("VisibilityNotify (type 15) must be emitted on map"); + let window = u32::from_le_bytes([vis[4], vis[5], vis[6], vis[7]]); + assert_eq!(window, WINDOW_XID, "VisibilityNotify targets the window"); + assert_eq!(vis[8], 0, "state must be Unobscured (0)"); +} + +/// xts5 Xlib4 (`EWin.mc`) creates a window, destroys it, then +/// invokes each window-manipulation request on the freed xid and +/// expects a `BadWindow` protocol error back. Before this fix, +/// every handler silently returned `RequestOutcome::Handled`, +/// causing ~24 FAILs across the Xlib4 cluster +/// (`Got Success, Expecting BadWindow`). +/// +/// One test per affected handler so a regression names the +/// specific request rather than a single bundled failure. +#[test] +fn window_handlers_on_freed_xid_return_bad_window() { + use std::io::Read; + const APP: u32 = 200; + const BAD: u32 = 0x0080_dead; + + // (opcode, header.data, body, label, requires_body_len) + let cases: &[(u8, u8, Vec, &str)] = &[ + ( + 1, + 24, + create_window_body_with_parent(BAD), + "CreateWindow(parent)", + ), + ( + 2, + 0, + change_window_attributes_body(BAD), + "ChangeWindowAttributes", + ), + (4, 0, BAD.to_le_bytes().to_vec(), "DestroyWindow"), + (5, 0, BAD.to_le_bytes().to_vec(), "DestroySubwindows"), + (8, 0, BAD.to_le_bytes().to_vec(), "MapWindow"), + (9, 0, BAD.to_le_bytes().to_vec(), "MapSubwindows"), + (10, 0, BAD.to_le_bytes().to_vec(), "UnmapWindow"), + (11, 0, BAD.to_le_bytes().to_vec(), "UnmapSubwindows"), + (12, 0, configure_window_body(BAD), "ConfigureWindow"), + (13, 0, BAD.to_le_bytes().to_vec(), "CirculateWindow"), + ]; + + for (i, (opcode, data, body, label)) in cases.iter().enumerate() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP + i as u32); + let mut backend = RecordingBackend::new(); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body length fits"); + let seq = SequenceNumber((i + 1) as u16); + process_request( + &mut state, + &mut backend, + ClientId(APP + i as u32), + seq, + RequestHeader { + opcode: *opcode, + data: *data, + length_units, + }, + body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap_or_else(|e| { + panic!("{label}: expected 32-byte error reply, got {e:?}"); + }); + assert_eq!( + buf[0], 0, + "{label}: byte 0 = error class (0); got {}", + buf[0] + ); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_WINDOW, + "{label}: expected BadWindow (3) for freed xid; got error code {}", + buf[1], + ); + // bytes [4..8] = error_value (the bad xid) + let bad_value = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]); + assert_eq!( + bad_value, BAD, + "{label}: error_value must echo the freed window xid" + ); + // byte [10] = major_opcode (this is the request that errored) + assert_eq!( + buf[10], *opcode, + "{label}: BadWindow error must carry the request's \ + major opcode (expected {opcode}); got {}", + buf[10], + ); + } +} + +fn create_window_body_with_parent(parent_xid: u32) -> Vec { + // ProcCreateWindow body (header.data carries depth): + // wid u32, parent u32, x i16, y i16, width u16, height u16, + // border_width u16, class u16, visual u32, value_mask u32, … + // Use class=CopyFromParent(0), visual=CopyFromParent(0), no + // attributes — the parent BadWindow check fires first. + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&0x0080_0001u32.to_le_bytes()); // new wid (will not be used) + body.extend_from_slice(&parent_xid.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); // x + body.extend_from_slice(&0i16.to_le_bytes()); // y + body.extend_from_slice(&10u16.to_le_bytes()); // width + body.extend_from_slice(&10u16.to_le_bytes()); // height + body.extend_from_slice(&0u16.to_le_bytes()); // border_width + body.extend_from_slice(&0u16.to_le_bytes()); // class + body.extend_from_slice(&0u32.to_le_bytes()); // visual + body.extend_from_slice(&0u32.to_le_bytes()); // value_mask + body +} + +fn change_window_attributes_body(window_xid: u32) -> Vec { + // ProcChangeWindowAttributes body: window u32, value_mask u32, + // values… No values needed — the window BadWindow check + // fires before attribute application. + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&window_xid.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // value_mask + body +} + +fn configure_window_body(window_xid: u32) -> Vec { + // ProcConfigureWindow body: window u32, value_mask u16, pad + // u16, values… No values needed — BadWindow check fires + // before mask is read. + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&window_xid.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); // value_mask + body.extend_from_slice(&0u16.to_le_bytes()); // pad + body +} + +/// CreateWindow body with an explicit class/visual and a value list. +/// `depth` travels in `header.data`, not the body. +fn border_create_body(wid: u32, parent: u32, value_mask: u32, values: &[u32]) -> Vec { + let mut body = Vec::with_capacity(28 + values.len() * 4); + body.extend_from_slice(&wid.to_le_bytes()); + body.extend_from_slice(&parent.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); // x + body.extend_from_slice(&0i16.to_le_bytes()); // y + body.extend_from_slice(&10u16.to_le_bytes()); // width + body.extend_from_slice(&10u16.to_le_bytes()); // height + body.extend_from_slice(&0u16.to_le_bytes()); // border_width + body.extend_from_slice(&1u16.to_le_bytes()); // class = InputOutput + body.extend_from_slice(&0u32.to_le_bytes()); // visual = CopyFromParent + body.extend_from_slice(&value_mask.to_le_bytes()); + for v in values { + body.extend_from_slice(&v.to_le_bytes()); + } + body +} + +/// Pick the border-source forward out of a recorded call list. +fn border_forwards(calls: &[RecordedCall]) -> Vec<(u32, u32, Vec)> { + calls + .iter() + .filter_map(|c| match c { + RecordedCall::ChangeSubwindowAttributes { + host_xid, + value_mask, + values, + } if value_mask & (CWA_BORDER_PIXMAP | CWA_BORDER_PIXEL) != 0 => { + Some((*host_xid, *value_mask, values.clone())) + } + _ => None, + }) + .collect() +} + +/// CWCursor on CreateWindow takes effect like ChangeWindowAttributes' +/// (Xorg `CreateWindow` → `ChangeWindowAttributes`): the window keeps +/// the cursor and the backend shows it; an unknown cursor is BadCursor. +#[test] +fn create_window_cursor_is_kept_and_forwarded() { + const CURSOR: ResourceId = ResourceId(0x0080_0010); + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.resources.create_glyph_cursor(ClientId(1), CURSOR); + state.resources.set_cursor_host_xid( + CURSOR, + crate::backend::CursorHandle::from_raw(0x00ab_0001).unwrap(), + ); + let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, 0x4000, &[CURSOR.0]); + let calls = run_border_request_recording(&mut state, 1, 0, &body); + assert_no_error(&read_all_available(&mut peer), "CreateWindow with a cursor"); + let window = state.resources.window(ResourceId(0x0080_0001)).unwrap(); + assert_eq!(window.cursor, Some(CURSOR)); + let host = window.host_xid.unwrap().as_raw(); + assert!(calls.contains(&RecordedCall::DefineCursor { + host_window_xid: host, + cursor_host_xid: 0x00ab_0001, + })); + + let body = border_create_body(0x0080_0002, ROOT_WINDOW.0, 0x4000, &[0x0080_0011]); + run_border_request(&mut state, 1, 0, &body); + assert_error_code( + &read_all_available(&mut peer), + x11::error::BAD_CURSOR, + "unknown cursor", + ); +} + +/// #196: a window holds its cursor (Xorg `pCurs->refcnt`, +/// `dix/window.c:1536`), so FreeCursor of a cursor set by CreateWindow +/// keeps it — for an InputOutput and an InputOnly window alike, the +/// latter having no backend window to hold it — until the window +/// changes cursor (`:1559`) or is destroyed (`:968`); then it is freed +/// once. +#[test] +fn create_window_cursor_outlives_free_cursor_until_the_window_drops_it() { + let host_frees = |calls: &[RecordedCall]| -> Vec { + calls + .iter() + .filter_map(|c| match c { + RecordedCall::FreeCursor(h) => Some(*h), + _ => None, + }) + .collect() + }; + for (class, drop_by_destroy) in [(1u16, false), (1, true), (2, false), (2, true)] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let cursor = ResourceId(0x0080_0010); + let window = 0x0080_0001; + state.resources.create_glyph_cursor(ClientId(1), cursor); + state.resources.set_cursor_host_xid( + cursor, + crate::backend::CursorHandle::from_raw(0x00ab_0001).unwrap(), + ); + let mut body = border_create_body(window, ROOT_WINDOW.0, 0x4000, &[cursor.0]); + body[18..20].copy_from_slice(&class.to_le_bytes()); + run_border_request(&mut state, 1, 0, &body); + assert_no_error(&read_all_available(&mut peer), "CreateWindow"); + + let calls = run_border_request_recording(&mut state, 95, 0, &cursor.0.to_le_bytes()); + assert_eq!(host_frees(&calls), Vec::::new(), "class {class}: held"); + + let calls = if drop_by_destroy { + run_border_request_recording(&mut state, 4, 0, &window.to_le_bytes()) + } else { + run_border_request_recording(&mut state, 2, 0, &border_cwa_body(window, 0x4000, &[0])) + }; + assert_eq!(host_frees(&calls), vec![0x00ab_0001], "class {class}"); + assert_no_error(&read_all_available(&mut peer), "no error"); + } +} + +/// The positive control: a cursor two windows hold goes with the last. +#[test] +fn freed_cursor_goes_with_the_last_window_holding_it() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let cursor = ResourceId(0x0080_0010); + state.resources.create_glyph_cursor(ClientId(1), cursor); + state.resources.set_cursor_host_xid( + cursor, + crate::backend::CursorHandle::from_raw(0x00ab_0001).unwrap(), + ); + for w in [0x0080_0001u32, 0x0080_0002] { + let body = border_create_body(w, ROOT_WINDOW.0, 0x4000, &[cursor.0]); + run_border_request(&mut state, 1, 0, &body); + } + let mut calls = run_border_request_recording(&mut state, 95, 0, &cursor.0.to_le_bytes()); + calls.extend(run_border_request_recording( + &mut state, + 4, + 0, + &0x0080_0001u32.to_le_bytes(), + )); + assert!(!calls.contains(&RecordedCall::FreeCursor(0x00ab_0001))); + let calls = run_border_request_recording(&mut state, 4, 0, &0x0080_0002u32.to_le_bytes()); + assert_eq!( + calls + .iter() + .filter(|c| **c == RecordedCall::FreeCursor(0x00ab_0001)) + .count(), + 1 + ); +} + +/// Xorg `dix/window.c:818` — a depth that differs from the parent's +/// with NO border attribute is BadMatch, because the inherited border +/// (`:879`) would carry the parent's depth. This is why awesome sends +/// `border-pixel=0x00000000` on every depth-32 CreateWindow. +#[test] +fn create_window_depth_differs_without_border_attribute_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, 0, &[]); + run_border_request(&mut state, 1, 32, &body); + let bytes = read_all_available(&mut peer); + assert_error_code( + &bytes, + x11::error::BAD_MATCH, + "depth 32 under depth-24 parent", + ); +} + +/// The same request WITH `CWBorderPixel` is legal — the awesome +/// pattern. +#[test] +fn create_window_depth_differs_with_border_pixel_is_accepted() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, CWA_BORDER_PIXEL, &[0]); + run_border_request(&mut state, 1, 32, &body); + let bytes = read_all_available(&mut peer); + assert_no_error(&bytes, "depth 32 with border-pixel"); + assert!( + state.resources.window(ResourceId(0x0080_0001)).is_some(), + "window should have been created" + ); +} + +/// `CWBorderPixmap` = `CopyFromParent` (xid 0) requires matching +/// depths (`dix/window.c:1254`). +#[test] +fn create_window_border_pixmap_copy_from_parent_depth_mismatch_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, CWA_BORDER_PIXMAP, &[0]); + run_border_request(&mut state, 1, 32, &body); + let bytes = read_all_available(&mut peer); + assert_error_code( + &bytes, + x11::error::BAD_MATCH, + "CopyFromParent border across depths", + ); +} + +/// A border pixmap xid that names nothing is BadPixmap. +#[test] +fn create_window_border_pixmap_unknown_xid_is_bad_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let body = border_create_body( + 0x0080_0001, + ROOT_WINDOW.0, + CWA_BORDER_PIXMAP, + &[0x0099_9999], + ); + run_border_request(&mut state, 1, 24, &body); + let bytes = read_all_available(&mut peer); + assert_error_code(&bytes, x11::error::BAD_PIXMAP, "stale border pixmap"); +} + +/// A real border pixmap of the wrong depth is BadMatch +/// (`dix/window.c:1275`). +#[test] +fn create_window_border_pixmap_depth_mismatch_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: ResourceId(0x0080_1200), + drawable: ROOT_WINDOW, + width: 4, + height: 4, + depth: 1, + }, + ); + let body = border_create_body( + 0x0080_0001, + ROOT_WINDOW.0, + CWA_BORDER_PIXMAP, + &[0x0080_1200], + ); + run_border_request(&mut state, 1, 24, &body); + let bytes = read_all_available(&mut peer); + assert_error_code(&bytes, x11::error::BAD_MATCH, "depth-1 border on depth-24"); +} + +/// With both bits set the pixel wins and the pixmap is never +/// resolved — Xorg clears `CWBorderPixmap` from the mask before the +/// ddx layer sees it (`dix/window.c:1298`). So a bogus pixmap xid +/// alongside a pixel must NOT error. +#[test] +fn create_window_border_pixel_overrides_pixmap_and_skips_its_validation() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let body = border_create_body( + 0x0080_0001, + ROOT_WINDOW.0, + CWA_BORDER_PIXMAP | CWA_BORDER_PIXEL, + &[0x0099_9999, 0x00ff_0000], + ); + run_border_request(&mut state, 1, 24, &body); + let bytes = read_all_available(&mut peer); + assert_no_error(&bytes, "pixel overrides a bogus pixmap"); + assert_eq!( + state + .resources + .window(ResourceId(0x0080_0001)) + .map(|w| w.border), + Some(crate::resources::BorderSource::Pixel(0x00ff_0000)), + ); +} + +#[test] +fn change_window_attributes_border_pixmap_unknown_xid_is_bad_pixmap() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_window(&mut state, ResourceId(0x0080_0001), ROOT_WINDOW, 10, 10); + let body = border_cwa_body(0x0080_0001, CWA_BORDER_PIXMAP, &[0x0099_9999]); + run_border_request(&mut state, 2, 0, &body); + let bytes = read_all_available(&mut peer); + assert_error_code(&bytes, x11::error::BAD_PIXMAP, "CWA stale border pixmap"); +} + +#[test] +fn change_window_attributes_border_pixmap_depth_mismatch_is_bad_match() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_window(&mut state, ResourceId(0x0080_0001), ROOT_WINDOW, 10, 10); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: ResourceId(0x0080_1200), + drawable: ROOT_WINDOW, + width: 4, + height: 4, + depth: 1, + }, + ); + let body = border_cwa_body(0x0080_0001, CWA_BORDER_PIXMAP, &[0x0080_1200]); + run_border_request(&mut state, 2, 0, &body); + let bytes = read_all_available(&mut peer); + assert_error_code(&bytes, x11::error::BAD_MATCH, "CWA border depth mismatch"); +} + +/// The awesome request shape: a 16-byte CWA carrying ONLY +/// `CWBorderPixel`. Before #133 this parsed into a struct where every +/// field was `None` and did nothing. +#[test] +fn change_window_attributes_border_pixel_only_installs_the_pixel() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_window(&mut state, ResourceId(0x0080_0001), ROOT_WINDOW, 10, 10); + let body = border_cwa_body(0x0080_0001, CWA_BORDER_PIXEL, &[0xffff_0000]); + run_border_request(&mut state, 2, 0, &body); + let bytes = read_all_available(&mut peer); + assert_no_error(&bytes, "CWA border-pixel only"); + assert_eq!( + state + .resources + .window(ResourceId(0x0080_0001)) + .map(|w| w.border), + Some(crate::resources::BorderSource::Pixel(0xffff_0000)), + ); +} + +/// #133 step 2 (P3) — THE test for the forward path. The awesome +/// request shape (a CWA carrying only `CWBorderPixel`) must reach +/// the backend as a `change_subwindow_attributes` with the real X11 +/// CW bit `0x08` and the pixel value. Before step 2 a border change +/// reached the backend by no route at all: the only CWA forward +/// fired on a background change. +#[test] +fn change_window_attributes_border_pixel_forwards_to_backend() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + let host_xid = state + .resources + .window(win) + .and_then(|w| w.host_xid) + .expect("seed_window assigns a host xid") + .as_raw(); + + let body = border_cwa_body(win.0, CWA_BORDER_PIXEL, &[0xffff_0000]); + let calls = run_border_request_recording(&mut state, 2, 0, &body); + assert_no_error(&read_all_available(&mut peer), "CWA border-pixel only"); + assert_eq!( + border_forwards(&calls), + vec![(host_xid, CWA_BORDER_PIXEL, vec![0xffff_0000])], + "CWBorderPixel must forward as mask 0x08 with the pixel" + ); +} + +/// A border TILE forwards as `CWBorderPixmap` (`0x04`) carrying the +/// pixmap's HOST xid, not the client-visible one — same primitive +/// hand-off as a background pixmap, so the `yserver` crate never +/// needs `resources::BorderSource`. +#[test] +fn change_window_attributes_border_pixmap_forwards_host_xid() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + let host_xid = state + .resources + .window(win) + .and_then(|w| w.host_xid) + .expect("host xid") + .as_raw(); + let tile = ResourceId(0x0080_1300); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: tile, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + depth: 24, + }, + ); + assert!( + state.resources.set_pixmap_host_xid( + tile, + crate::backend::PixmapHandle::from_raw(0x9999_0001).expect("non-zero") + ), + "tile pixmap must exist" + ); + + let body = border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]); + let calls = run_border_request_recording(&mut state, 2, 0, &body); + assert_no_error(&read_all_available(&mut peer), "CWA border-pixmap"); + assert_eq!( + border_forwards(&calls), + vec![(host_xid, CWA_BORDER_PIXMAP, vec![0x9999_0001])], + ); +} + +/// #143 — THE regression gate for the awesome border flicker. +/// +/// awesome recolours a focused/unfocused frame with a CWA carrying +/// only `CWBorderPixel`. We repainted the ring into the redirect +/// backing but reported no protocol DAMAGE for it, so picom — which +/// partial-repaints from `EXT_buffer_age` — kept one ring colour per +/// back buffer and alternated between them at frame rate. Xorg +/// reports it from `ChangeWindowAttributes` itself: `borderClip − +/// winSize` → `PaintWindow(..., PW_BORDER)` (`dix/window.c:1581-1589`) +/// → `PolyFillRect` on the window pixmap (`mi/miexpose.c:448-471`, +/// `:558`) → `damagePolyFillRect` (`miext/damage/damage.c:1194`). +/// +/// Geometry is the captured one: 1276×704 at `border_width = 2`. +#[test] +fn change_window_attributes_border_pixel_damages_the_ring() { + use crate::server::DamageObject; + use yserver_protocol::x11::xfixes::RegionRect; + const DAMAGE_XID: u32 = 0x0080_9143; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 1276, 704); + if let Some(w) = state.resources.window_mut(win) { + w.border_width = 2; + } + assert!( + state.resources.map_window(win).mapping_changed, + "window must map" + ); + // Raw level: `area` on the wire then carries the real rect + // instead of the NonEmpty full-extent substitute, so the test + // can prove the negative origin survives the i16 encoding. + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: win, + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let body = border_cwa_body(win.0, CWA_BORDER_PIXEL, &[0x0000_ff00]); + run_border_request(&mut state, 2, 0, &body); + + let rects = state + .damage_objects + .get(&DAMAGE_XID) + .expect("damage object") + .rects + .clone(); + assert_eq!( + rects, + vec![ + RegionRect { + x: -2, + y: -2, + width: 1280, + height: 2 + }, + RegionRect { + x: -2, + y: 0, + width: 2, + height: 704 + }, + RegionRect { + x: 1276, + y: 0, + width: 2, + height: 704 + }, + RegionRect { + x: -2, + y: 704, + width: 1280, + height: 2 + }, + ], + "a border-source change must damage the whole ring, including the \ + negative-origin top and left strips", + ); + + // And it must reach the client as real DamageNotify events, + // with the negative origin intact on the wire (`area.x` is + // INT16 at byte 16). + let bytes = read_all_available(&mut peer); + let notifies: Vec<&[u8]> = bytes + .chunks_exact(32) + .filter(|c| c[0] == crate::nested::DAMAGE_FIRST_EVENT) + .collect(); + assert_eq!( + notifies.len(), + 4, + "one DamageNotify per ring strip at ReportLevel Raw", + ); + let areas: Vec<(i16, i16, u16, u16)> = notifies + .iter() + .map(|c| { + ( + i16::from_le_bytes([c[16], c[17]]), + i16::from_le_bytes([c[18], c[19]]), + u16::from_le_bytes([c[20], c[21]]), + u16::from_le_bytes([c[22], c[23]]), + ) + }) + .collect(); + assert!( + areas.contains(&(-2, -2, 1280, 2)), + "the top strip must arrive at a NEGATIVE origin, got {areas:?}", + ); + assert!( + areas.contains(&(-2, 0, 2, 704)), + "the left strip must arrive at a NEGATIVE x, got {areas:?}", + ); +} + +/// The ring damage follows Xorg's two gates and no others: nothing +/// for an unbordered window (`HasBorder(pWin)`, `dix/window.c:1586`) +/// and nothing for a non-viewable one (`pWin->viewable`, same line). +#[test] +fn change_window_attributes_border_pixel_damages_nothing_unbordered_or_unmapped() { + use crate::server::DamageObject; + const DAMAGE_XID: u32 = 0x0080_9144; + for (bw, map) in [(0u16, true), (2, false)] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 64, 64); + if let Some(w) = state.resources.window_mut(win) { + w.border_width = bw; + } + if map { + assert!( + state.resources.map_window(win).mapping_changed, + "window must map" + ); + } + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: win, + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let body = border_cwa_body(win.0, CWA_BORDER_PIXEL, &[0x0000_ff00]); + run_border_request(&mut state, 2, 0, &body); + assert_no_error(&read_all_available(&mut peer), "CWA border-pixel"); + + assert!( + state.damage_objects[&DAMAGE_XID].rects.is_empty(), + "bw={bw} mapped={map}: no ring to report", + ); + } +} + +/// #143, the resize half. `5d7270c1` reported the ring on a +/// border-source change and on backing activation; a RESIZE +/// repaints it too — `rotate_redirected_backing_on_resize` +/// reallocates and `allocate_redirected_backing` paints the new +/// ring — and reported nothing, so a partial-repaint compositor +/// (picom on `EXT_buffer_age`) kept a ring at the OLD extent in one +/// back buffer and the new one in the other. The bottom and right +/// strips are the ones that move when a window is resized about a +/// fixed origin, which is exactly the observed fingerprint: those +/// two edges flickered at awesome's ~1 Hz clock tick and settled +/// gone. +/// +/// Xorg reports it: `compReallocPixmap` reallocates whenever the +/// bordered extent differs (`composite/compalloc.c:698`) and that +/// branch alone calls `compSetPixmap` (`:700`), whose visitor +/// queues `compRepaintBorder` for `bw != 0` +/// (`composite/compwindow.c:137-139`) — a `PolyFillRect` on the +/// window pixmap (`mi/miexpose.c:558`) that `damagePolyFillRect` +/// (`miext/damage/damage.c:1194`) reports. +/// +/// bw = 2 and the captured 1276x704, shrunk and grown. +#[test] +fn configure_window_resize_damages_the_ring_at_the_new_geometry() { + use crate::{ + resources::RedirectedBacking, + server::{CompositeRedirectMode, DamageObject, RedirectRecord}, + }; + use yserver_protocol::x11::xfixes::RegionRect; + const DAMAGE_XID: u32 = 0x0080_9145; + const BW: u16 = 2; + // (old_w, old_h, new_w, new_h, label) + for (old_w, old_h, new_w, new_h, label) in [ + (1276u16, 704u16, 636u16, 348u16, "shrink"), + (636, 348, 1276, 704, "grow"), + ] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, old_w, old_h); + if let Some(w) = state.resources.window_mut(win) { + w.border_width = BW; + w.redirected_backing = Some(RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(0x0050_0001), + width: old_w + 2 * BW, + height: old_h + 2 * BW, + depth: 24, + }); + } + assert!( + state.resources.map_window(win).mapping_changed, + "window must map" + ); + state + .composite_redirects + .redirect_window( + win, + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); + // ReportLevel Raw, so `rects` keeps the real strips instead + // of the NonEmpty full-extent substitute. + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: win, + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + // ConfigureWindow, CWWidth | CWHeight. + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&win.0.to_le_bytes()); + body.extend_from_slice(&0x000cu16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&u32::from(new_w).to_le_bytes()); + body.extend_from_slice(&u32::from(new_h).to_le_bytes()); + run_border_request(&mut state, 12, 0, &body); + + let rects = state.damage_objects[&DAMAGE_XID].rects.clone(); + let bw = i16::try_from(BW).unwrap(); + let ring = [ + RegionRect { + x: -bw, + y: -bw, + width: new_w + 2 * BW, + height: BW, + }, + RegionRect { + x: -bw, + y: 0, + width: BW, + height: new_h, + }, + RegionRect { + x: i16::try_from(new_w).unwrap(), + y: 0, + width: BW, + height: new_h, + }, + RegionRect { + x: -bw, + y: i16::try_from(new_h).unwrap(), + width: new_w + 2 * BW, + height: BW, + }, + ]; + assert_eq!( + rects.get(..4), + Some(&ring[..]), + "{label}: a resize must damage the whole ring at the NEW \ + geometry, before the full-extent configure damage, and the \ + top/left strips carry NEGATIVE origins; got {rects:?}", + ); + // The bottom and right strips are the ones whose position + // MOVED — the #143 fingerprint. Spell them out so a + // regression that reports the ring at the OLD extent fails + // here and not only on the ordering assert above. + assert!( + rects.contains(&ring[2]) && rects.contains(&ring[3]), + "{label}: the right and bottom strips must sit at the NEW \ + extent ({new_w}x{new_h}), not the old one ({old_w}x{old_h})", + ); + assert!( + rects.contains(&RegionRect { + x: 0, + y: 0, + width: new_w, + height: new_h, + }), + "{label}: the pre-existing full-extent configure damage must \ + still fire alongside the ring", + ); + + // And it reaches the client, negative origins intact on the + // wire (`area.x`/`area.y` are INT16 at bytes 16..20). + let bytes = read_all_available(&mut peer); + let areas: Vec<(i16, i16, u16, u16)> = bytes + .chunks_exact(32) + .filter(|c| c[0] == crate::nested::DAMAGE_FIRST_EVENT) + .map(|c| { + ( + i16::from_le_bytes([c[16], c[17]]), + i16::from_le_bytes([c[18], c[19]]), + u16::from_le_bytes([c[20], c[21]]), + u16::from_le_bytes([c[22], c[23]]), + ) + }) + .collect(); + for r in &ring { + assert!( + areas.contains(&(r.x, r.y, r.width, r.height)), + "{label}: ring strip {r:?} must arrive as a DamageNotify, got {areas:?}", + ); + } + } +} + +/// The resize ring damage follows the same two Xorg gates as the +/// border-source one — nothing at `bw == 0` (`HasBorder(pWin)`) and +/// nothing for a non-viewable window (`pWin->viewable`, +/// `dix/window.c:1586`) — so an unbordered resize keeps reporting +/// exactly the one full-extent rect it always did. +#[test] +fn configure_window_resize_damages_no_ring_unbordered_or_unmapped() { + use crate::{ + resources::RedirectedBacking, + server::{CompositeRedirectMode, DamageObject, RedirectRecord}, + }; + use yserver_protocol::x11::xfixes::RegionRect; + const DAMAGE_XID: u32 = 0x0080_9146; + for (bw, map) in [(0u16, true), (2, false)] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 128, 64); + if let Some(w) = state.resources.window_mut(win) { + w.border_width = bw; + w.redirected_backing = Some(RedirectedBacking { + host_pixmap: crate::backend::PixmapHandle::from_raw_for_test(0x0050_0001), + width: 128 + 2 * bw, + height: 64 + 2 * bw, + depth: 24, + }); + } + if map { + assert!( + state.resources.map_window(win).mapping_changed, + "window must map" + ); + } + state + .composite_redirects + .redirect_window( + win, + RedirectRecord { + mode: CompositeRedirectMode::Manual, + owner: ClientId(1), + }, + ) + .unwrap(); + state.damage_objects.insert( + DAMAGE_XID, + DamageObject { + owner: ClientId(1), + drawable: win, + level: 0, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&win.0.to_le_bytes()); + body.extend_from_slice(&0x000cu16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&64u32.to_le_bytes()); + body.extend_from_slice(&32u32.to_le_bytes()); + run_border_request(&mut state, 12, 0, &body); + assert_no_error(&read_all_available(&mut peer), "ConfigureWindow resize"); + + let expected: Vec = if map { + vec![RegionRect { + x: 0, + y: 0, + width: 64, + height: 32, + }] + } else { + Vec::new() + }; + assert_eq!( + state.damage_objects[&DAMAGE_XID].rects, expected, + "bw={bw} mapped={map}: no ring to report on a resize", + ); + } +} + +/// A tile with no host storage degrades to the pixel bit with a +/// defined value, mirroring the background block: a backend that +/// cannot sample the tile is better off with a solid colour than +/// with a dangling xid. +#[test] +fn change_window_attributes_border_pixmap_without_host_storage_degrades_to_pixel() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + let host_xid = state + .resources + .window(win) + .and_then(|w| w.host_xid) + .expect("host xid") + .as_raw(); + let tile = ResourceId(0x0080_1301); + state.resources.create_pixmap( + ClientId(1), + CreatePixmapRequest { + pixmap: tile, + drawable: ROOT_WINDOW, + width: 8, + height: 8, + depth: 24, + }, + ); + + let body = border_cwa_body(win.0, CWA_BORDER_PIXMAP, &[tile.0]); + let calls = run_border_request_recording(&mut state, 2, 0, &body); + assert_no_error(&read_all_available(&mut peer), "hostless border tile"); + assert_eq!( + border_forwards(&calls), + vec![(host_xid, CWA_BORDER_PIXEL, vec![0])], + ); +} + +/// A CWA changing background AND border produces BOTH forwards — +/// the border block is a sibling of the background block, not a +/// replacement, and each carries only its own bits. +#[test] +fn change_window_attributes_background_and_border_forward_separately() { + const CWA_BACK_PIXEL: u32 = 0x0002; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x0080_0001); + seed_window(&mut state, win, ROOT_WINDOW, 10, 10); + let host_xid = state + .resources + .window(win) + .and_then(|w| w.host_xid) + .expect("host xid") + .as_raw(); + + // Value list in ascending mask-bit order: back-pixel, then + // border-pixel. + let body = border_cwa_body( + win.0, + CWA_BACK_PIXEL | CWA_BORDER_PIXEL, + &[0x0000_00ff, 0x00ff_0000], + ); + let calls = run_border_request_recording(&mut state, 2, 0, &body); + assert_no_error(&read_all_available(&mut peer), "bg + border in one CWA"); + let cwa: Vec<_> = calls + .iter() + .filter_map(|c| match c { + RecordedCall::ChangeSubwindowAttributes { + host_xid, + value_mask, + values, + } => Some((*host_xid, *value_mask, values.clone())), + _ => None, + }) + .collect(); + assert_eq!( + cwa, + vec![ + (host_xid, CWA_BACK_PIXEL, vec![0x0000_00ff]), + (host_xid, CWA_BORDER_PIXEL, vec![0x00ff_0000]), + ], + "background forward first, then the border forward" + ); +} + +/// CreateWindow forwards the INITIAL border source too. Without it +/// a window created with a border pixel that is never changed again +/// would leave the backend mirror with no source at all — and +/// CreateWindow inherits the parent's border (`dix/window.c:879`), +/// so even a client supplying no border attribute can start out +/// with a non-default one. +#[test] +fn create_window_forwards_the_initial_border_source() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let body = border_create_body(0x0080_0001, ROOT_WINDOW.0, CWA_BORDER_PIXEL, &[0x00ff_0000]); + let calls = run_border_request_recording(&mut state, 1, 24, &body); + assert_no_error(&read_all_available(&mut peer), "create with border pixel"); + let host_xid = state + .resources + .window(ResourceId(0x0080_0001)) + .and_then(|w| w.host_xid) + .expect("created window has a host xid") + .as_raw(); + assert_eq!( + border_forwards(&calls), + vec![(host_xid, CWA_BORDER_PIXEL, vec![0x00ff_0000])], + ); +} + +/// xts5 Xlib4 `XChangeWindowAttributes` 22-25 / Xlib4 +/// `XCreateWindow` 20-22 set a CWBackPixmap / CWColormap / +/// CWCursor value to a freed xid and expect BadPixmap / +/// BadColormap / BadCursor. Mirrors Xorg's per-attribute +/// `dixLookupResource` order in `dix/window.c::CreateWindow` and +/// `ChangeWindowAttributes`. +#[test] +fn change_window_attributes_with_stale_value_returns_specific_bad_error() { + use std::io::Read; + const APP: u32 = 300; + const WIN: u32 = 0x0090_0001; + const BAD_PIX: u32 = 0x0090_dead; + const BAD_CMAP: u32 = 0x0090_beef; + const BAD_CURS: u32 = 0x0090_face; + + // (mask, value, expected_error, label) + let cases: &[(u32, u32, u8, &str)] = &[ + ( + 0x0001, + BAD_PIX, + yserver_protocol::x11::error::BAD_PIXMAP, + "CWBackPixmap", + ), + ( + 0x2000, + BAD_CMAP, + yserver_protocol::x11::error::BAD_COLORMAP, + "CWColormap", + ), + ( + 0x4000, + BAD_CURS, + yserver_protocol::x11::error::BAD_CURSOR, + "CWCursor", + ), + ]; + + for (i, (mask, value, expected_err, label)) in cases.iter().enumerate() { + let mut state = ServerState::new(); + let app_id = APP + i as u32; + let mut peer = install_client(&mut state, app_id); + let mut backend = RecordingBackend::new(); + + // Create a live target window owned by this client so the + // BadWindow gate doesn't fire ahead of the value check. + let win = WIN + i as u32; + state.resources.create_window( + ClientId(app_id), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 10, + height: 10, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&win.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&value.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body length fits"); + + process_request( + &mut state, + &mut backend, + ClientId(app_id), + SequenceNumber(1), + RequestHeader { + opcode: 2, + data: 0, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).unwrap_or_else(|e| { + panic!("{label}: expected 32-byte error reply, got {e:?}"); + }); + assert_eq!( + buf[0], 0, + "{label}: byte 0 = error class (0); got {}", + buf[0] + ); + assert_eq!( + buf[1], *expected_err, + "{label}: expected error code {expected_err} for stale xid; got {}", + buf[1], + ); + let bad_value = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]); + assert_eq!( + bad_value, *value, + "{label}: error_value must echo the stale resource xid" + ); + assert_eq!( + buf[10], 2, + "{label}: error must carry the ChangeWindowAttributes \ + major opcode (2); got {}", + buf[10], + ); + } +} + +/// xts5 Xlib4 ConfigureWindow validations beyond BadWindow. +/// Mirrors Xorg `dix/window.c::ConfigureWindow:2203-2266` — every +/// check fires *before* any state mutation. +#[test] +fn configure_window_validates_inputonly_sibling_and_size() { + use std::io::Read; + const APP: u32 = 400; + const PARENT: u32 = 0x00a0_0001; + const INPUT_ONLY: u32 = 0x00a0_0002; + const SIB_A: u32 = 0x00a0_0003; + const SIB_B: u32 = 0x00a0_0004; + const ORPHAN: u32 = 0x00a0_0005; + const BAD_SIB: u32 = 0x00a0_dead; + const CW_X: u16 = 0x0001; + const CW_WIDTH: u16 = 0x0004; + const CW_HEIGHT: u16 = 0x0008; + const CW_BORDER_WIDTH: u16 = 0x0010; + const CW_SIBLING: u16 = 0x0020; + const CW_STACK_MODE: u16 = 0x0040; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + // Two siblings under PARENT and one orphan that's not their sibling. + for (id, parent, class) in [ + (PARENT, crate::resources::ROOT_WINDOW.0, 1u16), + (INPUT_ONLY, PARENT, 2u16), + (SIB_A, PARENT, 1u16), + (SIB_B, PARENT, 1u16), + (ORPHAN, crate::resources::ROOT_WINDOW.0, 1u16), + ] { + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(id), + parent: ResourceId(parent), + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + + // (label, body, expected_error) + let cases: Vec<(&str, Vec, u8)> = vec![ + ( + "InputOnly + CWBorderWidth → BadMatch", + build_configure_body(INPUT_ONLY, CW_BORDER_WIDTH, &[1u16.to_le_bytes()]), + yserver_protocol::x11::error::BAD_MATCH, + ), + ( + "CWSibling without CWStackMode → BadMatch", + build_configure_body( + SIB_A, + CW_SIBLING, + [SIB_B.to_le_bytes(); 1] + .iter() + .map(|b| { + let mut buf = [0u8; 2]; + buf.copy_from_slice(&b[..2]); + buf + }) + .collect::>() + .as_slice(), + ), + yserver_protocol::x11::error::BAD_MATCH, + ), + ( + "CWSibling with non-sibling → BadMatch", + build_configure_body_u32(SIB_A, CW_SIBLING | CW_STACK_MODE, ORPHAN, 0), + yserver_protocol::x11::error::BAD_MATCH, + ), + ( + "CWSibling with unknown xid → BadWindow", + build_configure_body_u32(SIB_A, CW_SIBLING | CW_STACK_MODE, BAD_SIB, 0), + yserver_protocol::x11::error::BAD_WINDOW, + ), + ( + "CWWidth=0 → BadValue", + build_configure_body(SIB_A, CW_WIDTH, &[0u16.to_le_bytes()]), + yserver_protocol::x11::error::BAD_VALUE, + ), + ( + "CWHeight=0 → BadValue", + build_configure_body(SIB_A, CW_HEIGHT, &[0u16.to_le_bytes()]), + yserver_protocol::x11::error::BAD_VALUE, + ), + ( + "CWX alone → no error (MOVE_WIN path)", + build_configure_body(SIB_A, CW_X, &[5u16.to_le_bytes()]), + 0, // 0 means: expect NO error reply + ), + ]; + + for (i, (label, body, expected_err)) in cases.iter().enumerate() { + let seq = SequenceNumber((i + 1) as u16); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body length fits"); + process_request( + &mut state, + &mut backend, + ClientId(APP), + seq, + RequestHeader { + opcode: 12, + data: 0, + length_units, + }, + body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + match peer.read_exact(&mut buf) { + Ok(()) => { + if *expected_err == 0 { + panic!("{label}: did not expect an error reply, got {buf:?}"); + } + assert_eq!(buf[0], 0, "{label}: byte 0 = error class (0)"); + assert_eq!( + buf[1], *expected_err, + "{label}: error code mismatch — got {}", + buf[1] + ); + } + Err(e) if *expected_err == 0 => { + // Expected — no error reply. + assert_eq!(e.kind(), std::io::ErrorKind::WouldBlock); + } + Err(e) => { + panic!("{label}: expected error reply with code {expected_err}, got {e:?}") + } + } + } +} + +fn build_configure_body(window_xid: u32, value_mask: u16, values: &[[u8; 2]]) -> Vec { + let mut body = Vec::with_capacity(8 + values.len() * 4); + body.extend_from_slice(&window_xid.to_le_bytes()); + body.extend_from_slice(&value_mask.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); // pad + for v in values { + body.extend_from_slice(v); + body.extend_from_slice(&0u16.to_le_bytes()); // each value is u32 on the wire + } + body +} + +fn build_configure_body_u32(window_xid: u32, value_mask: u16, v0: u32, v1: u32) -> Vec { + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&window_xid.to_le_bytes()); + body.extend_from_slice(&value_mask.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); // pad + body.extend_from_slice(&v0.to_le_bytes()); + body.extend_from_slice(&v1.to_le_bytes()); + body +} + +/// xts5 Xlib4 XCreateWindow CreateWindow class/border/depth rules: +/// parent InputOnly + child InputOutput → BadMatch (test 43), +/// InputOnly + non-zero border_width → BadMatch (test 31), +/// InputOnly + non-zero depth → BadMatch (test 44). +#[test] +fn create_window_validates_class_constraints() { + use std::io::Read; + const APP: u32 = 500; + const PARENT_IPO: u32 = 0x00b0_0001; + const PARENT_IPI: u32 = 0x00b0_0002; + const CHILD: u32 = 0x00b0_0003; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + // One InputOutput parent and one InputOnly parent. + for (id, parent, class) in [ + (PARENT_IPO, crate::resources::ROOT_WINDOW.0, 1u16), + (PARENT_IPI, crate::resources::ROOT_WINDOW.0, 2u16), + ] { + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(id), + parent: ResourceId(parent), + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + + // (label, depth, parent, class, border_width, expected_err) + let cases: &[(&str, u8, u32, u16, u16, u8)] = &[ + ( + "parent InputOnly + class InputOutput", + 24, + PARENT_IPI, + 1, + 0, + yserver_protocol::x11::error::BAD_MATCH, + ), + ( + "class InputOnly + non-zero border_width", + 0, + PARENT_IPO, + 2, + 1, + yserver_protocol::x11::error::BAD_MATCH, + ), + ( + "class InputOnly + non-zero depth", + 24, + PARENT_IPO, + 2, + 0, + yserver_protocol::x11::error::BAD_MATCH, + ), + ]; + + for (i, (label, depth, parent, class, bw, expected_err)) in cases.iter().enumerate() { + let mut body = Vec::with_capacity(32); + body.extend_from_slice(&CHILD.to_le_bytes()); + body.extend_from_slice(&parent.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); // x + body.extend_from_slice(&0i16.to_le_bytes()); // y + body.extend_from_slice(&10u16.to_le_bytes()); // width + body.extend_from_slice(&10u16.to_le_bytes()); // height + body.extend_from_slice(&bw.to_le_bytes()); // border_width + body.extend_from_slice(&class.to_le_bytes()); // class + body.extend_from_slice(&0u32.to_le_bytes()); // visual = CopyFromParent + body.extend_from_slice(&0u32.to_le_bytes()); // value_mask + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + let seq = SequenceNumber((i + 1) as u16); + process_request( + &mut state, + &mut backend, + ClientId(APP), + seq, + RequestHeader { + opcode: 1, + data: *depth, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf) + .unwrap_or_else(|e| panic!("{label}: expected error reply, got {e:?}")); + assert_eq!(buf[0], 0, "{label}: byte 0 = error class"); + assert_eq!( + buf[1], *expected_err, + "{label}: expected error code {expected_err}, got {}", + buf[1] + ); + assert_eq!( + buf[10], 1, + "{label}: BadMatch must carry CreateWindow opcode" + ); + } +} + +/// The issue-#248 probe (`tools/damage-after-map-probe.c`, `map1`): root's +/// subwindows Manual-redirected by a compositor (client 2) that selects +/// SubstructureNotify on root and holds a NonEmpty Damage on frame `W`; +/// the app (client 1) maps `W` with its child `C` already mapped. Returns +/// the compositor's and the app's events in the probe's notation. +fn map_redirected_frame_events(background_pixel: bool) -> (Vec, Vec) { + use crate::{nested::DAMAGE_FIRST_EVENT, server::DamageObject}; + use yserver_protocol::x11::damage as x11damage; + + const APP: u32 = 1; + const COMP: u32 = 2; + const W: u32 = 0x0010_0001; + const C: u32 = 0x0010_0002; + const DAMAGE_ID: u32 = 0x0020_0001; + + let mut state = ServerState::new(); + let mut app = install_client(&mut state, APP); + let mut comp = install_client(&mut state, COMP); + let mut backend = RecordingBackend::new().with_redirect_activation(); + let background = background_pixel.then_some(0x0080_8080); + for (window, parent, x, y, width, height) in [ + (W, ROOT_WINDOW, 50, 50, 300, 200), + (C, ResourceId(W), 10, 10, 280, 180), + ] { + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent, + x, + y, + width, + height, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + background_pixel: background, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(window)) + .unwrap() + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test( + window | 0x0040_0000, + )); + state + .clients + .get_mut(&APP) + .unwrap() + .event_masks + .insert(ResourceId(window), 0x0000_8000); + } + let _ = state.resources.map_window(ResourceId(C)); + // RedirectSubwindows(root, Manual). + let outcome = process_request( + &mut state, + &mut backend, + ClientId(COMP), + SequenceNumber(1), + RequestHeader { + opcode: 144, + data: 2, + length_units: 3, + }, + &[ROOT_WINDOW.0.to_le_bytes().as_slice(), &[1, 0, 0, 0]].concat(), + None, + ) + .expect("RedirectSubwindows"); + assert!(matches!(outcome, RequestOutcome::Handled)); + assert_eq!( + state.composite_redirects.window_mode(ResourceId(W)), + Some(crate::server::CompositeRedirectMode::Manual) + ); + state + .clients + .get_mut(&COMP) + .unwrap() + .event_masks + .insert(ROOT_WINDOW, 0x0008_0000 | 0x0002_0000); + state.damage_objects.insert( + DAMAGE_ID, + DamageObject { + owner: ClientId(COMP), + drawable: ResourceId(W), + level: x11damage::report_level::NON_EMPTY, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + let _ = read_all_available(&mut comp); + + handle_map_window( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber(2), + crate::access::RequestOpcodes { major: 8, minor: 0 }, + &W.to_le_bytes(), + ) + .expect("handle_map_window"); + + let u16_at = |e: &[u8], at: usize| u16::from_le_bytes([e[at], e[at + 1]]); + let i16_at = |e: &[u8], at: usize| i16::from_le_bytes([e[at], e[at + 1]]); + let u32_at = |e: &[u8], at: usize| u32::from_le_bytes(e[at..at + 4].try_into().unwrap()); + let comp_events = read_all_available(&mut comp) + .chunks_exact(32) + .filter_map(|e| match e[0] & 0x7f { + 19 if u32_at(e, 8) == W => Some("MapNotify".to_owned()), + t if t == DAMAGE_FIRST_EVENT && u32_at(e, 4) == W => Some(format!( + "Damage({},{} {}x{})", + i16_at(e, 16), + i16_at(e, 18), + u16_at(e, 20), + u16_at(e, 22) + )), + _ => None, + }) + .collect(); + let app_events = read_all_available(&mut app) + .chunks_exact(32) + .filter(|e| e[0] & 0x7f == 12) + .map(|e| { + let name = if u32_at(e, 4) == W { "W" } else { "C" }; + format!( + "Expose({name} {},{} {}x{})", + u16_at(e, 8), + u16_at(e, 10), + u16_at(e, 12), + u16_at(e, 14) + ) + }) + .collect(); + (comp_events, app_events) +} + +/// The app's Expose events of the probe's `map1`, identical on Xorg and +/// Xvfb for both backgrounds. +const PROBE_MAP_EXPOSES: [&str; 5] = [ + "Expose(W 0,0 300x10)", + "Expose(W 0,10 10x180)", + "Expose(W 290,10 10x180)", + "Expose(W 0,190 300x10)", + "Expose(C 0,0 280x180)", +]; + +/// Xorg delivers MapNotify before `RealizeTree` allocates the redirect +/// backing, and the background paint of the exposures damages the frame +/// after it (`dix/window.c:2677-2689`). Measured: `a/pixel map1` = +/// `MapNotify Damage(0,0 300x200)`. +#[test] +fn map_redirected_window_with_background_pixel_damages_after_map_notify() { + let (comp, app) = map_redirected_frame_events(true); + assert_eq!(comp, ["MapNotify", "Damage(0,0 300x200)"]); + assert_eq!(app, PROBE_MAP_EXPOSES); +} + +/// `miPaintWindow` paints nothing for background None, so the map reports +/// no damage at all (`mi/miexpose.c:438-440`). Measured: `a/none map1` = +/// `MapNotify` alone. +#[test] +fn map_redirected_window_with_background_none_reports_no_damage() { + let (comp, app) = map_redirected_frame_events(false); + assert_eq!(comp, ["MapNotify"]); + assert_eq!(app, PROBE_MAP_EXPOSES); +} + +/// The background an exposure paints goes to the window, not to its +/// redirect backing's pixmap: the backend resolves the window to the +/// backing with the offset of the window's border, while the pixmap's +/// own origin is the window's outer corner. Painted on the pixmap, a +/// resized window with a border of 2 lost its own border's top and left +/// and the right and bottom of its subwindows' borders. +#[test] +fn an_exposure_of_a_redirected_window_paints_through_the_window() { + use crate::{ + backend::{PixmapHandle, WindowHandle}, + resources::RedirectedBacking, + }; + const WINDOW: ResourceId = ResourceId(0x0040_0010); + const HOST: u32 = 0x0040_0090; + const BACKING: u32 = 0x0040_00d0; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: WINDOW, + parent: ROOT_WINDOW, + width: 100, + height: 80, + border_width: 2, + background_pixel: Some(0x00ff_ffff), + ..Default::default() + }, + ); + assert!(state.resources.map_window(WINDOW).mapping_changed); + let window = state.resources.window_mut(WINDOW).expect("window"); + window.host_xid = Some(WindowHandle::from_raw_for_test(HOST)); + window.redirected_backing = Some(RedirectedBacking { + host_pixmap: PixmapHandle::from_raw_for_test(BACKING), + width: 104, + height: 84, + depth: 24, + }); + let mut backend = RecordingBackend::new(); + let region = [x11::xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 80, + }]; + send_window_exposures(&mut state, &mut backend, None, WINDOW, ®ion, true); + let fills: Vec<(u32, i16, i16)> = backend + .calls() + .into_iter() + .filter_map(|call| match call { + RecordedCall::FillRectangle { host_xid, x, y, .. } => Some((host_xid, x, y)), + _ => None, + }) + .collect(); + assert_eq!(fills, vec![(HOST, 0, 0)]); +} + +/// Xorg ReparentWindow unmaps a mapped window before it moves +/// (`UnmapWindow(pWin, FALSE)`, `dix/window.c:2518-2519`), so the repaint +/// of what it covered is not clipped by it, then maps it in the new place +/// (`dix/window.c:2589-2590`). The backend must see it unmapped before that +/// repaint: a cover left mapped there clips the lower sibling's background +/// fill in a shared backing (fvwm3's resize, variant B of the measurement). +#[test] +fn reparent_of_a_mapped_window_unmaps_it_on_the_backend_before_the_exposure_paint() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let [frame, lower, cover, park] = + [0x0010_0300, 0x0010_0301, 0x0010_0302, 0x0010_0303].map(ResourceId); + for (id, parent, x, bg) in [ + (frame, ROOT_WINDOW, 0, None), + (lower, frame, 0, Some(0x00ff_0000)), + (cover, frame, 0, None), + (park, ROOT_WINDOW, 100, None), + ] { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: id, + parent, + x, + width: 40, + height: 40, + class: 1, + visual: crate::resources::ROOT_VISUAL, + background_pixel: bg, + ..Default::default() + }, + ); + state.resources.window_mut(id).expect("window").host_xid = + Some(crate::backend::WindowHandle::from_raw_for_test(id.0)); + } + for w in [lower, cover, frame, park] { + let _ = state.resources.map_window(w); + } + let mut backend = RecordingBackend::new(); + let mut body = Vec::new(); + body.extend_from_slice(&cover.0.to_le_bytes()); + body.extend_from_slice(&park.0.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + body.extend_from_slice(&0i16.to_le_bytes()); + handle_reparent_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { major: 7, minor: 0 }, + &body, + ) + .expect("ReparentWindow"); + let calls = backend.calls(); + let at = |pred: &dyn Fn(&RecordedCall) -> bool, what: &str| { + calls + .iter() + .position(pred) + .unwrap_or_else(|| panic!("{what} not recorded: {calls:?}")) + }; + let unmap = at( + &|c| matches!(c, RecordedCall::UnmapSubwindow(x) if *x == cover.0), + "unmap_subwindow(cover)", + ); + let paint = at( + &|c| matches!(c, RecordedCall::FillRectangle { host_xid, .. } if *host_xid == lower.0), + "the lower sibling's exposure paint", + ); + let reparent = at( + &|c| matches!(c, RecordedCall::ReparentSubwindow { host_xid, .. } if *host_xid == cover.0), + "reparent_subwindow(cover)", + ); + let map = at( + &|c| matches!(c, RecordedCall::MapSubwindow(x) if *x == cover.0), + "map_subwindow(cover)", + ); + assert!( + unmap < paint, + "unmapped before the exposure paint: {calls:?}" + ); + assert!(reparent < map, "mapped again in the new place: {calls:?}"); + assert_eq!( + state.resources.window(cover).map(|w| w.map_state), + Some(MapState::Viewable) + ); +} + +/// Xorg `miResizeWindow` unmaps each UnmapGravity child of a viewable +/// window whose size changes, `UnmapWindow(pChild, TRUE)` +/// (`mi/miwindow.c:389-398`): after the parent's ConfigureNotify +/// (`dix/window.c:2365-2381`, before `ResizeWindow`), an UnmapNotify with +/// from_configure, before the GravityNotify of the other children +/// (`ResizeChildrenWinSize`, `mi/miwindow.c:444`). Measured order on Xorg +/// (redirected-backing-probe UG): ConfigureNotify W, UnmapNotify on G then +/// on W, GravityNotify on K then on W. A pure move (`MoveWindow`) and an +/// unviewable parent leave the child mapped. +#[test] +fn a_parent_resize_unmaps_an_unmap_gravity_child() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let [w, g, k] = [0x0010_0400, 0x0010_0401, 0x0010_0402].map(ResourceId); + for (id, parent, x, width, gravity) in [ + (w, ROOT_WINDOW, 0, 200, 1), + (k, w, 180, 20, 3), // NorthEast + (g, w, 0, 100, 0), // Unmap + ] { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: id, + parent, + x, + width, + height: 20, + class: 1, + visual: crate::resources::ROOT_VISUAL, + win_gravity: Some(gravity), + ..Default::default() + }, + ); + } + for id in [k, g, w] { + let _ = state.resources.map_window(id); + } + let masks = &mut state.clients.get_mut(&1).expect("client").event_masks; + masks.insert(w, 0x0002_0000 | 0x0008_0000); // Structure | SubstructureNotify + masks.insert(g, 0x0002_0000); + masks.insert(k, 0x0002_0000); + let _ = read_all_available(&mut peer); + let configure = |state: &mut ServerState, mask: u16, values: &[u32]| { + let mut backend = RecordingBackend::new(); + handle_configure_window( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 12, + minor: 0, + }, + &cw_restack_body(w.0, mask, values), + ) + .expect("ConfigureWindow"); + }; + let events = |bytes: &[u8]| -> Vec<(u8, u32, u32, u8)> { + bytes + .chunks(32) + .filter(|e| e.len() == 32 && matches!(e[0] & 0x7f, 18 | 22 | 24)) + .map(|e| { + let at = |o: usize| u32::from_le_bytes([e[o], e[o + 1], e[o + 2], e[o + 3]]); + ( + e[0] & 0x7f, + at(4), + at(8), + if e[0] & 0x7f == 18 { e[12] } else { 0 }, + ) + }) + .collect() + }; + + // A pure move is MoveWindow: no UnmapGravity unmap. + configure(&mut state, 0x0003, &[10, 10]); + let _ = read_all_available(&mut peer); + assert_eq!( + state.resources.window(g).map(|win| win.map_state), + Some(MapState::Viewable), + "a move keeps the UnmapGravity child mapped" + ); + + configure(&mut state, 0x0004, &[150]); + assert_eq!( + events(&read_all_available(&mut peer)), + vec![ + (22, w.0, w.0, 0), + (18, g.0, g.0, 1), + (18, w.0, g.0, 1), + (24, k.0, k.0, 0), + (24, w.0, k.0, 0), + ], + "ConfigureNotify, UnmapNotify(from_configure) on G then W, GravityNotify", + ); + assert_eq!( + state.resources.window(g).map(|win| win.map_state), + Some(MapState::Unmapped) + ); + + // Under an unmapped parent the child stays mapped (`WasViewable`). + let _ = state.resources.map_window(g); + let _ = state.resources.unmap_window(w); + configure(&mut state, 0x0004, &[120]); + assert_ne!( + state.resources.window(g).map(|win| win.map_state), + Some(MapState::Unmapped), + "an unviewable parent's resize leaves the child mapped" + ); +} + +/// #297: Xorg's `ProcDestroyWindow` frees only a window with a parent +/// (`dix/dispatch.c:829`), so `DestroyWindow(root)` succeeds and changes +/// nothing. yserver walked root's whole subtree and destroyed every window in +/// the backend while the core kept them; the next ReparentWindow into one of +/// them panicked in the KMS backend. +#[test] +fn destroy_window_on_root_is_a_no_op() { + use crate::backend::{WindowHandle, recording::RecordedCall}; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0020; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + state + .resources + .window_mut(ROOT_WINDOW) + .expect("root installed") + .host_xid = Some(WindowHandle::from_raw_for_test(0x0040_0001)); + state.resources.create_window( + ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + width: 200, + height: 80, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed") + .host_xid = Some(WindowHandle::from_raw_for_test(0x0040_0020)); + + handle_destroy_window( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &ROOT_WINDOW.0.to_le_bytes(), + ) + .expect("handle_destroy_window"); + + assert!( + !backend + .calls() + .iter() + .any(|call| matches!(call, RecordedCall::DestroySubwindow(_))), + "DestroyWindow(root) must not destroy anything in the backend" + ); + assert!(state.resources.window(ROOT_WINDOW).is_some()); + assert!(state.resources.window(ResourceId(WINDOW_XID)).is_some()); +} + +const ORDER_T: u32 = 0x0010_0001; +const ORDER_C: u32 = 0x0010_0002; +const ORDER_PRESENT_EID_T: u32 = 0x0030_0001; +const ORDER_PRESENT_EID_C: u32 = 0x0030_0002; + +/// A stream of events as `tools/destroy-order-probe.c` prints them; a +/// GenericEvent carries its extra length. +fn describe_order_events(bytes: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut rest = bytes; + while rest.len() >= 32 { + let len = if rest[0] & 0x7f == 35 { + 32 + 4 * u32::from_le_bytes([rest[4], rest[5], rest[6], rest[7]]) as usize + } else { + 32 + }; + out.push(describe_order_event(&rest[..len])); + rest = &rest[len..]; + } + assert!(rest.is_empty(), "a trailing partial event"); + out +} + +/// `grb`'s and `obs`'s own windows in the probe's `setter-*` cases. +const ORDER_G: u32 = 0x0020_0001; +const ORDER_W: u32 = 0x0030_0001; + +/// One event as `tools/destroy-order-probe.c` prints it. +fn describe_order_event(ev: &[u8]) -> String { + let u32_at = |at: usize| u32::from_le_bytes([ev[at], ev[at + 1], ev[at + 2], ev[at + 3]]); + let i16_at = |at: usize| i16::from_le_bytes([ev[at], ev[at + 1]]); + let u16_at = |at: usize| u16::from_le_bytes([ev[at], ev[at + 1]]); + let nm = |id: u32| match id { + 0 => "None".to_owned(), + _ if id == ROOT_WINDOW.0 => "root".to_owned(), + ORDER_T => "T".to_owned(), + ORDER_C => "C".to_owned(), + ORDER_G => "G".to_owned(), + ORDER_W => "W".to_owned(), + _ => format!("0x{id:x}"), + }; + let detail = |d: u8| { + [ + "Ancestor", + "Virtual", + "Inferior", + "Nonlinear", + "NonlinearVirtual", + "Pointer", + "PointerRoot", + "DetailNone", + ] + .get(usize::from(d)) + .copied() + .unwrap_or("?") + }; + let mode = |m: u8| { + ["Normal", "Grab", "Ungrab", "WhileGrabbed"] + .get(usize::from(m)) + .copied() + .unwrap_or("?") + }; + match ev[0] & 0x7f { + t @ (7 | 8) => format!( + "{}(event={} child={} detail={} mode={} root={},{} event={},{} sf=0x{:x})", + if t == 7 { "EnterNotify" } else { "LeaveNotify" }, + nm(u32_at(12)), + nm(u32_at(16)), + detail(ev[1]), + mode(ev[30]), + i16_at(20), + i16_at(22), + i16_at(24), + i16_at(26), + ev[31], + ), + t @ (9 | 10) => format!( + "{}(event={} detail={} mode={})", + if t == 9 { "FocusIn" } else { "FocusOut" }, + nm(u32_at(4)), + detail(ev[1]), + mode(ev[8]), + ), + 12 => format!( + "Expose({} {},{} {}x{} count={})", + nm(u32_at(4)), + u16_at(8), + u16_at(10), + u16_at(12), + u16_at(14), + u16_at(16), + ), + 17 => format!( + "DestroyNotify(event={} window={})", + nm(u32_at(4)), + nm(u32_at(8)) + ), + 18 => format!( + "UnmapNotify(event={} window={} fromConfigure={})", + nm(u32_at(4)), + nm(u32_at(8)), + ev[12], + ), + 35 => format!( + "PresentConfigureNotify(eid={} window={} x={} y={} w={} h={} off={},{} pixmap={}x{} \ + flags=0x{:x})", + match u32_at(12) { + ORDER_PRESENT_EID_T => "eT".to_owned(), + ORDER_PRESENT_EID_C => "eC".to_owned(), + eid => format!("0x{eid:x}"), + }, + nm(u32_at(16)), + i16_at(20), + i16_at(22), + u16_at(24), + u16_at(26), + i16_at(28), + i16_at(30), + u16_at(32), + u16_at(34), + u32_at(36), + ), + 29 => format!("SelectionClear(owner={})", nm(u32_at(8))), + 30 => format!( + "SelectionRequest(owner={} requestor={})", + nm(u32_at(8)), + nm(u32_at(12)) + ), + 31 => format!( + "SelectionNotify(requestor={} property={})", + nm(u32_at(8)), + u32_at(20) + ), + t if t == crate::nested::XFIXES_FIRST_EVENT => format!( + "XFixesSelectionNotify(subtype={} window={} owner={})", + ev[1], + nm(u32_at(4)), + nm(u32_at(8)), + ), + t => format!("event{t}"), + } +} + +/// `tools/destroy-order-probe.c`'s scenario: mapped T (100,100 200x200, +/// child of root) with mapped C (50,50 100x100); the pointer at `pointer`; +/// a survivor (`grb`) set a selection on C, holds an active pointer grab on C and +/// has the focus on C (RevertToParent). +fn destroy_order_fixture(pointer: (i16, i16)) -> (ServerState, UnixStream, UnixStream) { + destroy_order_fixture_set_by(pointer, ORDER_GRB) +} + +/// [`destroy_order_fixture`] with the selection on C set by `setter`: +/// `ORDER_GRB` as in the probe's plain cases, `ORDER_APP` as with its +/// `appsel` modifier. +fn destroy_order_fixture_set_by( + pointer: (i16, i16), + setter: u32, +) -> (ServerState, UnixStream, UnixStream) { + let (mut state, _app, grb, mut obs) = selection_order_base(pointer); + set_order_selection(&mut state, &mut obs, setter, ORDER_C); + set_test_pointer_grab(&mut state, ORDER_GRB, ORDER_C, false, false); + state.core_focus = crate::server::CoreFocus { + raw: ORDER_C, + revert_to: 2, + time: 0, + }; + (state, grb, obs) +} + +const ORDER_APP: u32 = 1; +const ORDER_GRB: u32 = 2; +const ORDER_OBS: u32 = 3; + +/// The probe's windows and `obs` selections, without the selection owner, +/// grab or focus. Returns the `app`, `grb` and `obs` peers. +fn selection_order_base(pointer: (i16, i16)) -> (ServerState, UnixStream, UnixStream, UnixStream) { + const APP: u32 = ORDER_APP; + const OBS: u32 = ORDER_OBS; + let mut state = ServerState::new(); + let app = install_client(&mut state, APP); + let grb = install_client(&mut state, ORDER_GRB); + let obs = install_client(&mut state, OBS); + for (window, parent, x, y, size) in [ + (ORDER_T, ROOT_WINDOW.0, 100, 100, 200), + (ORDER_C, ORDER_T, 50, 50, 100), + ] { + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent: ResourceId(parent), + x, + y, + width: size, + height: size, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + } + let _ = state.resources.map_window(ResourceId(ORDER_C)); + let _ = state.resources.map_window(ResourceId(ORDER_T)); + + // SubstructureNotify|Exposure|FocusChange|EnterWindow|LeaveWindow on root, + // StructureNotify|FocusChange|EnterWindow|LeaveWindow on T and C. + let masks = &mut state.clients.get_mut(&OBS).unwrap().event_masks; + masks.insert( + ROOT_WINDOW, + 0x0008_0000 | 0x8000 | 0x0020_0000 | 0x10 | 0x20, + ); + masks.insert(ResourceId(ORDER_T), 0x0002_0000 | 0x0020_0000 | 0x10 | 0x20); + masks.insert(ResourceId(ORDER_C), 0x0002_0000 | 0x0020_0000 | 0x10 | 0x20); + let selection = state.atoms.intern(ORDER_SELECTION, false); + state.xfixes_selection_masks.insert( + (OBS, ROOT_WINDOW, selection), + yserver_protocol::x11::xfixes::SELECTION_ALL_EVENTS_MASK, + ); + state.pointer_root = pointer; + (state, app, grb, obs) +} + +const ORDER_SELECTION: &str = "DESTROY_ORDER_PROBE"; + +/// `SetSelectionOwner(window, DESTROY_ORDER_PROBE, CurrentTime)` from +/// `client`; the SetSelectionOwner notify `obs` gets is dropped, the probe +/// prints it before the step it measures. +fn set_order_selection(state: &mut ServerState, obs: &mut UnixStream, client: u32, window: u32) { + let selection = state.atoms.intern(ORDER_SELECTION, false); + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&selection.0.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + crate::core_loop::process_request::selection::handle_set_selection_owner( + state, + ClientId(client), + SequenceNumber(1), + crate::access::RequestOpcodes { + major: 22, + minor: 0, + }, + &body, + ) + .expect("handle_set_selection_owner"); + let _ = read_all_or_buffered(state, ORDER_OBS, obs); +} + +/// The event stream of `DestroyWindow(T)`, measured on Xephyr with +/// `tools/destroy-order-probe t`, matches `DeleteWindow`: UnmapNotify +/// (`dix/window.c:2854`); at unrealize the grab on C deactivates, then the +/// focus on C reverts (`dix/events.c:5915-5985`); the exposure of what T +/// covered (`window.c:2866`); then per window DestroyNotify and its +/// SelectionWindowDestroy (`window.c:1041-1050`, `:999`). +/// +/// Xephyr also sends `LeaveNotify(T, Ancestor, Normal)` and +/// `EnterNotify(root, Inferior, Normal)` between the Expose and +/// DestroyNotify(C): WindowsRestructured's crossings, which come from the +/// backend's `windows_restructured` and RecordingBackend does not produce. +#[test] +fn destroy_window_event_order_matches_xorg() { + let (mut state, mut grb, mut obs) = destroy_order_fixture((110, 110)); + assert_eq!( + destroy_t_and_read_order_stream(&mut state, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "LeaveNotify(event=C child=None detail=Ancestor mode=Ungrab root=110,110 event=-40,-40 sf=0x3)", + "EnterNotify(event=T child=None detail=Inferior mode=Ungrab root=110,110 event=10,10 sf=0x2)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "XFixesSelectionNotify(subtype=1 window=root owner=None)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!( + read_all_or_buffered(&mut state, 2, &mut grb).is_empty(), + "the grab's owner gets nothing (Xephyr: no event)" + ); + // Probe epilogue: focus root, RevertToNone; another client's grab succeeds. + assert_eq!(state.core_focus.raw, ROOT_WINDOW.0); + assert_eq!(state.core_focus.revert_to, 0); + assert!(state.active_pointer_grab.is_none()); +} + +/// `tools/destroy-order-probe c`: the pointer inside the grab window C, so the +/// grab deactivation's `DoEnterLeaveEvents(C, C, NotifyUngrab)` sends nothing. +/// The same two backend crossings are left out as above. +#[test] +fn destroy_window_event_order_with_the_pointer_in_the_grab_window_matches_xorg() { + let (mut state, mut grb, mut obs) = destroy_order_fixture((200, 200)); + assert_eq!( + destroy_t_and_read_order_stream(&mut state, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "XFixesSelectionNotify(subtype=1 window=root owner=None)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.active_pointer_grab.is_none()); +} + +/// DestroyWindow(T) by client 1; what client 3 (`obs`) received. +fn destroy_t_and_read_order_stream(state: &mut ServerState, obs: &mut UnixStream) -> Vec { + let mut backend = RecordingBackend::new(); + handle_destroy_window( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &ORDER_T.to_le_bytes(), + ) + .expect("handle_destroy_window"); + describe_order_events(&read_all_or_buffered(state, 3, obs)) +} + +/// `DeleteWindowFromAnyEvents(w, TRUE)` frees the passive grabs on the +/// window (`dix/events.c:5997-5998`), so a window recreated with the same id +/// does not inherit them. +#[test] +fn destroy_window_drops_passive_grabs_and_a_recycled_id_does_not_match_them() { + const WIN: u32 = 0x0010_0040; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let create = |state: &mut ServerState| { + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + width: 50, + height: 50, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WIN)); + }; + create(&mut state); + state.button_grabs.push(crate::server::PassiveButtonGrab { + owner: ClientId(1), + device_id: 0, + grab_window: ResourceId(WIN), + button: 0, + modifiers: 0x8000, + owner_events: false, + event_mask: 0, + pointer_mode: 1, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + state.key_grabs.push(crate::server::KeyGrab { + owner: ClientId(1), + device_id: 0, + grab_window: ResourceId(WIN), + keycode: 0, + modifiers: 0x8000, + owner_events: false, + pointer_mode: 1, + keyboard_mode: 1, + via_xi2: false, + xi2_mask: 0, + }); + state.xi1_passive_grabs.push(crate::server::Xi1PassiveGrab { + owner: ClientId(1), + deviceid: 2, + grab_window: ResourceId(WIN), + detail: 0, + modifiers: 0x8000, + owner_events: false, + this_mode: 1, + other_mode: 1, + is_key: false, + }); + let master = Some(crate::xinput::DEVICEID_MASTER_POINTER); + let pointer = crate::xinput::DEVICEID_MASTER_POINTER; + assert!( + state + .find_passive_grab(ResourceId(WIN), 1, 0, pointer, master) + .is_some(), + "the grab matches before the destroy" + ); + + let mut backend = RecordingBackend::new(); + handle_destroy_window( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &WIN.to_le_bytes(), + ) + .expect("handle_destroy_window"); + assert!(state.button_grabs.is_empty()); + assert!(state.key_grabs.is_empty()); + assert!(state.xi1_passive_grabs.is_empty()); + + create(&mut state); + assert!( + state + .find_passive_grab(ResourceId(WIN), 1, 0, pointer, master) + .is_none(), + "the recycled id does not match the destroyed window's grab" + ); +} + +/// `tools/destroy-order-probe t disconnect-appsel`, measured on Xephyr: `app` +/// closes its connection instead of destroying T. `app` set the selection, so +/// `DeleteClientFromAnySelections` (`dix/dispatch.c:3495`) sends +/// SelectionClientClose first and no SelectionWindowDestroy follows; the rest +/// is `DestroyWindow(T)`'s stream. The two backend crossings are left out as +/// in [`destroy_window_event_order_matches_xorg`]. +#[test] +fn disconnect_event_order_matches_xorg() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((110, 110), ORDER_APP); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "XFixesSelectionNotify(subtype=2 window=root owner=None)", + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "LeaveNotify(event=C child=None detail=Ancestor mode=Ungrab root=110,110 event=-40,-40 sf=0x3)", + "EnterNotify(event=T child=None detail=Inferior mode=Ungrab root=110,110 event=10,10 sf=0x2)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + // A survivor's grab on a window of the departing client's subtree is + // released (`dix/events.c:5915-5931`); probe epilogue as above. + assert!(state.active_pointer_grab.is_none()); + assert_eq!(state.core_focus.raw, ROOT_WINDOW.0); + assert_eq!(state.core_focus.revert_to, 0); +} + +/// `tools/destroy-order-probe c disconnect-appsel`, measured on Xephyr. +#[test] +fn disconnect_event_order_with_the_pointer_in_the_grab_window_matches_xorg() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((200, 200), ORDER_APP); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "XFixesSelectionNotify(subtype=2 window=root owner=None)", + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.active_pointer_grab.is_none()); +} + +/// `tools/destroy-order-probe t disconnect`, measured on Xephyr: `grb` set +/// the selection on `app`'s C, then `app` disconnects. `grb` is still +/// connected, so `DeleteClientFromAnySelections` (`dix/selection.c:128-139`) +/// leaves the selection alone; C's `FreeWindowResources` sends +/// SelectionWindowDestroy after its DestroyNotify (`dix/window.c:999`). The +/// two backend crossings are left out as in +/// [`destroy_window_event_order_matches_xorg`]. +#[test] +fn disconnect_of_the_window_owner_sends_window_destroy_when_another_client_set_the_selection() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((110, 110), ORDER_GRB); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "LeaveNotify(event=C child=None detail=Ancestor mode=Ungrab root=110,110 event=-40,-40 sf=0x3)", + "EnterNotify(event=T child=None detail=Inferior mode=Ungrab root=110,110 event=10,10 sf=0x2)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "XFixesSelectionNotify(subtype=1 window=root owner=None)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, ORDER_GRB, &mut grb).is_empty()); + assert!(state.selections.values().all(|s| s.window.0 == 0)); +} + +/// `tools/destroy-order-probe c disconnect`, measured on Xephyr; Xephyr's +/// three WindowsRestructured crossings after the Expose are left out. +#[test] +fn disconnect_of_the_window_owner_with_the_pointer_in_c_sends_window_destroy_for_another_setter() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((200, 200), ORDER_GRB); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "XFixesSelectionNotify(subtype=1 window=root owner=None)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, ORDER_GRB, &mut grb).is_empty()); + assert!(state.selections.values().all(|s| s.window.0 == 0)); +} + +/// Every event `client` has received so far, as the probe prints it. +fn order_stream(state: &mut ServerState, client: u32, peer: &mut UnixStream) -> Vec { + read_all_or_buffered(state, client, peer) + .chunks_exact(32) + .map(describe_order_event) + .collect() +} + +/// `tools/destroy-order-probe c setter-disconnect`, measured on Xephyr: +/// `grb` sets the selection on `app`'s C and disconnects. +/// +/// ```text +/// disconnect grb +/// obs: XFixesSelectionNotify(subtype=2 window=root owner=None) +/// selection owner: None +/// destroy T +/// obs: UnmapNotify(event=T window=T fromConfigure=0) +/// obs: UnmapNotify(event=root window=T fromConfigure=0) +/// obs: Expose(root 100,100 200x200 count=0) +/// obs: LeaveNotify(event=C ...) LeaveNotify(event=T ...) EnterNotify(event=root ...) +/// obs: DestroyNotify(event=C window=C) +/// obs: DestroyNotify(event=T window=T) +/// obs: DestroyNotify(event=root window=T) +/// selection owner: None +/// ``` +/// +/// `DeleteClientFromAnySelections` matches `Selection.client`, the client +/// that set the owner (`dix/selection.c:128-139`, `:220`), so ClientClose +/// fires although C is `app`'s, and the selection no longer names C when C +/// is destroyed. The three crossings come from WindowsRestructured and are +/// left out. +#[test] +fn disconnect_of_the_selection_setter_sends_client_close_for_a_window_it_does_not_own() { + let (mut state, mut app, mut grb, mut obs) = selection_order_base((200, 200)); + set_order_selection(&mut state, &mut obs, ORDER_GRB, ORDER_C); + let _ = order_stream(&mut state, ORDER_GRB, &mut grb); + + let mut backend = RecordingBackend::new(); + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(ORDER_GRB), + ); + assert_eq!( + order_stream(&mut state, ORDER_OBS, &mut obs), + ["XFixesSelectionNotify(subtype=2 window=root owner=None)"] + ); + assert!(order_stream(&mut state, ORDER_APP, &mut app).is_empty()); + assert!( + state.selections.values().all(|s| s.window.0 == 0), + "selection owner: None" + ); + + handle_destroy_window( + &mut state, + &mut backend, + None, + ClientId(ORDER_APP), + SequenceNumber(2), + RequestHeader { + opcode: 4, + data: 0, + length_units: 2, + }, + &ORDER_T.to_le_bytes(), + ) + .expect("handle_destroy_window"); + assert_eq!( + order_stream(&mut state, ORDER_OBS, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); +} + +/// `tools/destroy-order-probe c winowner-disconnect`, measured on Xephyr: +/// `grb` sets the selection on `app`'s C, then `app` disconnects. +/// +/// ```text +/// disconnect app +/// obs: UnmapNotify(event=T window=T fromConfigure=0) +/// obs: UnmapNotify(event=root window=T fromConfigure=0) +/// obs: Expose(root 100,100 200x200 count=0) +/// obs: LeaveNotify(event=C ...) LeaveNotify(event=T ...) EnterNotify(event=root ...) +/// obs: DestroyNotify(event=C window=C) +/// obs: XFixesSelectionNotify(subtype=1 window=root owner=None) +/// obs: DestroyNotify(event=T window=T) +/// obs: DestroyNotify(event=root window=T) +/// selection owner: None +/// ``` +#[test] +fn disconnect_of_the_window_owner_sends_window_destroy_not_client_close() { + let (mut state, _app, mut grb, mut obs) = selection_order_base((200, 200)); + set_order_selection(&mut state, &mut obs, ORDER_GRB, ORDER_C); + let _ = order_stream(&mut state, ORDER_GRB, &mut grb); + + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "XFixesSelectionNotify(subtype=1 window=root owner=None)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(order_stream(&mut state, ORDER_GRB, &mut grb).is_empty()); + assert!( + state.selections.values().all(|s| s.window.0 == 0), + "selection owner: None" + ); +} + +fn create_order_window(state: &mut ServerState, owner: u32, window: u32) { + state.resources.create_window( + ClientId(owner), + CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent: ROOT_WINDOW, + width: 10, + height: 10, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); +} + +/// `tools/destroy-order-probe c setter-route`, measured on Xephyr: `grb` +/// sets the selection on `app`'s C; `obs` converts it into its window W, +/// then takes it over on W. +/// +/// ```text +/// obs ConvertSelection +/// obs: event16 (CreateNotify of W) +/// grb: SelectionRequest(owner=C requestor=W) +/// obs SetSelectionOwner W +/// obs: XFixesSelectionNotify(subtype=0 window=root owner=W) +/// grb: SelectionClear(owner=C) +/// selection owner: W +/// ``` +/// +/// Both go to `Selection.client` (`dix/selection.c:183-191`, `:297-301`), +/// not to the client that created the owner window; `app` gets nothing. +#[test] +fn selection_request_and_clear_go_to_the_setting_client() { + let (mut state, mut app, mut grb, mut obs) = selection_order_base((200, 200)); + create_order_window(&mut state, ORDER_OBS, ORDER_W); + set_order_selection(&mut state, &mut obs, ORDER_GRB, ORDER_C); + let _ = order_stream(&mut state, ORDER_GRB, &mut grb); + let selection = state.atoms.intern(ORDER_SELECTION, false); + + let mut body = Vec::with_capacity(20); + for word in [ORDER_W, selection.0, 31, 31, 0] { + body.extend_from_slice(&word.to_le_bytes()); + } + crate::core_loop::process_request::selection::handle_convert_selection( + &mut state, + ClientId(ORDER_OBS), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 24, + minor: 0, + }, + &body, + ) + .expect("handle_convert_selection"); + assert!(order_stream(&mut state, ORDER_OBS, &mut obs).is_empty()); + assert!(order_stream(&mut state, ORDER_APP, &mut app).is_empty()); + assert_eq!( + order_stream(&mut state, ORDER_GRB, &mut grb), + ["SelectionRequest(owner=C requestor=W)"] + ); + + let mut body = Vec::with_capacity(12); + for word in [ORDER_W, selection.0, 0] { + body.extend_from_slice(&word.to_le_bytes()); + } + crate::core_loop::process_request::selection::handle_set_selection_owner( + &mut state, + ClientId(ORDER_OBS), + SequenceNumber(3), + crate::access::RequestOpcodes { + major: 22, + minor: 0, + }, + &body, + ) + .expect("handle_set_selection_owner"); + assert_eq!( + order_stream(&mut state, ORDER_OBS, &mut obs), + ["XFixesSelectionNotify(subtype=0 window=root owner=W)"] + ); + assert!(order_stream(&mut state, ORDER_APP, &mut app).is_empty()); + assert_eq!( + order_stream(&mut state, ORDER_GRB, &mut grb), + ["SelectionClear(owner=C)"] + ); +} + +/// `tools/destroy-order-probe c setter-retake`, measured on Xephyr: `grb` +/// sets the selection on `app`'s C, moves it to its own G and back to C, +/// then `app` takes it on T. +/// +/// ```text +/// grb SetSelectionOwner G +/// obs: event16 (CreateNotify of G) +/// obs: XFixesSelectionNotify(subtype=0 window=root owner=G) +/// grb SetSelectionOwner C +/// obs: XFixesSelectionNotify(subtype=0 window=root owner=C) +/// app SetSelectionOwner T +/// obs: XFixesSelectionNotify(subtype=0 window=root owner=T) +/// grb: SelectionClear(owner=C) +/// ``` +/// +/// SelectionClear is gated on the setting client (`dix/selection.c:183`): +/// `grb` moving its selection between windows clears nothing, whoever owns +/// the windows; `app` taking it from `grb` clears `grb`, although C is +/// `app`'s own window. +#[test] +fn selection_clear_is_gated_on_the_setting_client_not_the_window_owner() { + let (mut state, mut app, mut grb, mut obs) = selection_order_base((200, 200)); + create_order_window(&mut state, ORDER_GRB, ORDER_G); + set_order_selection(&mut state, &mut obs, ORDER_GRB, ORDER_C); + let _ = order_stream(&mut state, ORDER_GRB, &mut grb); + let selection = state.atoms.intern(ORDER_SELECTION, false); + let mut set = |state: &mut ServerState, client: u32, window: u32| { + let mut body = Vec::with_capacity(12); + for word in [window, selection.0, 0] { + body.extend_from_slice(&word.to_le_bytes()); + } + crate::core_loop::process_request::selection::handle_set_selection_owner( + state, + ClientId(client), + SequenceNumber(2), + crate::access::RequestOpcodes { + major: 22, + minor: 0, + }, + &body, + ) + .expect("handle_set_selection_owner"); + ( + order_stream(state, ORDER_OBS, &mut obs), + order_stream(state, ORDER_APP, &mut app), + order_stream(state, ORDER_GRB, &mut grb), + ) + }; + let none: [&str; 0] = []; + + let (o, a, g) = set(&mut state, ORDER_GRB, ORDER_G); + assert_eq!(o, ["XFixesSelectionNotify(subtype=0 window=root owner=G)"]); + assert_eq!(a, none, "grb SetSelectionOwner G: app gets nothing"); + assert_eq!(g, none); + + let (o, a, g) = set(&mut state, ORDER_GRB, ORDER_C); + assert_eq!(o, ["XFixesSelectionNotify(subtype=0 window=root owner=C)"]); + assert_eq!(a, none); + assert_eq!(g, none); + + let (o, a, g) = set(&mut state, ORDER_APP, ORDER_T); + assert_eq!(o, ["XFixesSelectionNotify(subtype=0 window=root owner=T)"]); + assert_eq!(a, none); + assert_eq!(g, ["SelectionClear(owner=C)"], "app SetSelectionOwner T"); +} + +/// Client 1 disconnects; what client 3 (`obs`) received. +fn disconnect_app_and_read_order_stream( + state: &mut ServerState, + obs: &mut UnixStream, +) -> Vec { + let mut backend = RecordingBackend::new(); + crate::core_loop::process_disconnect::process_disconnect(state, &mut backend, ClientId(1)); + assert!(!state.clients.contains_key(&1)); + describe_order_events(&read_all_or_buffered(state, 3, obs)) +} + +/// [`destroy_order_fixture_set_by`] with the probe's `present` modifier: C has +/// a 3px border and `obs` selects PresentConfigureNotify on T and C. +fn present_order_fixture( + pointer: (i16, i16), + setter: u32, +) -> (ServerState, UnixStream, UnixStream) { + use yserver_protocol::x11::present as x11present; + let (mut state, grb, obs) = destroy_order_fixture_set_by(pointer, setter); + state + .resources + .window_mut(ResourceId(ORDER_C)) + .unwrap() + .border_width = 3; + for (eid, window) in [ + (ORDER_PRESENT_EID_T, ORDER_T), + (ORDER_PRESENT_EID_C, ORDER_C), + ] { + state.present_event_selections.insert( + eid, + crate::server::PresentEventSelection { + owner: ClientId(3), + window: ResourceId(window), + event_mask: x11present::EVENT_MASK_CONFIGURE_NOTIFY, + }, + ); + } + (state, grb, obs) +} + +/// `tools/destroy-order-probe t destroy-present`, measured on Xephyr: each +/// window's `PresentConfigureNotify(PresentWindowDestroyed)` comes from the +/// screen `DestroyWindow` hook at the end of its `FreeWindowResources` +/// (`dix/window.c:1018`, `present/present_screen.c:96-103`), so after its +/// DestroyNotify and SelectionWindowDestroy. x/y are `drawable.x/y`, the +/// absolute origin inside the border (C: 100 + 50 + 3); w/h and the pixmap +/// size are the inside size; flags `PresentWindowDestroyed` +/// (`present/present_event.c:105-130`). The two backend crossings are left +/// out as in [`destroy_window_event_order_matches_xorg`]. +#[test] +fn destroy_window_sends_present_window_destroyed_in_xorg_order() { + let (mut state, mut grb, mut obs) = present_order_fixture((110, 110), ORDER_GRB); + assert_eq!( + destroy_t_and_read_order_stream(&mut state, &mut obs), + [ + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "LeaveNotify(event=C child=None detail=Ancestor mode=Ungrab root=110,110 event=-43,-43 sf=0x3)", + "EnterNotify(event=T child=None detail=Inferior mode=Ungrab root=110,110 event=10,10 sf=0x2)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "XFixesSelectionNotify(subtype=1 window=root owner=None)", + "PresentConfigureNotify(eid=eC window=C x=153 y=153 w=100 h=100 off=0,0 pixmap=100x100 flags=0x1)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + "PresentConfigureNotify(eid=eT window=T x=100 y=100 w=200 h=200 off=0,0 pixmap=200x200 flags=0x1)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.present_event_selections.is_empty()); +} + +/// `tools/destroy-order-probe t disconnect-present-appsel`, measured on +/// Xephyr: the same per-window notifies when the owner's disconnect destroys +/// T, to a surviving selector. +#[test] +fn disconnect_sends_present_window_destroyed_in_xorg_order() { + let (mut state, mut grb, mut obs) = present_order_fixture((110, 110), ORDER_APP); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "XFixesSelectionNotify(subtype=2 window=root owner=None)", + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "LeaveNotify(event=C child=None detail=Ancestor mode=Ungrab root=110,110 event=-43,-43 sf=0x3)", + "EnterNotify(event=T child=None detail=Inferior mode=Ungrab root=110,110 event=10,10 sf=0x2)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "PresentConfigureNotify(eid=eC window=C x=153 y=153 w=100 h=100 off=0,0 pixmap=100x100 flags=0x1)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + "PresentConfigureNotify(eid=eT window=T x=100 y=100 w=200 h=200 off=0,0 pixmap=200x200 flags=0x1)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.present_event_selections.is_empty()); +} + +/// The probe's `kbd` modifier: the departing `app` also holds a keyboard grab +/// on T, the focus still on C. +fn grab_keyboard_on_t_for_app(state: &mut ServerState) { + state.active_keyboard_grab = Some(crate::server::ActiveKeyboardGrab { + owner: ClientId(1), + grab_window: ResourceId(ORDER_T), + source: crate::server::ActiveKeyboardGrabSource::Explicit, + owner_events: false, + via_xi2: false, + xi2_mask: 0, + }); +} + +/// `tools/destroy-order-probe c disconnect-kbd-appsel`, measured on Xephyr. +/// The three backend crossings between the Expose and DestroyNotify(C) are +/// left out (see [`destroy_window_event_order_matches_xorg`]). +#[test] +fn disconnect_releasing_a_keyboard_grab_with_the_pointer_in_c_sends_ungrab_focus_events() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((200, 200), ORDER_APP); + grab_keyboard_on_t_for_app(&mut state); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "XFixesSelectionNotify(subtype=2 window=root owner=None)", + "FocusOut(event=C detail=Pointer mode=Ungrab)", + "FocusOut(event=T detail=Inferior mode=Ungrab)", + "FocusIn(event=C detail=Ancestor mode=Ungrab)", + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.active_keyboard_grab.is_none()); +} + +/// `tools/destroy-order-probe c disconnect-ptr-appsel`, measured on Xephyr: +/// the departing client's own pointer grab on T, the pointer in C. +/// `ReleaseActiveGrabs` → `DeactivatePointerGrab` (`dix/events.c:1659-1714`) +/// sends `DoEnterLeaveEvents(grab T → sprite C, NotifyUngrab)` to the +/// survivors before any window goes. The three backend crossings are left +/// out as above. +#[test] +fn disconnect_releasing_a_pointer_grab_sends_ungrab_crossings() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((200, 200), ORDER_APP); + set_test_pointer_grab(&mut state, 1, ORDER_T, false, false); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "XFixesSelectionNotify(subtype=2 window=root owner=None)", + "LeaveNotify(event=T child=None detail=Inferior mode=Ungrab root=200,200 event=100,100 sf=0x2)", + "EnterNotify(event=C child=None detail=Ancestor mode=Ungrab root=200,200 event=50,50 sf=0x3)", + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.active_pointer_grab.is_none()); +} + +/// `tools/destroy-order-probe t disconnect-ptr-appsel`, measured on Xephyr: +/// the pointer already in the grab window T, so the deactivation's +/// `DoEnterLeaveEvents(T, T)` sends nothing (`dix/enterleave.c:602-603`). +#[test] +fn disconnect_releasing_a_pointer_grab_with_the_pointer_in_the_grab_window_sends_no_crossings() { + let (mut state, mut grb, mut obs) = destroy_order_fixture_set_by((110, 110), ORDER_APP); + set_test_pointer_grab(&mut state, 1, ORDER_T, false, false); + assert_eq!( + disconnect_app_and_read_order_stream(&mut state, &mut obs), + [ + "XFixesSelectionNotify(subtype=2 window=root owner=None)", + "UnmapNotify(event=T window=T fromConfigure=0)", + "UnmapNotify(event=root window=T fromConfigure=0)", + "FocusOut(event=C detail=Ancestor mode=Normal)", + "FocusOut(event=T detail=Virtual mode=Normal)", + "FocusIn(event=root detail=Inferior mode=Normal)", + "Expose(root 100,100 200x200 count=0)", + "DestroyNotify(event=C window=C)", + "DestroyNotify(event=T window=T)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!(read_all_or_buffered(&mut state, 2, &mut grb).is_empty()); + assert!(state.active_pointer_grab.is_none()); +} + +/// X owns mapped T; survivor Y owns its mapped child C and an unrelated +/// top-level. X's disconnect destroys C with T (`DeleteWindow` crushes the +/// whole subtree, `dix/window.c:1023-1050`); Y gets T's UnmapNotify through +/// root (`:2855`), C's DestroyNotify and T's; X gets nothing (`clientGone`, +/// `dix/dispatch.c:3518`). Y's state on C goes, on its other window stays. +#[test] +fn disconnect_destroys_a_survivors_child_and_sends_the_departing_client_nothing() { + const X: u32 = 1; + const Y: u32 = 2; + const OTHER: u32 = 0x0020_0003; + let mut state = ServerState::new(); + let mut x_peer = install_capture_client(&mut state, X); + let mut y_peer = install_client(&mut state, Y); + for (owner, window, parent) in [ + (X, ORDER_T, ROOT_WINDOW.0), + (Y, ORDER_C, ORDER_T), + (Y, OTHER, ROOT_WINDOW.0), + ] { + state.resources.create_window( + ClientId(owner), + CreateWindowRequest { + depth: 24, + window: ResourceId(window), + parent: ResourceId(parent), + width: 50, + height: 50, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(window)); + } + // X: SubstructureNotify on T. Y: StructureNotify on C and OTHER, + // SubstructureNotify on root. + state + .clients + .get_mut(&X) + .unwrap() + .event_masks + .insert(ResourceId(ORDER_T), 0x0008_0000); + let y_masks = &mut state.clients.get_mut(&Y).unwrap().event_masks; + y_masks.insert(ResourceId(ORDER_C), 0x0002_0000); + y_masks.insert(ResourceId(OTHER), 0x0002_0000); + y_masks.insert(ROOT_WINDOW, 0x0008_0000); + for (damage, window) in [(0x0020_0010, ORDER_C), (0x0020_0011, OTHER)] { + state.damage_objects.insert( + damage, + crate::server::DamageObject { + owner: ClientId(Y), + drawable: ResourceId(window), + level: 3, + rects: Vec::new(), + pending_notify_fired: false, + last_reported_geometry: None, + list_pos: 0, + created: 0, + }, + ); + state + .shape_select_masks + .insert((Y, ResourceId(window)), true); + state.present_event_selections.insert( + damage + 0x10, + crate::server::PresentEventSelection { + owner: ClientId(Y), + window: ResourceId(window), + event_mask: 1, + }, + ); + } + + let mut backend = RecordingBackend::new(); + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(X)); + + // Y's PresentConfigureNotify selection on C (mask 1) gets C's + // PresentWindowDestroyed after C's DestroyNotify (`dix/window.c:1018`, + // `present/present_screen.c:96-103`). + assert_eq!( + describe_order_events(&read_all_or_buffered(&mut state, Y, &mut y_peer)), + [ + "UnmapNotify(event=root window=T fromConfigure=0)", + "DestroyNotify(event=C window=C)", + "PresentConfigureNotify(eid=0x200020 window=C x=0 y=0 w=50 h=50 off=0,0 pixmap=50x50 flags=0x1)", + "DestroyNotify(event=root window=T)", + ] + ); + assert!( + read_all_available(&mut x_peer).is_empty(), + "the departing client gets nothing" + ); + assert!(!state.clients.contains_key(&X)); + let y = &state.clients[&Y]; + assert!(!y.write_failed); + assert!(!y.event_masks.contains_key(&ResourceId(ORDER_C))); + assert!(y.event_masks.contains_key(&ResourceId(OTHER))); + assert!(state.resources.window(ResourceId(ORDER_C)).is_none()); + assert!(state.resources.window(ResourceId(OTHER)).is_some()); + let damaged: Vec = state.damage_objects.values().map(|d| d.drawable).collect(); + assert_eq!(damaged, [ResourceId(OTHER)]); + assert_eq!( + state.shape_select_masks.keys().copied().collect::>(), + [(Y, ResourceId(OTHER))] + ); + let present: Vec = state + .present_event_selections + .values() + .map(|s| s.window) + .collect(); + assert_eq!(present, [ResourceId(OTHER)]); +} + +// ── At-most-one-client event-mask bits ───────────────────────────── +// +// Xorg `dix/events.c:4624-4636` (`EventSelectForWindow`): a client may not +// select SubstructureRedirect, ResizeRedirect or ButtonPress on a window +// where ANOTHER client already has that bit; the error value is the window +// (set by the lookup, `dix/resource.c:1217`). Expected values below are +// `tools/redirect-exclusive-probe.c` against Xephyr; case numbers quote it. + +const SUBSTRUCTURE_REDIRECT: u32 = 0x0010_0000; +const SUBSTRUCTURE_NOTIFY: u32 = 0x0008_0000; +const RESIZE_REDIRECT: u32 = 0x0004_0000; +const BUTTON_PRESS: u32 = 0x0004; +const BUTTON_RELEASE: u32 = 0x0008; +const CW_EVENT_MASK: u32 = 0x0800; + +/// Sends a ChangeWindowAttributes and returns the error it produced as +/// (code, bad value, major), or `None` on success. +fn cwa( + state: &mut ServerState, + peer: &mut UnixStream, + client: u32, + window: u32, + value_mask: u32, + values: &[u32], +) -> Option<(u8, u32, u8)> { + let body = border_cwa_body(window, value_mask, values); + let mut backend = RecordingBackend::new(); + process_request( + state, + &mut backend, + ClientId(client), + SequenceNumber(1), + RequestHeader { + opcode: 2, + data: 0, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + &body, + None, + ) + .expect("process_request"); + wire_packets(peer).iter().find(|p| p[0] == 0).map(|p| { + let (code, value, _, major) = error_fields(p); + (code, value, major) + }) +} + +fn mask_of(state: &ServerState, client: u32, window: u32) -> u32 { + state.clients[&client] + .event_masks + .get(&ResourceId(window)) + .copied() + .unwrap_or(0) +} + +#[test] +fn second_client_substructure_redirect_on_root_is_bad_access() { + const A: u32 = 1; + const B: u32 = 2; + const ROOT: u32 = ROOT_WINDOW.0; + let mut state = ServerState::new(); + let mut a = install_client(&mut state, A); + let mut b = install_client(&mut state, B); + let denied = Some((x11::error::BAD_ACCESS, ROOT, 2)); + + // 1, 2: a takes SubstructureRedirect; b is refused. + assert_eq!( + cwa( + &mut state, + &mut a, + A, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + None + ); + assert_eq!( + cwa( + &mut state, + &mut b, + B, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + denied + ); + // 3: the holder may re-select it. + let both = SUBSTRUCTURE_REDIRECT | SUBSTRUCTURE_NOTIFY; + assert_eq!( + cwa(&mut state, &mut a, A, ROOT, CW_EVENT_MASK, &[both]), + None + ); + // 4, 5: b may select other bits, but not alongside the held one; its + // mask is left as it was. + assert_eq!( + cwa( + &mut state, + &mut b, + B, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_NOTIFY] + ), + None + ); + assert_eq!( + cwa(&mut state, &mut b, B, ROOT, CW_EVENT_MASK, &[both]), + denied + ); + assert_eq!(mask_of(&state, B, ROOT), SUBSTRUCTURE_NOTIFY); + // 6, 7, 8: once a drops it b gets it, and then a is refused. + assert_eq!( + cwa( + &mut state, + &mut a, + A, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_NOTIFY] + ), + None + ); + assert_eq!( + cwa( + &mut state, + &mut b, + B, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + None + ); + assert_eq!( + cwa( + &mut state, + &mut a, + A, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + denied + ); + assert_eq!(mask_of(&state, A, ROOT), SUBSTRUCTURE_NOTIFY); +} + +#[test] +fn disconnected_redirect_holder_releases_the_bit() { + const B: u32 = 2; + const C: u32 = 3; + const ROOT: u32 = ROOT_WINDOW.0; + let mut state = ServerState::new(); + let mut b = install_client(&mut state, B); + let mut c = install_client(&mut state, C); + // 10, 11, 12. + assert_eq!( + cwa( + &mut state, + &mut c, + C, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + None + ); + assert_eq!( + cwa( + &mut state, + &mut b, + B, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + Some((x11::error::BAD_ACCESS, ROOT, 2)) + ); + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut RecordingBackend::new(), + ClientId(C), + ); + assert_eq!( + cwa( + &mut state, + &mut b, + B, + ROOT, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + None + ); +} + +#[test] +fn button_press_and_resize_redirect_are_exclusive_per_window() { + const A: u32 = 1; + const B: u32 = 2; + const W: u32 = 0x0020_0000; + let mut state = ServerState::new(); + let mut a = install_client(&mut state, A); + let mut b = install_client(&mut state, B); + seed_window(&mut state, ResourceId(W), ROOT_WINDOW, 50, 50); + // 14: a selected ButtonPress on W (as CreateWindow's CWEventMask does). + state + .clients + .get_mut(&A) + .unwrap() + .event_masks + .insert(ResourceId(W), BUTTON_PRESS); + let denied = Some((x11::error::BAD_ACCESS, W, 2)); + + // 15-18. + assert_eq!( + cwa(&mut state, &mut b, B, W, CW_EVENT_MASK, &[BUTTON_PRESS]), + denied + ); + assert_eq!( + cwa(&mut state, &mut b, B, W, CW_EVENT_MASK, &[BUTTON_RELEASE]), + None + ); + assert_eq!( + cwa( + &mut state, + &mut b, + B, + W, + CW_EVENT_MASK, + &[SUBSTRUCTURE_REDIRECT] + ), + None + ); + let press_release = BUTTON_PRESS | BUTTON_RELEASE; + assert_eq!( + cwa(&mut state, &mut a, A, W, CW_EVENT_MASK, &[press_release]), + None + ); + // 19-21: b's ResizeRedirect bars a from it, alone or combined. + assert_eq!( + cwa(&mut state, &mut b, B, W, CW_EVENT_MASK, &[RESIZE_REDIRECT]), + None + ); + assert_eq!( + cwa(&mut state, &mut a, A, W, CW_EVENT_MASK, &[RESIZE_REDIRECT]), + denied + ); + let resize_press = RESIZE_REDIRECT | BUTTON_PRESS; + assert_eq!( + cwa(&mut state, &mut a, A, W, CW_EVENT_MASK, &[resize_press]), + denied + ); + // 21': a's mask is untouched. + assert_eq!(mask_of(&state, A, W), press_release); +} + +#[test] +fn refused_event_mask_applies_only_the_attributes_before_it() { + const A: u32 = 1; + const B: u32 = 2; + const W: u32 = 0x0020_0000; + const CW_BIT_GRAVITY: u32 = 0x0010; + const CW_WIN_GRAVITY: u32 = 0x0020; + const CW_OVERRIDE_REDIRECT: u32 = 0x0200; + const CW_DONT_PROPAGATE: u32 = 0x1000; + const KEY_PRESS: u32 = 0x0001; + let mut state = ServerState::new(); + let _a = install_client(&mut state, A); + let mut b = install_client(&mut state, B); + seed_window(&mut state, ResourceId(W), ROOT_WINDOW, 50, 50); + state + .clients + .get_mut(&A) + .unwrap() + .event_masks + .insert(ResourceId(W), BUTTON_PRESS); + state + .clients + .get_mut(&B) + .unwrap() + .event_masks + .insert(ResourceId(W), RESIZE_REDIRECT); + + // 22: bit gravity Static, win gravity SouthEast, override-redirect, + // conflicting ButtonPress, then dont-propagate KeyPress. + let mask = + CW_BIT_GRAVITY | CW_WIN_GRAVITY | CW_OVERRIDE_REDIRECT | CW_EVENT_MASK | CW_DONT_PROPAGATE; + assert_eq!( + cwa( + &mut state, + &mut b, + B, + W, + mask, + &[10, 9, 1, BUTTON_PRESS, KEY_PRESS] + ), + Some((x11::error::BAD_ACCESS, W, 2)) + ); + // 22': bit_gravity=10 win_gravity=9 override_redirect=1 your_mask=0x40000 + // do_not_propagate=0x0. + let w = state.resources.window(ResourceId(W)).unwrap(); + assert_eq!( + ( + w.bit_gravity, + w.win_gravity, + w.override_redirect, + w.do_not_propagate_mask + ), + (10, 9, true, 0) + ); + assert_eq!(mask_of(&state, B, W), RESIZE_REDIRECT); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xfixes_shape.rs b/crates/yserver-core/src/core_loop/process_request/tests/xfixes_shape.rs new file mode 100644 index 000000000..63a7f8643 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xfixes_shape.rs @@ -0,0 +1,2473 @@ +use super::*; + +/// XFixes `SetCursorName(cursor, "name")` interns the name as an +/// atom and stores it on the cursor; the subsequent +/// `GetCursorName(cursor)` returns the same atom + name bytes. +/// A cursor that was never named reports atom=0 (None) + empty +/// name, matching Xorg `xfixes/cursor.c:ProcXFixesGetCursorName`'s +/// `pCursor->name == 0` branch. +#[test] +fn xfixes_cursor_name_round_trip() { + use std::io::Read; + + const CLIENT_ID: u32 = 1; + const CURSOR_XID: u32 = 0x0090_0042; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + state + .resources + .create_cursor(ClientId(CLIENT_ID), ResourceId(CURSOR_XID)); + + let name = b"xterm"; + // SetCursorName body: cursor(4) + nbytes(2) + pad(2) + name + pad. + let mut set_body = Vec::with_capacity(16); + set_body.extend_from_slice(&CURSOR_XID.to_le_bytes()); + #[allow(clippy::cast_possible_truncation)] + set_body.extend_from_slice(&(name.len() as u16).to_le_bytes()); + set_body.extend_from_slice(&[0u8; 2]); + set_body.extend_from_slice(name); + while !set_body.len().is_multiple_of(4) { + set_body.push(0); + } + + let header = yserver_protocol::x11::RequestHeader { + opcode: 140, // XFIXES major (dispatcher reads minor from header.data) + data: 23, // SET_CURSOR_NAME + length_units: 3, + }; + handle_xfixes_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &set_body, + ) + .expect("SetCursorName"); + + // The atom must be stored on the cursor and resolve back to + // the original name. + let stored = state + .resources + .cursor_name_atom(ResourceId(CURSOR_XID)) + .expect("name atom present after SetCursorName"); + assert!(stored.0 != 0, "non-None atom expected for non-empty name"); + assert_eq!( + state.atoms.name(stored).map(str::as_bytes), + Some(name.as_ref()), + "interned atom must reverse-resolve to the original name", + ); + + // GetCursorName body: cursor(4). + let get_body = CURSOR_XID.to_le_bytes().to_vec(); + let get_header = yserver_protocol::x11::RequestHeader { + opcode: 140, + data: 24, // GET_CURSOR_NAME + length_units: 2, + }; + handle_xfixes_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(2), + get_header, + &get_body, + ) + .expect("GetCursorName"); + + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 1024]; + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + // Reply layout: type(1) + pad(1) + sequence(2) + length(4) + + // atom(4) + nbytes(2) + pad(18) + name(n) + pad-to-4. + assert_eq!(wire[0], 1, "X_Reply type byte"); + let reply_atom = u32::from_le_bytes(wire[8..12].try_into().unwrap()); + let reply_nbytes = u16::from_le_bytes(wire[12..14].try_into().unwrap()) as usize; + assert_eq!(reply_atom, stored.0, "reply atom matches stored atom"); + assert_eq!(reply_nbytes, name.len()); + assert_eq!( + &wire[32..32 + name.len()], + name, + "reply name bytes match the original", + ); + + // GetCursorName on an unnamed cursor → atom=0, nbytes=0. + const UNNAMED_XID: u32 = 0x0090_0099; + state + .resources + .create_cursor(ClientId(CLIENT_ID), ResourceId(UNNAMED_XID)); + let get_body = UNNAMED_XID.to_le_bytes().to_vec(); + handle_xfixes_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(3), + get_header, + &get_body, + ) + .expect("GetCursorName unnamed"); + let mut wire2 = Vec::new(); + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire2.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + let reply_atom = u32::from_le_bytes(wire2[8..12].try_into().unwrap()); + let reply_nbytes = u16::from_le_bytes(wire2[12..14].try_into().unwrap()) as usize; + assert_eq!(reply_atom, 0, "unnamed cursor reports atom=0 (None)"); + assert_eq!(reply_nbytes, 0, "unnamed cursor reports empty name"); +} + +/// One XFIXES request through the real dispatcher (version gate +/// included), little-endian body. +fn xfixes_req( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + minor: u8, + body: &[u8], +) { + process_request( + state, + backend, + ClientId(client), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + None, + ) + .expect("xfixes request"); +} + +fn xfixes_u32s(values: &[u32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +const XFIXES_OWNER: u32 = 1; +const XFIXES_WRITER: u32 = 2; +const XFIXES_REGION: u32 = 0x0100_0001; +const XFIXES_SOURCE: u32 = 0x0100_0002; +const XFIXES_SOURCE2: u32 = 0x0100_0003; + +fn xfixes_rect_body(id: u32, rect: yserver_protocol::x11::xfixes::RegionRect) -> Vec { + let mut body = id.to_le_bytes().to_vec(); + body.extend_from_slice(&rect.x.to_le_bytes()); + body.extend_from_slice(&rect.y.to_le_bytes()); + body.extend_from_slice(&rect.width.to_le_bytes()); + body.extend_from_slice(&rect.height.to_le_bytes()); + body +} + +fn assert_xfixes_single_write_preserves_owner( + minor: u8, + body: &[u8], + expected: &[(i16, i16, u16, u16)], +) { + use yserver_protocol::x11::xfixes as x11xfixes; + + let mut state = ServerState::new(); + let mut owner_peer = install_client(&mut state, XFIXES_OWNER); + let mut writer_peer = install_client(&mut state, XFIXES_WRITER); + state.xfixes_client_major.insert(XFIXES_OWNER, 5); + state.xfixes_client_major.insert(XFIXES_WRITER, 5); + let mut backend = RecordingBackend::new(); + + let rect = |x, y, width, height| yserver_protocol::x11::xfixes::RegionRect { + x, + y, + width, + height, + }; + for (id, initial) in [ + (XFIXES_REGION, rect(1, 2, 3, 4)), + (XFIXES_SOURCE, rect(10, 20, 30, 40)), + (XFIXES_SOURCE2, rect(12, 22, 6, 8)), + ] { + xfixes_req( + &mut state, + &mut backend, + XFIXES_OWNER, + x11xfixes::CREATE_REGION, + &xfixes_rect_body(id, initial), + ); + } + + // Each invocation starts from fresh owner-created regions and sends one + // destination-writing request from the other client. + xfixes_req(&mut state, &mut backend, XFIXES_WRITER, minor, body); + assert!( + wire_packets(&mut writer_peer).is_empty(), + "writer request succeeds" + ); + + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(XFIXES_WRITER), + ); + + xfixes_req( + &mut state, + &mut backend, + XFIXES_OWNER, + x11xfixes::FETCH_REGION, + &XFIXES_REGION.to_le_bytes(), + ); + let reply = read_all_available(&mut owner_peer); + let expected_wire: Vec = expected + .iter() + .flat_map(|(x, y, width, height)| { + x.to_le_bytes() + .into_iter() + .chain(y.to_le_bytes()) + .chain(width.to_le_bytes()) + .chain(height.to_le_bytes()) + }) + .collect(); + assert_eq!( + reply.len(), + 32 + expected_wire.len(), + "FetchRegion returns every expected rectangle after writer disconnect", + ); + assert_eq!(reply.first(), Some(&1), "FetchRegion returns a reply"); + assert_eq!( + &reply[32..], + expected_wire, + "FetchRegion returns the written region contents", + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; CopyRegion's rectangle must still be fetchable after disconnect. +#[test] +fn xfixes_write_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + assert_xfixes_single_write_preserves_owner( + x11xfixes::COPY_REGION, + &xfixes_u32s(&[XFIXES_SOURCE, XFIXES_REGION]), + &[(10, 20, 30, 40)], + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; SetRegion's replacement must survive that writer's disconnect. +#[test] +fn xfixes_set_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + assert_xfixes_single_write_preserves_owner( + x11xfixes::SET_REGION, + &xfixes_rect_body( + XFIXES_REGION, + yserver_protocol::x11::xfixes::RegionRect { + x: 2, + y: 3, + width: 4, + height: 5, + }, + ), + &[(2, 3, 4, 5)], + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; UnionRegion's result must survive that writer's disconnect. +#[test] +fn xfixes_union_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + assert_xfixes_single_write_preserves_owner( + x11xfixes::UNION_REGION, + &xfixes_u32s(&[XFIXES_SOURCE, XFIXES_SOURCE2, XFIXES_REGION]), + &[(10, 20, 30, 40)], + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; IntersectRegion's result must survive that writer's disconnect. +#[test] +fn xfixes_intersect_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + assert_xfixes_single_write_preserves_owner( + x11xfixes::INTERSECT_REGION, + &xfixes_u32s(&[XFIXES_SOURCE, XFIXES_SOURCE2, XFIXES_REGION]), + &[(12, 22, 6, 8)], + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; SubtractRegion's result must survive that writer's disconnect. +#[test] +fn xfixes_subtract_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + assert_xfixes_single_write_preserves_owner( + x11xfixes::SUBTRACT_REGION, + &xfixes_u32s(&[XFIXES_SOURCE, XFIXES_SOURCE2, XFIXES_REGION]), + &[ + (10, 20, 30, 2), + (10, 22, 2, 8), + (18, 22, 22, 8), + (10, 30, 30, 30), + ], + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; InvertRegion's four output rectangles must survive disconnect. +#[test] +fn xfixes_invert_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + let mut body = XFIXES_SOURCE.to_le_bytes().to_vec(); + body.extend_from_slice(&0_i16.to_le_bytes()); + body.extend_from_slice(&0_i16.to_le_bytes()); + body.extend_from_slice(&100_u16.to_le_bytes()); + body.extend_from_slice(&100_u16.to_le_bytes()); + body.extend_from_slice(&XFIXES_REGION.to_le_bytes()); + assert_xfixes_single_write_preserves_owner( + x11xfixes::INVERT_REGION, + &body, + &[ + (0, 0, 100, 20), + (0, 20, 10, 40), + (40, 20, 60, 40), + (0, 60, 100, 40), + ], + ); +} + +/// Mutation: make `store_xfixes_region` assign an existing destination to the +/// writer; RegionExtents' rectangle must survive that writer's disconnect. +#[test] +fn xfixes_region_extents_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + assert_xfixes_single_write_preserves_owner( + x11xfixes::REGION_EXTENTS, + &xfixes_u32s(&[XFIXES_SOURCE, XFIXES_REGION]), + &[(10, 20, 30, 40)], + ); +} + +/// Mutation: assign the destination's owner to the writer in TranslateRegion; +/// the translated rectangle must remain fetchable after disconnect. +#[test] +fn xfixes_translate_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + let mut body = XFIXES_REGION.to_le_bytes().to_vec(); + body.extend_from_slice(&1_i16.to_le_bytes()); + body.extend_from_slice(&2_i16.to_le_bytes()); + assert_xfixes_single_write_preserves_owner(x11xfixes::TRANSLATE_REGION, &body, &[(2, 4, 3, 4)]); +} + +/// Mutation: assign the destination's owner to the writer in ExpandRegion; +/// the expanded rectangle must remain fetchable after disconnect. +#[test] +fn xfixes_expand_region_into_other_clients_region_keeps_owner() { + use yserver_protocol::x11::xfixes as x11xfixes; + + let mut body = xfixes_u32s(&[XFIXES_SOURCE, XFIXES_REGION]); + for margin in [1_u16, 2, 3, 4] { + body.extend_from_slice(&margin.to_le_bytes()); + } + assert_xfixes_single_write_preserves_owner(x11xfixes::EXPAND_REGION, &body, &[(9, 17, 33, 47)]); +} + +/// QueryVersion follows Xorg's rule and gates requests on the +/// negotiated major. Ground truth: Xorg 21.1.24 Xvfb, raw xcb probe — +/// HideCursor before QueryVersion is BadRequest (major 138 there, +/// minor 29, value 0); 4.0 → 4.0; then 2.0 → 2.0 while HideCursor +/// still succeeds and DeletePointerBarrier (a 5.0 request) is +/// BadRequest; 7.0 is capped at the server version. +#[test] +fn xfixes_query_version_negotiates_and_gates_requests() { + use yserver_protocol::x11::xfixes as x11xfixes; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let root = ROOT_WINDOW.0; + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::HIDE_CURSOR, + &xfixes_u32s(&[root]), + ); + let packets = wire_packets(&mut peer); + assert_eq!(packets.len(), 1); + assert_eq!( + error_fields(&packets[0]), + (x11::error::BAD_REQUEST, 0, 29, XFIXES_MAJOR_OPCODE) + ); + assert!(state.xfixes_cursor_hide_counts.is_empty()); + + let query = |state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + major: u32, + minor: u32| { + xfixes_req( + state, + backend, + 1, + x11xfixes::QUERY_VERSION, + &xfixes_u32s(&[major, minor]), + ); + let packets = wire_packets(peer); + assert_eq!(packets.len(), 1); + assert_eq!(packets[0][0], 1, "reply"); + (le_u32(&packets[0], 8), le_u32(&packets[0], 12)) + }; + assert_eq!(query(&mut state, &mut backend, &mut peer, 4, 0), (4, 0)); + assert_eq!(query(&mut state, &mut backend, &mut peer, 2, 0), (2, 0)); + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::HIDE_CURSOR, + &xfixes_u32s(&[root]), + ); + assert!(wire_packets(&mut peer).is_empty(), "4.0 request set kept"); + assert_eq!(state.xfixes_cursor_hide_counts.get(&1), Some(&1)); + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::DELETE_POINTER_BARRIER, + &xfixes_u32s(&[0x1234]), + ); + let packets = wire_packets(&mut peer); + assert_eq!( + error_fields(&packets[0]), + (x11::error::BAD_REQUEST, 0, 32, XFIXES_MAJOR_OPCODE) + ); + + assert_eq!(query(&mut state, &mut backend, &mut peer, 7, 0), (5, 0)); + assert_eq!(query(&mut state, &mut backend, &mut peer, 3, 7), (3, 7)); +} + +/// Hide/Show counting, captured on Xvfb: bad window → BadWindow (value +/// = window) for both; ShowCursor without a hide → BadMatch (value = +/// window); two hides need two shows and a third show is BadMatch. +/// Across clients the sprite hides on the first hide anywhere and +/// comes back when the last hider shows or disconnects. +#[test] +fn xfixes_hide_show_cursor_counts_per_client() { + use yserver_protocol::x11::xfixes as x11xfixes; + let mut state = ServerState::new(); + let mut peer1 = install_client(&mut state, 1); + let _peer2 = install_client(&mut state, 2); + state.xfixes_client_major.insert(1, 5); + state.xfixes_client_major.insert(2, 5); + let mut backend = RecordingBackend::new(); + let root = ROOT_WINDOW.0; + let hidden_calls = |backend: &RecordingBackend| -> Vec { + backend + .calls + .lock() + .unwrap() + .iter() + .filter_map(|c| match c { + RecordedCall::SetCursorHidden(h) => Some(*h), + _ => None, + }) + .collect() + }; + + for minor in [x11xfixes::HIDE_CURSOR, x11xfixes::SHOW_CURSOR] { + xfixes_req( + &mut state, + &mut backend, + 1, + minor, + &xfixes_u32s(&[0x0bad_bad0]), + ); + let packets = wire_packets(&mut peer1); + assert_eq!( + error_fields(&packets[0]), + ( + x11::error::BAD_WINDOW, + 0x0bad_bad0, + u16::from(minor), + XFIXES_MAJOR_OPCODE + ) + ); + } + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SHOW_CURSOR, + &xfixes_u32s(&[root]), + ); + let packets = wire_packets(&mut peer1); + assert_eq!( + error_fields(&packets[0]), + (x11::error::BAD_MATCH, root, 30, XFIXES_MAJOR_OPCODE) + ); + assert!(hidden_calls(&backend).is_empty()); + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::HIDE_CURSOR, + &xfixes_u32s(&[root]), + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::HIDE_CURSOR, + &xfixes_u32s(&[root]), + ); + xfixes_req( + &mut state, + &mut backend, + 2, + x11xfixes::HIDE_CURSOR, + &xfixes_u32s(&[root]), + ); + assert_eq!( + hidden_calls(&backend), + vec![true], + "one edge for three hides" + ); + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SHOW_CURSOR, + &xfixes_u32s(&[root]), + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SHOW_CURSOR, + &xfixes_u32s(&[root]), + ); + assert!(wire_packets(&mut peer1).is_empty()); + assert_eq!(hidden_calls(&backend), vec![true], "client 2 still hides"); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SHOW_CURSOR, + &xfixes_u32s(&[root]), + ); + let packets = wire_packets(&mut peer1); + assert_eq!( + error_fields(&packets[0]), + (x11::error::BAD_MATCH, root, 30, XFIXES_MAJOR_OPCODE) + ); + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(2)); + assert_eq!( + hidden_calls(&backend), + vec![true, false], + "disconnect shows" + ); + assert!(state.xfixes_cursor_hide_counts.is_empty()); + assert!(!state.xfixes_client_major.contains_key(&2)); +} + +/// CursorNotify fan-out, per the Xvfb capture: one event per +/// (client, window) selection carrying that window, the cursor serial +/// and its name atom; a destroyed window's selection is gone; bad mask +/// → BadValue, bad window → BadWindow. +#[test] +fn xfixes_cursor_notify_goes_to_each_selection() { + use yserver_protocol::x11::xfixes as x11xfixes; + const CHILD: u32 = 0x0040_0001; + const CURSOR: u32 = 0x0040_0010; + const HOST: u32 = 0x0001_0077; + let mut state = ServerState::new(); + let mut peer1 = install_client(&mut state, 1); + let mut peer2 = install_client(&mut state, 2); + state.xfixes_client_major.insert(1, 5); + state.xfixes_client_major.insert(2, 5); + let mut backend = RecordingBackend::new(); + let root = ROOT_WINDOW.0; + create_present_test_window(&mut state, CHILD, 0, 0, 10, 10); + state + .resources + .create_cursor(ClientId(1), ResourceId(CURSOR)); + state.resources.set_cursor_host_xid( + ResourceId(CURSOR), + crate::backend::CursorHandle::from_raw(HOST).unwrap(), + ); + let name = state.atoms.intern("bname", false); + state + .resources + .set_cursor_name_atom(ResourceId(CURSOR), name); + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SELECT_CURSOR_INPUT, + &xfixes_u32s(&[root, 2]), + ); + assert_eq!( + error_fields(&wire_packets(&mut peer1)[0]), + (x11::error::BAD_VALUE, 2, 3, XFIXES_MAJOR_OPCODE) + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SELECT_CURSOR_INPUT, + &xfixes_u32s(&[0x0bad_bad0, 1]), + ); + assert_eq!( + error_fields(&wire_packets(&mut peer1)[0]), + (x11::error::BAD_WINDOW, 0x0bad_bad0, 3, XFIXES_MAJOR_OPCODE) + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SELECT_CURSOR_INPUT, + &xfixes_u32s(&[root, 1]), + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::SELECT_CURSOR_INPUT, + &xfixes_u32s(&[CHILD, 1]), + ); + assert!(wire_packets(&mut peer1).is_empty()); + + backend.displayed_cursor_change = Some(crate::backend::DisplayedCursor { + host_xid: HOST, + serial: 3, + }); + emit_xfixes_cursor_notify(&mut state, &mut backend); + let events = wire_packets(&mut peer1); + assert_eq!(events.len(), 2, "one per selection"); + let mut windows = Vec::new(); + for e in &events { + assert_eq!(e[0], crate::nested::XFIXES_FIRST_EVENT + 1); + assert_eq!(e[1], x11xfixes::DISPLAY_CURSOR_NOTIFY); + windows.push(le_u32(e, 4)); + assert_eq!(le_u32(e, 8), 3, "serial"); + assert_eq!(le_u32(e, 16), name.0, "name atom"); + } + windows.sort_unstable(); + assert_eq!(windows, vec![root, CHILD]); + assert!( + wire_packets(&mut peer2).is_empty(), + "client 2 never selected" + ); + emit_xfixes_cursor_notify(&mut state, &mut backend); + assert!( + wire_packets(&mut peer1).is_empty(), + "the report is consumed" + ); + + // Destroying the child drops its selection (Xorg CursorFreeWindow). + destroy_window_subtree(&mut state, &mut backend, None, ResourceId(CHILD)).expect("destroy"); + backend.displayed_cursor_change = Some(crate::backend::DisplayedCursor { + host_xid: 0x0001_0099, + serial: 1, + }); + emit_xfixes_cursor_notify(&mut state, &mut backend); + let events = wire_packets(&mut peer1); + assert_eq!(events.len(), 1); + assert_eq!(le_u32(&events[0], 4), root); + assert_eq!(le_u32(&events[0], 16), 0, "unnamed cursor"); +} + +/// ChangeCursor: every XID of the destination cursor now names the +/// source cursor, and the backend replaces its displayed uses. Xvfb: +/// bad source / bad destination → BadCursor naming it. +#[test] +fn xfixes_change_cursor_retargets_cursor_and_backend() { + use yserver_protocol::x11::xfixes as x11xfixes; + const A: u32 = 0x0040_0020; + const D: u32 = 0x0040_0021; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.xfixes_client_major.insert(1, 5); + let mut backend = RecordingBackend::new(); + for (xid, host) in [(A, 0x0001_0010), (D, 0x0001_0020)] { + state.resources.create_cursor(ClientId(1), ResourceId(xid)); + state.resources.set_cursor_host_xid( + ResourceId(xid), + crate::backend::CursorHandle::from_raw(host).unwrap(), + ); + } + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::CHANGE_CURSOR, + &xfixes_u32s(&[0x0bad_bad0, A]), + ); + assert_eq!( + error_fields(&wire_packets(&mut peer)[0]), + (x11::error::BAD_CURSOR, 0x0bad_bad0, 26, XFIXES_MAJOR_OPCODE) + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::CHANGE_CURSOR, + &xfixes_u32s(&[D, 0x0bad_bad0]), + ); + assert_eq!( + error_fields(&wire_packets(&mut peer)[0]), + (x11::error::BAD_CURSOR, 0x0bad_bad0, 26, XFIXES_MAJOR_OPCODE) + ); + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::CHANGE_CURSOR, + &xfixes_u32s(&[D, A]), + ); + assert!(wire_packets(&mut peer).is_empty()); + assert_eq!( + state.resources.cursor_host_xid(ResourceId(A)), + Some(0x0001_0020) + ); + let calls = backend.calls.lock().unwrap().clone(); + assert!(calls.contains(&RecordedCall::ReplaceCursor { + old_host_xid: 0x0001_0010, + new_host_xid: 0x0001_0020, + })); + // A and D now share one host cursor: freeing one XID must not free it. + assert_eq!(state.resources.free_cursor(ResourceId(A)), None); + assert_eq!( + state.resources.free_cursor(ResourceId(D)), + Some(0x0001_0020) + ); +} + +/// ChangeCursorByName matches the cursor object's name even after the +/// client freed its XID (the window still shows it); a name nobody +/// interned matches nothing and is not an error (Xvfb: OK). +#[test] +fn xfixes_change_cursor_by_name_replaces_named_cursors() { + use yserver_protocol::x11::xfixes as x11xfixes; + const A: u32 = 0x0040_0030; + const B: u32 = 0x0040_0031; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.xfixes_client_major.insert(1, 5); + let mut backend = RecordingBackend::new(); + for (xid, host) in [(A, 0x0001_0030), (B, 0x0001_0031)] { + state.resources.create_cursor(ClientId(1), ResourceId(xid)); + state.resources.set_cursor_host_xid( + ResourceId(xid), + crate::backend::CursorHandle::from_raw(host).unwrap(), + ); + } + let name = state.atoms.intern("bname", false); + state.resources.set_cursor_name_atom(ResourceId(B), name); + let _ = state.resources.free_cursor(ResourceId(B)); + + let by_name = |name: &[u8]| { + let mut body = Vec::new(); + body.extend_from_slice(&A.to_le_bytes()); + body.extend_from_slice(&u16::try_from(name.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0, 0]); + body.extend_from_slice(name); + body.resize(body.len().div_ceil(4) * 4, 0); + body + }; + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::CHANGE_CURSOR_BY_NAME, + &by_name(b"zzznoname"), + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::CHANGE_CURSOR_BY_NAME, + &by_name(b"bname"), + ); + assert!(wire_packets(&mut peer).is_empty()); + let replaces: Vec = backend + .calls + .lock() + .unwrap() + .iter() + .filter(|c| matches!(c, RecordedCall::ReplaceCursor { .. })) + .cloned() + .collect(); + assert_eq!( + replaces, + vec![RecordedCall::ReplaceCursor { + old_host_xid: 0x0001_0031, + new_host_xid: 0x0001_0030, + }] + ); + assert_eq!(state.resources.cursor_name_for_host(0x0001_0031), None); +} + +/// ExpandRegion against Xvfb: {(10,10 5x5),(30,30 5x5)} expanded by +/// l1 r2 t3 b4 → {(9,7 8x12),(29,27 8x12)}; by l20 r20 → the +/// overlapping boxes are unioned into {(-10,10 45x5),(10,30 45x5)}; an +/// empty source leaves the destination as it was; bad source or +/// destination → XFixes BadRegion (error base + 0) naming it. +#[test] +fn xfixes_expand_region_matches_xvfb() { + use yserver_protocol::x11::xfixes::{self as x11xfixes, RegionRect}; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state.xfixes_client_major.insert(1, 5); + let mut backend = RecordingBackend::new(); + let rect = |x, y, width, height| RegionRect { + x, + y, + width, + height, + }; + let region = |rects: Vec| crate::server::XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::from_rects(&rects), + }; + state + .xfixes_regions + .insert(0x10, region(vec![rect(10, 10, 5, 5), rect(30, 30, 5, 5)])); + state + .xfixes_regions + .insert(0x11, region(vec![rect(100, 100, 7, 7)])); + state.xfixes_regions.insert(0x12, region(Vec::new())); + let expand = |src: u32, dst: u32, l: u16, r: u16, t: u16, b: u16| { + let mut body = xfixes_u32s(&[src, dst]); + for v in [l, r, t, b] { + body.extend_from_slice(&v.to_le_bytes()); + } + body + }; + + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::EXPAND_REGION, + &expand(0x10, 0x11, 1, 2, 3, 4), + ); + assert_eq!( + state.xfixes_regions[&0x11].rects(), + vec![rect(9, 7, 8, 12), rect(29, 27, 8, 12)] + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::EXPAND_REGION, + &expand(0x10, 0x11, 20, 20, 0, 0), + ); + assert_eq!( + state.xfixes_regions[&0x11].rects(), + vec![rect(-10, 10, 45, 5), rect(10, 30, 45, 5)] + ); + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::EXPAND_REGION, + &expand(0x12, 0x11, 1, 1, 1, 1), + ); + assert_eq!( + state.xfixes_regions[&0x11].rects(), + vec![rect(-10, 10, 45, 5), rect(10, 30, 45, 5)] + ); + assert!(wire_packets(&mut peer).is_empty()); + + for (src, dst) in [(0x0bad_bad0, 0x11), (0x10, 0x0bad_bad0)] { + xfixes_req( + &mut state, + &mut backend, + 1, + x11xfixes::EXPAND_REGION, + &expand(src, dst, 1, 1, 1, 1), + ); + assert_eq!( + error_fields(&wire_packets(&mut peer)[0]), + ( + crate::nested::XFIXES_FIRST_ERROR, + 0x0bad_bad0, + 28, + XFIXES_MAJOR_OPCODE + ) + ); + } +} + +fn xfixes_create_barrier( + state: &mut ServerState, + client: ClientId, + barrier: u32, + window: u32, + x1: i16, + y1: i16, + x2: i16, + y2: i16, + directions: u32, + devices: &[u16], +) -> io::Result { + use yserver_protocol::x11::xfixes as x11xfixes; + + let mut body = Vec::new(); + body.extend_from_slice(&barrier.to_le_bytes()); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&x1.to_le_bytes()); + body.extend_from_slice(&y1.to_le_bytes()); + body.extend_from_slice(&x2.to_le_bytes()); + body.extend_from_slice(&y2.to_le_bytes()); + body.extend_from_slice(&directions.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&(devices.len() as u16).to_le_bytes()); + for &device in devices { + body.extend_from_slice(&device.to_le_bytes()); + } + + let header = RequestHeader { + opcode: 140, + data: x11xfixes::CREATE_POINTER_BARRIER, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }; + handle_xfixes_request( + state, + &mut RecordingBackend::new(), + None, + client, + SequenceNumber(1), + header, + &body, + ) +} + +fn xfixes_delete_barrier( + state: &mut ServerState, + client: ClientId, + barrier: u32, +) -> io::Result { + use yserver_protocol::x11::xfixes as x11xfixes; + let body = barrier.to_le_bytes(); + let header = RequestHeader { + opcode: 140, + data: x11xfixes::DELETE_POINTER_BARRIER, + length_units: 2, + }; + handle_xfixes_request( + state, + &mut RecordingBackend::new(), + None, + client, + SequenceNumber(1), + header, + &body, + ) +} + +fn xi2_barrier_release( + state: &mut ServerState, + client: ClientId, + entries: &[(u16, u32, u32)], +) -> io::Result { + let mut body = Vec::new(); + body.extend_from_slice(&(entries.len() as u32).to_le_bytes()); + for &(deviceid, barrier, eventid) in entries { + body.extend_from_slice(&deviceid.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&barrier.to_le_bytes()); + body.extend_from_slice(&eventid.to_le_bytes()); + } + handle_xi2_request( + state, + &mut RecordingBackend::new(), + None, + client, + SequenceNumber(1), + xi2_header_for_body(61, &body), + &body, + ) +} + +#[test] +fn create_pointer_barrier_stores_resource() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let bid = 0x0040_0001u32; + + xfixes_create_barrier( + &mut state, + ClientId(1), + bid, + ROOT_WINDOW.0, + 100, + 0, + 100, + 200, + 0, + &[], + ) + .expect("create barrier"); + + let b = state.pointer_barriers.get(&bid).expect("stored"); + assert_eq!((b.x1, b.y1, b.x2, b.y2), (100, 0, 100, 200)); + assert_eq!(b.event_id, 1); + assert_eq!(b.release_event_id, 0); + assert!(read_all_available(&mut peer).is_empty()); +} + +#[test] +fn create_pointer_barrier_diagonal_is_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let bid = 0x0040_0001u32; + + xfixes_create_barrier( + &mut state, + ClientId(1), + bid, + ROOT_WINDOW.0, + 0, + 0, + 50, + 80, + 0, + &[], + ) + .expect("request handled"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], x11::error::BAD_VALUE); + assert!(!state.pointer_barriers.contains_key(&bid)); +} + +#[test] +fn create_pointer_barrier_bad_window() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + xfixes_create_barrier( + &mut state, + ClientId(1), + 0x0040_0001, + 0x9999, + 100, + 0, + 100, + 200, + 0, + &[], + ) + .expect("request handled"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_WINDOW); +} + +#[test] +fn create_pointer_barrier_negative_on_fixed_axis_is_bad_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + xfixes_create_barrier( + &mut state, + ClientId(1), + 0x0040_0001, + ROOT_WINDOW.0, + -1, + 0, + -1, + 200, + 0, + &[], + ) + .expect("request handled"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_VALUE); +} + +#[test] +fn create_pointer_barrier_bad_device() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + + xfixes_create_barrier( + &mut state, + ClientId(1), + 0x0040_0001, + ROOT_WINDOW.0, + 100, + 0, + 100, + 200, + 0, + &[3], + ) + .expect("request handled"); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], XI2_FIRST_ERROR); +} + +#[test] +fn delete_pointer_barrier_frees_and_owner_checks() { + let mut state = ServerState::new(); + let mut peer1 = install_client(&mut state, 1); + let mut peer2 = install_client(&mut state, 2); + let bid = 0x0040_0001u32; + + xfixes_create_barrier( + &mut state, + ClientId(1), + bid, + ROOT_WINDOW.0, + 100, + 0, + 100, + 200, + 0, + &[], + ) + .expect("create barrier"); + assert!(read_all_available(&mut peer1).is_empty()); + + xfixes_delete_barrier(&mut state, ClientId(2), bid).expect("wrong-client delete handled"); + let bytes = read_all_available(&mut peer2); + assert_eq!(bytes[1], x11::error::BAD_ACCESS); + assert!(state.pointer_barriers.contains_key(&bid)); + + xfixes_delete_barrier(&mut state, ClientId(1), bid).expect("owner delete handled"); + assert!(!state.pointer_barriers.contains_key(&bid)); +} + +#[test] +fn xi2_barrier_release_arms_matching_barrier() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let bid = 0x0040_0002u32; + + xfixes_create_barrier( + &mut state, + ClientId(1), + bid, + ROOT_WINDOW.0, + 100, + 0, + 100, + 200, + 0, + &[], + ) + .expect("create barrier"); + + xi2_barrier_release(&mut state, ClientId(1), &[(2, bid, 1)]).expect("release handled"); + + let barrier = state.pointer_barriers.get(&bid).expect("barrier"); + assert_eq!(barrier.release_event_id, 1); +} + +#[test] +fn delete_while_hit_emits_released_leave() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + if let Some(client) = state.clients.get_mut(&1) { + client.xi2_masks.insert((ROOT_WINDOW, 2), 1 << 26); + } + let bid = 0x0040_0003u32; + + xfixes_create_barrier( + &mut state, + ClientId(1), + bid, + ROOT_WINDOW.0, + 100, + 0, + 100, + 200, + 0, + &[], + ) + .expect("create barrier"); + { + let barrier = state.pointer_barriers.get_mut(&bid).expect("barrier"); + barrier.hit = true; + barrier.event_id = 1; + barrier.last_timestamp = 10; + } + // Sprite resting on the barrier. The released leave must carry the + // CURRENT position (not 0,0 — the pre-fix bug). + state.pointer_root = (100, 50); + + xfixes_delete_barrier(&mut state, ClientId(1), bid).expect("owner delete handled"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 68); + assert_eq!(bytes[0], 35, "GenericEvent"); + assert_eq!(bytes[1], XI2_MAJOR_OPCODE, "XI2 major opcode"); + assert_eq!(&bytes[8..10], &26u16.to_le_bytes(), "BarrierLeave"); + assert_eq!( + &bytes[36..40], + &1u32.to_le_bytes(), + "XIBarrierPointerReleased" + ); + assert_eq!(&bytes[40..42], &0u16.to_le_bytes(), "sourceid = 0"); + // root_x/root_y carry the current sprite position as FP1616 (v<<16), + // not the pre-fix 0,0. + assert_eq!( + &bytes[44..48], + &(100i32 << 16).to_le_bytes(), + "root_x = 100" + ); + assert_eq!(&bytes[48..52], &(50i32 << 16).to_le_bytes(), "root_y = 50"); + assert!(!state.pointer_barriers.contains_key(&bid)); +} + +#[test] +fn shape_input_change_emits_shape_notify_to_selectors() { + // A client that ShapeSelectInput'd a window must receive a + // ShapeNotify when that window's input region changes. Regression + // for the cinnamon "nemo rises" bug: nautilus grows its input shape + // from a tiny startup rect to full size; without ShapeNotify the + // compositing WM keeps the stale tiny region, treats the window as + // click-through over most of its area, and focuses/raises the + // window below on a click. + use yserver_protocol::x11::{shape as x11shape, xfixes::RegionRect}; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let win = ResourceId(0x1b00004); + seed_window(&mut state, win, ROOT_WINDOW, 800, 600); + + // WM selected ShapeNotify on the window. + state.shape_select_masks.insert((1, win), true); + + // Window sets its (grown) input shape, then we notify. + crate::nested::set_shape_rects( + &mut state, + win, + x11shape::KIND_INPUT, + vec![RegionRect { + x: 13, + y: 13, + width: 1482, + height: 1024, + }], + ); + emit_shape_notify(&mut state, win, x11shape::KIND_INPUT); + + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 32, "one 32-byte ShapeNotify"); + assert_eq!( + bytes[0], + crate::nested::SHAPE_FIRST_EVENT, + "ShapeNotify type" + ); + assert_eq!(bytes[1], x11shape::KIND_INPUT, "kind = Input"); + assert_eq!(&bytes[4..8], &win.0.to_le_bytes(), "affected window"); + assert_eq!(bytes[20], 1, "shaped = true"); + + // A client that did NOT select gets nothing. + let mut peer2 = install_client(&mut state, 2); + emit_shape_notify(&mut state, win, x11shape::KIND_INPUT); + assert!( + read_all_available(&mut peer2).is_empty(), + "non-selecting client must not receive ShapeNotify" + ); +} + +/// A `ShapeMask(kind=Input, src=None)` that clears an already-unset +/// input shape is a no-op and must NOT generate a ShapeNotify — +/// matching Xorg. xfwm4 re-asserts exactly this on its panel frames +/// repeatedly; a spurious notify each time made it re-derive the +/// frame's input shape from a stale geometry-default rect, so XFCE +/// bottom-panel buttons fell through to xfdesktop (HW xfce +/// 2026-06-22). Drives the real `handle_shape_request` MASK path. +#[test] +fn shape_mask_none_clearing_unset_input_emits_no_shape_notify() { + use yserver_protocol::x11::shape as x11shape; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let win = ResourceId(0x1b00004); + seed_window(&mut state, win, ROOT_WINDOW, 25, 49); + // WM (xfwm4-like) selected ShapeNotify on the window. + state.shape_select_masks.insert((1, win), true); + + // MASK body: op(1) dest_kind(1) pad(2) dest(4) x_off(2) y_off(2) src(4). + let mut body = vec![0u8; 16]; + body[0] = x11shape::OP_SET; + body[1] = x11shape::KIND_INPUT; + body[4..8].copy_from_slice(&win.0.to_le_bytes()); + // src stays 0 == None → clear the (already-unset) input shape. + let header = yserver_protocol::x11::RequestHeader { + opcode: 129, // SHAPE major (unused by handle_shape_request) + data: 2, // SHAPE minor: Mask + length_units: 5, + }; + handle_shape_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("ShapeMask"); + + assert!( + read_all_available(&mut peer).is_empty(), + "no-op input clear must emit no ShapeNotify", + ); +} + +/// XFIXES SUBTRACT_REGION partial-overlap: subtracting a +/// region that overlaps part of `a` must return the bands of +/// `a` *not* covered by `b`. The pre-fix dispatcher collapsed +/// any overlap to an empty result; compositors that build +/// "screen MINUS windows" wallpaper clips this way would end +/// up with no clip at all. +#[test] +fn xfixes_subtract_region_partial_overlap_returns_remaining_bands() { + use crate::server::XFixesRegion; + use yserver_protocol::x11::xfixes::RegionRect; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + // Region A: a 100x100 square at the origin. + state.xfixes_regions.insert( + 0x10, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::from_rects(&[RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }]), + }, + ); + // Region B: a 50x100 strip overlapping the right half of A. + state.xfixes_regions.insert( + 0x11, + XFixesRegion { + owner: ClientId(1), + region: crate::region::Region::from_rects(&[RegionRect { + x: 50, + y: 0, + width: 50, + height: 100, + }]), + }, + ); + // SUBTRACT_REGION body: source1(4) + source2(4) + dest(4). + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&0x10u32.to_le_bytes()); + body.extend_from_slice(&0x11u32.to_le_bytes()); + body.extend_from_slice(&0x12u32.to_le_bytes()); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(1, 5); + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 140, // XFIXES major + data: yserver_protocol::x11::xfixes::SUBTRACT_REGION, + length_units: 4, + }, + &body, + None, + ) + .unwrap(); + + let result = state + .xfixes_regions + .get(&0x12) + .expect("dest region recorded"); + assert!( + !result.rects().is_empty(), + "partial-overlap subtraction must NOT collapse to empty — \ + pre-fix this returns Vec::new() and breaks compositor \ + wallpaper-clip computation", + ); + // Geometrically: A (0,0 100x100) minus B (50,0 50x100) + // leaves the left band (0,0 50x100). Allow any equivalent + // rect decomposition that covers exactly that area. + let total_area: u64 = result + .rects() + .iter() + .map(|r| u64::from(r.width) * u64::from(r.height)) + .sum(); + assert_eq!( + total_area, + 50 * 100, + "result area must be 5000 (the left half of A); got rects {:?}", + result.rects(), + ); + // No result rect may extend into B's x-range [50, 100). + for r in &result.rects() { + assert!( + r.x + i16::try_from(r.width).unwrap_or(i16::MAX) <= 50, + "result rect {r:?} extends into the subtracted region", + ); + } +} + +/// Audit #7 (code-review follow-up): Xorg's +/// `ProcXFixesCreateRegionFromPicture` (`xfixes/region.c:257-258`) +/// returns `RenderErrBase + BadPicture` when the picture has no +/// underlying drawable. yserver models this case as +/// `PictureKind::Sourceless` (SolidFill / gradient pictures). +/// Pre-fix the handler fell through to `picture_client_clip_rects` +/// and surfaced BadMatch — wrong error class for a sourceless +/// picture. +#[test] +fn create_region_from_picture_with_sourceless_picture_returns_bad_picture() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + const APP: u32 = 84; + const PICTURE_XID: u32 = 0x0084_0001; + const REGION_XID: u32 = 0x0084_0002; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + state.resources.create_picture( + ResourceId(PICTURE_XID), + crate::resources::PictureState { + client: ClientId(APP), + host_picture_xid: Some(crate::backend::PictureHandle::from_raw_for_test(0x42)), + host_owned_pixmap: None, + kind: crate::resources::PictureKind::Sourceless, + drawable: None, + window: None, + }, + ); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(®ION_XID.to_le_bytes()); + body.extend_from_slice(&PICTURE_XID.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION_FROM_PICTURE, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!( + buf[1], + crate::nested::RENDER_FIRST_ERROR + 1, + "expected BadPicture (Render first_error + 1 = 153) for \ + sourceless picture; got {}", + buf[1], + ); + assert!( + !state.xfixes_regions.contains_key(®ION_XID), + "no region must be inserted on BadPicture", + ); +} + +/// Audit #7 (code-review follow-up): Xorg's +/// `ProcXFixesCreateRegionFromPicture` uses `VERIFY_PICTURE` +/// (`xfixes/region.c:255`) which returns +/// `RenderErrBase + BadPicture` for an unknown picture xid, +/// not BadDrawable. yserver was emitting BadDrawable. +#[test] +fn create_region_from_picture_with_unknown_picture_returns_bad_picture() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + const APP: u32 = 85; + const UNKNOWN_PIC: u32 = 0x0085_dead; + const REGION_XID: u32 = 0x0085_0001; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(®ION_XID.to_le_bytes()); + body.extend_from_slice(&UNKNOWN_PIC.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION_FROM_PICTURE, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!( + buf[1], + crate::nested::RENDER_FIRST_ERROR + 1, + "expected BadPicture for unknown picture xid (Xorg VERIFY_PICTURE \ + returns RenderErrBase+BadPicture, NOT BadDrawable); got {}", + buf[1], + ); +} + +/// Audit #7 (code-review follow-up): Xorg's +/// `ProcXFixesCreateRegionFromWindow` (`xfixes/region.c:158-163`) +/// returns BadWindow when `dixLookupResourceByType` on the +/// window xid fails, with `client->error_value = stuff->window`. +/// Pre-fix yserver passed any xid (including 0) through to +/// `shape_rects_for` and silently inserted a default/empty +/// region. +#[test] +fn create_region_from_window_with_unknown_window_returns_bad_window() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + const APP: u32 = 82; + const REGION_XID: u32 = 0x0082_0001; + const UNKNOWN_WIN: u32 = 0x0082_ffff; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + // body: region(4) + window(4) + kind(1) + pad(3) + let mut body = Vec::with_capacity(12); + body.extend_from_slice(®ION_XID.to_le_bytes()); + body.extend_from_slice(&UNKNOWN_WIN.to_le_bytes()); + body.push(0); // kind = Bounding (valid) + body.extend_from_slice(&[0u8; 3]); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION_FROM_WINDOW, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_WINDOW, + "expected BadWindow (3) for unknown window xid; got {}", + buf[1], + ); + assert_eq!( + u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]), + UNKNOWN_WIN, + "error.bad_value must carry the offending window xid", + ); + assert!( + !state.xfixes_regions.contains_key(®ION_XID), + "no region must be inserted on BadWindow", + ); +} + +/// Audit #7 (code-review follow-up): Xorg's +/// `ProcXFixesCreateRegionFromWindow` (`xfixes/region.c:164-181`) +/// accepts only `WindowRegionBounding` (0) and `WindowRegionClip` +/// (1); any other `kind` returns BadValue with +/// `client->error_value = stuff->kind`. The SHAPE-shaped value 2 +/// (Input) is rejected per X11 XFIXES spec. +#[test] +fn create_region_from_window_with_invalid_kind_returns_bad_value() { + use std::io::Read; + use yserver_protocol::x11::{CreateWindowRequest, xfixes as x11xfixes}; + const APP: u32 = 83; + const REGION_XID: u32 = 0x0083_0001; + const WIN_XID: u32 = 0x0083_0002; + const INVALID_KIND: u8 = 2; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + // Window must exist so the BadWindow gate doesn't fire + // first — we want to isolate the BadValue(kind) path. + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + + let mut body = Vec::with_capacity(12); + body.extend_from_slice(®ION_XID.to_le_bytes()); + body.extend_from_slice(&WIN_XID.to_le_bytes()); + body.push(INVALID_KIND); + body.extend_from_slice(&[0u8; 3]); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION_FROM_WINDOW, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_VALUE, + "expected BadValue (2) for kind={INVALID_KIND}; got {}", + buf[1], + ); + assert_eq!( + u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]), + u32::from(INVALID_KIND), + "error.bad_value must carry the offending kind", + ); + assert!( + !state.xfixes_regions.contains_key(®ION_XID), + "no region must be inserted on BadValue", + ); +} + +/// Audit #7 (code-review follow-up): every XFIXES +/// `CreateRegion*` opcode begins with +/// `LEGAL_NEW_RESOURCE(stuff->region, client)` in Xorg +/// (`xfixes/region.c:78,114,157,213,…`). Reusing an existing +/// region XID must surface BadIDChoice. Pre-fix yserver silently +/// overwrote `state.xfixes_regions[region]` via `.insert(…)`, +/// matching the colormap/window/etc. bug class that the +/// codebase already gates elsewhere. +#[test] +fn create_region_with_in_use_xid_returns_bad_id_choice() { + use std::io::Read; + use yserver_protocol::x11::xfixes as x11xfixes; + const APP: u32 = 80; + const REGION_XID: u32 = 0x0080_0001; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + // Pre-populate the region xid so the new request is a + // duplicate. + state.xfixes_regions.insert( + REGION_XID, + crate::server::XFixesRegion { + owner: ClientId(APP), + region: crate::region::Region::default(), + }, + ); + + // CreateRegion body: region(4) + N×8 (rects). Zero rects = + // empty region; the duplicate-xid check must fire BEFORE + // any rect parsing. + let mut body = Vec::with_capacity(4); + body.extend_from_slice(®ION_XID.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!(buf[0], 0, "first byte = error class"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_ID_CHOICE, + "expected BadIDChoice (14) when reusing an existing region xid; got {}", + buf[1], + ); + // The duplicate must not be overwritten — the pre-existing + // entry's marker (empty rects placeholder) survives intact. + let r = state + .xfixes_regions + .get(®ION_XID) + .expect("pre-existing region must remain"); + assert!( + r.rects().is_empty(), + "pre-existing region must not be overwritten on BadIDChoice; \ + got rects={:?}", + r.rects(), + ); +} + +/// Audit #7 (code-review follow-up): the duplicate-xid gate +/// also applies to `CREATE_REGION_FROM_GC` (and all other +/// CreateRegion variants). The GC path is the audit-#7 patch +/// site — confirm the new gate is wired in front of the raw +/// clip-copy too. +#[test] +fn create_region_from_gc_with_in_use_xid_returns_bad_id_choice() { + use std::io::Read; + use yserver_protocol::x11::{ + ClipRectangles, CreateGcRequest, CreateWindowRequest, SetClipRectanglesRequest, + xfixes as x11xfixes, + }; + const APP: u32 = 81; + const WIN_XID: u32 = 0x0081_0001; + const GC_XID: u32 = 0x0081_0002; + const REGION_XID: u32 = 0x0081_0003; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_gc( + ClientId(APP), + CreateGcRequest { + gc: ResourceId(GC_XID), + drawable: ResourceId(WIN_XID), + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + // Single-rect clip so the GC's `clientClip` exists. + let mut rect_bytes = Vec::with_capacity(8); + rect_bytes.extend_from_slice(&0i16.to_le_bytes()); + rect_bytes.extend_from_slice(&0i16.to_le_bytes()); + rect_bytes.extend_from_slice(&5u16.to_le_bytes()); + rect_bytes.extend_from_slice(&5u16.to_le_bytes()); + state.resources.set_clip_rectangles( + yserver_protocol::x11::ClientId(1), + SetClipRectanglesRequest { + gc: ResourceId(GC_XID), + clip: ClipRectangles { + ordering: 0, + x_origin: 0, + y_origin: 0, + rectangles: rect_bytes, + }, + }, + ); + + // Pre-occupy REGION_XID. + state.xfixes_regions.insert( + REGION_XID, + crate::server::XFixesRegion { + owner: ClientId(APP), + region: crate::region::Region::default(), + }, + ); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(®ION_XID.to_le_bytes()); + body.extend_from_slice(&GC_XID.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION_FROM_GC, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + peer.set_nonblocking(true).unwrap(); + let mut buf = [0u8; 32]; + peer.read_exact(&mut buf).expect("error reply delivered"); + assert_eq!( + buf[1], + yserver_protocol::x11::error::BAD_ID_CHOICE, + "CreateRegionFromGC must gate on LEGAL_NEW_RESOURCE before \ + copying the GC's clip; got error code {}", + buf[1], + ); +} + +/// Audit #7 (`docs/protocol-audit-2026-05-19.md`): +/// `CreateRegionFromGC` must return the GC's clip rectangles in +/// their RAW clip-coordinate space — Xorg's +/// `ProcXFixesCreateRegionFromGC` (`xfixes/region.c:219-226`) +/// just `XFixesRegionCopy(pGC->clientClip)` with NO origin +/// translation applied. yserver was offsetting by +/// `(clip.x_origin, clip.y_origin)` at insert time. When a WM +/// later re-installs the resulting region as a GC's clip via +/// `SetGcClipRegion(gc, region, x_origin, y_origin)`, the +/// GC-side origin is applied a SECOND time → double-translation +/// → wrong area shadowed/repainted. +#[test] +fn create_region_from_gc_copies_clip_rects_without_origin_translation() { + use yserver_protocol::x11::{ + ClipRectangles, CreateGcRequest, CreateWindowRequest, SetClipRectanglesRequest, + xfixes as x11xfixes, + }; + const APP: u32 = 70; + const WIN_XID: u32 = 0x0070_0001; + const GC_XID: u32 = 0x0070_0002; + const REGION_XID: u32 = 0x0070_0003; + const X_ORIGIN: i16 = 100; + const Y_ORIGIN: i16 = 200; + const RECT_X: i16 = 10; + const RECT_Y: i16 = 20; + const RECT_W: u16 = 5; + const RECT_H: u16 = 5; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + + // Drawable to attach the GC to. + state.resources.create_window( + ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_gc( + ClientId(APP), + CreateGcRequest { + gc: ResourceId(GC_XID), + drawable: ResourceId(WIN_XID), + function: None, + plane_mask: None, + foreground: None, + background: None, + line_width: None, + line_style: None, + cap_style: None, + join_style: None, + fill_style: None, + fill_rule: None, + tile: None, + stipple: None, + tile_x_origin: None, + tile_y_origin: None, + font: None, + subwindow_mode: None, + graphics_exposures: None, + clip_x_origin: None, + clip_y_origin: None, + clip_mask: None, + dash_offset: None, + dashes: None, + arc_mode: None, + }, + ); + + // Set the GC's clip: single rect at (10, 20, 5×5) in + // clip-coordinate space, with origin (100, 200). The wire + // format is (x i16, y i16, w u16, h u16) per rect. + let mut rect_bytes = Vec::with_capacity(8); + rect_bytes.extend_from_slice(&RECT_X.to_le_bytes()); + rect_bytes.extend_from_slice(&RECT_Y.to_le_bytes()); + rect_bytes.extend_from_slice(&RECT_W.to_le_bytes()); + rect_bytes.extend_from_slice(&RECT_H.to_le_bytes()); + state.resources.set_clip_rectangles( + yserver_protocol::x11::ClientId(1), + SetClipRectanglesRequest { + gc: ResourceId(GC_XID), + clip: ClipRectangles { + ordering: 0, + x_origin: X_ORIGIN, + y_origin: Y_ORIGIN, + rectangles: rect_bytes, + }, + }, + ); + + // CREATE_REGION_FROM_GC body: region(4) + gc(4). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(®ION_XID.to_le_bytes()); + body.extend_from_slice(&GC_XID.to_le_bytes()); + let length_units = u32::try_from(1 + body.len().div_ceil(4)).expect("body fits"); + // The client negotiated XFIXES (Xorg gates requests on QueryVersion). + state.xfixes_client_major.insert(APP, 5); + process_request( + &mut state, + &mut backend, + ClientId(APP), + SequenceNumber(1), + RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: x11xfixes::CREATE_REGION_FROM_GC, + length_units, + }, + &body, + None, + ) + .expect("process_request"); + + let region = state + .xfixes_regions + .get(®ION_XID) + .expect("CreateRegionFromGC inserted region"); + assert_eq!( + region.rects().len(), + 1, + "expected exactly one rect from the GC's single-rect clip; got {:?}", + region.rects(), + ); + let r = ®ion.rects()[0]; + assert_eq!( + (r.x, r.y, r.width, r.height), + (RECT_X, RECT_Y, RECT_W, RECT_H), + "rect must be in raw clip-coord space (NOT translated by \ + clip_origin=({X_ORIGIN},{Y_ORIGIN})); the symptom of \ + over-translation is x={}, y={} (= raw + clip_origin).", + r.x, + r.y, + ); +} + +// DRIFT 1 + Multi-monitor Bug A regression: the Bounding-shape mirror +// must distinguish three states via the Option API — +// unset → None (drop the entry; scene tracks live geometry — +// the multi-monitor Bug A fix), NOT the +// materialized default geometry rect; +// empty → Some(0) (explicit empty region — distinct from unset); +// concrete → Some(n) (the real rects). +#[test] +fn bounding_shape_mirror_distinguishes_unset_empty_and_concrete() { + use yserver_protocol::x11::shape as x11shape; + + const WINDOW_XID: u32 = 0x0010_0001; + const HOST_XID: u32 = 0x0040_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 2560, + height: 1440, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed") + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + + // No explicit Bounding shape set → mirror must push empty rects. + mirror_shape_to_host_state( + &state, + &mut backend, + None, + ResourceId(WINDOW_XID), + x11shape::KIND_BOUNDING, + ); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_BOUNDING, + rects: None, + } + ), + "unset Bounding shape must mirror None (drop backend entry), \ + not the materialized 2560x1440 default geometry rect, and NOT \ + an explicit empty region (Some(0)) — DRIFT 1 distinction", + ); + + // An explicitly-set EMPTY Bounding shape is a DISTINCT state from + // unset: it mirrors Some(0), not None. This is the DRIFT 1 fix — + // the old &[]-based API collapsed both to a zero-length call. + crate::nested::set_shape_rects( + &mut state, + ResourceId(WINDOW_XID), + x11shape::KIND_BOUNDING, + vec![], + ); + mirror_shape_to_host_state( + &state, + &mut backend, + None, + ResourceId(WINDOW_XID), + x11shape::KIND_BOUNDING, + ); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_BOUNDING, + rects: Some(0), + } + ), + "explicit EMPTY Bounding shape must mirror Some(0) (an empty \ + region), distinct from unset's None", + ); + + // After an explicit non-empty Bounding shape, mirror the concrete rect(s). + crate::nested::set_shape_rects( + &mut state, + ResourceId(WINDOW_XID), + x11shape::KIND_BOUNDING, + vec![yserver_protocol::x11::xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }], + ); + mirror_shape_to_host_state( + &state, + &mut backend, + None, + ResourceId(WINDOW_XID), + x11shape::KIND_BOUNDING, + ); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_BOUNDING, + rects: Some(1), + } + ), + "explicitly-set Bounding shape must mirror the concrete rect", + ); +} + +/// Cinnamon's lock screen, as muffin sends it: an XFIXES region that +/// `InvertRegion` empties, set as the COW's Bounding shape, must reach the +/// backend as an explicit EMPTY region, and region None as unset — the +/// two stay distinct (`ProcXFixesSetWindowShapeRegion`, `xfixes/region.c`: +/// a NULL region pointer unshapes, a copied empty region shapes to +/// nothing). +#[test] +fn xfixes_set_window_shape_region_keeps_empty_distinct_from_none() { + use yserver_protocol::x11::{shape as x11shape, xfixes as x11xfixes}; + + const REGION: u32 = 0x0010_0042; + let cow = crate::resources::COMPOSITE_OVERLAY_WINDOW; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state + .resources + .materialize_cow_resource(crate::backend::WindowHandle::from_raw_for_test(cow.0)); + + let mut send = |state: &mut ServerState, minor: u8, body: Vec| { + let header = yserver_protocol::x11::RequestHeader { + opcode: XFIXES_MAJOR_OPCODE, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }; + handle_xfixes_request( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("XFIXES request"); + }; + let full = [0_i16, 0, 5120, 1440] + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>(); + let shape_body = |region: u32| { + let mut body = cow.0.to_le_bytes().to_vec(); + body.extend_from_slice(&[x11shape::KIND_BOUNDING, 0, 0, 0, 0, 0, 0, 0]); + body.extend_from_slice(®ion.to_le_bytes()); + body + }; + + let mut create = REGION.to_le_bytes().to_vec(); + create.extend_from_slice(&full); + send(&mut state, x11xfixes::CREATE_REGION, create); + let mut invert = REGION.to_le_bytes().to_vec(); + invert.extend_from_slice(&full); + invert.extend_from_slice(®ION.to_le_bytes()); + send(&mut state, x11xfixes::INVERT_REGION, invert); + send( + &mut state, + x11xfixes::SET_WINDOW_SHAPE_REGION, + shape_body(REGION), + ); + assert!(crate::nested::shape_kind_is_set( + &state, + cow, + x11shape::KIND_BOUNDING + )); + assert!(crate::nested::shape_rects_for(&state, cow, x11shape::KIND_BOUNDING).is_empty()); + + send( + &mut state, + x11xfixes::SET_WINDOW_SHAPE_REGION, + shape_body(0), + ); + assert!(!crate::nested::shape_kind_is_set( + &state, + cow, + x11shape::KIND_BOUNDING + )); + + let mirrored: Vec<_> = backend + .calls() + .into_iter() + .filter_map(|call| match call { + crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid, + kind: x11shape::KIND_BOUNDING, + rects, + } if host_xid == cow.0 => Some(rects), + _ => None, + }) + .collect(); + assert_eq!(mirrored, vec![Some(0), None]); +} + +// #133: the CLIP mirror must make the same unset/empty/concrete +// distinction as Bounding. Before step 5 the scene only consulted the +// bounding shape, so freezing the geometry rect for an unset clip shape +// was inert; step 5 clips descendants to the parent's clip shape, and a +// frozen rect then truncates the children after the parent resizes. That +// is the wezterm white block: awesome resets its frame's clip shape at +// 820x583, the frame later becomes 608x734, and 168 rows of the client +// vanished. Input is deliberately NOT in the guard — it feeds the cursor +// hit-test, which wants a concrete region. +#[test] +fn clip_shape_mirror_leaves_an_unset_region_unmaterialized() { + use yserver_protocol::x11::shape as x11shape; + + const WINDOW_XID: u32 = 0x0010_0002; + const HOST_XID: u32 = 0x0040_0002; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: crate::resources::ROOT_WINDOW, + x: 0, + y: 0, + width: 820, + height: 583, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed") + .host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + + let mirror = |state: &ServerState, backend: &mut RecordingBackend, kind: u8| { + mirror_shape_to_host_state(state, backend, None, ResourceId(WINDOW_XID), kind); + }; + + mirror(&state, &mut backend, x11shape::KIND_CLIP); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_CLIP, + rects: None, + } + ), + "an unset Clip shape must mirror None, not the 820x583 geometry \ + rect that goes stale on the next resize", + ); + + // Input keeps materializing the default rect — the cursor hit-test + // consumes a concrete region and does not clip descendants. + mirror(&state, &mut backend, x11shape::KIND_INPUT); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_INPUT, + rects: Some(1), + } + ), + "an unset Input shape still mirrors the default geometry rect", + ); + + // An explicit EMPTY clip region is a distinct state from unset. + crate::nested::set_shape_rects( + &mut state, + ResourceId(WINDOW_XID), + x11shape::KIND_CLIP, + vec![], + ); + mirror(&state, &mut backend, x11shape::KIND_CLIP); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_CLIP, + rects: Some(0), + } + ), + "explicit EMPTY Clip shape mirrors Some(0), distinct from unset", + ); + + // And a real clip shape is still mirrored through. + crate::nested::set_shape_rects( + &mut state, + ResourceId(WINDOW_XID), + x11shape::KIND_CLIP, + vec![yserver_protocol::x11::xfixes::RegionRect { + x: 0, + y: 0, + width: 100, + height: 100, + }], + ); + mirror(&state, &mut backend, x11shape::KIND_CLIP); + assert_eq!( + backend.calls().last(), + Some( + &crate::backend::recording::RecordedCall::SetShapeRectangles { + host_xid: HOST_XID, + kind: x11shape::KIND_CLIP, + rects: Some(1), + } + ), + "explicitly-set Clip shape must mirror the concrete rect", + ); +} + +/// GDK clips a native child of a client-side window with its bounding +/// shape and shifts the shape when it scrolls. Xorg's `miSetShape` +/// (`mi/miwindow.c:637-677`) then exposes what the window no longer +/// covers to its parent and what it newly covers to itself — the +/// parent's button bar is repainted only on that Expose. Measured on +/// Xorg 21.1 by tools/vng-scenarios/child-clip-probe.c: the shape +/// (0,0 170x60) of V at (10,10) becoming (0,30 170x60) exposes +/// P 10,10 170x30 and V 0,60 170x30. +#[test] +fn bounding_shape_change_exposes_what_it_uncovers_and_covers() { + use yserver_protocol::x11::{shape as x11shape, xfixes::RegionRect}; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let (p, v) = (ResourceId(0x1c0_0001), ResourceId(0x1c0_0002)); + seed_window(&mut state, p, ROOT_WINDOW, 190, 100); + seed_window(&mut state, v, p, 170, 120); + for w in [p, v] { + state.resources.window_mut(w).unwrap().map_state = crate::resources::MapState::Viewable; + } + let vw = state.resources.window_mut(v).unwrap(); + (vw.x, vw.y) = (10, 10); + crate::nested::set_shape_rects( + &mut state, + v, + x11shape::KIND_BOUNDING, + vec![RegionRect { + x: 0, + y: 0, + width: 170, + height: 60, + }], + ); + let client = state.clients.get_mut(&1).unwrap(); + client.event_masks.insert(p, 0x0000_8000); + client.event_masks.insert(v, 0x0000_8000); + + // RECTANGLES body: op kind ordering pad dest(4) x_off(2) y_off(2) rects. + let mut body = vec![x11shape::OP_SET, x11shape::KIND_BOUNDING, 0, 0]; + body.extend_from_slice(&v.0.to_le_bytes()); + body.extend_from_slice(&[0; 4]); + for field in [0u16, 30, 170, 60] { + body.extend_from_slice(&field.to_le_bytes()); + } + let header = yserver_protocol::x11::RequestHeader { + opcode: 129, + data: x11shape::RECTANGLES, + length_units: 6, + }; + handle_shape_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("ShapeRectangles"); + + let exposes: Vec<(u32, [u16; 4])> = read_all_available(&mut peer) + .chunks_exact(32) + .filter(|e| e[0] & 0x7f == 12) + .map(|e| { + let at = |i: usize| u16::from_le_bytes([e[i], e[i + 1]]); + ( + u32::from_le_bytes([e[4], e[5], e[6], e[7]]), + [at(8), at(10), at(12), at(14)], + ) + }) + .collect(); + assert_eq!( + exposes, + vec![(p.0, [10, 10, 170, 30]), (v.0, [0, 60, 170, 30])] + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi1.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi1.rs new file mode 100644 index 000000000..d09a97f9e --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi1.rs @@ -0,0 +1,1622 @@ +use super::*; +use yserver_protocol::x11::AtomId; + +#[test] +fn xi1_device_bell_rejects_feedback_without_bell_proc() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Device 3 advertises KbdFeedback id 0, but yserver has no audible + // BellProc. Xorg Xi/devbell.c returns BadValue in this case. + let body = [3, 0, 0, 50]; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(7), + xi2_header_for_body(32, &body), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "X error"); + assert_eq!(wire[1], x11::error::BAD_VALUE); + assert_eq!(u16::from_le_bytes(wire[2..4].try_into().unwrap()), 7); + assert_eq!(u16::from_le_bytes(wire[8..10].try_into().unwrap()), 32); + assert_eq!(wire[10], XI2_MAJOR_OPCODE); +} + +#[test] +fn xi1_device_bell_validates_percent_before_feedback_class() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // Both percent=101 and feedbackclass=99 are invalid. Xorg reports + // the percent first and places its raw CARD8 value in errorValue. + let body = [3, 0, 99, 101]; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(8), + xi2_header_for_body(32, &body), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire[1], x11::error::BAD_VALUE); + assert_eq!(u32::from_le_bytes(wire[4..8].try_into().unwrap()), 101); +} + +/// XI1 device-property event code is 16; with `XI_FIRST_EVENT = 66` +/// the wire type byte is 82. The XEventClass packs +/// `(deviceid << 8) | event_code`, so for the virtual XTEST pointer +/// (deviceid 4) the class is `(4 << 8) | 82 = 0x0452`. +const XI1_DEV_PROP_CLASS_XTEST_POINTER: u32 = + ((crate::xinput::DEVICEID_XTEST_POINTER as u32) << 8) | 82; +const XI1_DEV_PROP_CLASS_XTEST_KEYBOARD: u32 = + ((crate::xinput::DEVICEID_XTEST_KEYBOARD as u32) << 8) | 82; + +#[test] +fn xi1_dynamic_hotplug_selects_the_device_256_presence_class() { + const DEVICE_PRESENCE_CLASS: u32 = 256 << 8; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[DEVICE_PRESENCE_CLASS]); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(19), + xi2_header_for_body(6, &body), + &body, + ) + .expect("device 256 is valid for XI1 presence selection"); + + let wire = read_all_available(&mut peer); + assert!( + wire.is_empty(), + "SelectExtensionEvent has no reply or error" + ); + let client = state.clients.get(&1).expect("selected client"); + assert!( + client + .xi1_window_event_classes + .get(&ROOT_WINDOW) + .is_some_and(|classes| classes.contains(&DEVICE_PRESENCE_CLASS)), + "preserve the special presence class on its selected window" + ); + assert!( + client.xi1_event_classes.contains(&DEVICE_PRESENCE_CLASS), + "presence class participates in server-wide event delivery" + ); +} + +#[test] +fn xi1_dynamic_hotplug_does_not_treat_an_ordinary_class_as_presence() { + const DEVICE_PRESENCE_CLASS: u32 = 256 << 8; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Device 256's low byte is `_devicePresence` (0). Other classes + // with that special device id are stripped by Xorg but do not + // select presence; a real device's event class is not a substitute. + let other_device_256_class: u32 = (256 << 8) | 15; + let ordinary_device_class: u32 = ((crate::xinput::DEVICEID_XTEST_POINTER as u32) << 8) | 81; + let body = xi1_select_extension_event_body( + ROOT_WINDOW.0, + &[other_device_256_class, ordinary_device_class], + ); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(20), + xi2_header_for_body(6, &body), + &body, + ) + .expect("unsupported ordinary classes remain ignored"); + + let wire = read_all_available(&mut peer); + assert!( + wire.is_empty(), + "SelectExtensionEvent has no reply or error" + ); + let client = state.clients.get(&1).expect("selected client"); + assert!( + !client.xi1_event_classes.contains(&DEVICE_PRESENCE_CLASS), + "ordinary XI1 classes must not subscribe to presence" + ); + assert!( + client.xi1_window_event_classes.values().all(|classes| { + !classes.contains(&DEVICE_PRESENCE_CLASS) + && !classes.contains(&other_device_256_class) + && !classes.contains(&ordinary_device_class) + }), + "only the recognized device 256 class is stored" + ); +} + +/// Scan a wire buffer for the first XI1 `DevicePropertyNotify` +/// (type byte == 82) and return the 32-byte slice. T5's +/// `find_xi2_property_event` keyed off GenericEvent + evtype 12; +/// XI1 is a sequential event code so a single-byte type match is +/// enough — and it explicitly cannot collide with the XI2 +/// `GenericEvent` (35) or other extension events in our range. +fn find_xi1_device_property_notify(wire: &[u8]) -> Option<&[u8]> { + let end = wire.len().checked_sub(32)?; + (0..=end).find_map(|i| (wire[i] == 82).then(|| &wire[i..i + 32])) +} + +#[test] +fn xi1_button_shape_query_device_state_uses_core_pointer_shape() { + // Mutation killed: hard-code the former seven-button/four-valuator + // physical shape for the XTEST pointer instead of its CorePointer + // class shape. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + { + let entry = state + .xi1_device_input_state + .entry(crate::xinput::DEVICEID_XTEST_POINTER) + .or_default(); + entry.buttons_down[0] = 0b0000_0010; // button 1 down + entry.valuators = [120, 45, 0, 0]; // axes as of last motion + } + let before = xi_query_side_effect_snapshot(&state, 1); + + let wire = dispatch_xi_request_wire( + &mut state, + &mut peer, + 1, + 30, + &[ + u8::try_from(crate::xinput::DEVICEID_XTEST_POINTER).unwrap(), + 0, + 0, + 0, + ], + ); + assert_eq!( + wire.len(), + 32 + 36 + 12, + "reply + xButtonState + xValuatorState" + ); + assert_eq!(wire[8], 2, "num_classes"); + let bs = &wire[32..68]; + assert_eq!((bs[0], bs[1], bs[2]), (1, 36, 10), "ButtonClass/len/count"); + assert_eq!(bs[4], 0b0000_0010, "button 1 down bit"); + let vs = &wire[68..]; + assert_eq!( + (vs[0], vs[1], vs[2], vs[3]), + (2, 12, 2, 0), + "ValuatorClass/len/axes/mode" + ); + assert_eq!(i32::from_le_bytes(vs[4..8].try_into().unwrap()), 120); + assert_eq!(i32::from_le_bytes(vs[8..12].try_into().unwrap()), 45); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_button_shape_xtest_get_mapping_has_ten_entries() { + // Mutation killed: keep GetDeviceButtonMapping's old seven-entry + // reply instead of reading the XTEST device's ButtonClass shape. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 28, &[4, 0, 0, 0]); + + assert_eq!(wire[0], 1, "GetDeviceButtonMapping reply"); + assert_eq!(wire[8], 10, "nElts follows XTEST's ten-button class"); + assert_eq!(wire.len(), 32 + 12, "ten map bytes padded to three words"); + assert_eq!(&wire[32..42], &(1..=10).collect::>()); + assert_eq!(&wire[42..44], &[0, 0], "reply map padding"); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_button_shape_set_mapping_accepts_ten_and_eleven_entries() { + // Mutation killed: restore a seven-entry map length ceiling, which + // rejects Xorg's valid eleven-entry request on device 4. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + + for (sequence, map) in [(1, (1..=10).collect::>()), (2, (1..=11).collect())] { + let mut body = vec![4, u8::try_from(map.len()).unwrap(), 0, 0]; + body.extend_from_slice(&map); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, sequence, 29, &body); + assert_eq!( + wire.len(), + 32, + "MappingSuccess reply for {} entries", + map.len() + ); + assert_eq!(wire[0], 1, "SetDeviceButtonMapping reply"); + assert_eq!(wire[8], 0, "MappingSuccess"); + assert!(read_all_available(&mut peer).is_empty()); + } + + assert_eq!(state.xi1_button_map, [(4, (1..=11).collect())].into()); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_button_shape_physical_pointer_keeps_seven_buttons_and_four_valuators() { + // Mutation killed: apply CorePointer's ten-button/two-valuator shape + // to a physical slave whose XI class descriptors remain seven/four. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical_pointer = seed_pointer_for_t3(&mut state); + let before = xi_query_side_effect_snapshot(&state, 1); + + let mapping = dispatch_xi_request_wire( + &mut state, + &mut peer, + 1, + 28, + &[u8::try_from(physical_pointer).unwrap(), 0, 0, 0], + ); + assert_eq!(mapping[8], 7, "physical button-map count"); + assert_eq!(&mapping[32..39], &(1..=7).collect::>()); + + let query = dispatch_xi_request_wire( + &mut state, + &mut peer, + 2, + 30, + &[u8::try_from(physical_pointer).unwrap(), 0, 0, 0], + ); + assert_eq!(query[34], 7, "physical ButtonClass reports seven buttons"); + assert_eq!( + query[32 + 36 + 2], + 4, + "physical ValuatorClass reports four axes" + ); + assert_eq!(query.len(), 32 + 36 + 20); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_list_input_devices_uses_each_registry_shape() { + // Kills: restore ListInputDevices' fixed seven-button/four-axis + // pointer descriptor for master 2 instead of its current CorePointer + // registry shape (Xorg Xi/listdev.c:100-107, 277-283). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical = state.xi_register_source(&crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(0x51a9), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + pointer: true, + ..Default::default() + }, + name: "shape-sweep-mouse".into(), + device_node: "/dev/input/event-shape-sweep".into(), + sysname: "event-shape-sweep".into(), + vendor_id: 1, + product_id: 2, + is_touchpad: false, + config: Default::default(), + })[0]; + let before = xi_query_side_effect_snapshot(&state, 1); + + let wire = dispatch_wire_request(&mut state, &mut peer, 1, XI2_MAJOR_OPCODE, 2, &[]); + assert_eq!(wire[0], 1, "XListInputDevices reply"); + let device_count = usize::from(wire[8]); + let mut devices = Vec::with_capacity(device_count); + let mut offset = 32; + for _ in 0..device_count { + devices.push((u16::from(wire[offset + 4]), usize::from(wire[offset + 5]))); + offset += 8; + } + let mut shapes = HashMap::new(); + for (id, classes) in devices { + let mut buttons = None; + let mut axes = None; + for _ in 0..classes { + let class_type = wire[offset]; + let class_len = usize::from(wire[offset + 1]); + match class_type { + 1 => buttons = Some(u16::from_le_bytes([wire[offset + 2], wire[offset + 3]])), + 2 => axes = Some(wire[offset + 2]), + _ => {} + } + offset += class_len; + } + shapes.insert(id, (buttons, axes)); + } + assert_eq!(shapes.get(&2), Some(&(Some(10), Some(2))), "master 2"); + assert_eq!(shapes.get(&4), Some(&(Some(10), Some(2))), "XTEST 4"); + assert_eq!(shapes.get(&physical), Some(&(Some(7), Some(4))), "physical"); + assert_eq!(state.xi_devices.device(2).unwrap().class_sourceid, 2); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_device_state_notify_uses_current_shape() { + // Kills: report seven buttons/four axes and emit a valuator + // continuation for XTEST 4; Xorg counts the device's current button + // and valuator classes in FixDeviceStateNotify and + // DeliverStateNotifyEvent (Xi/exevents.c:282-285, + // dix/enterleave.c:715-729, 753-760). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let baseline = xi_query_side_effect_snapshot(&state, 1); + let child = ResourceId(0x0040_0a01); + xi_hotplug_dispatch( + &mut state, + &mut backend, + 1, + 1, + 1, + 0, + &xi_hotplug_create_window_body(child.0, ROOT_WINDOW.0), + ); + xi_hotplug_dispatch(&mut state, &mut backend, 1, 2, 8, 0, &child.0.to_le_bytes()); + let state_class = (u32::from(crate::xinput::DEVICEID_XTEST_POINTER) << 8) + | u32::from(crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_STATE_NOTIFY_OFFSET); + let select = xi1_select_extension_event_body(child.0, &[state_class]); + xi_hotplug_dispatch(&mut state, &mut backend, 1, 3, XI2_MAJOR_OPCODE, 6, &select); + assert!( + read_all_available(&mut peer).is_empty(), + "selection has no reply" + ); + + let mut focus_body = child.0.to_le_bytes().to_vec(); + focus_body.extend_from_slice(&0u32.to_le_bytes()); // CurrentTime + focus_body.push(0); // RevertToNone + focus_body.push(u8::try_from(crate::xinput::DEVICEID_XTEST_POINTER).unwrap()); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 4, 21, &focus_body); + assert_eq!(wire.len(), 32, "DeviceStateNotify has no continuation"); + assert_eq!( + wire[0], + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_STATE_NOTIFY_OFFSET + ); + assert_eq!(wire[1], crate::xinput::DEVICEID_XTEST_POINTER as u8); + assert_eq!(wire[9], 10, "ButtonClass count follows CorePointer"); + assert_eq!(wire[10], 2, "ValuatorClass count follows CorePointer"); + + // Restore focus, then destroy the selecting window through the core + // dispatcher so its selection is removed by the normal resource path. + focus_body[..4].copy_from_slice(&1u32.to_le_bytes()); // PointerRoot + let _ = dispatch_xi_request_wire(&mut state, &mut peer, 5, 21, &focus_body); + xi_hotplug_dispatch(&mut state, &mut backend, 1, 6, 4, 0, &child.0.to_le_bytes()); + let _ = read_all_available(&mut peer); + assert!(state.resources.window(child).is_none()); + assert_eq!( + crate::core_loop::xi1_focus::device_focus(&state, crate::xinput::DEVICEID_XTEST_POINTER) + .focus, + 1, + "focus returned to PointerRoot" + ); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), baseline); +} + +#[test] +fn xi1_shape_sweep_get_device_motion_events_uses_class_axis_count() { + // Kills: keep GetDeviceMotionEvents' four-axis reply for a two-axis + // master; Xorg copies v->numAxes into the reply (Xi/gtmotion.c:107-120). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical = state.xi_register_source(&crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(0x51aa), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + pointer: true, + ..Default::default() + }, + name: "motion-shape-mouse".into(), + device_node: "/dev/input/event-motion-shape".into(), + sysname: "event-motion-shape".into(), + vendor_id: 1, + product_id: 3, + is_touchpad: false, + config: Default::default(), + })[0]; + let before = xi_query_side_effect_snapshot(&state, 1); + let master = dispatch_xi_request_wire( + &mut state, + &mut peer, + 1, + 10, + &[0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0], + ); + assert_eq!(master.len(), 32); + assert_eq!(master[12], 2, "master has two valuators"); + let mut body = vec![0; 8]; + body.extend_from_slice(&u32::from(physical).to_le_bytes()); + let physical_wire = dispatch_xi_request_wire(&mut state, &mut peer, 2, 10, &body); + assert_eq!(physical_wire.len(), 32); + assert_eq!( + physical_wire[12], 4, + "physical pointer keeps four valuators" + ); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_get_device_control_uses_class_axis_count() { + // Kills: keep GetDeviceControl's fixed four-axis resolution block; + // Xorg sizes and serializes it from v->numAxes (Xi/getdctl.c:192-197, + // :219). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 34, &[1, 0, 2, 0]); + assert_eq!(wire.len(), 64, "reply + 2-axis resolution state"); + assert_eq!(u32::from_le_bytes(wire[36..40].try_into().unwrap()), 2); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_set_device_valuators_rejects_axis_after_master_shape() { + // Kills: validate SetDeviceValuators against four global axes instead + // of the master's two current axes; Xorg compares against + // dev->valuator->numAxes (Xi/setdval.c:110-117). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + let mut body = vec![2, 2, 1, 0]; // device 2, first axis 2, one value + body.extend_from_slice(&0i32.to_le_bytes()); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 33, &body); + assert_eq!(wire[0], 0, "X error"); + assert_eq!(wire[1], x11::error::BAD_VALUE); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_set_device_valuators_xtest_pointer_is_bad_match() { + // Kills: accept valid-axis writes on the XTEST pointer. Xorg returns + // BadMatch for IsXTestDevice (Xi/setdval.c:113-114), before the + // range check (:116), so an out-of-range write is BadMatch too; the + // master pointer (id 2) is still accepted. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut body = vec![4, 0, 1, 0]; // XTEST pointer, axis 0, one value + body.extend_from_slice(&7i32.to_le_bytes()); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 33, &body); + assert_eq!(wire[0], 0, "X error"); + assert_eq!(wire[1], x11::error::BAD_MATCH); + body[1] = 9; // out of range + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 33, &body); + assert_eq!(wire[1], x11::error::BAD_MATCH); + let mut ok = vec![2, 0, 1, 0]; + ok.extend_from_slice(&7i32.to_le_bytes()); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 33, &ok); + assert_eq!(wire[0], 1, "master pointer still accepted"); +} + +#[test] +fn xi1_shape_sweep_change_pointer_device_matches_xorg_bad_device() { + // Kills: keep axis-based ChangePointerDevice handling. Xorg's + // ProcXChangePointerDevice returns BadDevice unconditionally after + // request-size validation (Xi/chgptr.c:92-98). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 12, &[0, 1, 2, 0]); + assert_eq!(wire[0], 0, "X error"); + assert_eq!(wire[1], XI1_ERROR_BAD_DEVICE); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_change_device_control_rejects_axis_after_master_shape() { + // Kills: validate ChangeDeviceControl against four global axes; + // Xorg checks first_valuator + num_valuators against the device's + // valuator class (Xi/chgdctl.c:157-160). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + let mut body = vec![1, 0, 2, 0, 1, 0, 12, 0, 2, 1, 0, 0]; + body.extend_from_slice(&0i32.to_le_bytes()); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 35, &body); + assert_eq!(wire[0], 0, "X error"); + assert_eq!(wire[1], x11::error::BAD_VALUE); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_physical_device_control_keeps_four_axes() { + // Kills: apply the two-axis CorePointer shape to a physical device + // whose current XI classes retain four valuators. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical = state.xi_register_source(&crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(0x51ab), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + pointer: true, + ..Default::default() + }, + name: "physical-control-mouse".into(), + device_node: "/dev/input/event-control-shape".into(), + sysname: "event-control-shape".into(), + vendor_id: 1, + product_id: 4, + is_touchpad: false, + config: Default::default(), + })[0]; + let before = xi_query_side_effect_snapshot(&state, 1); + let wire = dispatch_xi_request_wire( + &mut state, + &mut peer, + 1, + 34, + &[1, 0, u8::try_from(physical).unwrap(), 0], + ); + assert_eq!(wire.len(), 88, "reply + 4-axis resolution state"); + assert_eq!(u32::from_le_bytes(wire[36..40].try_into().unwrap()), 4); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_core_pointer_mapping_uses_master_button_count() { + // Kills: keep core Get/SetPointerMapping at the former seven-button + // constant; Xorg reads PickPointer(client)->button->numButtons + // (dix/devices.c:1904-1912, 1994-2016). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let before = xi_query_side_effect_snapshot(&state, 1); + let get = dispatch_wire_request(&mut state, &mut peer, 1, 117, 0, &[]); + assert_eq!(get[1], 10, "CorePointer has ten buttons"); + assert_eq!(&get[32..42], &(1..=10).collect::>()); + + let map: Vec = (1..=10).collect(); + let mut body = map.clone(); + body.resize(12, 0); + let set = dispatch_wire_request(&mut state, &mut peer, 2, 116, 10, &body); + assert!( + set.len() >= 64, + "MappingNotify plus SetPointerMapping reply" + ); + assert_eq!(set[set.len() - 32], 1, "SetPointerMapping reply"); + let after = dispatch_wire_request(&mut state, &mut peer, 3, 117, 0, &[]); + assert_eq!(after[1], 10); + assert_eq!(&after[32..42], &map); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_shape_sweep_fake_input_validates_current_master_buttons() { + // Kills: branch on device ID (master always ten buttons) instead of + // checking the class currently copied onto master 2. Xorg validates + // details against dev->button->numButtons (Xext/xtest.c:401-409). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical = state.xi_register_source(&crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(0x51ac), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + pointer: true, + ..Default::default() + }, + name: "master-shape-mouse".into(), + device_node: "/dev/input/event-master-shape".into(), + sysname: "event-master-shape".into(), + vendor_id: 1, + product_id: 5, + is_touchpad: false, + config: Default::default(), + })[0]; + assert!(state.xi_record_last_slave(2, physical)); + assert_eq!(state.xi_devices.device(2).unwrap().class_sourceid, physical); + assert_eq!( + state + .xi_devices + .device(2) + .unwrap() + .class_shape + .button_count(), + 7 + ); + let before = xi_query_side_effect_snapshot(&state, 1); + + let mut body = vec![0; 32]; + body[0] = crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; + body[1] = 8; + body[31] = 2; + let wire = dispatch_wire_request(&mut state, &mut peer, 1, 146, 2, &body); + assert_eq!(wire[0], 0, "X error"); + assert_eq!(wire[1], x11::error::BAD_VALUE); + assert_eq!(u32::from_le_bytes(wire[4..8].try_into().unwrap()), 8); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xi1_button_map_prefix_preserves_the_unsupplied_tail() { + // Kills: replacing the entire stored map with a short request instead + // of Xorg's prefix memcpy (`dix/inpututils.c:72-80`). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let stable_before = xi_query_side_effect_snapshot(&state, 1); + let custom: Vec = (11..=20).collect(); + let mut full = vec![4, 10, 0, 0]; + full.extend_from_slice(&custom); + let first = dispatch_xi_request_wire(&mut state, &mut peer, 1, 29, &full); + assert_eq!(first[0], 1); + assert_eq!(first[8], 0, "full custom map succeeds"); + + let mut prefix = vec![4, 1, 0, 0, 1]; + prefix.resize(8, 0); + let second = dispatch_xi_request_wire(&mut state, &mut peer, 2, 29, &prefix); + assert_eq!(second[0], 1); + assert_eq!(second[8], 0, "one-entry prefix succeeds"); + let get = dispatch_xi_request_wire(&mut state, &mut peer, 3, 28, &[4, 0, 0, 0]); + assert_eq!(get[8], 10); + assert_eq!(&get[32..42], &[1, 12, 13, 14, 15, 16, 17, 18, 19, 20]); + assert_eq!( + state.xi1_button_map.get(&4), + Some(&vec![1, 12, 13, 14, 15, 16, 17, 18, 19, 20]) + ); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), stable_before); +} + +#[test] +fn t6_xi1_select_extension_event_populates_client_class_set() { + // Selecting a DevicePropertyNotify class for XTEST pointer 4 stores + // the exact wire-form class in `xi1_event_classes`. Classes the + // server does not yet implement (e.g. a hypothetical XI1 + // motion-event class 0x04XX with the wrong low byte) are + // silently dropped — Xorg's behaviour. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Body: window=ROOT, count=2, [DevicePropertyNotify(XTEST pointer), + // motion-event(XTEST pointer)]. The motion-event class has low byte + // != 82 so must be dropped. + let unknown_class: u32 = ((crate::xinput::DEVICEID_XTEST_POINTER as u32) << 8) | 70; // bogus DeviceMotion class + let body = xi1_select_extension_event_body( + ROOT_WINDOW.0, + &[XI1_DEV_PROP_CLASS_XTEST_POINTER, unknown_class], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + let client = state.clients.get(&1).expect("client installed"); + assert!( + client + .xi1_event_classes + .contains(&XI1_DEV_PROP_CLASS_XTEST_POINTER), + "DevicePropertyNotify class stored verbatim" + ); + assert!( + !client.xi1_event_classes.contains(&unknown_class), + "unsupported XI1 event classes dropped" + ); + assert_eq!( + client.xi1_event_classes.len(), + 1, + "exactly one class accepted" + ); +} + +#[test] +fn t6_xi1_select_extension_event_replaces_classes_for_device() { + // Xorg's SelectExtensionEvent REPLACES the prior selection for + // every deviceid mentioned in the request. So a follow-up call + // with an empty class list for the same device drops the entry. + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Step 1: select DevicePropertyNotify for XTEST pointer 4. + let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_XTEST_POINTER]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + assert!( + state + .clients + .get(&1) + .unwrap() + .xi1_event_classes + .contains(&XI1_DEV_PROP_CLASS_XTEST_POINTER) + ); + // Step 2: re-select with a class list that names XTEST pointer 4 but + // requests a class we don't handle. The replacement must clear + // the prior device-4 entry. + let unknown_class_dev4: u32 = ((crate::xinput::DEVICEID_XTEST_POINTER as u32) << 8) | 70; + let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[unknown_class_dev4]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + let client = state.clients.get(&1).unwrap(); + assert!( + client.xi1_event_classes.is_empty(), + "replacement with no supported classes clears XTEST pointer selection" + ); +} + +#[test] +fn t6_xi1_select_extension_event_other_device_preserved() { + // Replacement is scoped to the deviceids mentioned in the new + // request. Pre-select XTEST pointer 4 + XTEST keyboard 5; re-select + // only XTEST pointer 4. The keyboard entry must survive (Xorg's + // per-device replace). + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let class_dev5 = XI1_DEV_PROP_CLASS_XTEST_KEYBOARD; + // Seed via the dispatch — two classes, two devices. + let body = xi1_select_extension_event_body( + ROOT_WINDOW.0, + &[XI1_DEV_PROP_CLASS_XTEST_POINTER, class_dev5], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + // Re-select only XTEST pointer 4 (with the supported class). The + // keyboard entry must remain — its deviceid wasn't named here. + let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_XTEST_POINTER]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + let client = state.clients.get(&1).unwrap(); + assert!( + client + .xi1_event_classes + .contains(&XI1_DEV_PROP_CLASS_XTEST_POINTER), + "XTEST pointer selection re-installed" + ); + assert!( + client.xi1_event_classes.contains(&class_dev5), + "XTEST keyboard selection untouched" + ); +} + +#[test] +fn xi1_get_selected_extension_events_reports_this_and_all_clients() { + let mut state = ServerState::new(); + let mut peer1 = install_client(&mut state, 1); + let _peer2 = install_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let motion_dev4: u32 = ((crate::xinput::DEVICEID_XTEST_POINTER as u32) << 8) | 70; + let property_dev5 = XI1_DEV_PROP_CLASS_XTEST_KEYBOARD; + + let body = xi1_select_extension_event_body( + ROOT_WINDOW.0, + &[XI1_DEV_PROP_CLASS_XTEST_POINTER, motion_dev4], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + let body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[property_dev5]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(2), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + + let body = ROOT_WINDOW.0.to_le_bytes(); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header_for_body(7, &body), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer1); + assert_eq!(wire.len(), 32 + 5 * 4); + assert_eq!(wire[1], 7, "XI1 reply subtype"); + assert_eq!(u32::from_le_bytes(wire[4..8].try_into().unwrap()), 5); + assert_eq!(u16::from_le_bytes(wire[8..10].try_into().unwrap()), 2); + assert_eq!(u16::from_le_bytes(wire[10..12].try_into().unwrap()), 3); + let classes: Vec = wire[32..] + .chunks_exact(4) + .map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap())) + .collect(); + assert_eq!( + classes, + vec![ + motion_dev4, + XI1_DEV_PROP_CLASS_XTEST_POINTER, + motion_dev4, + XI1_DEV_PROP_CLASS_XTEST_POINTER, + property_dev5, + ], + "this-client list precedes the all-clients list" + ); +} + +#[test] +fn xi_config_completion_t6_xi1_change_delivers_device_property_notify() { + // End-to-end: a client SelectExtensionEvent(DevicePropertyNotify + // for XTEST pointer 4), then someone (here, the same client via XI2 + // XIChangeProperty minor 57) writes a property. The 32-byte + // XI1 event must land on the selecting client with the right + // type byte, atom, and deviceid. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let physical_class = (u32::from(TEST_PHYSICAL_POINTER_ID) << 8) | 82; + // Subscribe via SelectExtensionEvent only (no XI2 mask), so the + // ONLY event on the wire is the XI1 one. + let select_body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[physical_class]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &select_body), + &select_body, + ) + .unwrap(); + // Drain anything the select produced (must be empty — minor 6 + // is event-only, no reply). + assert!( + read_all_available(&mut peer).is_empty(), + "SelectExtensionEvent emits no reply" + ); + + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 2, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "exactly one 32-byte XI1 event"); + let ev = find_xi1_device_property_notify(&wire).expect("XI1 event present"); + assert_eq!(ev[0], 82, "type = XI_FIRST_EVENT(66) + 16"); + assert_eq!(ev[1], 0, "state = PropertyNewValue"); + assert_eq!( + u32::from_le_bytes([ev[8], ev[9], ev[10], ev[11]]), + tap_atom, + "atom" + ); + assert_eq!( + ev[31], + u8::try_from(TEST_PHYSICAL_POINTER_ID).unwrap(), + "deviceid (last byte)" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn t6_xi1_delete_property_delivers_event_with_state_one() { + // The delete path (XI2 minor 58) must also fan out an XI1 + // event, with `state = 1` (PropertyDelete). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + let select_body = + xi1_select_extension_event_body(ROOT_WINDOW.0, &[XI1_DEV_PROP_CLASS_XTEST_POINTER]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &select_body), + &select_body, + ) + .unwrap(); + let _ = read_all_available(&mut peer); + + let mut body = Vec::new(); + body.extend_from_slice(&4u16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header(58), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "exactly one 32-byte XI1 event"); + let ev = find_xi1_device_property_notify(&wire).expect("XI1 event present"); + assert_eq!(ev[1], 1, "state = PropertyDelete"); + assert_eq!( + u32::from_le_bytes([ev[8], ev[9], ev[10], ev[11]]), + 100, + "atom" + ); + assert_eq!(ev[31], 4, "deviceid"); +} + +#[test] +fn xi_config_completion_t6_xi1_unselected_client_gets_nothing() { + // A client that did NOT call SelectExtensionEvent must not + // receive an XI1 DevicePropertyNotify — even if the property + // change happens on the device it cares about. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + // No SelectExtensionEvent, no XI2 mask. + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "unselected client receives nothing" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_t6_xi1_wrong_device_class_does_not_match() { + // Selecting DevicePropertyNotify for XTEST keyboard 5 must NOT route a + // physical pointer property change to that client (parallel to the + // XI2 same-property-different-device test in T5). + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let class_dev5 = XI1_DEV_PROP_CLASS_XTEST_KEYBOARD; + let select_body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[class_dev5]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &select_body), + &select_body, + ) + .unwrap(); + let _ = read_all_available(&mut peer); + + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 2, + xi2_header(57), + &body, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "device-5 selection must not see physical pointer events" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn t6_xi1_select_extension_event_short_body_bad_length() { + // A body shorter than the 8-byte fixed header must yield + // BadLength. The error reply uses minor=6 and major=137. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Only 4 bytes — missing the count/pad portion. + let body = vec![0u8; 4]; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "single 32-byte X error reply"); + assert_eq!(wire[0], 0, "X error opcode"); + assert_eq!(wire[1], 16, "BadLength code"); +} + +#[test] +fn t6_xi1_select_extension_event_truncated_class_list_bad_length() { + // count = 2 but only one class on the wire → BadLength. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = Vec::new(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); // count = 2 + body.extend_from_slice(&0u16.to_le_bytes()); // pad + body.extend_from_slice(&XI1_DEV_PROP_CLASS_XTEST_POINTER.to_le_bytes()); // only one class + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &body), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire[0], 0, "X error opcode"); + assert_eq!(wire[1], 16, "BadLength"); +} + +#[test] +fn xi_config_completion_t6_dual_selection_delivers_each_event_path() { + // A client that selected `XI_PropertyEvent` via XI2's + // `xi2_masks` AND a `DevicePropertyNotify` class via XI1's + // `SelectExtensionEvent` receives TWO independent events from + // a single property write — one per protocol path. The fan-outs + // do not deduplicate across paths because a client may be + // running adapter code that bridges both (e.g. a GTK app that + // uses XI2 directly plus a legacy libXi consumer in the same + // process). Pins the no-cross-path-dedup invariant. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let physical_class = (u32::from(TEST_PHYSICAL_POINTER_ID) << 8) | 82; + // XI2 selection. + select_xi2_property_event_on_root(&mut state, 1, TEST_PHYSICAL_POINTER_ID); + // XI1 selection. + let select_body = xi1_select_extension_event_body(ROOT_WINDOW.0, &[physical_class]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(6, &select_body), + &select_body, + ) + .unwrap(); + assert!( + read_all_available(&mut peer).is_empty(), + "SelectExtensionEvent emits no reply" + ); + + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 2, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 64, "two 32-byte events (XI2 + XI1)"); + // Both events must be present — anchor by type byte. + let xi2 = find_xi2_property_event(&wire).expect("XI2 GenericEvent present"); + assert_eq!(xi2[0], 35, "GenericEvent"); + assert_eq!(u16::from_le_bytes([xi2[8], xi2[9]]), 12, "evtype = 12"); + assert_eq!( + u16::from_le_bytes([xi2[10], xi2[11]]), + TEST_PHYSICAL_POINTER_ID, + "deviceid" + ); + let xi1 = find_xi1_device_property_notify(&wire).expect("XI1 event present"); + assert_eq!(xi1[0], 82, "XI_FIRST_EVENT + 16"); + assert_eq!( + xi1[31], + u8::try_from(TEST_PHYSICAL_POINTER_ID).unwrap(), + "XI1 deviceid (last byte)" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_readonly_descriptor_yields_bad_access() { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, _) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let properties_before = xi_property_snapshot(&state); + // `…Enabled Default` is the ReadOnly companion (Access::ReadOnly). + let default_atom = state + .atoms + .intern("libinput Tapping Enabled Default", false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + // Capture the seeded value so we can confirm the write was + // rejected and the registry was not mutated. + let before = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .get(&AtomId(default_atom)) + .cloned() + .expect("default seeded"); + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + default_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 2, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, 10, 2, 57); + + let after = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .get(&AtomId(default_atom)) + .cloned() + .expect("default still present"); + assert_eq!(before.data, after.data, "read-only value unchanged"); + assert_eq!(xi_property_snapshot(&state), properties_before); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +// ----------------------------------------------------------------- +// XI 1.x `SendExtensionEvent` (minor 31) — dispatch + specials. +// ----------------------------------------------------------------- + +/// Build an `xSendExtensionEventReq` body (the bytes after the +/// 4-byte X request header) for a single 32-byte event payload and +/// a single XEventClass. +fn xi1_send_extension_event_body( + destination: u32, + deviceid: u8, + propagate: bool, + event: &[u8; 32], + classes: &[u32], +) -> Vec { + let mut body = Vec::with_capacity(12 + 32 + classes.len() * 4); + body.extend_from_slice(&destination.to_le_bytes()); // 0..4 destination + body.push(deviceid); // 4 deviceid + body.push(u8::from(propagate)); // 5 propagate + #[allow(clippy::cast_possible_truncation)] + let count = classes.len() as u16; + body.extend_from_slice(&count.to_le_bytes()); // 6..8 count + body.push(1); // 8 num_events + body.extend_from_slice(&[0u8; 3]); // 9..12 pad + body.extend_from_slice(event); // 12..44 one xEvent + for c in classes { + body.extend_from_slice(&c.to_le_bytes()); + } + body +} + +/// `length_units` covering the 4-byte X header + the body produced +/// by [`xi1_send_extension_event_body`] for a single 32-byte event: +/// `4 + 8*num_events + class_count` = `4 + 8 + classes.len()`. +#[allow(clippy::cast_possible_truncation)] +fn xi1_send_extension_event_header(class_count: usize) -> RequestHeader { + RequestHeader { + opcode: 131, + data: 31, + length_units: 12 + class_count as u32, + } +} + +/// 32-byte XI1 DeviceKeyPress wire template — only the type byte +/// matters for these tests; everything else is zero. +fn xi1_device_key_press_event(first_event: u8) -> [u8; 32] { + let mut ev = [0u8; 32]; + ev[0] = first_event + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; + ev +} + +/// XI1 _noExtensionEvent code (9) — see /usr/include/X11/extensions/XI.h. +/// `noextensioneventclass = (deviceid << 8) | 9` is the sentinel +/// Xlib's `NoExtensionEvent` macro produces. Xorg +/// `CreateMaskFromList` maps it to a per-device mask of 0, which +/// short-circuits `DeliverToWindowOwner`'s filter check +/// (`filter == CantBeFiltered`) and so the destination window's +/// CREATOR receives the event regardless of any selection. +const XI1_NO_EXTENSION_EVENT_OFFSET: u8 = 9; + +fn seed_test_window(state: &mut ServerState, owner: u32, xid: u32) { + state.resources.create_window( + ClientId(owner), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); +} + +#[test] +fn xi1_send_extension_event_with_noextensioneventclass_delivers_to_window_creator() { + // XSendExtensionEvent test 1 (xts5 XI/SendExtensionEvent.m:124): + // a client creates a window and SendExtensionEvent's an XI1 + // event to it with `event_list = &noextensioneventclass`. The + // expected behaviour mirrors Xorg `Xi/sendexev.c::SendEvent` → + // `dix/events.c::DeliverToWindowOwner`: when the per-device + // mask is empty (i.e. `noextensioneventclass`), the owner + // receives the event unconditionally. Without this path xts5 + // SendExtensionEvent 1–4 / 11 / 12 / 14 / 16 all fail with + // "Expected event (DeviceKeyPress) not received". + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let win_xid = 0x4000_0001u32; + seed_test_window(&mut state, 1, win_xid); + + let no_class = (4u32 << 8) | u32::from(XI1_NO_EXTENSION_EVENT_OFFSET); + let event = xi1_device_key_press_event(crate::server::XI_FIRST_EVENT); + let body = xi1_send_extension_event_body(win_xid, 4, false, &event, &[no_class]); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi1_send_extension_event_header(1), + &body, + ) + .unwrap(); + + let wire = read_all_available(&mut peer); + assert_eq!( + wire.len(), + 32, + "exactly one 32-byte XI1 event delivered to creator" + ); + assert_eq!( + wire[0], + (crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET) | 0x80, + "type byte is DeviceKeyPress with send_event (0x80) bit set" + ); +} + +#[test] +fn xi1_send_extension_event_pointer_window_resolves_to_sprite() { + // dest = 0 (PointerWindow) must resolve to the window currently + // containing the sprite (Xorg SendEvent:2915 — `pWin = spriteWin`). + // With the sprite at (0,0) on the root and a 100x100 child + // window covering the origin, the child's creator gets the + // event when noextensioneventclass is used. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let win_xid = 0x4000_0002u32; + seed_test_window(&mut state, 1, win_xid); + // Map the window so `direct_child_at` finds it. + if let Some(w) = state.resources.window_mut(ResourceId(win_xid)) { + w.map_state = crate::resources::MapState::Viewable; + } + state.pointer_root = (10, 10); + + let no_class = (4u32 << 8) | u32::from(XI1_NO_EXTENSION_EVENT_OFFSET); + let event = xi1_device_key_press_event(crate::server::XI_FIRST_EVENT); + let body = xi1_send_extension_event_body(0, 4, false, &event, &[no_class]); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi1_send_extension_event_header(1), + &body, + ) + .unwrap(); + + let wire = read_all_available(&mut peer); + assert_eq!( + wire.len(), + 32, + "PointerWindow special resolves to sprite, creator gets event" + ); +} + +#[test] +fn xi1_send_extension_event_input_focus_resolves_to_device_focus() { + // dest = 1 (InputFocus) must resolve to the device's focus + // window when the focus is a real window (not PointerRoot / + // None) — Xorg SendEvent:2917-2942. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let win_xid = 0x4000_0003u32; + seed_test_window(&mut state, 1, win_xid); + state.xi1_device_focus.insert( + 4, + crate::server::Xi1DeviceFocus { + focus: win_xid, + revert_to: 0, + time: 0, + }, + ); + + let no_class = (4u32 << 8) | u32::from(XI1_NO_EXTENSION_EVENT_OFFSET); + let event = xi1_device_key_press_event(crate::server::XI_FIRST_EVENT); + let body = xi1_send_extension_event_body(1, 4, false, &event, &[no_class]); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi1_send_extension_event_header(1), + &body, + ) + .unwrap(); + + let wire = read_all_available(&mut peer); + assert_eq!( + wire.len(), + 32, + "InputFocus special resolves to device-focus window, creator gets event" + ); +} + +#[test] +fn xi1_send_extension_event_propagate_walks_to_selecting_ancestor() { + // xts5 XI/SendExtensionEvent purpose 11: 3-level window + // hierarchy, only the top has a selection for `dbpc`, send + // to bottom with propagate=True. Walk must reach the top. + // Mirrors Xorg SendEvent's `for (; pWin; pWin = pWin->parent)` + // loop (xserver.git Xi/exevents.c:2952-2962). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let grandparent_xid = 0x4000_0010u32; + let parent_xid = 0x4000_0011u32; + let child_xid = 0x4000_0012u32; + seed_test_window(&mut state, 2, grandparent_xid); + state.resources.create_window( + ClientId(2), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(parent_xid), + parent: ResourceId(grandparent_xid), + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(2), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(child_xid), + parent: ResourceId(parent_xid), + x: 0, + y: 0, + width: 25, + height: 25, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + // Client 1 selects DeviceButtonPress (offset 3) on the + // GRANDPARENT only. Neither parent nor child have any + // selectors. With propagate=True, the dispatch must reach + // grandparent. + let dbpc = (4u32 << 8) + | u32::from(crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET); + if let Some(c) = state.clients.get_mut(&1) { + c.xi1_window_event_classes + .entry(ResourceId(grandparent_xid)) + .or_default() + .insert(dbpc); + } + + let mut event = [0u8; 32]; + event[0] = crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; + let body = xi1_send_extension_event_body(child_xid, 4, true, &event, &[dbpc]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi1_send_extension_event_header(1), + &body, + ) + .unwrap(); + + let wire = read_all_available(&mut peer); + assert_eq!( + wire.len(), + 32, + "propagate=True walks ancestors, grandparent selector receives event" + ); + assert_eq!( + wire[0], + (crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET) | 0x80, + "type byte is DeviceButtonPress + send_event" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs new file mode 100644 index 000000000..dc4d834c5 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs @@ -0,0 +1,3715 @@ +use super::*; +use crate::xinput::XI2_DEVICE_CHANGED_MASK; +use yserver_protocol::x11::AtomId; + +#[test] +fn xi_get_focus_returns_real_focus_window() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Master keyboard (device 3) focused on a real window. The master + // keyboard's focus IS the core focus (Xorg: `inputInfo.keyboard-> + // focus`, which ProcSetInputFocus and ProcXIGetFocus share). + let win = 0x4000_0005u32; + state.core_focus = crate::server::CoreFocus { + raw: win, + revert_to: 0, + time: 0, + }; + // XIGetFocus { deviceid:CARD16=3 } + pad. + let header = RequestHeader { + opcode: 137, + data: 50, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[3u8, 0, 0, 0], + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert_eq!( + bytes.len(), + 32, + "XIGetFocus reply is 32 bytes: {bytes:02x?}" + ); + assert_eq!(bytes[0], 1, "X_Reply"); + assert_eq!(&bytes[8..12], &win.to_le_bytes(), "focus window @ byte 8"); +} + +#[test] +fn xi_get_focus_invalid_device_returns_bad_device() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // deviceid 0 = XIAllDevices: not a specific device → BadDevice. + let header = RequestHeader { + opcode: 137, + data: 50, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[0u8, 0, 0, 0], + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert!(bytes.len() >= 32, "expected error reply: {bytes:02x?}"); + assert_eq!(bytes[0], 0, "error packet"); + assert_eq!(bytes[1], XI1_ERROR_BAD_DEVICE, "BadDevice"); + assert_eq!(&bytes[8..10], &50u16.to_le_bytes(), "minor echoed"); +} + +// ── XIWarpPointer / XISetFocus / XIChangeHierarchy / XISelectEvents ── +// +// Expected values below are Xvfb 21.1.24 captures (raw-socket probe, +// little-endian client unless noted), cross-checked against +// Xi/xiwarppointer.c, Xi/xisetdevfocus.c, Xi/xichangehierarchy.c and +// Xi/xiselectev.c. + +/// Send one XInput request (major 137) from client 1 and return what +/// the client received. +fn send_xi_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut UnixStream, + minor: u8, + body: &[u8], +) -> Vec { + let header = RequestHeader { + opcode: 137, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }; + handle_xi2_request( + state, + backend, + None, + ClientId(1), + SequenceNumber(1), + header, + body, + ) + .expect("xi request"); + read_all_available(peer) +} + +fn assert_xi_error(bytes: &[u8], code: u8, value: u32, minor: u16) { + assert_eq!(bytes.len(), 32, "one error packet: {bytes:02x?}"); + assert_eq!(bytes[0], 0, "error packet: {bytes:02x?}"); + assert_eq!(bytes[1], code, "error code: {bytes:02x?}"); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + value, + "errorValue: {bytes:02x?}" + ); + assert_eq!( + u16::from_le_bytes(bytes[8..10].try_into().unwrap()), + minor, + "minor opcode: {bytes:02x?}" + ); + assert_eq!(bytes[10], XI2_MAJOR_OPCODE, "major opcode"); +} + +/// A mapped 100×100 child of the root at (100, 100), owned by client 1. +fn seed_mapped_window_at_100(state: &mut ServerState, xid: u32) { + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x: 100, + y: 100, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(xid)); +} + +fn fp1616(v: f64) -> i32 { + #[allow(clippy::cast_possible_truncation)] + let raw = (v * 65536.0).round() as i32; + raw +} + +#[allow(clippy::too_many_arguments)] +fn xi_warp_body( + src: u32, + dst: u32, + src_x: f64, + src_y: f64, + src_w: u16, + src_h: u16, + dst_x: f64, + dst_y: f64, + deviceid: u16, +) -> Vec { + let mut b = Vec::with_capacity(32); + b.extend_from_slice(&src.to_le_bytes()); + b.extend_from_slice(&dst.to_le_bytes()); + b.extend_from_slice(&fp1616(src_x).to_le_bytes()); + b.extend_from_slice(&fp1616(src_y).to_le_bytes()); + b.extend_from_slice(&src_w.to_le_bytes()); + b.extend_from_slice(&src_h.to_le_bytes()); + b.extend_from_slice(&fp1616(dst_x).to_le_bytes()); + b.extend_from_slice(&fp1616(dst_y).to_le_bytes()); + b.extend_from_slice(&deviceid.to_le_bytes()); + b.extend_from_slice(&[0, 0]); + b +} + +#[allow(clippy::too_many_arguments)] +fn send_core_warp( + state: &mut ServerState, + backend: &mut RecordingBackend, + src: u32, + dst: u32, + src_x: i16, + src_y: i16, + src_w: u16, + src_h: u16, + dst_x: i16, + dst_y: i16, +) { + let mut b = Vec::with_capacity(20); + b.extend_from_slice(&src.to_le_bytes()); + b.extend_from_slice(&dst.to_le_bytes()); + b.extend_from_slice(&src_x.to_le_bytes()); + b.extend_from_slice(&src_y.to_le_bytes()); + b.extend_from_slice(&src_w.to_le_bytes()); + b.extend_from_slice(&src_h.to_le_bytes()); + b.extend_from_slice(&dst_x.to_le_bytes()); + b.extend_from_slice(&dst_y.to_le_bytes()); + process_request( + state, + backend, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 41, + data: 0, + length_units: 6, + }, + &b, + None, + ) + .expect("WarpPointer"); +} + +#[test] +fn xi_warp_pointer_moves_to_truncated_fp1616_destination() { + // Xvfb: XIWarpPointer(dst=root, 10.75, 20.25) → pointer (10, 20); + // then relative (-0.5, -1.5) → (10, 19); relative (+0.99, +2.5) + // → (10, 21). ProcXIWarpPointer stores the FP16.16 values in + // ints, so the fraction truncates toward zero. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = xi_warp_body(0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 10.75, 20.25, 2); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert!(bytes.is_empty(), "XIWarpPointer has no reply: {bytes:02x?}"); + assert_eq!(backend.warped_to, Some((10, 20))); + + state.pointer_root = (10, 20); + let body = xi_warp_body(0, 0, 0.0, 0.0, 0, 0, -0.5, -1.5, 2); + let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_eq!(backend.warped_to, Some((10, 19))); + + state.pointer_root = (10, 19); + let body = xi_warp_body(0, 0, 0.0, 0.0, 0, 0, 0.99, 2.5, 2); + let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_eq!(backend.warped_to, Some((10, 21))); +} + +#[test] +fn xi_warp_pointer_to_window_and_clamped_to_the_screen() { + // Xvfb (1024×768): dst=W(100,100) (5, 6) → (105, 106); + // (-5.5, -6.5) → (95, 94); dst=root (5000, 5000) → (w-1, h-1); + // (-3, -3) → (0, 0). The test root is 800×600. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + const W: u32 = 0x0040_0001; + seed_mapped_window_at_100(&mut state, W); + for (dx, dy, want) in [(5.0, 6.0, (105, 106)), (-5.5, -6.5, (95, 94))] { + let body = xi_warp_body(0, W, 0.0, 0.0, 0, 0, dx, dy, 2); + let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_eq!(backend.warped_to, Some(want), "dst=W ({dx}, {dy})"); + } + for (dx, dy, want) in [ + (5000.0, 5000.0, (799, 599)), + (800.0, 600.0, (799, 599)), + (-3.0, -3.0, (0, 0)), + ] { + let body = xi_warp_body(0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, dx, dy, 2); + let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_eq!(backend.warped_to, Some(want), "dst=root ({dx}, {dy})"); + } +} + +#[test] +fn xi_warp_pointer_rejects_everything_but_the_master_pointer() { + // ProcXIWarpPointer: BadDevice unless the device is a master + // pointer or a floating slave (yserver has no floating slaves). + // errorValue = deviceid. Xvfb: devices 0,1,3,4,5,99 → BadDevice. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for dev in [0u16, 1, 3, 4, 5, 99] { + let body = xi_warp_body(0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 5.0, 5.0, dev); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, u32::from(dev), 41); + } + // The device is checked before the windows. + let body = xi_warp_body(0, 0x00de_ad00, 0.0, 0.0, 0, 0, 5.0, 5.0, 3); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, 3, 41); + assert_eq!(backend.warped_to, None, "no rejected request may warp"); +} + +#[test] +fn xi_warp_pointer_bad_windows_report_dst_before_src() { + // Xvfb: dst bad → BadWindow(dst); src bad → BadWindow(src); both + // bad → BadWindow(dst). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = xi_warp_body(0, 0x00de_ad00, 0.0, 0.0, 0, 0, 5.0, 5.0, 2); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00de_ad00, 41); + let body = xi_warp_body(0x00be_ef00, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 5.0, 5.0, 2); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00be_ef00, 41); + let body = xi_warp_body(0x00be_ef00, 0x00de_ad00, 0.0, 0.0, 0, 0, 5.0, 5.0, 2); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00de_ad00, 41); + assert_eq!(backend.warped_to, None); +} + +#[test] +fn xi_warp_pointer_source_rectangle_follows_xorgs_xi_arithmetic() { + // Xorg keeps two copies of the source-rectangle test. The XI one + // compares the right edge against 0 instead of the pointer x + // (`winX + src_x + src_width < 0`), so with W at (100,100) 100×100 + // and src rect (0,0,10,10): + // pointer (160,105): XIWarpPointer WARPS, core WarpPointer doesn't; + // pointer (105,160): neither warps (the bottom edge is checked); + // pointer (105,110): XI warps (bottom edge inclusive). + // Both also require the pointer to be visible in the source window: + // pointer (50,50), src rect (-100,-100,0,0): no warp. + // The src coordinates truncate: pointer (104,104) with src_x 4.9 + // warps, with 5.0 doesn't; pointer (99,99) with -0.9 doesn't. + const W: u32 = 0x0040_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_mapped_window_at_100(&mut state, W); + let cases = [ + ((160_i16, 105_i16), (0.0, 0.0, 10_u16, 10_u16), true), + ((105, 160), (0.0, 0.0, 10, 10), false), + ((105, 110), (0.0, 0.0, 10, 10), true), + ((50, 50), (-100.0, -100.0, 0, 0), false), + ((104, 104), (4.9, 4.9, 0, 0), true), + ((104, 104), (5.0, 5.0, 0, 0), false), + ((99, 99), (-0.9, -0.9, 0, 0), false), + ]; + for (pointer, (sx, sy, sw, sh), warps) in cases { + let mut backend = RecordingBackend::new(); + state.pointer_root = pointer; + let body = xi_warp_body(W, ROOT_WINDOW.0, sx, sy, sw, sh, 300.0, 300.0, 2); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert!(bytes.is_empty(), "no error: {bytes:02x?}"); + assert_eq!( + backend.warped_to, + warps.then_some((300, 300)), + "pointer {pointer:?} src ({sx},{sy},{sw},{sh})" + ); + } + // src = root: always inside. + let mut backend = RecordingBackend::new(); + state.pointer_root = (50, 50); + let body = xi_warp_body(ROOT_WINDOW.0, ROOT_WINDOW.0, 0.0, 0.0, 0, 0, 70.0, 70.0, 2); + let _ = send_xi_request(&mut state, &mut backend, &mut peer, 41, &body); + assert_eq!(backend.warped_to, Some((70, 70))); +} + +#[test] +fn core_warp_pointer_source_rectangle_matches_xorg() { + // ProcWarpPointer (Xvfb): W at (100,100) 100×100, src rect + // (0,0,10,10): pointer (160,105) → no warp; (110,105) → warp (the + // right edge is inclusive: `winX + srcX + srcWidth < x`); + // (50,50) with src rect (-100,-100,0,0) → no warp (the pointer is + // not visible in W). Bad windows report dst before src. + const W: u32 = 0x0040_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_mapped_window_at_100(&mut state, W); + for (pointer, (sx, sy, sw, sh), warps) in [ + ((160, 105), (0, 0, 10, 10), false), + ((110, 105), (0, 0, 10, 10), true), + ((105, 110), (0, 0, 10, 10), true), + ((50, 50), (-100, -100, 0, 0), false), + ] { + let mut backend = RecordingBackend::new(); + state.pointer_root = pointer; + send_core_warp( + &mut state, + &mut backend, + W, + ROOT_WINDOW.0, + sx, + sy, + sw, + sh, + 300, + 300, + ); + assert_eq!( + backend.warped_to, + warps.then_some((300, 300)), + "pointer {pointer:?} src ({sx},{sy},{sw},{sh})" + ); + } + let mut backend = RecordingBackend::new(); + send_core_warp( + &mut state, + &mut backend, + 0x00be_ef00, + 0x00de_ad00, + 0, + 0, + 0, + 0, + 5, + 5, + ); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], x11::error::BAD_WINDOW); + assert_eq!( + u32::from_le_bytes(bytes[4..8].try_into().unwrap()), + 0x00de_ad00, + "dst is looked up first" + ); +} + +fn xi_set_focus_body(focus: u32, time: u32, deviceid: u16) -> Vec { + let mut b = Vec::with_capacity(12); + b.extend_from_slice(&focus.to_le_bytes()); + b.extend_from_slice(&time.to_le_bytes()); + b.extend_from_slice(&deviceid.to_le_bytes()); + b.extend_from_slice(&[0, 0]); + b +} + +/// Split a byte stream into X packets (GenericEvents carry a tail). +fn split_packets(bytes: &[u8]) -> Vec<&[u8]> { + let mut out = Vec::new(); + let mut pos = 0; + while pos + 32 <= bytes.len() { + let mut len = 32; + if bytes[pos] & 0x7f == 35 || bytes[pos] == 1 { + len += 4 * u32::from_le_bytes(bytes[pos + 4..pos + 8].try_into().unwrap()) as usize; + } + out.push(&bytes[pos..pos + len]); + pos += len; + } + out +} + +#[test] +fn xi_set_focus_on_the_master_keyboard_is_core_set_input_focus() { + // Xvfb: XISetFocus(dev 3, W) → GetInputFocus = W with revert_to + // RevertToParent (ProcXISetFocus passes RevertToParent), XIGetFocus + // (3) = W, and the core + XI2 FocusIn/FocusOut chain is delivered. + const W: u32 = 0x0040_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_mapped_window_at_100(&mut state, W); + { + let client = state.clients.get_mut(&1).unwrap(); + client.event_masks.insert(ResourceId(W), FOCUS_CHANGE_MASK); + client + .xi2_masks + .insert((ResourceId(W), 0), (1 << 9) | (1 << 10)); + } + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(W, 0, 3), + ); + assert_eq!(state.core_focus.raw, W); + assert_eq!(state.core_focus.revert_to, 2, "RevertToParent"); + let packets = split_packets(&bytes); + assert!( + packets + .iter() + .any(|p| p[0] == 9 && u32::from_le_bytes(p[4..8].try_into().unwrap()) == W), + "core FocusIn on W: {packets:02x?}" + ); + assert!( + packets.iter().any(|p| p[0] == 35 + && u16::from_le_bytes(p[8..10].try_into().unwrap()) == 9 + && u32::from_le_bytes(p[24..28].try_into().unwrap()) == W), + "XI2 FocusIn on W: {packets:02x?}" + ); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[3, 0, 0, 0]); + assert_eq!(&bytes[8..12], &W.to_le_bytes(), "XIGetFocus(3) = W"); + + // Xvfb: None and PointerRoot are accepted and reported back. + for focus in [0u32, 1] { + let _ = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(focus, 0, 3), + ); + assert_eq!(state.core_focus.raw, focus); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[3, 0, 0, 0]); + let bytes = split_packets(&bytes).last().unwrap().to_vec(); + assert_eq!(&bytes[8..12], &focus.to_le_bytes()); + } + + // A time later than the server's clock is silently ignored. + let _ = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(W, 0x7fff_ffff, 3), + ); + assert_eq!(state.core_focus.raw, 1, "future-timestamp request ignored"); +} + +#[test] +fn xi_set_focus_errors_match_xorg() { + // Xvfb: devices without a focus class (the pointers) and unknown + // ids → BadDevice, errorValue 0 (ProcXISetFocus sets none); a + // missing window → BadWindow; an unviewable one → BadMatch with + // the window as errorValue. + const UNMAPPED: u32 = 0x0040_0002; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(1), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(UNMAPPED), + parent: ROOT_WINDOW, + width: 10, + height: 10, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + for dev in [0u16, 1, 2, 4, 99] { + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(ROOT_WINDOW.0, 0, dev), + ); + assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, 0, 49); + } + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(0x00de_ad00, 0, 3), + ); + assert_xi_error(&bytes, x11::error::BAD_WINDOW, 0x00de_ad00, 49); + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(UNMAPPED, 0, 3), + ); + assert_xi_error(&bytes, x11::error::BAD_MATCH, UNMAPPED, 49); + // FollowKeyboard on the master keyboard itself would make it + // follow itself (Xvfb segfaults on it); yserver rejects it. + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(3, 0, 3), + ); + assert_xi_error(&bytes, x11::error::BAD_VALUE, 3, 49); + assert_eq!(state.core_focus.raw, 1, "focus untouched by errors"); +} + +#[test] +fn xi_set_focus_on_the_slave_keyboard_sets_its_own_focus() { + // Xvfb: XISetFocus(dev 5, W) leaves the core focus alone and + // XIGetFocus(5) = W; FollowKeyboard (3) is accepted on a slave + // and reported back as 3. + const W: u32 = 0x0040_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_mapped_window_at_100(&mut state, W); + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(W, 0, 5), + ); + assert!(bytes.is_empty(), "{bytes:02x?}"); + assert_eq!(state.core_focus.raw, 1, "core focus unchanged"); + let f = crate::core_loop::xi1_focus::device_focus(&state, 5); + assert_eq!((f.focus, f.revert_to), (W, 2)); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[5, 0, 0, 0]); + assert_eq!(&bytes[8..12], &W.to_le_bytes()); + let _ = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 49, + &xi_set_focus_body(3, 0, 5), + ); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[5, 0, 0, 0]); + assert_eq!(&bytes[8..12], &3u32.to_le_bytes(), "FollowKeyboard"); +} + +#[test] +fn xi_get_focus_rejects_pointer_devices() { + // Xvfb: XIGetFocus on devices without a focus class (2, 4) → + // BadDevice, errorValue 0. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for dev in [2u8, 4] { + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 50, &[dev, 0, 0, 0]); + assert_xi_error(&bytes, XI1_ERROR_BAD_DEVICE, 0, 50); + } +} + +fn xi_hierarchy_body(num_changes: u8, changes: &[&[u8]]) -> Vec { + let mut b = vec![num_changes, 0, 0, 0]; + for c in changes { + b.extend_from_slice(c); + } + b +} + +fn le_u16s(values: &[u16]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +fn remove_master_change(dev: u16, mode: u8) -> Vec { + let mut c = le_u16s(&[2, 3, dev]); + c.extend_from_slice(&[mode, 0]); + c.extend_from_slice(&le_u16s(&[2, 3])); + c +} + +#[test] +fn xi_change_hierarchy_answers_like_xorg_for_the_fixed_devices() { + // Every row is an Xvfb 21.1.24 capture. Xvfb's devices 4/5 are the + // XTest slaves, which Xorg refuses to attach/detach ("these are + // fixed"); yserver's 4/5 are fixed too, so the answers match + // device-for-device. `None` = Success (no reply, no event). + const BAD_DEVICE: u8 = XI1_ERROR_BAD_DEVICE; + let attach = |dev: u16, master: u16| le_u16s(&[3, 2, dev, master]); + let detach = |dev: u16| le_u16s(&[4, 2, dev, 0]); + // (label, request body, expected error (code, errorValue)). + type Case = (&'static str, Vec, Option<(u8, u32)>); + let cases: Vec = vec![ + ("empty", xi_hierarchy_body(0, &[]), None), + ( + "remove 2 float", + xi_hierarchy_body(1, &[&remove_master_change(2, 2)]), + Some((BAD_DEVICE, 0)), + ), + ( + "remove 3 attach", + xi_hierarchy_body(1, &[&remove_master_change(3, 1)]), + Some((BAD_DEVICE, 0)), + ), + ( + "remove 2 mode 5", + xi_hierarchy_body(1, &[&remove_master_change(2, 5)]), + Some((x11::error::BAD_VALUE, 0)), + ), + ( + "remove 4", + xi_hierarchy_body(1, &[&remove_master_change(4, 2)]), + Some((BAD_DEVICE, 4)), + ), + ( + "remove 99", + xi_hierarchy_body(1, &[&remove_master_change(99, 2)]), + Some((BAD_DEVICE, 0)), + ), + ( + "remove 0", + xi_hierarchy_body(1, &[&remove_master_change(0, 2)]), + Some((BAD_DEVICE, 0)), + ), + ( + "attach 4->2", + xi_hierarchy_body(1, &[&attach(4, 2)]), + Some((BAD_DEVICE, 4)), + ), + ( + "attach 4->3", + xi_hierarchy_body(1, &[&attach(4, 3)]), + Some((BAD_DEVICE, 4)), + ), + ( + "attach 5->3", + xi_hierarchy_body(1, &[&attach(5, 3)]), + Some((BAD_DEVICE, 5)), + ), + ( + "attach 2->3", + xi_hierarchy_body(1, &[&attach(2, 3)]), + Some((BAD_DEVICE, 2)), + ), + ( + "attach 99->2", + xi_hierarchy_body(1, &[&attach(99, 2)]), + Some((BAD_DEVICE, 0)), + ), + ( + "detach 4", + xi_hierarchy_body(1, &[&detach(4)]), + Some((BAD_DEVICE, 4)), + ), + ( + "detach 5", + xi_hierarchy_body(1, &[&detach(5)]), + Some((BAD_DEVICE, 5)), + ), + ( + "detach 2", + xi_hierarchy_body(1, &[&detach(2)]), + Some((BAD_DEVICE, 2)), + ), + ( + "detach 99", + xi_hierarchy_body(1, &[&detach(99)]), + Some((BAD_DEVICE, 0)), + ), + ( + "unknown type skipped", + xi_hierarchy_body(1, &[&le_u16s(&[9, 1])]), + None, + ), + ( + "unknown then remove 2", + xi_hierarchy_body(2, &[&le_u16s(&[9, 1]), &remove_master_change(2, 2)]), + Some((BAD_DEVICE, 0)), + ), + ( + "remove with length 2", + xi_hierarchy_body(1, &[&le_u16s(&[2, 2, 2, 2, 0, 3])]), + Some((x11::error::BAD_LENGTH, 0)), + ), + ( + "attach with length 3", + xi_hierarchy_body(1, &[&le_u16s(&[3, 3, 4, 2, 0, 0])]), + Some((x11::error::BAD_LENGTH, 0)), + ), + ( + "num_changes 2, one change", + xi_hierarchy_body(2, &[&remove_master_change(2, 2)]), + Some((BAD_DEVICE, 0)), + ), + ( + "change length past the request", + xi_hierarchy_body(1, &[&le_u16s(&[3, 9, 4, 2])]), + Some((x11::error::BAD_LENGTH, 0)), + ), + ( + "add master, name longer than the request", + xi_hierarchy_body(1, &[&[1, 0, 2, 0, 4, 0, 1, 1]]), + Some((x11::error::BAD_LENGTH, 0)), + ), + ]; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for (label, body, want) in cases { + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 43, &body); + match want { + None => assert!(bytes.is_empty(), "{label}: {bytes:02x?}"), + Some((code, value)) => { + assert!(!bytes.is_empty(), "{label}: expected an error"); + assert_eq!(bytes[1], code, "{label}: {bytes:02x?}"); + assert_xi_error(&bytes, code, value, 43); + } + } + } +} + +#[test] +fn xi_change_hierarchy_add_master_is_refused_with_bad_alloc() { + // Xorg creates the pair; yserver's device set is fixed, so it + // answers the way Xorg does when it cannot allocate a device + // (AllocDevicePair → BadAlloc) and sends no HierarchyChanged. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 0), 1 << 11); + let mut add = le_u16s(&[1, 3, 3]); + add.extend_from_slice(&[1, 1]); + add.extend_from_slice(b"foo\0"); + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 43, + &xi_hierarchy_body(1, &[&add]), + ); + assert_xi_error(&bytes, x11::error::BAD_ALLOC, 0, 43); +} + +#[test] +fn xi_change_hierarchy_reads_changes_in_client_byte_order() { + // The change list is opaque to the request swapper; a big-endian + // client's AttachSlave(4 → 2) must still name device 4. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.clients.get_mut(&1).unwrap().byte_order = ClientByteOrder::BigEndian; + let change: Vec = [3u16, 2, 4, 2] + .iter() + .flat_map(|v| v.to_be_bytes()) + .collect(); + let bytes = send_xi_request( + &mut state, + &mut backend, + &mut peer, + 43, + &xi_hierarchy_body(1, &[&change]), + ); + assert_eq!(bytes[1], XI1_ERROR_BAD_DEVICE, "{bytes:02x?}"); + assert_eq!(&bytes[4..8], &4u32.to_be_bytes(), "errorValue = device 4"); +} + +#[test] +fn xi_unknown_minor_is_bad_request() { + // Xvfb: XI minors 0, 62, 200, 255 → BadRequest (ProcIDispatch). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for minor in [0u8, 62, 200, 255] { + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, minor, &[0; 8]); + assert_xi_error(&bytes, x11::error::BAD_REQUEST, 0, u16::from(minor)); + } +} + +fn xi_select_body(window: u32, masks: &[(u16, &[u32])]) -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(&window.to_le_bytes()); + b.extend_from_slice(&u16::try_from(masks.len()).unwrap().to_le_bytes()); + b.extend_from_slice(&[0, 0]); + for (dev, words) in masks { + b.extend_from_slice(&dev.to_le_bytes()); + b.extend_from_slice(&u16::try_from(words.len()).unwrap().to_le_bytes()); + for w in *words { + // Event masks are bit arrays: byte i holds bits 8i..8i+7. + b.extend_from_slice(&w.to_le_bytes()); + } + } + b +} + +/// Send a client-order XI request through the request-body swap used by +/// `client_reader`, then dispatch it through the production +/// `process_request` entry point. +fn send_xi_wire_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + peer: &mut impl TestPeer, + client_id: u32, + sequence: u16, + minor: u8, + byte_order: ClientByteOrder, + mut body: Vec, +) -> Vec { + yserver_protocol::x11::request_swap::swap_request_body(137, minor, byte_order, &mut body); + process_request( + state, + backend, + ClientId(client_id), + SequenceNumber(sequence), + RequestHeader { + opcode: 137, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + &body, + None, + ) + .expect("XI request dispatch"); + let mut reply = read_all_available(peer); + reply.extend( + state + .clients + .get_mut(&client_id) + .expect("test client") + .outbound + .drain(..), + ); + reply +} + +fn xi_dynamic_select_wire_body( + byte_order: ClientByteOrder, + window: u32, + masks: &[(u16, [u8; 4])], +) -> Vec { + let mut body = WireBody(byte_order, Vec::new()) + .u32(window) + .u16(u16::try_from(masks.len()).unwrap()) + .bytes(&[0, 0]); + for (device_id, mask) in masks { + body = body.u16(*device_id).u16(1).bytes(mask); + } + body.1 +} + +fn xi_dynamic_passive_grab_wire_body( + byte_order: ClientByteOrder, + window: u32, + detail: u32, + device_id: u16, + event_mask: &[u8], + modifiers: &[u32], +) -> Vec { + assert!(event_mask.len().is_multiple_of(4)); + let mut body = WireBody(byte_order, Vec::new()) + .u32(0) + .u32(window) + .u32(0) + .u32(detail) + .u16(device_id) + .u16(u16::try_from(modifiers.len()).unwrap()) + .u16(u16::try_from(event_mask.len() / 4).unwrap()) + .bytes(&[1, 1, 1, 0, 0, 0]) + .bytes(event_mask); + for modifier in modifiers { + body = body.u32(*modifier); + } + body.1 +} + +fn xi_dynamic_passive_ungrab_wire_body( + byte_order: ClientByteOrder, + window: u32, + detail: u32, + device_id: u16, + modifiers: &[u32], +) -> Vec { + let mut body = WireBody(byte_order, Vec::new()) + .u32(window) + .u32(detail) + .u16(device_id) + .u16(u16::try_from(modifiers.len()).unwrap()) + .bytes(&[1, 0, 0, 0]); + for modifier in modifiers { + body = body.u32(*modifier); + } + body.1 +} + +#[test] +fn xi_dynamic_request_swap_select_events_big_endian_matches_little_endian() { + const CLIENT_ID: u32 = 1; + let mut states = Vec::new(); + for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, CLIENT_ID); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = byte_order; + let mut backend = RecordingBackend::new(); + let _ = xi_dynamic_grab_source(&mut state, 91, false, true, "select-a"); + let _ = xi_dynamic_grab_source(&mut state, 92, false, true, "select-b"); + let body = xi_dynamic_select_wire_body( + byte_order, + ROOT_WINDOW.0, + &[ + (6, [0x04, 0, 0, 0]), + (7, [0x08, 0, 0, 0]), + (1, [0x10, 0, 0, 0]), + ], + ); + let reply = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 1, + 46, + byte_order, + body, + ); + assert!(reply.is_empty(), "selection should not reply: {reply:02x?}"); + states.push(state.clients[&CLIENT_ID].xi2_masks.clone()); + } + assert_eq!( + states[0], states[1], + "BE selections must match LE selections" + ); + assert_eq!(states[1].get(&(ROOT_WINDOW, 6)), Some(&0x04)); + assert_eq!(states[1].get(&(ROOT_WINDOW, 7)), Some(&0x08)); + assert_eq!(states[1].get(&(ROOT_WINDOW, 1)), Some(&0x10)); +} + +#[test] +fn xi_dynamic_request_swap_passive_grab_big_endian_matches_little_endian() { + const CLIENT_ID: u32 = 1; + const WINDOW: u32 = 0x0010_0061; + let mut grab_records = Vec::new(); + for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, CLIENT_ID); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = byte_order; + let mut backend = RecordingBackend::new(); + let (_, keyboard_id) = xi_dynamic_grab_source(&mut state, 93, true, false, "grab-keyboard"); + let body = xi_dynamic_passive_grab_wire_body( + byte_order, + WINDOW, + 67, + keyboard_id, + &[0x02, 0, 0, 0], + &[4, 1], + ); + let reply = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 1, + 54, + byte_order, + body, + ); + assert_eq!(reply.len(), 32, "passive grab reply: {reply:02x?}"); + let records: Vec<_> = state + .key_grabs + .iter() + .map(|grab| (grab.device_id, grab.keycode, grab.modifiers, grab.xi2_mask)) + .collect(); + grab_records.push(records); + } + assert_eq!(grab_records[0], grab_records[1]); + assert_eq!( + grab_records[1], + vec![(6, 67, 4, 2), (6, 67, 1, 2)], + "both declared modifiers and byte mask must retain their LE values" + ); +} + +#[test] +fn xi_dynamic_request_swap_passive_ungrab_big_endian_matches_little_endian() { + const CLIENT_ID: u32 = 1; + const WINDOW: u32 = 0x0010_0062; + let mut remaining_grabs = Vec::new(); + for byte_order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, CLIENT_ID); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = byte_order; + let mut backend = RecordingBackend::new(); + let (_, keyboard_id) = + xi_dynamic_grab_source(&mut state, 94, true, false, "ungrab-keyboard"); + let (_, other_keyboard_id) = + xi_dynamic_grab_source(&mut state, 95, true, false, "other-keyboard"); + for device_id in [keyboard_id, other_keyboard_id] { + let body = xi_dynamic_passive_grab_wire_body( + byte_order, + WINDOW, + 67, + device_id, + &[0x02, 0, 0, 0], + &[4, 1], + ); + let _ = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 1, + 54, + byte_order, + body, + ); + } + let body = + xi_dynamic_passive_ungrab_wire_body(byte_order, WINDOW, 67, keyboard_id, &[4, 1]); + let reply = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 2, + 55, + byte_order, + body, + ); + assert!(reply.is_empty(), "passive ungrab is void: {reply:02x?}"); + remaining_grabs.push( + state + .key_grabs + .iter() + .map(|grab| (grab.device_id, grab.keycode, grab.modifiers)) + .collect::>(), + ); + } + assert_eq!(remaining_grabs[0], remaining_grabs[1]); + assert_eq!(remaining_grabs[1], vec![(7, 67, 4), (7, 67, 1)]); +} + +#[test] +fn xi_dynamic_request_swap_rejects_select_record_overrun_without_mutation() { + const CLIENT_ID: u32 = 1; + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, CLIENT_ID); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = ClientByteOrder::BigEndian; + let mut backend = RecordingBackend::new(); + let _ = xi_dynamic_grab_source(&mut state, 96, false, true, "malformed-select"); + + let valid = xi_dynamic_select_wire_body( + ClientByteOrder::BigEndian, + ROOT_WINDOW.0, + &[(7, [0x08, 0, 0, 0])], + ); + let _ = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 1, + 46, + ClientByteOrder::BigEndian, + valid, + ); + let before = state.clients[&CLIENT_ID].xi2_masks.clone(); + + // mask_len=2 words, but only one word remains in the request body. + let malformed = WireBody(ClientByteOrder::BigEndian, Vec::new()) + .u32(ROOT_WINDOW.0) + .u16(1) + .bytes(&[0, 0]) + .u16(6) + .u16(2) + .bytes(&[0x04, 0, 0, 0]) + .1; + let reply = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 2, + 46, + ClientByteOrder::BigEndian, + malformed, + ); + assert_eq!(reply.get(1), Some(&x11::error::BAD_LENGTH), "{reply:02x?}"); + assert_eq!(state.clients[&CLIENT_ID].xi2_masks, before); +} + +#[test] +fn xi_dynamic_request_swap_rejects_modifier_overrun_without_grab() { + const CLIENT_ID: u32 = 1; + const WINDOW: u32 = 0x0010_0063; + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, CLIENT_ID); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = ClientByteOrder::BigEndian; + let mut backend = RecordingBackend::new(); + let (_, keyboard_id) = xi_dynamic_grab_source(&mut state, 97, true, false, "malformed-grab"); + + let mut malformed = WireBody(ClientByteOrder::BigEndian, Vec::new()) + .u32(0) + .u32(WINDOW) + .u32(0) + .u32(67) + .u16(keyboard_id) + .u16(2) + .u16(0) + .bytes(&[1, 1, 1, 0, 0, 0]) + .u32(4) + .1; + assert_eq!(malformed.len(), 32); + let reply = send_xi_wire_request( + &mut state, + &mut backend, + &mut peer, + CLIENT_ID, + 1, + 54, + ClientByteOrder::BigEndian, + std::mem::take(&mut malformed), + ); + assert_eq!(reply.get(1), Some(&x11::error::BAD_LENGTH), "{reply:02x?}"); + assert!( + state.key_grabs.is_empty(), + "malformed modifiers install no grab" + ); +} + +#[test] +fn xi_select_events_keeps_bit_32_and_rejects_bits_past_the_last_event() { + // Xvfb: select dev 2 = {2, 30, 31, 32} (mask_len 2) + dev 3 = {3}; + // XIGetSelectedEvents returns exactly + // 02000200 040000c0 01000000 03000100 08000000 + // (masks in device order, trailing zero words trimmed). Selecting + // bit 33 → BadValue(33), bit 69 → BadValue(69), and the rejected + // request changes nothing. + const W: u32 = 0x0040_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_mapped_window_at_100(&mut state, W); + let lo = (1u32 << 2) | (1 << 30) | (1 << 31); + let body = xi_select_body(W, &[(2, &[lo, 1]), (3, &[1 << 3])]); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); + assert!(bytes.is_empty(), "{bytes:02x?}"); + let expected_tail: [u8; 20] = [ + 0x02, 0x00, 0x02, 0x00, 0x04, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, + 0x00, 0x08, 0x00, 0x00, 0x00, + ]; + let reply = send_xi_request(&mut state, &mut backend, &mut peer, 60, &W.to_le_bytes()); + assert_eq!(reply.len(), 52, "{reply:02x?}"); + assert_eq!(&reply[4..8], &5u32.to_le_bytes(), "reply length"); + assert_eq!(&reply[8..10], &2u16.to_le_bytes(), "num_masks"); + assert_eq!(&reply[32..], &expected_tail); + + let body = xi_select_body(W, &[(2, &[0, 1 << 1])]); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); + assert_xi_error(&bytes, x11::error::BAD_VALUE, 33, 46); + let body = xi_select_body(W, &[(2, &[1 << 2, 0, 1 << 5])]); + let bytes = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); + assert_xi_error(&bytes, x11::error::BAD_VALUE, 69, 46); + let reply = send_xi_request(&mut state, &mut backend, &mut peer, 60, &W.to_le_bytes()); + assert_eq!( + &reply[32..], + &expected_tail, + "rejected selects applied nothing" + ); +} + +#[test] +fn xi_get_selected_events_header_fields_use_client_byte_order() { + // Xvfb, big-endian client, same selection as above: + // 00020002 040000c0 01000000 00030001 08000000 + // deviceid/mask_len/num_masks swap; the mask bytes don't. + const W: u32 = 0x0040_0001; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_mapped_window_at_100(&mut state, W); + state.clients.get_mut(&1).unwrap().byte_order = ClientByteOrder::BigEndian; + let lo = (1u32 << 2) | (1 << 30) | (1 << 31); + // Request bodies reach the handler already swapped to LE. + let body = xi_select_body(W, &[(2, &[lo, 1]), (3, &[1 << 3])]); + let _ = send_xi_request(&mut state, &mut backend, &mut peer, 46, &body); + let reply = send_xi_request(&mut state, &mut backend, &mut peer, 60, &W.to_le_bytes()); + assert_eq!(&reply[4..8], &5u32.to_be_bytes(), "reply length"); + assert_eq!(&reply[8..10], &2u16.to_be_bytes(), "num_masks"); + assert_eq!( + &reply[32..], + &[ + 0x00, 0x02, 0x00, 0x02, 0x04, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x03, + 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, + ] + ); +} + +#[test] +fn xi_get_device_key_mapping_matches_core_keyboard_mapping() { + // yserver models a single keyboard, so XI1 GetDeviceKeyMapping on + // a key-class device must surface the same keysyms a client reads + // via core GetKeyboardMapping (Xorg drives both from + // XkbGetCoreMap). Inject deterministic ChangeKeyboardMapping rows + // and assert the two replies carry identical map data. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // RecordingBackend reports keysyms-per-keycode = 2; match it. + state.keymap_overrides.insert(10, vec![0x0061, 0x0041]); + state.keymap_overrides.insert(11, vec![0x0062, 0x0042]); + + // Core GetKeyboardMapping { first=10, count=2 }. + handle_get_keyboard_mapping( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + &[10u8, 2], + ) + .expect("core"); + let core = read_all_available(&mut peer); + // byte[1] = keysyms-per-keycode; payload from byte 32. + let core_kpc = core[1]; + let core_syms = core[32..].to_vec(); + + // XI1 GetDeviceKeyMapping on master keyboard (device 3), + // { deviceid=3, first=10, count=2 }. + let header = RequestHeader { + opcode: 137, + data: 24, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + header, + &[3u8, 10, 2, 0], + ) + .expect("xi1"); + let xi = read_all_available(&mut peer); + + assert_eq!(xi[0], 1, "X_Reply"); + assert_eq!(xi[1], 24, "RepType = X_GetDeviceKeyMapping"); + // byte[8] = keysyms-per-keycode for XI1 (vs byte[1] for core). + assert_eq!(xi[8], core_kpc, "XI1 kpc matches core kpc"); + assert_eq!( + &xi[32..], + &core_syms[..], + "XI1 device keymap payload matches core keyboard mapping" + ); + // And the injected keysyms actually came through. + let expect: Vec = [0x0061u32, 0x0041, 0x0062, 0x0042] + .iter() + .flat_map(|k| k.to_le_bytes()) + .collect(); + assert_eq!(&xi[32..], &expect[..], "injected keysyms surfaced"); +} + +#[test] +fn xi_get_device_key_mapping_on_pointer_device_is_bad_match() { + // Device 2 is the master pointer — no key class → BadMatch + // (Xorg getkmap.c: dev->key == NULL → BadMatch). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 137, + data: 24, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[2u8, 8, 1, 0], + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0, "error packet"); + assert_eq!(bytes[1], x11::error::BAD_MATCH, "BadMatch"); +} + +#[test] +fn xi_change_device_key_mapping_round_trips_via_get() { + // XI1 ChangeDeviceKeyMapping (minor 25) must write the same + // `keymap_overrides` rows that GetDeviceKeyMapping (minor 24) / + // core GetKeyboardMapping read back — Xorg drives both off the + // shared XkbGetCoreMap. Regression for the XTS + // `XChangeDeviceKeyMapping-3` round-trip that used to fail + // because minor 25 emitted MappingNotify but never stored. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + // ChangeDeviceKeyMapping { deviceid=3, first=10, kpk=2, count=2 } + // with fresh keysyms (distinct from any read-path defaults). + let mut body: Vec = vec![3, 10, 2, 2]; + for k in [0x0078u32, 0x0058, 0x0079, 0x0059] { + body.extend_from_slice(&k.to_le_bytes()); + } + let header = RequestHeader { + opcode: 137, + data: 25, + length_units: 2 + 2 * 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("change"); + // Drain the MappingNotify the change fans out. + let _ = read_all_available(&mut peer); + + // The override store now reflects the write. + assert_eq!( + state.keymap_overrides.get(&10), + Some(&vec![0x0078u32, 0x0058]) + ); + assert_eq!( + state.keymap_overrides.get(&11), + Some(&vec![0x0079u32, 0x0059]) + ); + + // GetDeviceKeyMapping { deviceid=3, first=10, count=2 } surfaces it. + let header = RequestHeader { + opcode: 137, + data: 24, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + header, + &[3u8, 10, 2, 0], + ) + .expect("get"); + let xi = read_all_available(&mut peer); + assert_eq!(xi[0], 1, "X_Reply"); + assert_eq!(xi[1], 24, "RepType = X_GetDeviceKeyMapping"); + let expect: Vec = [0x0078u32, 0x0058, 0x0079, 0x0059] + .iter() + .flat_map(|k| k.to_le_bytes()) + .collect(); + assert_eq!( + &xi[32..32 + expect.len()], + &expect[..], + "written keysyms read back" + ); +} + +#[test] +fn xi_get_device_motion_events_pointer_returns_history() { + let mut state = ServerState::new(); + state.start_instant = std::time::Instant::now() - std::time::Duration::from_secs(1); + state + .pointer_motion_history + .push_back(crate::server::PointerMotionRecord { + time: 500, + root_x: 120, + root_y: 45, + }); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 137, + data: 10, + length_units: 4, + }; + // { start:CARD32, stop:CARD32, deviceid@8 }. + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[144, 1, 0, 0, 88, 2, 0, 0, 2, 0, 0, 0], // 400..600 + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes.len(), 44); + assert_eq!(bytes[0], 1, "X_Reply"); + assert_eq!(bytes[1], 10, "RepType = X_GetDeviceMotionEvents"); + assert_eq!(&bytes[8..12], &1u32.to_le_bytes(), "nEvents"); + assert_eq!(bytes[12], 2, "master pointer reports two valuators"); + assert_eq!(bytes[13], 1, "mode = Absolute"); + assert_eq!(u32::from_le_bytes(bytes[32..36].try_into().unwrap()), 500); + assert_eq!(i32::from_le_bytes(bytes[36..40].try_into().unwrap()), 120); + assert_eq!(i32::from_le_bytes(bytes[40..44].try_into().unwrap()), 45); +} + +#[test] +fn xi_get_device_motion_events_keyboard_is_bad_match() { + // Device 3 = master keyboard (no valuators) → BadMatch + // (Xorg gtmotion.c: v == NULL → BadMatch). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 137, + data: 10, + length_units: 4, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0], + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 0, "error packet"); + assert_eq!(bytes[1], x11::error::BAD_MATCH, "BadMatch"); +} + +#[test] +fn xi_get_feedback_control_kbd_mirrors_keyboard_control() { + // The XI1 KbdFeedbackState must carry the same bell/click/LED + // state as core GetKeyboardControl (Xorg: the KbdFeedback ctrl + // *is* the keyboard control). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.keyboard_control.bell_pitch = 0x0321; + state.keyboard_control.bell_duration = 0x0654; + state.keyboard_control.bell_percent = 77; + state.keyboard_control.key_click_percent = 42; + state.keyboard_control.led_mask = 0x0000_0003; + state.keyboard_control.global_auto_repeat = true; + + // GetFeedbackControl { deviceid=3 } (master keyboard). + let header = RequestHeader { + opcode: 137, + data: 22, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[3u8, 0, 0, 0], + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[0], 1, "X_Reply"); + assert_eq!(bytes[1], 22, "RepType"); + assert_eq!(&bytes[8..10], &1u16.to_le_bytes(), "num_feedbacks"); + // KbdFeedbackState begins at byte 32. + let kbd = &bytes[32..]; + assert_eq!(kbd[0], 0, "KbdFeedbackClass"); + assert_eq!(&kbd[4..6], &0x0321u16.to_le_bytes(), "pitch == bell_pitch"); + assert_eq!(&kbd[6..8], &0x0654u16.to_le_bytes(), "duration"); + assert_eq!(&kbd[8..12], &0x0000_0003u32.to_le_bytes(), "led_mask"); + assert_eq!(kbd[16], 1, "global_auto_repeat"); + assert_eq!(kbd[17], 42, "click == key_click_percent"); + assert_eq!(kbd[18], 77, "percent == bell_percent"); +} + +#[test] +fn xi_get_feedback_control_ptr_mirrors_pointer_control() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.pointer_control.accel_numerator = 5; + state.pointer_control.accel_denominator = 3; + state.pointer_control.threshold = 9; + + // GetFeedbackControl { deviceid=2 } (master pointer). + let header = RequestHeader { + opcode: 137, + data: 22, + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[2u8, 0, 0, 0], + ) + .expect("process"); + let bytes = read_all_available(&mut peer); + assert_eq!(bytes[1], 22, "RepType"); + assert_eq!(&bytes[8..10], &1u16.to_le_bytes(), "num_feedbacks"); + let ptr = &bytes[32..]; + assert_eq!(ptr[0], 1, "PtrFeedbackClass"); + assert_eq!(&ptr[6..8], &5u16.to_le_bytes(), "accelNum"); + assert_eq!(&ptr[8..10], &3u16.to_le_bytes(), "accelDenom"); + assert_eq!(&ptr[10..12], &9u16.to_le_bytes(), "threshold"); +} + +#[test] +fn xi_change_keyboard_feedback_updates_shared_control_atomically() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = vec![0; 28]; + body[0..4].copy_from_slice(&0x1fu32.to_le_bytes()); + body[4] = 3; // key device + body[5] = 0; // KbdFeedbackClass + body[9] = 0; // feedback id + body[10..12].copy_from_slice(&20u16.to_le_bytes()); + body[14] = 42; + body[15] = 77; + body[16..18].copy_from_slice(&801i16.to_le_bytes()); + body[18..20].copy_from_slice(&321i16.to_le_bytes()); + body[20..24].copy_from_slice(&3u32.to_le_bytes()); + body[24..28].copy_from_slice(&2u32.to_le_bytes()); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(23, &body), + &body, + ) + .unwrap(); + assert_eq!(state.keyboard_control.key_click_percent, 42); + assert_eq!(state.keyboard_control.bell_percent, 77); + assert_eq!(state.keyboard_control.bell_pitch, 801); + assert_eq!(state.keyboard_control.bell_duration, 321); + assert_eq!(state.keyboard_control.led_mask, 2); + + let before = state.keyboard_control.clone(); + body[14] = 10; + body[15] = 101; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header_for_body(23, &body), + &body, + ) + .unwrap(); + assert_eq!( + state.keyboard_control.key_click_percent, + before.key_click_percent + ); + assert_eq!(state.keyboard_control.bell_percent, before.bell_percent); +} + +#[test] +fn xi_change_pointer_feedback_updates_shared_control() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = vec![0; 20]; + body[0..4].copy_from_slice(&7u32.to_le_bytes()); + body[4] = 2; // pointer device + body[5] = 1; // PtrFeedbackClass + body[8] = 1; + body[9] = 0; + body[10..12].copy_from_slice(&12u16.to_le_bytes()); + body[14..16].copy_from_slice(&5i16.to_le_bytes()); + body[16..18].copy_from_slice(&3i16.to_le_bytes()); + body[18..20].copy_from_slice(&9i16.to_le_bytes()); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(23, &body), + &body, + ) + .unwrap(); + assert_eq!(state.pointer_control.accel_numerator, 5); + assert_eq!(state.pointer_control.accel_denominator, 3); + assert_eq!(state.pointer_control.threshold, 9); +} + +#[test] +fn xi_change_device_resolution_zero_round_trips() { + // A fresh master pointer has two valuators in Xorg's CorePointerProc + // (`dix/devices.c:662-690`), so DEVICE_RESOLUTION returns two axes. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut change = vec![0; 16]; + change[0..2].copy_from_slice(&1u16.to_le_bytes()); + change[2] = 2; + change[4..6].copy_from_slice(&1u16.to_le_bytes()); + change[6..8].copy_from_slice(&12u16.to_le_bytes()); + change[8] = 0; + change[9] = 1; + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header_for_body(35, &change), + &change, + ) + .unwrap(); + let change_reply = read_all_available(&mut peer); + assert_eq!(change_reply[0], 1); + assert_eq!(change_reply[8], 0, "Success"); + + let get = [1, 0, 2, 0]; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header_for_body(34, &get), + &get, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 64); + assert_eq!(u32::from_le_bytes(wire[36..40].try_into().unwrap()), 2); + for value in wire[40..].chunks_exact(4) { + assert_eq!(u32::from_le_bytes(value.try_into().unwrap()), 0); + } +} + +#[test] +fn xi_query_version_negotiates_up_to_server_24() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 131, + data: 47, + length_units: 2, + }; + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[2, 0, 4, 0], + ) + .expect("XIQueryVersion 2.4"); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "XIQueryVersion reply size"); + assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2); + assert_eq!(u16::from_le_bytes([wire[10], wire[11]]), 4); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + header, + &[2, 0, 3, 0], + ) + .expect("XIQueryVersion 2.3"); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "XIQueryVersion reply size"); + assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2); + assert_eq!(u16::from_le_bytes([wire[10], wire[11]]), 3); +} + +/// XI1 GetExtensionVersion answers the server's XI version, as Xorg's +/// `ProcXGetExtensionVersion` (Xi/getvers.c: `XIVersion` = 2.4; Xvfb's +/// `xinput --version` reports "XI version on server: 2.4"), with +/// RepType = X_GetExtensionVersion. libXi decides from this reply +/// whether XI 2.2 fields such as a raw event's `sourceid` are valid: +/// the old hard-coded 2.0 made `xinput test-xi2 --root` print every +/// raw key event as `device: 3 (0)` (#173; Xorg: `3 (5)`). A length +/// that doesn't match `nbytes` is BadLength. +#[test] +fn xi_get_extension_version_reports_the_server_version_like_xorg() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let name = b"XInputExtension"; + let mut body = vec![name.len() as u8, 0, 0, 0]; + body.extend_from_slice(name); + body.push(0); + let header = RequestHeader { + opcode: 131, + data: 1, + length_units: 6, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("GetExtensionVersion"); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "reply size"); + assert_eq!((wire[0], wire[1]), (1, 1), "X_Reply, RepType"); + assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 2, "major"); + assert_eq!(u16::from_le_bytes([wire[10], wire[11]]), 4, "minor"); + assert_eq!(wire[12], 1, "present"); + + let short = RequestHeader { + length_units: 5, + ..header + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + short, + &body[..16], + ) + .expect("GetExtensionVersion, wrong length"); + let wire = read_all_available(&mut peer); + assert_eq!((wire[0], wire[1]), (0, x11::error::BAD_LENGTH), "BadLength"); +} + +/// The XI version a client announced is remembered the way Xorg's +/// `ProcXIQueryVersion` stores it, because `FilterRawEvents` reads it. +/// Xvfb capture (probe mon:…:0,2 / 2,0 / 3,2, then a keyboard grab): +/// 2.0 then 2.2 stays 2.0 (still filtered as XI 2.0); 2.2 then 2.0 +/// keeps 2.2 (Xorg answers the 2.0 query with BadValue); 2.3 then 2.2 +/// keeps 2.3; a client that never asks has no version (not filtered). +#[test] +fn xi_query_version_records_client_version_like_xorg() { + let header = RequestHeader { + opcode: 131, + data: 47, + length_units: 2, + }; + let stored_after = |minors: &[u16]| { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for (i, minor) in minors.iter().enumerate() { + let m = minor.to_le_bytes(); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(u16::try_from(i + 1).unwrap()), + header, + &[2, 0, m[0], m[1]], + ) + .expect("XIQueryVersion"); + } + state.xi2_client_versions.get(&ClientId(1)).copied() + }; + assert_eq!(stored_after(&[]), None); + assert_eq!(stored_after(&[0]), Some((2, 0))); + assert_eq!(stored_after(&[0, 2]), Some((2, 0))); + assert_eq!(stored_after(&[2, 0]), Some((2, 2))); + assert_eq!(stored_after(&[3, 2]), Some((2, 3))); + assert_eq!(stored_after(&[2, 3]), Some((2, 3))); + // Capped at the server's version, as the reply is. + assert_eq!(stored_after(&[9]), Some((2, 4))); +} + +/// XIGrabDevice(keyboard) and an XI2 passive key grab keep the grab's +/// event mask: Xorg delivers an XI2 raw key event to the grab owner +/// only when that mask selects it (DeliverOneGrabbedEvent reads +/// `grab->xi2mask`). +#[test] +fn xi2_keyboard_grabs_keep_their_event_mask() { + const MASK: u32 = (1 << 2) | (1 << 3) | (1 << 13) | (1 << 14); + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + + let mut body = Vec::new(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); // window + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&3u16.to_le_bytes()); // master keyboard + body.extend_from_slice(&[1, 1, 0, 0]); // async, async, owner_events=0, pad + body.extend_from_slice(&1u16.to_le_bytes()); // mask_len + body.extend_from_slice(&MASK.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 131, + data: 51, + length_units: 7, + }, + &body, + ) + .expect("XIGrabDevice keyboard"); + assert_eq!(state.active_keyboard_grab.map(|g| g.xi2_mask), Some(MASK)); + + let mut body = Vec::new(); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); // grab_window + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&38u32.to_le_bytes()); // detail + body.extend_from_slice(&3u16.to_le_bytes()); // deviceid + body.extend_from_slice(&1u16.to_le_bytes()); // num_modifiers + body.extend_from_slice(&1u16.to_le_bytes()); // mask_len + body.extend_from_slice(&[1, 1, 1, 0]); // Keycode, async, async, owner_events + body.extend_from_slice(&0u16.to_le_bytes()); // pad + body.extend_from_slice(&MASK.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // modifier 0 + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 131, + data: 54, + length_units: 9, + }, + &body, + ) + .expect("XIPassiveGrabDevice keycode"); + assert_eq!(state.key_grabs.last().map(|g| g.xi2_mask), Some(MASK)); +} + +/// XI_DeviceChanged events (GenericEvent 35, evtype 1) on `wire`, as +/// `(deviceid, sourceid, reason)`. +fn device_changed_events(wire: &[u8]) -> Vec<(u16, u16, u8)> { + let mut found = Vec::new(); + let mut at = 0; + while at + 32 <= wire.len() { + let length = if wire[at] == 35 || wire[at] == 1 { + 32 + u32::from_le_bytes(wire[at + 4..at + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + if wire[at] == 35 && u16::from_le_bytes([wire[at + 8], wire[at + 9]]) == 1 { + found.push(( + u16::from_le_bytes([wire[at + 10], wire[at + 11]]), + u16::from_le_bytes([wire[at + 18], wire[at + 19]]), + wire[at + 20], + )); + } + at += length; + } + found +} + +#[test] +fn xi_select_events_on_root_sends_no_device_changed_for_a_fresh_master() { + // Xorg sends no DeviceChanged on XISelectEvents (Xi/xiselectev.c); a + // master no slave has driven has no switch to report. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 131, + data: 46, + length_units: 5, + }; + let mut body = Vec::new(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); // XIAllDevices + body.extend_from_slice(&1u16.to_le_bytes()); // 1 mask word + body.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &body, + ) + .expect("XISelectEvents"); + + assert_eq!(device_changed_events(&read_all_available(&mut peer)), []); +} + +/// Wine's winex11 at start (`x11drv_xinput2_init`): DeviceChanged selected +/// on the root for XIAllMasterDevices, then XIGetClientPointer and +/// XIQueryDevice of that pointer. A SlaveSwitch it is then sent makes it +/// XOpenDevice the event's sourceid (`update_device_mapping`), so no event +/// may name a master there: XOpenDevice of a master is BadDevice, as in +/// Xorg, and ends the Wine process. +#[test] +fn wines_xinput2_start_is_sent_no_switch_to_a_master() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut wire = Vec::new(); + let mut select = Vec::new(); + select.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&0u16.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); // XIAllMasterDevices + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); + wire.extend(dispatch_xi_request_wire( + &mut state, &mut peer, 26, 46, &select, + )); + // XIGetClientPointer(None). + let pointer = dispatch_xi_request_wire(&mut state, &mut peer, 27, 45, &[0; 4]); + assert_eq!(pointer[0], 1, "XIGetClientPointer reply"); + let deviceid = u16::from_le_bytes([pointer[10], pointer[11]]); + assert_eq!(deviceid, crate::xinput::DEVICEID_MASTER_POINTER); + let mut query = deviceid.to_le_bytes().to_vec(); + query.extend_from_slice(&[0, 0]); + let queried = dispatch_xi_request_wire(&mut state, &mut peer, 28, 48, &query); + assert_eq!(queried[0], 1, "XIQueryDevice reply"); + wire.extend(read_all_available(&mut peer)); + for (_, sourceid, _) in device_changed_events(&wire) { + assert!( + state + .xi_devices + .device(sourceid) + .is_some_and(|device| device.attached_master.is_some()), + "a DeviceChanged names master {sourceid} as its source" + ); + } + // What winex11 would then ask, and Xorg refuses (Xi/opendev.c). + let opened = dispatch_wire_request( + &mut state, + &mut peer, + 34, + XI2_MAJOR_OPCODE, + 3, + &[2, 0, 0, 0], + ); + assert_eq!(opened[0], 0, "XOpenDevice of a master is an error"); +} + +#[test] +fn xi_slave_switch_bootstrap_uses_last_pointer_slave_or_master_classes() { + use crate::{ + backend::recording::RecordingBackend, + core_loop::{DeviceInfo, InputOrigin, pointer_fanout::pointer_event_fanout_to_state}, + host_x11::{HostPointerEvent, HostXidMap, PointerEventKind}, + xinput::{InputCapabilities, InputSourceId, XiFacetKind}, + }; + + fn select_master_pointer( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + ) { + let mut body = Vec::new(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); + handle_xi2_request( + state, + backend, + None, + ClientId(client), + SequenceNumber(sequence), + RequestHeader { + opcode: 131, + data: 46, + length_units: 5, + }, + &body, + ) + .expect("XISelectEvents on master pointer"); + } + + fn device_changed(bytes: &[u8]) -> (u16, u16, u8, u16, Option) { + let offset = (0..bytes.len().saturating_sub(32)) + .find(|&offset| { + bytes[offset] == 35 + && u16::from_le_bytes([bytes[offset + 8], bytes[offset + 9]]) == 1 + }) + .unwrap_or_else(|| panic!("bootstrap XI_DeviceChanged event missing: {bytes:?}")); + let deviceid = u16::from_le_bytes([bytes[offset + 10], bytes[offset + 11]]); + let num_classes = u16::from_le_bytes([bytes[offset + 16], bytes[offset + 17]]); + let sourceid = u16::from_le_bytes([bytes[offset + 18], bytes[offset + 19]]); + let reason = bytes[offset + 20]; + let mut class_offset = offset + 32; + let mut valuator_two = None; + for _ in 0..num_classes { + let class_type = u16::from_le_bytes([bytes[class_offset], bytes[class_offset + 1]]); + let units = + u16::from_le_bytes([bytes[class_offset + 2], bytes[class_offset + 3]]) as usize; + let class_source = + u16::from_le_bytes([bytes[class_offset + 4], bytes[class_offset + 5]]); + if class_type == 2 + && u16::from_le_bytes([bytes[class_offset + 6], bytes[class_offset + 7]]) == 2 + { + valuator_two = Some(( + class_source, + i32::from_le_bytes( + bytes[class_offset + 28..class_offset + 32] + .try_into() + .unwrap(), + ), + )); + } + class_offset += units * 4; + } + let scroll_value = valuator_two.map(|(class_source, value)| { + assert_eq!(class_source, sourceid, "classes use the reported source"); + value + }); + (deviceid, sourceid, reason, num_classes, scroll_value) + } + + let mut state = ServerState::new(); + let mut bootstrap_peer = install_capture_client(&mut state, 101); + let mut backend = RecordingBackend::new(); + + // Before: this expected the physical pointer shape on a fresh master. + // Xorg initializes the core master pair through CorePointerProc + // (`dix/devices.c:724-730, 655-694`), so the initial master has three + // classes and no valuator 2; XIQueryDevice serializes stored source IDs + // (`Xi/xiquerydevice.c:278,326`). + select_master_pointer(&mut state, &mut backend, 101, 1); + assert_eq!( + state + .clients + .get(&101) + .unwrap() + .xi2_masks + .get(&(ROOT_WINDOW, 2)), + Some(&u64::from(XI2_DEVICE_CHANGED_MASK)), + "master pointer DeviceChanged selection was installed" + ); + let fallback = read_all_available(&mut bootstrap_peer); + assert_eq!( + device_changed_events(&fallback), + [], + "no slave has driven the master: no switch to report" + ); + + let source = InputSourceId(0xA71); + let info = DeviceInfo { + source_id: source, + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: "Razer mouse".to_owned(), + device_node: "/dev/input/event-razer".to_owned(), + sysname: "event-razer".to_owned(), + vendor_id: 1, + product_id: 2, + is_touchpad: false, + config: Default::default(), + }; + let source_id = state.xi_register_source(&info)[0]; + let wheel = HostPointerEvent { + origin: InputOrigin::Physical(source), + kind: PointerEventKind::ButtonPress, + detail: 5, + host_xid: 0, + time: 2, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + wheel, + true, + false, + ); + let release = HostPointerEvent { + kind: PointerEventKind::ButtonRelease, + time: 3, + ..wheel + }; + let _dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + release, + true, + false, + ); + let _ = read_all_available(&mut bootstrap_peer); + + let mut late_peer = install_capture_client(&mut state, 102); + select_master_pointer(&mut state, &mut backend, 102, 2); + assert_eq!( + device_changed(&read_all_available(&mut late_peer)), + (2, source_id, 1, 7, Some(1)), + "a late selector bootstraps from the stored physical class set and scroll state" + ); + assert_eq!(state.xi_last_slave(2), Some(source_id)); + assert_eq!( + state + .xi_devices + .device(source_id) + .unwrap() + .scroll_axis_values, + [1, 0] + ); + assert_eq!(state.xi_devices.devices().len(), 5); + assert!(state.xi_devices.source(source).is_some()); + assert_eq!( + state.xi_devices.facet(source, XiFacetKind::PointerTouch), + Some(source_id) + ); + assert_eq!(state.buttons_down, 0); + assert!(state.sync_pending.is_empty()); + assert!(state.unpublished_pointer_buttons_down.is_empty()); +} + +#[test] +fn xi_device_changed_device_change_reason_uses_existing_facet_classes() { + use crate::{ + core_loop::DeviceInfo, + xinput::{InputCapabilities, InputSourceId, XiFacetKind}, + }; + + let mut state = ServerState::new(); + let mut selected = install_client(&mut state, 111); + let mut unrelated = install_client(&mut state, 112); + let source = InputSourceId(0xA72); + let info = DeviceInfo { + source_id: source, + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: "HyperX mouse".to_owned(), + device_node: "/dev/input/event-hyperx".to_owned(), + sysname: "event-hyperx".to_owned(), + vendor_id: 3, + product_id: 4, + is_touchpad: false, + config: Default::default(), + }; + let device_id = state.xi_register_source(&info)[0]; + state + .clients + .get_mut(&111) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, device_id), u64::from(XI2_DEVICE_CHANGED_MASK)); + + let dropped = crate::xinput::hotplug::emit_xi2_device_changed( + &mut state, + device_id, + crate::xinput::hotplug::XiDeviceChangeReason::DeviceChange, + device_id, + ); + assert!(dropped.is_empty()); + let wire = read_all_available(&mut selected); + let offset = (0..wire.len().saturating_sub(32)) + .find(|&offset| { + wire[offset] == 35 && u16::from_le_bytes([wire[offset + 8], wire[offset + 9]]) == 1 + }) + .expect("XI_DeviceChanged class update"); + assert_eq!( + u16::from_le_bytes([wire[offset + 10], wire[offset + 11]]), + device_id + ); + assert_eq!( + u16::from_le_bytes([wire[offset + 18], wire[offset + 19]]), + device_id + ); + assert_eq!(wire[offset + 20], 2, "XI2.h XIDeviceChange"); + let num_classes = u16::from_le_bytes([wire[offset + 16], wire[offset + 17]]) as usize; + assert_eq!(num_classes, 7); + let mut class_offset = offset + 32; + for _ in 0..num_classes { + assert_eq!( + u16::from_le_bytes([wire[class_offset + 4], wire[class_offset + 5]]), + device_id, + "class block identifies the changed facet" + ); + let units = u16::from_le_bytes([wire[class_offset + 2], wire[class_offset + 3]]) as usize; + class_offset += units * 4; + } + assert_eq!( + class_offset, + offset + + 32 + + u32::from_le_bytes(wire[offset + 4..offset + 8].try_into().unwrap()) as usize * 4 + ); + assert!(read_all_available(&mut unrelated).is_empty()); + assert_eq!( + state.xi_last_slave(2), + None, + "class-change emission is not a source switch" + ); + assert_eq!(state.xi_devices.devices().len(), 5); + assert!(state.xi_devices.source(source).is_some()); + assert_eq!( + state.xi_devices.facet(source, XiFacetKind::PointerTouch), + Some(device_id) + ); + assert!(state.sync_pending.is_empty()); + assert!(state.unpublished_pointer_buttons_down.is_empty()); +} + +#[test] +fn xi_select_events_rejects_hierarchy_changed_outside_all_devices() { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + for (sequence, device_id) in [1_u16, 2, 4].into_iter().enumerate() { + let mut body = Vec::new(); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&1_u16.to_le_bytes()); + body.extend_from_slice(&0_u16.to_le_bytes()); + body.extend_from_slice(&device_id.to_le_bytes()); + body.extend_from_slice(&1_u16.to_le_bytes()); + body.extend_from_slice(&(1_u32 << 11).to_le_bytes()); // XI_HierarchyChanged + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(u16::try_from(sequence + 1).unwrap()), + xi2_header(46), + &body, + ) + .expect("XISelectEvents dispatch"); + + let error = read_all_available(&mut peer); + assert_eq!( + error.len(), + 32, + "BadValue error for deviceid {device_id}; client={:?}; outbound={}", + state.clients[&1].xi2_masks, + state.clients[&1].outbound.len(), + ); + assert_eq!(error[0], 0, "an X11 error, not a reply"); + assert_eq!(error[1], yserver_protocol::x11::error::BAD_VALUE); + assert_eq!( + u32::from_le_bytes(error[4..8].try_into().unwrap()), + 11, + "errorValue is XI_HierarchyChanged" + ); + assert!( + !state.clients[&1] + .xi2_masks + .contains_key(&(ROOT_WINDOW, device_id)), + "the rejected selection leaves client masks unchanged" + ); + } + + let mut all_devices = Vec::new(); + all_devices.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + all_devices.extend_from_slice(&1_u16.to_le_bytes()); + all_devices.extend_from_slice(&0_u16.to_le_bytes()); + all_devices.extend_from_slice(&0_u16.to_le_bytes()); // XIAllDevices + all_devices.extend_from_slice(&1_u16.to_le_bytes()); + all_devices.extend_from_slice(&(1_u32 << 11).to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(8), + xi2_header(46), + &all_devices, + ) + .expect("XIAllDevices may select hierarchy changes"); + assert_eq!( + state.clients[&1].xi2_masks.get(&(ROOT_WINDOW, 0)), + Some(&(1_u64 << 11)) + ); + assert!(read_all_available(&mut peer).is_empty()); +} + +// ----------------------------------------------------------------- +// Tier 2 Task 4: device naming from the registry + XI1/XI2 sync +// ----------------------------------------------------------------- + +/// Drive XIQueryDevice (opcode 48) for XIAllDevices and parse out +/// `(id, name)` for each device in the little-endian reply. Validate +/// the reply length and every variable-sized device/class record. +fn query_device_ids_and_names( + state: &mut ServerState, + peer: &mut UnixStream, +) -> Vec<(u16, String)> { + let mut backend = RecordingBackend::new(); + handle_xi2_request( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(48), + &[0, 0, 0, 0], // deviceid=XIAllDevices, pad + ) + .expect("XIQueryDevice"); + let wire = read_all_available(peer); + assert_eq!(wire[0], 1, "XIQueryDevice reply, not an X error: {wire:?}"); + let reply_length = u32::from_le_bytes(wire[4..8].try_into().unwrap()) as usize; + assert_eq!( + wire.len(), + 32 + reply_length * 4, + "reply length covers all records" + ); + let num_devices = u16::from_le_bytes([wire[8], wire[9]]) as usize; + let mut off = 32; + let mut out = Vec::new(); + for _ in 0..num_devices { + assert!( + off + 12 <= wire.len(), + "device-info header is in reply bounds" + ); + let id = u16::from_le_bytes([wire[off], wire[off + 1]]); + let num_classes = u16::from_le_bytes([wire[off + 6], wire[off + 7]]) as usize; + let name_len = u16::from_le_bytes([wire[off + 8], wire[off + 9]]) as usize; + let name_start = off + 12; + assert!( + name_start + name_len <= wire.len(), + "device name is in reply bounds" + ); + let name = String::from_utf8(wire[name_start..name_start + name_len].to_vec()).unwrap(); + // Advance: 12-byte info header + name (padded to 4) + classes. + let mut pos = name_start + name_len; + while !pos.is_multiple_of(4) { + pos += 1; + } + // Walk class blocks by their 4-byte-unit length field (u16 at + // offset +2 of each class header). + for _ in 0..num_classes { + assert!(pos + 4 <= wire.len(), "class header is in reply bounds"); + let units = u16::from_le_bytes([wire[pos + 2], wire[pos + 3]]) as usize; + assert!(units > 0, "XI2 class record has a nonzero length"); + pos += units * 4; + assert!( + pos <= wire.len(), + "class record length stays in reply bounds" + ); + } + out.push((id, name)); + off = pos; + } + assert_eq!(off, wire.len(), "all reply bytes belong to device records"); + out +} + +#[test] +fn xiquerydevice_short_body_returns_well_formed_badlength_error() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(48), + &[], + ) + .expect("malformed XIQueryDevice is handled as an X error"); + + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(&wire[0..4], &[0, x11::error::BAD_LENGTH, 1, 0]); + assert_eq!(&wire[4..8], &[0, 0, 0, 0]); + assert_eq!(&wire[8..11], &[48, 0, 137]); + assert_eq!(&wire[11..], &[0; 21]); +} + +/// Drive XListInputDevices (XI 1.x, major 131 minor 2) and parse out +/// `(id, name)` for each device. +fn list_input_devices_ids_and_names( + state: &mut ServerState, + peer: &mut UnixStream, +) -> Vec<(u16, String)> { + let mut backend = RecordingBackend::new(); + let header = RequestHeader { + opcode: 131, + data: 2, + // ListInputDevices (XI minor 2) is Fixed(1): just the 4-byte + // request header = 1 unit. (Was 0 — pre-dated the length + // gate, now BadLengths before the handler enumerates devices.) + length_units: 1, + }; + handle_xi2_request( + state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + header, + &[], + ) + .expect("XListInputDevices"); + let wire = read_all_available(peer); + let ndevices = wire[8] as usize; + // Device-info array: 8 bytes each (type ATOM, id, num_classes, + // use, pad). Track ids and per-device class counts. + let mut ids = Vec::new(); + let mut class_counts = Vec::new(); + let mut off = 32; + for _ in 0..ndevices { + ids.push(u16::from(wire[off + 4])); + class_counts.push(wire[off + 5] as usize); + off += 8; + } + // Class-info blocks: walk by the BYTE length field (offset +1). + for &nc in &class_counts { + for _ in 0..nc { + let len = wire[off + 1] as usize; + off += len; + } + } + // STR name list: 1 length byte + bytes, in device order. + let mut out = Vec::new(); + for &id in &ids { + let n = wire[off] as usize; + let name = String::from_utf8(wire[off + 1..off + 1 + n].to_vec()).unwrap(); + out.push((id, name)); + off += 1 + n; + } + out +} + +#[test] +fn xiquerydevice_reports_slave_pointer_registry_name_after_rename() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + seed_pointer_for_t3(&mut state); + // Physical facets start at 6; 4 stays the virtual XTEST pointer. + state + .xi_devices + .iter_mut() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .name = "SynPS/2 Synaptics TouchPad".to_owned(); + + let devs = query_device_ids_and_names(&mut state, &mut peer); + let slave = devs + .iter() + .find(|(id, _)| *id == TEST_PHYSICAL_POINTER_ID) + .expect("physical touchpad facet"); + assert_eq!( + slave.1, "SynPS/2 Synaptics TouchPad", + "XIQueryDevice must report the physical facet's registry name" + ); + assert_eq!( + devs.iter().find(|(id, _)| *id == 4).unwrap().1, + crate::xinput::registry::NAME_XTEST_POINTER + ); +} + +#[test] +fn xi1_and_xi2_report_same_device_ids_and_names() { + // Default (no touchpad): both enumerations must agree. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let xi2 = query_device_ids_and_names(&mut state, &mut peer); + let xi1 = list_input_devices_ids_and_names(&mut state, &mut peer); + assert_eq!(xi2, xi1, "XI1 and XI2 must agree on (id, name) by default"); + + // A physical touchpad gets its own ID; both enumerations must + // still agree after that physical facet is renamed. + seed_pointer_for_t3(&mut state); + state + .xi_devices + .iter_mut() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .name = "ETPS/2 Elantech Touchpad".to_owned(); + let xi2 = query_device_ids_and_names(&mut state, &mut peer); + let xi1 = list_input_devices_ids_and_names(&mut state, &mut peer); + assert_eq!( + xi2, xi1, + "XI1 and XI2 must agree on (id, name) after a touchpad rename" + ); + assert_eq!( + xi2.iter() + .find(|(id, _)| *id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .1, + "ETPS/2 Elantech Touchpad", + "both enumerations carry the renamed physical touchpad facet" + ); + assert_eq!( + xi2.iter().find(|(id, _)| *id == 4).unwrap().1, + crate::xinput::registry::NAME_XTEST_POINTER + ); +} + +/// Device 4 must keep Xorg's CorePointerProc shape, while physical pointer +/// facets retain their GDK-compatible generic XI2 classes. +#[test] +fn xi_xtest_classes_query_device_4_has_core_pointer_shape() { + // Kills routing XTEST 4 through the physical pointer class encoder: + // that mutation returns seven classes, four axes, and scroll classes. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical_pointer = seed_pointer_for_t3(&mut state); + let before = xi_query_side_effect_snapshot(&state, 1); + + // XIQueryDevice(4), not XIAllDevices, is sent through process_request. + let (xtest_classes, xtest_num_classes) = + query_device_class_block(&mut state, &mut peer, crate::xinput::DEVICEID_XTEST_POINTER); + assert_eq!(xtest_num_classes, 3, "button + two valuator classes only"); + let xtest_classes_info = parse_xi2_class_headers(&xtest_classes, xtest_num_classes); + assert_eq!( + xtest_classes_info + .iter() + .map(|class| class.0) + .collect::>(), + [1, 2, 2], + "XTEST 4 has ButtonClass and exactly two ValuatorClass records" + ); + + let button = &xtest_classes_info[0]; + assert_eq!(button.1, 13, "10 buttons plus one state word"); + assert_eq!(u16::from_le_bytes([xtest_classes[6], xtest_classes[7]]), 10); + assert_eq!(u16::from_le_bytes([xtest_classes[4], xtest_classes[5]]), 4); + let expected_labels = [ + state.atoms.id_for("Button Left").unwrap().0, + state.atoms.id_for("Button Middle").unwrap().0, + state.atoms.id_for("Button Right").unwrap().0, + state.atoms.id_for("Button Wheel Up").unwrap().0, + state.atoms.id_for("Button Wheel Down").unwrap().0, + state.atoms.id_for("Button Horiz Wheel Left").unwrap().0, + state.atoms.id_for("Button Horiz Wheel Right").unwrap().0, + 0, + 0, + 0, + ]; + let actual_labels = (0..10) + .map(|index| { + let start = 12 + index * 4; + u32::from_le_bytes(xtest_classes[start..start + 4].try_into().unwrap()) + }) + .collect::>(); + assert_eq!( + actual_labels, expected_labels, + "XTEST labels are the seven core labels followed by three None atoms" + ); + + for (index, expected_label) in ["Rel X", "Rel Y"].into_iter().enumerate() { + let start = button.2 + button.1 * 4 + index * 44; + let class = &xtest_classes[start..start + 44]; + assert_eq!(u16::from_le_bytes([class[0], class[1]]), 2); + assert_eq!(u16::from_le_bytes([class[2], class[3]]), 11); + assert_eq!(u16::from_le_bytes([class[4], class[5]]), 4); + assert_eq!( + u16::from_le_bytes([class[6], class[7]]), + u16::try_from(index).unwrap() + ); + assert_eq!( + u32::from_le_bytes(class[8..12].try_into().unwrap()), + state.atoms.id_for(expected_label).unwrap().0 + ); + assert_eq!(i32::from_le_bytes(class[12..16].try_into().unwrap()), -1); + assert_eq!(i32::from_le_bytes(class[20..24].try_into().unwrap()), -1); + assert_eq!(class[40], 0, "Relative mode"); + } + + // The physical pointer stays on the existing generic 7-class shape. + let (physical_classes, physical_num_classes) = + query_device_class_block(&mut state, &mut peer, physical_pointer); + assert_eq!( + physical_num_classes, 7, + "physical pointer keeps its two scroll class declarations" + ); + let physical_classes_info = parse_xi2_class_headers(&physical_classes, physical_num_classes); + assert_eq!( + physical_classes_info + .iter() + .map(|class| class.0) + .collect::>(), + [1, 2, 2, 2, 2, 3, 3] + ); + assert_eq!( + u16::from_le_bytes([physical_classes[6], physical_classes[7]]), + 7 + ); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +/// Drive XIQueryDevice (opcode 48) and return the RAW class-block +/// bytes (and `num_classes`) for one exact device selector. +fn query_device_class_block( + state: &mut ServerState, + peer: &mut UnixStream, + target_id: u16, +) -> (Vec, u16) { + let mut body = target_id.to_le_bytes().to_vec(); + body.extend_from_slice(&[0, 0]); // XIQueryDevice pad + let wire = dispatch_xi_request_wire(state, peer, 1, 48, &body); + assert_eq!(wire[0], 1, "XIQueryDevice reply"); + let reply_length = u32::from_le_bytes(wire[4..8].try_into().unwrap()) as usize; + assert_eq!( + wire.len(), + 32 + reply_length * 4, + "reply length covers all records" + ); + let num_devices = u16::from_le_bytes([wire[8], wire[9]]) as usize; + let mut off = 32; + for _ in 0..num_devices { + let id = u16::from_le_bytes([wire[off], wire[off + 1]]); + let num_classes = u16::from_le_bytes([wire[off + 6], wire[off + 7]]); + let name_len = u16::from_le_bytes([wire[off + 8], wire[off + 9]]) as usize; + let mut pos = off + 12 + name_len; + while !pos.is_multiple_of(4) { + pos += 1; + } + let classes_start = pos; + for _ in 0..num_classes { + let units = u16::from_le_bytes([wire[pos + 2], wire[pos + 3]]) as usize; + pos += units * 4; + } + if id == target_id { + return (wire[classes_start..pos].to_vec(), num_classes); + } + off = pos; + } + panic!("requested device not present in XIQueryDevice reply"); +} + +fn parse_xi2_class_headers(classes: &[u8], num_classes: u16) -> Vec<(u16, usize, usize)> { + let mut parsed = Vec::with_capacity(usize::from(num_classes)); + let mut offset = 0; + for _ in 0..num_classes { + let class_type = u16::from_le_bytes([classes[offset], classes[offset + 1]]); + let units = usize::from(u16::from_le_bytes([ + classes[offset + 2], + classes[offset + 3], + ])); + assert!(units > 0, "XI2 class record has a nonzero length"); + parsed.push((class_type, units, offset)); + offset += units * 4; + } + assert_eq!(offset, classes.len(), "all bytes belong to class records"); + parsed +} + +/// XI1 reports `None` for masters and XTEST devices, while physical +/// pointer devices retain their MOUSE atom and class descriptors. +#[test] +fn xi_xtest_classes_xi1_list_and_open_device_match_xtest_pointer() { + // Kills reverting ids 2..5 to MOUSE/KEYBOARD atoms, or reusing the + // physical pointer's 7-button / four-axis ListInputDevices classes. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let physical_info = crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(u64::from(line!())), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: "Logitech USB mouse".into(), + device_node: "/dev/input/event-mouse".into(), + sysname: "event-mouse".into(), + vendor_id: 0x046d, + product_id: 0xc52f, + is_touchpad: false, + config: Default::default(), + }; + let physical_pointer = state.xi_register_source(&physical_info)[0]; + let mouse_atom = state.atoms.id_for(crate::xinput::XI_ATOM_MOUSE).unwrap().0; + let touchpad_info = crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(u64::from(line!())), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: "SynPS/2 Synaptics TouchPad".into(), + device_node: "/dev/input/event-touchpad".into(), + sysname: "event-touchpad".into(), + vendor_id: 0x06cb, + product_id: 0x00bd, + is_touchpad: true, + config: Default::default(), + }; + let physical_touchpad = state.xi_register_source(&touchpad_info)[0]; + let touchpad_atom = state + .atoms + .id_for(crate::xinput::XI_ATOM_TOUCHPAD) + .unwrap() + .0; + let keyboard_info = crate::core_loop::DeviceInfo { + source_id: crate::xinput::InputSourceId(u64::from(line!())), + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: true, + pointer: false, + touch: false, + }, + name: "USB keyboard".into(), + device_node: "/dev/input/event-keyboard".into(), + sysname: "event-keyboard".into(), + vendor_id: 0x046d, + product_id: 0xc31c, + is_touchpad: false, + config: Default::default(), + }; + let physical_keyboard = state.xi_register_source(&keyboard_info)[0]; + let keyboard_atom = state + .atoms + .id_for(crate::xinput::XI_ATOM_KEYBOARD) + .unwrap() + .0; + let before = xi_query_side_effect_snapshot(&state, 1); + + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 2, &[]); + assert_eq!(wire[0], 1, "XListInputDevices reply"); + let reply_length = u32::from_le_bytes(wire[4..8].try_into().unwrap()) as usize; + assert_eq!( + wire.len(), + 32 + reply_length * 4, + "reply length covers records" + ); + let count = usize::from(wire[8]); + let mut device_records = Vec::with_capacity(count); + let mut offset = 32; + for _ in 0..count { + let type_atom = u32::from_le_bytes(wire[offset..offset + 4].try_into().unwrap()); + let id = u16::from(wire[offset + 4]); + let class_count = wire[offset + 5]; + device_records.push((id, type_atom, class_count)); + offset += 8; + } + assert_eq!( + device_records + .iter() + .filter(|(id, _, _)| (2..=5).contains(id)) + .map(|(id, atom, _)| (*id, *atom)) + .collect::>(), + [(2, 0), (3, 0), (4, 0), (5, 0)], + "master and XTEST types are None" + ); + assert_eq!( + device_records + .iter() + .find(|(id, _, _)| *id == physical_pointer) + .unwrap() + .1, + mouse_atom, + "physical pointer type remains MOUSE" + ); + assert_eq!( + device_records + .iter() + .find(|(id, _, _)| *id == physical_touchpad) + .unwrap() + .1, + touchpad_atom, + "physical touchpad type remains TOUCHPAD" + ); + assert_eq!( + device_records + .iter() + .find(|(id, _, _)| *id == physical_keyboard) + .unwrap() + .1, + keyboard_atom, + "physical keyboard type remains KEYBOARD" + ); + + let mut xtest_pointer_classes = Vec::new(); + let mut physical_pointer_classes = Vec::new(); + for (device_id, _, class_count) in &device_records { + for _ in 0..*class_count { + let class_type = wire[offset]; + let class_len = usize::from(wire[offset + 1]); + assert!(class_len >= 4, "XI1 class descriptor has a valid length"); + if *device_id == crate::xinput::DEVICEID_XTEST_POINTER { + xtest_pointer_classes.push(wire[offset..offset + class_len].to_vec()); + } else if *device_id == physical_pointer { + physical_pointer_classes.push(wire[offset..offset + class_len].to_vec()); + } + assert!(matches!(class_type, 0..=3 | 5..=6)); + offset += class_len; + } + } + assert_eq!( + xtest_pointer_classes + .iter() + .map(|class| class[0]) + .collect::>(), + [1, 2], + "XTEST XI1 listing has ButtonClass and ValuatorClass" + ); + assert_eq!( + u16::from_le_bytes([xtest_pointer_classes[0][2], xtest_pointer_classes[0][3]]), + 10 + ); + assert_eq!(xtest_pointer_classes[1][2], 2, "XTEST has two valuators"); + assert_eq!( + xtest_pointer_classes[1][3], 0, + "XTEST valuators are relative" + ); + for axis in 0..2 { + let axis_start = 8 + axis * 12; + assert_eq!( + i32::from_le_bytes( + xtest_pointer_classes[1][axis_start + 4..axis_start + 8] + .try_into() + .unwrap() + ), + -1 + ); + assert_eq!( + i32::from_le_bytes( + xtest_pointer_classes[1][axis_start + 8..axis_start + 12] + .try_into() + .unwrap() + ), + -1 + ); + } + assert_eq!( + physical_pointer_classes + .iter() + .map(|class| class[0]) + .collect::>(), + [1, 2], + "physical XI1 pointer still has its existing classes" + ); + assert_eq!( + u16::from_le_bytes([ + physical_pointer_classes[0][2], + physical_pointer_classes[0][3] + ]), + 7 + ); + assert_eq!(physical_pointer_classes[1][2], 4); + + // XOpenDevice exposes class/event-base tags sourced from the same + // button and valuator classes (`Xi/opendev.c:120-155`). + let opened = dispatch_xi_request_wire(&mut state, &mut peer, 2, 3, &[4, 0, 0, 0]); + assert_eq!(opened.len(), 40, "four class tags follow the reply header"); + assert_eq!(opened[0], 1, "XOpenDevice reply"); + assert_eq!(opened[8], 4, "button, valuator, feedback, and other"); + assert_eq!(&opened[32..40], &[1, 69, 2, 71, 3, 0, 6, 76]); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn a_fresh_master_keeps_core_pointer_classes_of_its_own_and_is_sent_no_bootstrap() { + // Xorg's CorePointerProc creates 10 buttons and two relative valuators + // with no scroll classes (dix/devices.c:655-700; InitCoreDevices calls + // it at :724-730), each class sourced from the master itself + // (dix/devices.c:1357,1433). Selecting DeviceChanged reports nothing. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut select_body = Vec::new(); + select_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select_body.extend_from_slice(&1u16.to_le_bytes()); + select_body.extend_from_slice(&[0; 2]); + select_body.extend_from_slice(&0u16.to_le_bytes()); // XIAllDevices + select_body.extend_from_slice(&1u16.to_le_bytes()); + select_body.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); + let wire = dispatch_xi_request_wire(&mut state, &mut peer, 1, 46, &select_body); + assert_eq!(device_changed_events(&wire), []); + let (query_classes, query_num_classes) = query_device_class_block(&mut state, &mut peer, 2); + assert_eq!(query_num_classes, 3); + let class_headers = parse_xi2_class_headers(&query_classes, query_num_classes); + assert_eq!( + class_headers + .iter() + .map(|class| class.0) + .collect::>(), + [1, 2, 2] + ); + assert_eq!( + u16::from_le_bytes([query_classes[4], query_classes[5]]), + 2, + "the master's own classes are sourced from it" + ); + assert_eq!( + u16::from_le_bytes([query_classes[6], query_classes[7]]), + 10, + "CorePointerProc button class has ten buttons" + ); +} + +#[test] +fn legacy_device_changed_fanout_emits_for_selected_xtest_pointer() { + // Kills routing XTEST 4 through the generic physical pointer encoder; + // Xorg `CorePointerProc` defines 10 buttons and two relative axes. + use crate::{ + core_loop::fanout::emit_xi2_device_changed_slave_pointer, xinput::DEVICEID_XTEST_POINTER, + }; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let xtest_pointer = state + .xi_devices + .device(DEVICEID_XTEST_POINTER) + .expect("XTEST pointer"); + assert_eq!( + xtest_pointer.name, + crate::xinput::registry::NAME_XTEST_POINTER + ); + assert!( + xtest_pointer + .properties + .contains_key(&state.xtest_device_atom) + ); + let before = xi_query_side_effect_snapshot(&state, 1); + // Install the real XISelectEvents mask through the core dispatcher. + let mut select_body = Vec::new(); + select_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select_body.extend_from_slice(&1u16.to_le_bytes()); // num_masks + select_body.extend_from_slice(&0u16.to_le_bytes()); // pad + select_body.extend_from_slice(&DEVICEID_XTEST_POINTER.to_le_bytes()); + select_body.extend_from_slice(&1u16.to_le_bytes()); // mask_len + select_body.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); + assert!(dispatch_xi_request_wire(&mut state, &mut peer, 1, 46, &select_body).is_empty()); + assert!( + state.clients[&1] + .xi2_masks + .contains_key(&(ROOT_WINDOW, DEVICEID_XTEST_POINTER)) + ); + + // This helper emits only the bootstrapped XTEST pointer event; the + // physical source registry owns all dynamically allocated facets. + let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); + assert!(dropped.is_empty()); + let wire = read_all_available(&mut peer); + let off = (0..wire.len().saturating_sub(32)) + .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) + .expect("legacy XI_DeviceChanged fanout"); + assert_eq!(wire[off + 10], 4, "deviceid = XTEST pointer"); + assert_eq!(wire[off + 18], 4, "sourceid = the XTEST pointer itself"); + assert_eq!(wire[off + 20], 2, "reason = XIDeviceChange"); + assert_eq!(wire[off + 16], 3, "Button + two Valuator classes"); + + // A second helper call exercises the same selected-device fanout. + let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); + assert!(dropped.is_empty()); + let wire = read_all_available(&mut peer); + let off = (0..wire.len().saturating_sub(32)) + .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) + .expect("second legacy XI_DeviceChanged fanout"); + assert_eq!(wire[off + 10], 4, "deviceid = XTEST pointer"); + + // Clear the selection through XISelectEvents and confirm no request + // or event state remains after this scenario. + let mut unselect_body = Vec::new(); + unselect_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + unselect_body.extend_from_slice(&1u16.to_le_bytes()); // num_masks + unselect_body.extend_from_slice(&0u16.to_le_bytes()); // pad + unselect_body.extend_from_slice(&DEVICEID_XTEST_POINTER.to_le_bytes()); + unselect_body.extend_from_slice(&0u16.to_le_bytes()); // mask_len = remove + assert!(dispatch_xi_request_wire(&mut state, &mut peer, 4, 46, &unselect_body).is_empty()); + assert!( + !state.clients[&1] + .xi2_masks + .contains_key(&(ROOT_WINDOW, DEVICEID_XTEST_POINTER)) + ); + assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); +} + +#[test] +fn xtest_device_changed_is_not_selected_by_all_master_devices() { + use crate::core_loop::fanout::emit_xi2_device_changed_slave_pointer; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 1), u64::from(XI2_DEVICE_CHANGED_MASK)); + + let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); + assert!(dropped.is_empty()); + assert!( + read_all_available(&mut peer).is_empty(), + "XIAllMasterDevices must not receive DeviceChanged for XTEST slave 4", + ); + assert_eq!( + state + .xi_devices + .device(crate::xinput::DEVICEID_XTEST_POINTER) + .map(|d| d.id), + Some(crate::xinput::DEVICEID_XTEST_POINTER), + "only the static XTEST pointer is involved", + ); + assert_eq!( + state.xi_devices.source_ids().len(), + 0, + "the event must not pretend a physical source is device 4", + ); +} + +#[test] +fn device_changed_is_noop_when_no_client_selected() { + use crate::core_loop::fanout::emit_xi2_device_changed_slave_pointer; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // No xi2_masks selection → no event. + let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); + assert!(dropped.is_empty()); + assert!( + read_all_available(&mut peer).is_empty(), + "no DeviceChanged when nothing selected" + ); +} + +#[test] +fn device_changed_not_sent_for_selection_on_non_root_window() { + // DeviceChanged is a root-window hierarchy event. A client that + // selected it on some unrelated (non-root) window must NOT get it + // — otherwise the fanout spuriously delivers to the wrong window. + use crate::{ + core_loop::fanout::emit_xi2_device_changed_slave_pointer, xinput::DEVICEID_XTEST_POINTER, + }; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let non_root = ResourceId(0x4000_0001); + state.clients.get_mut(&1).unwrap().xi2_masks.insert( + (non_root, DEVICEID_XTEST_POINTER), + u64::from(XI2_DEVICE_CHANGED_MASK), + ); + let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); + assert!(dropped.is_empty()); + assert!( + read_all_available(&mut peer).is_empty(), + "selection on a non-root window must not receive DeviceChanged" + ); +} + +#[test] +fn xi_list_properties_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + seed_one_prop(&mut state, 200, 8, vec![2]); + + // body: XTEST pointer deviceid + pad. + let body = [ + u8::try_from(crate::xinput::DEVICEID_XTEST_POINTER).unwrap(), + 0, + 0, + 0, + ]; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(56), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!( + wire.len(), + 32 + 16, + "32 header + XTEST marker + Device Enabled + 2 client atoms" + ); + assert_eq!(wire[0], 1, "X_Reply"); + assert_eq!( + u32::from_le_bytes(wire[4..8].try_into().unwrap()), + 4, + "length" + ); + assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 4, "num_properties"); + let mut atoms = wire[32..] + .chunks_exact(4) + .map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap())) + .collect::>(); + let mut expected = vec![ + state.xtest_device_atom.0, + state.xi_device_enabled_atom.0, + 100, + 200, + ]; + atoms.sort_unstable(); + expected.sort_unstable(); + assert_eq!(atoms, expected, "the virtual XTEST Device marker is listed"); +} + +#[test] +fn xi_list_properties_bad_device() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = [99u8, 0, 0, 0]; // deviceid 99 — not present + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(7), + xi2_header(56), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "error is 32 bytes"); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!( + wire[1], XI2_FIRST_ERROR, + "BadDevice = XI2_FIRST_ERROR (157)" + ); + // sequence at bytes 2-3. + assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 7); +} + +#[test] +fn xi_get_property_full_read_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![0xAB]); + + // body: XTEST pointer deviceid, delete(1)=0, pad(1), property(4)=100, + // type(4)=0(Any), offset(4)=0, len(4)=100. + let mut body = Vec::new(); + body.extend_from_slice(&crate::xinput::DEVICEID_XTEST_POINTER.to_le_bytes()); + body.push(0); // delete + body.push(0); // pad + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(59), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32 + 4, "header + 1 byte padded to 4"); + assert_eq!( + u32::from_le_bytes(wire[8..12].try_into().unwrap()), + 19, + "type=INTEGER" + ); + assert_eq!( + u32::from_le_bytes(wire[12..16].try_into().unwrap()), + 0, + "bytes_after" + ); + assert_eq!( + u32::from_le_bytes(wire[16..20].try_into().unwrap()), + 1, + "num_items" + ); + assert_eq!(wire[20], 8, "format"); + assert_eq!(wire[32], 0xAB, "value byte"); +} + +#[test] +fn xi_get_property_bad_delete_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // XTEST pointer 4 exists; delete = 2 (illegal) → BadValue. + // Pre-register atom 100 so the BadAtom guard (T3) doesn't fire + // before the bad-delete check we're actually exercising. + state.atoms.register_for_test(AtomId(100), "test-prop-100"); + let mut body = Vec::new(); + body.extend_from_slice(&crate::xinput::DEVICEID_XTEST_POINTER.to_le_bytes()); + body.push(2); // delete = 2 (illegal) + body.push(0); + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&1u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(3), + xi2_header(59), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!(wire[1], 2, "BadValue"); +} + +#[test] +fn xi_change_then_get_roundtrip_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Pre-register atom 100 so the T3 BadAtom guard accepts it. + state.atoms.register_for_test(AtomId(100), "test-prop-100"); + + // XIChangeProperty: deviceid(2)=4, mode(1)=Replace, format(1)=8, + // property(4)=100, type(4)=INTEGER(19), num_items(4)=3, data=[7,8,9]+pad. + let mut body = Vec::new(); + body.extend_from_slice(&crate::xinput::DEVICEID_XTEST_POINTER.to_le_bytes()); + body.push(0); // mode Replace + body.push(8); // format + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&19u32.to_le_bytes()); + body.extend_from_slice(&3u32.to_le_bytes()); + body.extend_from_slice(&[7, 8, 9, 0]); // 3 data bytes + 1 pad + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(57), + &body, + ) + .unwrap(); + // ChangeProperty has no reply. + assert!(read_all_available(&mut peer).is_empty()); + + // GetProperty back. + let mut gbody = Vec::new(); + gbody.extend_from_slice(&crate::xinput::DEVICEID_XTEST_POINTER.to_le_bytes()); + gbody.push(0); + gbody.push(0); + gbody.extend_from_slice(&100u32.to_le_bytes()); + gbody.extend_from_slice(&0u32.to_le_bytes()); + gbody.extend_from_slice(&0u32.to_le_bytes()); + gbody.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header(59), + &gbody, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!( + u32::from_le_bytes(wire[16..20].try_into().unwrap()), + 3, + "num_items" + ); + assert_eq!(&wire[32..35], &[7, 8, 9], "value round-trips"); +} + +#[test] +fn xi_change_property_bad_format_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = Vec::new(); + body.extend_from_slice(&crate::xinput::DEVICEID_XTEST_POINTER.to_le_bytes()); + body.push(0); // mode + body.push(7); // format = 7 (illegal) + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&19u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(4), + xi2_header(57), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!(wire[1], 2, "BadValue"); +} + +#[test] +fn xi_change_property_unknown_device_outranks_bad_format() { + // Error-precedence: xserver ProcXIChangeProperty (xiproperty.c:1137) + // does the device lookup before validating mode/format, so an + // unknown device + illegal format must yield BadDevice, not BadValue. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = Vec::new(); + body.extend_from_slice(&99u16.to_le_bytes()); // deviceid 99 — absent + body.push(0); // mode + body.push(7); // format = 7 (illegal) + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&19u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(5), + xi2_header(57), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!(wire[1], XI2_FIRST_ERROR, "BadDevice outranks BadValue"); + assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 5, "sequence"); +} + +#[test] +fn xi_delete_property_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + + // body: XTEST pointer deviceid, pad(2), property(4)=100. + let mut body = Vec::new(); + body.extend_from_slice(&crate::xinput::DEVICEID_XTEST_POINTER.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(58), + &body, + ) + .unwrap(); + // No reply for DeleteProperty. + assert!(read_all_available(&mut peer).is_empty()); + let dev = state + .xi_devices + .device(crate::xinput::DEVICEID_XTEST_POINTER) + .unwrap(); + assert!( + !dev.properties.contains_key(&AtomId(100)), + "property removed" + ); +} + +/// GTK4 (gnome-text-editor, modern GTK apps) sets per-widget +/// cursors through XInput2's `XIChangeCursor` (opcode 42), not +/// core X11's `XDefineCursor`. Pre-fix the handler was a logging +/// no-op, so the I-beam cursor over a text widget never reached +/// the backend and the area kept showing the default arrow. +/// Treat it as `XDefineCursor` (per-device cursors aren't routed +/// yet; a single effective cursor on the window matches what +/// `AllMasterDevices`-style calls produce in practice). +#[test] +fn xi_change_cursor_propagates_define_cursor_to_backend() { + use crate::backend::recording::RecordedCall; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0030; + const HOST_XID: u32 = 0x0040_0030; + const CURSOR_XID: u32 = 0x0090_0001; + const CURSOR_HOST_XID: u32 = 0x00a0_0001; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 80, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + state + .resources + .create_cursor(ClientId(CLIENT_ID), ResourceId(CURSOR_XID)); + state.resources.set_cursor_host_xid( + ResourceId(CURSOR_XID), + crate::backend::CursorHandle::from_raw_panicking(CURSOR_HOST_XID), + ); + + // XIChangeCursor body: window(4), cursor(4), deviceid(2), pad(2). + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body.extend_from_slice(&CURSOR_XID.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, // doesn't matter — dispatcher is bypassed + data: 42, // XIChangeCursor minor + // XIChangeCursor is Fixed(4): 4 header + window(4) + cursor(4) + // + deviceid(2) + pad(2) = 16 bytes = 4 units. (Was 3 — pre- + // dated the length gate, now BadLengths before the handler.) + length_units: 4, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("handle_xi2_request"); + + let define_cursor_calls: Vec<_> = backend + .calls() + .into_iter() + .filter(|c| matches!(c, RecordedCall::DefineCursor { .. })) + .collect(); + assert_eq!( + define_cursor_calls, + vec![RecordedCall::DefineCursor { + host_window_xid: HOST_XID, + cursor_host_xid: CURSOR_HOST_XID, + }], + "XIChangeCursor must propagate to `backend.define_cursor` \ + so GTK4's per-widget cursor (I-beam on text areas, etc.) \ + becomes effective. Pre-fix the handler was a logging \ + no-op — gnome-text-editor and other GTK4 apps kept the \ + default arrow over text widgets.", + ); + + // cursor = None (xid 0) clears the per-window cursor. + let mut body_none = Vec::with_capacity(12); + body_none.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body_none.extend_from_slice(&0u32.to_le_bytes()); + body_none.extend_from_slice(&0u16.to_le_bytes()); + body_none.extend_from_slice(&[0u8; 2]); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(2), + header, + &body_none, + ) + .expect("handle_xi2_request none"); + + let define_cursor_calls: Vec<_> = backend + .calls() + .into_iter() + .filter(|c| matches!(c, RecordedCall::DefineCursor { .. })) + .collect(); + assert_eq!( + define_cursor_calls, + vec![ + RecordedCall::DefineCursor { + host_window_xid: HOST_XID, + cursor_host_xid: CURSOR_HOST_XID, + }, + RecordedCall::DefineCursor { + host_window_xid: HOST_XID, + cursor_host_xid: 0, + }, + ], + "XIChangeCursor with cursor=None (xid 0) must invoke \ + `backend.define_cursor(window, 0)` — same X11 None \ + semantics as the CWA cursor path.", + ); +} + +/// XI2 generic events of `evtype` on `wire`, as `(deviceid, sourceid)`: +/// DeviceChanged keeps its source at bytes 18-19 (`xXIDeviceChangedEvent`), +/// a raw event after its detail, at 20-21 (`xXIRawEvent`). +fn xi2_sources(wire: &[u8], evtype: u16) -> Vec<(u16, u16)> { + let source_at = if evtype == 1 { 18 } else { 20 }; + let mut found = Vec::new(); + let mut at = 0; + while at + 32 <= wire.len() { + let length = if wire[at] == 35 || wire[at] == 1 { + 32 + u32::from_le_bytes(wire[at + 4..at + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + if wire[at] == 35 && u16::from_le_bytes([wire[at + 8], wire[at + 9]]) == evtype { + found.push(( + u16::from_le_bytes([wire[at + 10], wire[at + 11]]), + u16::from_le_bytes([wire[at + source_at], wire[at + source_at + 1]]), + )); + } + at += length; + } + found +} + +/// A window system's seat as slaves of the core pair (a rootless host's +/// "Wayland pointer", as Xwayland's xwayland-pointer): its button reaches +/// Wine's raw-input selection on the masters with the slave as its source, +/// after a SlaveSwitch naming that slave, which Wine opens with XOpenDevice +/// (`X11DRV_RawButtonEvent`, `X11DRV_DeviceChanged`). A master as either +/// source is BadDevice to XOpenDevice and ends the Wine process. +#[test] +fn a_seat_slaves_button_names_the_slave_as_its_source() { + use crate::{ + backend::recording::RecordingBackend, + core_loop::{DeviceInfo, InputOrigin, pointer_fanout::pointer_event_fanout_to_state}, + host_x11::{HostPointerEvent, HostXidMap, PointerEventKind}, + xinput::{InputCapabilities, InputSourceId}, + }; + const XI_RAW_BUTTON_PRESS: u16 = 15; + + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 101); + let mut backend = RecordingBackend::new(); + let request = |state: &mut ServerState, backend: &mut RecordingBackend, minor, body: &[u8]| { + handle_xi2_request( + state, + backend, + None, + ClientId(101), + SequenceNumber(1), + RequestHeader { + opcode: 131, + data: minor, + length_units: u32::try_from((4 + body.len()).div_ceil(4)).unwrap(), + }, + body, + ) + .expect("XI request"); + }; + // XIQueryVersion 2.2, then Wine's selection on the masters. + request(&mut state, &mut backend, 47, &[2, 0, 2, 0]); + let mut select = Vec::new(); + select.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice(&0u16.to_le_bytes()); + select.extend_from_slice(&1u16.to_le_bytes()); // XIAllMasterDevices + select.extend_from_slice(&1u16.to_le_bytes()); + select.extend_from_slice( + &(XI2_DEVICE_CHANGED_MASK | (1u32 << XI_RAW_BUTTON_PRESS)).to_le_bytes(), + ); + request(&mut state, &mut backend, 46, &select); + let _ = read_all_available(&mut peer); + + let source = InputSourceId(u64::MAX - 1); + let slave = state.xi_register_source(&DeviceInfo { + source_id: source, + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: "Wayland pointer".to_owned(), + device_node: String::new(), + sysname: String::new(), + vendor_id: 0, + product_id: 0, + is_touchpad: false, + config: Default::default(), + })[0]; + assert_ne!(slave, crate::xinput::DEVICEID_MASTER_POINTER); + let press = HostPointerEvent { + origin: InputOrigin::Physical(source), + kind: PointerEventKind::ButtonPress, + detail: 1, + host_xid: 0, + time: 2, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + press, + true, + false, + ); + let wire = read_all_available(&mut peer); + let switches = xi2_sources(&wire, 1); + let raw = xi2_sources(&wire, XI_RAW_BUTTON_PRESS); + assert!( + !raw.is_empty(), + "the raw button reached the masters' selection" + ); + assert_eq!( + switches, + [(crate::xinput::DEVICEID_MASTER_POINTER, slave)], + "one SlaveSwitch, naming the slave" + ); + assert!( + raw.iter().all(|&(_, sourceid)| sourceid == slave), + "raw buttons sourced from the slave: {raw:?}" + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi2_allow.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi2_allow.rs new file mode 100644 index 000000000..1b45e8601 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi2_allow.rs @@ -0,0 +1,3377 @@ +use super::*; + +/// `XIPassiveGrabDevice` with grab_type=Button(0) installs entries +/// in `state.button_grabs`; grab_type=Keycode(1) installs entries +/// in `state.key_grabs`. One entry per modifier (or one entry with +/// modifiers=0 when num_modifiers=0). `XIPassiveUngrabDevice` +/// removes matching entries. +#[test] +fn xi_passive_grab_device_pushes_button_and_key_grabs() { + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0051; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + // Helper to build XIPassiveGrabDevice body per + // `xXIPassiveGrabDeviceReq` in X11/extensions/XI2proto.h: + // time, grab_window, cursor, detail, deviceid, num_modifiers, + // mask_len, grab_type, grab_mode, paired_device_mode, + // owner_events, pad1, mask, modifiers. + fn build_body( + window: u32, + detail: u32, + device_id: u16, + grab_type: u8, + modifiers: &[u32], + ) -> Vec { + #[allow(clippy::cast_possible_truncation)] + let num_modifiers = modifiers.len() as u16; + let mut b = Vec::with_capacity(28 + modifiers.len() * 4); + b.extend_from_slice(&0u32.to_le_bytes()); // time + b.extend_from_slice(&window.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); // cursor + b.extend_from_slice(&detail.to_le_bytes()); + b.extend_from_slice(&device_id.to_le_bytes()); + b.extend_from_slice(&num_modifiers.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); // mask_len + b.push(grab_type); + b.push(1); // grab_mode async + b.push(1); // paired async + b.push(0); // owner_events + b.extend_from_slice(&0u16.to_le_bytes()); // pad1 + for m in modifiers { + b.extend_from_slice(&m.to_le_bytes()); + } + b + } + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 54, + // XIPassiveGrabDevice is AtLeast(8) and has no exact-length + // gate (modifier count is read from the body's num_modifiers + // field, not derived from the request length). 8 is the spec + // minimum; was 6, which pre-dated the REQUEST_SIZE_MATCH gate + // and now BadLengths before the handler runs. + length_units: 8, + }; + + // Button grab on button 3 with modifiers [0, ControlMask(4)]. + let body = build_body( + WINDOW_XID, + 3, + crate::xinput::DEVICEID_MASTER_POINTER, + 0, + &[0, 4], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("button grab"); + assert_eq!(state.button_grabs.len(), 2, "one grab per modifier"); + assert!( + state + .button_grabs + .iter() + .any(|g| g.button == 3 && g.modifiers == 0) + ); + assert!( + state + .button_grabs + .iter() + .any(|g| g.button == 3 && g.modifiers == 4) + ); + + // Key grab on keycode 67 (F1) with no modifiers → single entry + // with modifier-mask 0. + let body = build_body( + WINDOW_XID, + 67, + crate::xinput::DEVICEID_MASTER_KEYBOARD, + 1, + &[], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(2), + header, + &body, + ) + .expect("key grab"); + assert_eq!(state.key_grabs.len(), 1); + assert_eq!(state.key_grabs[0].keycode, 67); + assert_eq!(state.key_grabs[0].modifiers, 0); + + // XI2 "Any" modifier (bit 31) → core X11 AnyModifier (0x8000). + let body = build_body( + WINDOW_XID, + 1, + crate::xinput::DEVICEID_MASTER_POINTER, + 0, + &[0x8000_0000], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(3), + header, + &body, + ) + .expect("any-modifier grab"); + assert!( + state + .button_grabs + .iter() + .any(|g| g.button == 1 && g.modifiers == 0x8000), + "XI2 Any (bit 31) maps to core X11 AnyModifier 0x8000", + ); + + // XIPassiveUngrabDevice — body: window(4) detail(4) deviceid(2) + // num_modifiers(2) grab_type(1) pad(3) modifiers. + fn build_ungrab_body( + window: u32, + detail: u32, + device_id: u16, + grab_type: u8, + modifiers: &[u32], + ) -> Vec { + #[allow(clippy::cast_possible_truncation)] + let num_modifiers = modifiers.len() as u16; + let mut b = Vec::with_capacity(16 + modifiers.len() * 4); + b.extend_from_slice(&window.to_le_bytes()); + b.extend_from_slice(&detail.to_le_bytes()); + b.extend_from_slice(&device_id.to_le_bytes()); + b.extend_from_slice(&num_modifiers.to_le_bytes()); + b.push(grab_type); + b.extend_from_slice(&[0u8; 3]); + for m in modifiers { + b.extend_from_slice(&m.to_le_bytes()); + } + b + } + let ungrab_header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 55, + // XIPassiveUngrabDevice is AtLeast(5), no exact gate. 5 is the + // spec minimum; was 4 (pre-gate placeholder → BadLength now). + length_units: 5, + }; + let body = build_ungrab_body( + WINDOW_XID, + 3, + crate::xinput::DEVICEID_MASTER_POINTER, + 0, + &[0, 4], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(4), + ungrab_header, + &body, + ) + .expect("button ungrab"); + assert!( + !state + .button_grabs + .iter() + .any(|g| g.button == 3 && (g.modifiers == 0 || g.modifiers == 4)), + "ungrab removes the matching button+modifier entries", + ); + // AnyModifier grab still present (we didn't ungrab it). + assert!( + state + .button_grabs + .iter() + .any(|g| g.button == 1 && g.modifiers == 0x8000) + ); +} + +/// Regression test for the XIPassiveGrabDevice field-offset bug. +/// `mask_len` and `grab_type` were swapped: a real client (muffin, +/// xfwm4) sending mask_len=2 + grab_type=Keycode(1) was mis-parsed +/// as grab_type=Enter(2), silently dropping every keyboard +/// accelerator. The body here matches `xXIPassiveGrabDeviceReq` +/// in `X11/extensions/XI2proto.h` byte-for-byte with mask_len=2, +/// which is what real WM clients send. +#[test] +fn xi_passive_grab_device_keycode_with_xi2_mask() { + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0051; + const KEYCODE: u32 = 116; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + // Spec-shaped body with mask_len=2 (two 4-byte mask words, + // matching what muffin emits for XI device-event masks). + let mut body = Vec::with_capacity(28 + 8 + 4); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); // grab_window + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&KEYCODE.to_le_bytes()); // detail + body.extend_from_slice(&3u16.to_le_bytes()); // deviceid (keyboard) + body.extend_from_slice(&1u16.to_le_bytes()); // num_modifiers + body.extend_from_slice(&2u16.to_le_bytes()); // mask_len = 2 + body.push(1); // grab_type = Keycode + body.push(1); // grab_mode async + body.push(1); // paired async + body.push(0); // owner_events + body.extend_from_slice(&0u16.to_le_bytes()); // pad1 + body.extend_from_slice(&[0u8; 8]); // mask (2 words) + body.extend_from_slice(&0u32.to_le_bytes()); // modifier 0 + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 54, + length_units: 10, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("keycode grab with mask"); + + assert_eq!( + state.key_grabs.len(), + 1, + "Keycode grab must be recorded — bug was misclassifying \ + as grab_type=Enter due to swapped mask_len/grab_type" + ); + #[allow(clippy::cast_possible_truncation)] + let expected_kc = KEYCODE as u8; + assert_eq!(state.key_grabs[0].keycode, expected_kc); + assert_eq!(state.key_grabs[0].modifiers, 0); + assert!(state.button_grabs.is_empty()); +} + +/// `XIAllowEvents` with `mode=AsyncDevice(0)` releases the +/// passive grab on the calling client's device, matching what +/// mutter/cinnamon shell call after their click-to-focus button +/// grab activates. Before this handler shipped, the call was a +/// debug-logged stub so `state.pointer_grab` stayed pinned until +/// the next ButtonRelease, leaking the grab across intermediate +/// motion events. +#[test] +fn xi_allow_events_async_device_releases_passive_pointer_grab() { + const CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x0010_0051; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + // Seed a SYNC passive grab that has activated: the grab is held, + // the device frozen, and the activating press stored — exactly the + // state the pointer-fanout Step-3 path leaves after a matched click. + set_test_pointer_grab(&mut state, CLIENT_ID, GRAB_WIN, true, false); + state.xi1_frozen.insert( + crate::xinput::DEVICEID_MASTER_POINTER, + crate::server::Xi1Freeze { + state: crate::server::Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + + // Body per `xXIAllowEventsReq`: time(4) + deviceid(2) + + // mode(1) + pad(1). deviceid=2 (master pointer), mode=0 + // (AsyncDevice). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(0); // mode = AsyncDevice + body.push(0); // pad + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + // AsyncDevice thaws the frozen pointer so events flow again (Xorg + // AsyncPointer). Per Xorg the passive grab itself persists until the + // button is released — what matters is the device is no longer + // frozen (the freeze gate would otherwise queue every later event). + assert!( + !state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .is_some_and(crate::server::Xi1Freeze::frozen), + "AsyncDevice must thaw the frozen pointer device" + ); +} + +#[test] +fn xi_allow_events_replay_device_replays_frozen_button_press_to_target() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const TARGET_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0051; + const TARGET_WIN: u32 = 0x0020_0052; + const HOST_XID: u32 = 0xCAFE_0001; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer + .set_nonblocking(true) + .expect("grab peer nonblocking"); + target_peer + .set_nonblocking(true) + .expect("target peer nonblocking"); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(TARGET_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + let _ = state.resources.map_window(ResourceId(TARGET_WIN)); + state + .clients + .get_mut(&TARGET_CLIENT_ID) + .expect("target client") + .event_masks + .insert(ResourceId(TARGET_WIN), 0x0000_0004); + + set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer( + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + )); + } + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) + .expect("register host xid"); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(2); // mode = ReplayDevice + body.push(0); // pad + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(TARGET_CLIENT_ID), ResourceId(TARGET_WIN))), + "the replayed press must install the implicit grab on the natural \ + recipient (#94 — Xorg ActivateImplicitGrab on the replayed delivery)" + ); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && !g.via_xi2), + "replayed core press installs a core-form implicit grab" + ); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_none() + ); + + let mut buf = [0u8; 32]; + let grab_read = grab_peer.read(&mut buf); + assert!( + matches!(grab_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "grab owner must not receive replayed ButtonPress; got {grab_read:?}", + ); + let target_read = target_peer.read(&mut buf); + assert!( + matches!(target_read, Ok(32)), + "target window subscriber should receive replayed ButtonPress; got {target_read:?}", + ); + assert_eq!(buf[0], 4, "event type should be ButtonPress"); + assert_eq!(&buf[12..16], &TARGET_WIN.to_le_bytes()); +} + +/// Regression for the MATE submenu-hover bug. mate-panel holds an +/// active XI2 grab on its main panel window with `owner_events=true`; +/// menu items it pops up are top-level override-redirect windows +/// OWNED BY mate-panel (siblings of the grab window, not +/// descendants). Pre-fix the active-grab-redirect check used pure +/// topology (`target == grab_window || is_descendant_of`), +/// which redirected motion on the menu items to the grab window +/// with grab-relative coords — GTK couldn't track which menu item +/// the cursor was over, hover-delay never fired the submenu. +/// The fix adds an ownership-aware path: window owned by the grab +/// client qualifies for natural delivery alongside descendants. +/// Note: this is a heuristic — the fully spec-correct rule is "the +/// event would normally be reported to the grab client" (a mask- +/// subscription check). Ownership is a close proxy: clients almost +/// always select events on windows they own. +#[test] +fn active_grab_owner_events_natural_delivery_to_sibling_window_owned_by_grab_client() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::ActivePointerGrab, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x0010_0070; + const SIBLING_WIN: u32 = 0x0010_0071; // top-level, owned by same client, not descendant of grab window + const HOST_GRAB_XID: u32 = 0xCAFE_0070; + const HOST_SIBLING_XID: u32 = 0xCAFE_0071; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut backend = RecordingBackend::new(); + peer.set_nonblocking(true).expect("nonblocking"); + + // Create two top-level windows under root, both owned by the + // grab client. They are siblings (both children of root), not + // in an ancestor relationship — the exact topology for + // mate-panel + popup-menu. + for (xid, host_xid) in [(GRAB_WIN, HOST_GRAB_XID), (SIBLING_WIN, HOST_SIBLING_XID)] { + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(xid)); + Backend::register_top_level(&mut backend, None, ResourceId(xid), host_xid) + .expect("register host xid"); + } + // XI2 mask selecting motion on the sibling window (the menu + // item the cursor will move over). XI_Motion evtype = 6 → + // mask bit 1<<6 = 0x40. + state + .clients + .get_mut(&GRAB_CLIENT_ID) + .expect("client") + .xi2_masks + .insert((ResourceId(SIBLING_WIN), 2), 0x40); + + // Install active grab on GRAB_WIN with owner_events=true. + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + event_mask: 0, + cursor: ResourceId(0), + time: 0, + owner_events: true, + via_xi2: true, + implicit: false, + passive: false, + xi2_mask: u64::MAX, + }); + // Sanity: sibling is NOT a descendant of grab window. + assert!( + !state + .resources + .is_descendant_of(ResourceId(SIBLING_WIN), ResourceId(GRAB_WIN)) + ); + // And IS owned by the grab client. + assert_eq!( + state.resources.window_owner(ResourceId(SIBLING_WIN)), + Some(ClientId(GRAB_CLIENT_ID)), + ); + + // Cursor at root_x=50, root_y=50 — landing on SIBLING_WIN. + // host_xid = SIBLING's host xid so the v2-style hit-test lands + // on the sibling window naturally. + let motion = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::MotionNotify, + host_xid: HOST_SIBLING_XID, + detail: 0, + time: 0x1000, + root_x: 50, + root_y: 50, + event_x: 50, + event_y: 50, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); + + // Read whatever landed on the wire. With the ownership-aware + // natural-delivery check, the XI2 motion must report against + // the sibling window (event=SIBLING_WIN) with sensible coords + // (event_x ≈ 50), NOT redirected to the grab window with + // grab-relative coords. Pre-fix the event would be on + // GRAB_WIN with grab-clamped coords — for this layout + // (sibling at the same root origin) the difference might be + // subtle in coords but the `event` window XID is the + // smoking-gun: GRAB vs SIBLING. + let mut buf = [0u8; 256]; + let n = peer.read(&mut buf).expect("client got at least one event"); + assert!(n >= 32, "expected at least one event, got {n} bytes"); + // Scan for a Generic XI2 event (type=35, second byte=major opcode of XInputExtension). + // We just need to find the `event` window XID in the body. + let mut found_sibling = false; + let mut found_grab = false; + let mut i = 0; + while i + 32 <= n { + // Generic event byte 0 is type. XI2 Motion event window + // sits at a known offset; rather than parsing the full + // event structure, scan for either window XID in the + // first 64 bytes of the body. Cheap+robust. + let slice = &buf[i..(i + 64).min(n)]; + if slice.windows(4).any(|w| w == SIBLING_WIN.to_le_bytes()) { + found_sibling = true; + } + if slice.windows(4).any(|w| w == GRAB_WIN.to_le_bytes()) { + found_grab = true; + } + i += 32; + } + assert!( + found_sibling, + "XI2 motion must address the sibling window (owner=grab client) under owner_events=true; got buf bytes {:?}", + &buf[..n.min(64)], + ); + // The grab window XID may also appear (e.g., in root/sourceid + // fields by coincidence) so we don't assert !found_grab — the + // load-bearing assertion is that the natural target window + // shows up in the body. + let _ = found_grab; +} + +/// Regression for the MATE menu-click bug: when a release was +/// queued during a sync passive grab freeze (because the WM hadn't +/// yet called AllowEvents), the replay path MUST drain both the +/// frozen press AND the queued release to the natural target — in +/// that order. Pre-fix the release leaked through during freeze +/// and the press was never replayed (frozen state cleared by the +/// rogue release path), so the app saw release-then-nothing. +#[test] +fn xi_allow_events_replay_device_drains_queued_release_after_press() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const TARGET_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0061; + const TARGET_WIN: u32 = 0x0020_0062; + const HOST_XID: u32 = 0xCAFE_0010; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer + .set_nonblocking(true) + .expect("grab peer nonblocking"); + target_peer + .set_nonblocking(true) + .expect("target peer nonblocking"); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(TARGET_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + let _ = state.resources.map_window(ResourceId(TARGET_WIN)); + // Target client selects ButtonPress | ButtonRelease. + state + .clients + .get_mut(&TARGET_CLIENT_ID) + .expect("target client") + .event_masks + .insert(ResourceId(TARGET_WIN), 0x0000_000c); + + set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x1c33, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); + } + // Queue a release that arrived while frozen. + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 0x1c89, + ..press + }; + state + .sync_pending + .push_back(crate::server::PendingSyncEvent { + device: crate::xinput::DEVICEID_MASTER_POINTER, + event: crate::server::QueuedInputEvent::HostPointer(release), + }); + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) + .expect("register host xid"); + + // XIAllowEvents ReplayDevice on master pointer (deviceid=2). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.push(2); // mode = ReplayDevice + body.push(0); // pad + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + // Both frozen slots cleared after drain. + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_none() + ); + assert!( + !state + .sync_pending + .iter() + .any(|p| p.device == crate::xinput::DEVICEID_MASTER_POINTER) + ); + assert!(state.active_pointer_grab.is_none()); + assert_eq!( + state.buttons_down, 0, + "replayed press and queued release leave the master clear" + ); + assert_eq!( + state.xi_devices.device(4).unwrap().buttons_down, + 0, + "replayed press and queued release leave XTEST 4 clear" + ); + + // Grab owner must not receive the replayed events (they go to + // the natural target). + let mut buf = [0u8; 32]; + let grab_read = grab_peer.read(&mut buf); + assert!( + matches!(grab_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "grab owner must not receive replay; got {grab_read:?}", + ); + + // Target must receive BOTH events in order. Read a sequence of + // 32-byte core events, expecting Press(type=4) then + // Release(type=5). The XI2 fanout would also fire (each event + // shipping a GenericEvent), so we read until we've seen one + // press and one release. + let mut saw_press = false; + let mut saw_release = false; + let mut press_offset = usize::MAX; + let mut release_offset = usize::MAX; + let mut total_read = 0usize; + // Slurp whatever the wire has — bound the read loop to avoid + // hanging if something goes wrong. + for iter in 0..8 { + let mut chunk = [0u8; 256]; + match target_peer.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + // Scan 32-byte boundaries for core ButtonPress(4) + // / ButtonRelease(5). GenericEvents (XI2) are + // type=35 and longer; their first byte still + // shows up at a 32-byte offset. + let mut i = 0; + while i + 32 <= n { + let evt_type = chunk[i] & 0x7F; + if evt_type == 4 && !saw_press { + saw_press = true; + press_offset = total_read + i; + } else if evt_type == 5 && !saw_release { + saw_release = true; + release_offset = total_read + i; + } + // GenericEvent is variable-length; advance by 32 conservatively. + i += 32; + } + total_read += n; + if saw_press && saw_release { + break; + } + } + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(e) => panic!("target read failed at iter {iter}: {e}"), + } + } + assert!(saw_press, "target must receive replayed ButtonPress"); + assert!(saw_release, "target must receive queued ButtonRelease"); + assert!( + press_offset < release_offset, + "Press must arrive BEFORE Release at the target (got press@{press_offset}, release@{release_offset})", + ); +} + +/// Regression: XI2 `XIAllowEvents(AsyncDevice)` must thaw the unified +/// per-device freeze AND replay the events withheld during the freeze. +/// muffin (Cinnamon) installs XI2 sync passive button grabs; activating +/// one engages `xi1_frozen[POINTER]` via `xi1_check_grab_for_syncs`, +/// after which the unified-freeze gate queues every core pointer event. +/// The XI2 AllowEvents handler historically never touched `xi1_frozen`, +/// so `AsyncDevice` left the pointer frozen forever and dropped the +/// withheld queue — the Cinnamon desktop never saw the drag's +/// ButtonRelease, leaving the selection rubber-band stuck. (Core grabs +/// — marco/xfwm4 — thaw via the core AllowEvents path, so MATE/XFCE +/// were unaffected.) +#[test] +fn xi_allow_events_async_device_thaws_freeze_and_replays_queue() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::{Xi1Freeze, Xi1SyncState}, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const TARGET_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0061; + const TARGET_WIN: u32 = 0x0020_0062; + const HOST_XID: u32 = 0xCAFE_0005; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer + .set_nonblocking(true) + .expect("grab peer nonblocking"); + target_peer + .set_nonblocking(true) + .expect("target peer nonblocking"); + + for (client, win) in [(GRAB_CLIENT_ID, GRAB_WIN), (TARGET_CLIENT_ID, TARGET_WIN)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + // Target selects ButtonPress | ButtonRelease. + state + .clients + .get_mut(&TARGET_CLIENT_ID) + .expect("target client") + .event_masks + .insert(ResourceId(TARGET_WIN), 0x0000_000c); + + // muffin's sync passive grab has activated: grab held, the + // activating press already delivered to the owner, the pointer + // device frozen, and a release queued during the freeze. + set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); + // The activated passive grab's defining record (present for any + // real activation) — its mask is what the drain-path redirect + // reports to the grab owner. + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + button: 1, + modifiers: 0x8000, + owner_events: false, + event_mask: 0x0000_000c, // press|release + pointer_mode: 0, // sync + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + state.xi1_frozen.insert( + crate::xinput::DEVICEID_MASTER_POINTER, + Xi1Freeze { + state: Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x2a00, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); + } + state + .sync_pending + .push_back(crate::server::PendingSyncEvent { + device: crate::xinput::DEVICEID_MASTER_POINTER, + event: crate::server::QueuedInputEvent::HostPointer(HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 0x2a50, + ..press + }), + }); + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) + .expect("register host xid"); + + // XIAllowEvents AsyncDevice on master pointer (deviceid=2). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(0); // mode = AsyncDevice + body.push(0); // pad + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + // The unified pointer freeze must be thawed — otherwise every + // later core pointer event is queued-then-dropped (dead pointer). + assert!( + !state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .is_some_and(crate::server::Xi1Freeze::frozen), + "AsyncDevice must thaw the unified per-device pointer freeze" + ); + assert!( + state.active_pointer_grab.is_none(), + "passive grab ended by the terminating (replayed) release, not by AsyncDevice" + ); + assert!( + !state + .sync_pending + .iter() + .any(|p| p.device == crate::xinput::DEVICEID_MASTER_POINTER), + "withheld queue must be replayed, not left pending" + ); + + // AsyncDevice thaws WITHOUT deactivating the grab (Xorg AllowSome + // THAWED, dix/events.c:1857 — DeactivateGrab is the NOT_GRABBED + // /Replay case only). So the withheld release replays THROUGH the + // grab (ComputeFreezes → PlayReleasedEvents → DeliverGrabbedEvent): + // it is reported to the GRAB OWNER on the grab window, then the + // terminating release ends the passive grab. It must NOT leak to + // the foreign natural target (pre-implicit-grab #94 bug). + assert!( + peer_saw_event(&mut grab_peer, 5, None), + "withheld ButtonRelease must replay THROUGH the grab to its owner \ + on AsyncDevice thaw" + ); + assert!( + !peer_saw_event(&mut target_peer, 5, None), + "the grab intercepts the release — it must not leak to the foreign \ + natural target (#94)" + ); +} + +/// Helper: drain a nonblocking peer and return true if any 32-byte core +/// event with `type & 0x7f == want_type` (and, if `want_detail` is Some, +/// matching `detail` byte) was delivered. +fn peer_saw_event(peer: &mut UnixStream, want_type: u8, want_detail: Option) -> bool { + for _ in 0..8 { + let mut chunk = [0u8; 512]; + match peer.read(&mut chunk) { + Ok(0) => return false, + Ok(n) => { + let mut i = 0; + while i + 32 <= n { + if chunk[i] & 0x7F == want_type && want_detail.is_none_or(|d| chunk[i + 1] == d) + { + return true; + } + i += 32; + } + } + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => return false, + Err(e) => panic!("peer read failed: {e}"), + } + } + false +} + +/// ISSUE 1 (known-issues.md 2026-07-15): `AllowEvents` admission keys ONLY +/// on the unified per-device sync state (Xorg `AllowSome`, +/// dix/events.c:1851). When the device is thawed in unified state, a +/// `ReplayDevice` from the grabbing client is a no-op — nothing is +/// replayed — regardless of any residual/legacy activating event. +#[test] +fn xi_allow_events_replay_no_op_when_unified_thawed() { + use crate::{ + resources::ROOT_VISUAL, + server::{Xi1Freeze, Xi1SyncState}, + }; + const GRAB_CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x0010_0101; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + grab_peer.set_nonblocking(true).expect("nonblocking"); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + state + .clients + .get_mut(&GRAB_CLIENT_ID) + .expect("grab client") + .event_masks + .insert(ResourceId(GRAB_WIN), 0x0000_000c); // ButtonPress|ButtonRelease + + set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); + // Unified state THAWED — the sole admission authority says "not frozen". + state.xi1_frozen.insert( + crate::xinput::DEVICEID_XTEST_POINTER, + Xi1Freeze { + state: Xi1SyncState::Thawed, + ..Default::default() + }, + ); + + // XIAllowEvents XIReplayDevice (mode 2) on master pointer (deviceid=2). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(2); // XIReplayDevice + body.push(0); + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + assert!( + !peer_saw_event(&mut grab_peer, 4, None) && !peer_saw_event(&mut grab_peer, 5, None), + "ReplayDevice on a unified-thawed device must be a no-op (no stale replay)" + ); +} + +/// ISSUE 2 (known-issues.md 2026-07-15): a thaw via a path OTHER than +/// AllowEvents must still replay the withheld queue (Xorg ComputeFreezes -> +/// PlayReleasedEvents, dix/events.c:1368-1372), not drop it. Drives the +/// production representation (`sync_pending`) that the freeze gate fills. +#[test] +fn out_of_band_pointer_thaw_replays_withheld_release() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::{PendingSyncEvent, QueuedInputEvent, Xi1Freeze, Xi1SyncState}, + }; + const GRAB_CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x0010_0111; + const HOST_XID: u32 = 0xCAFE_0011; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + grab_peer.set_nonblocking(true).expect("nonblocking"); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + state + .clients + .get_mut(&GRAB_CLIENT_ID) + .expect("grab client") + .event_masks + .insert(ResourceId(GRAB_WIN), 0x0000_000c); + Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) + .expect("register host xid"); + + set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); + // A real activated passive grab always has its defining + // `button_grabs` record present; the drain-path redirect reads its + // `event_mask` to know what to report to the grab owner (Xorg + // DeliverGrabbedEvent consults the grab's own mask). Without it the + // grab captures the release but reports nothing. + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + button: 1, + modifiers: 0x8000, + owner_events: false, + event_mask: 0x0000_000c, // press|release + pointer_mode: 0, // sync + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + state.xi1_frozen.insert( + crate::xinput::DEVICEID_XTEST_POINTER, + Xi1Freeze { + state: Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + // A release withheld during the freeze, in the global queue (what the + // production QUEUE-WHILE-FROZEN gate pushes). + state.sync_pending.push_back(PendingSyncEvent { + device: crate::xinput::DEVICEID_XTEST_POINTER, + event: QueuedInputEvent::HostPointer(HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + host_xid: HOST_XID, + detail: 1, + time: 0x2a50, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }), + }); + + // OUT-OF-BAND thaw (NOT AllowEvents). + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_thaw_device( + &mut state, + &mut backend, + &xid_map, + crate::xinput::DEVICEID_XTEST_POINTER, + ); + + assert!( + peer_saw_event(&mut grab_peer, 5, None), + "withheld ButtonRelease must be replayed on an out-of-band thaw, not dropped" + ); + assert!( + state.sync_pending.is_empty(), + "the global queue must be drained on thaw" + ); +} + +/// Global-queue replay preserves arrival order ACROSS devices (Xorg +/// PlayReleasedEvents over the single `syncEvents.pending`, +/// dix/events.c:1233-1291): a keyboard event queued before a pointer event +/// is replayed first when both thaw in a single `xi1_compute_freezes` pass. +#[test] +fn compute_freezes_replays_global_queue_in_arrival_order() { + use crate::{ + backend::Backend, + host_x11::{HostKeyEvent, HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::{CoreFocus, PendingSyncEvent, QueuedInputEvent, Xi1Freeze, Xi1SyncState}, + }; + const CLIENT_ID: u32 = 1; + const WIN: u32 = 0x0010_0121; + const HOST_XID: u32 = 0xCAFE_0021; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + peer.set_nonblocking(true).expect("nonblocking"); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WIN)); + Backend::register_top_level(&mut backend, None, ResourceId(WIN), HOST_XID) + .expect("register host xid"); + // KeyPress|KeyRelease|ButtonPress|ButtonRelease. + state + .clients + .get_mut(&CLIENT_ID) + .expect("client") + .event_masks + .insert(ResourceId(WIN), 0x0000_000f); + // Key delivery routes to the core focus window. + state.core_focus = CoreFocus { + raw: WIN, + revert_to: 0, + time: 0, + }; + + for dev in [ + crate::xinput::DEVICEID_XTEST_KEYBOARD, + crate::xinput::DEVICEID_XTEST_POINTER, + ] { + state.xi1_frozen.insert( + dev, + Xi1Freeze { + state: Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + } + // Enqueue KEY (release) THEN POINTER (release), in that global order. + state.sync_pending.push_back(PendingSyncEvent { + device: crate::xinput::DEVICEID_XTEST_KEYBOARD, + event: QueuedInputEvent::HostKey(HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed: false, + keycode: 38, + time: 0x1000, + root_x: 5, + root_y: 5, + event_x: 5, + event_y: 5, + state: 0, + }), + }); + state.sync_pending.push_back(PendingSyncEvent { + device: crate::xinput::DEVICEID_XTEST_POINTER, + event: QueuedInputEvent::HostPointer(HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + host_xid: HOST_XID, + detail: 1, + time: 0x2000, + root_x: 5, + root_y: 5, + event_x: 5, + event_y: 5, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }), + }); + + // Thaw BOTH, then ONE replay pass. + for dev in [ + crate::xinput::DEVICEID_XTEST_KEYBOARD, + crate::xinput::DEVICEID_XTEST_POINTER, + ] { + state.xi1_frozen.get_mut(&dev).unwrap().state = Xi1SyncState::Thawed; + } + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_compute_freezes(&mut state, &mut backend, &xid_map); + + // Read the full wire once and compare offsets: KeyRelease (3) precedes + // ButtonRelease (5). + let mut buf = [0u8; 8192]; + let n = peer.read(&mut buf).expect("read wire"); + assert!( + n >= 64, + "expected both replayed events on the wire (got {n} bytes)" + ); + let mut key_pos = None; + let mut btn_pos = None; + let mut i = 0; + while i + 32 <= n { + let ty = buf[i] & 0x7F; + if ty == 3 && key_pos.is_none() { + key_pos = Some(i); + } + if ty == 5 && btn_pos.is_none() { + btn_pos = Some(i); + } + i += 32; + } + assert!( + key_pos.is_some() && btn_pos.is_some(), + "both the keyboard and pointer events must be delivered (key={key_pos:?} btn={btn_pos:?})" + ); + assert!( + key_pos < btn_pos, + "keyboard event (queued first) must replay before the pointer event" + ); + assert!(state.sync_pending.is_empty(), "queue fully drained"); +} + +/// Regression for the double-button-map hazard: the freeze gate stores the +/// PHYSICAL detail, and replay re-enters button mapping exactly once. With +/// a non-identity `pointer_mapping_override` (physical 1 -> logical 3), the +/// replayed release must carry logical button 3 (mapped once), not a +/// twice-mapped value. +#[test] +fn frozen_pointer_replay_maps_button_exactly_once() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::{Xi1Freeze, Xi1SyncState}, + }; + const CLIENT_ID: u32 = 1; + const WIN: u32 = 0x0010_0131; + const HOST_XID: u32 = 0xCAFE_0031; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + peer.set_nonblocking(true).expect("nonblocking"); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WIN)); + Backend::register_top_level(&mut backend, None, ResourceId(WIN), HOST_XID) + .expect("register host xid"); + state + .clients + .get_mut(&CLIENT_ID) + .expect("client") + .event_masks + .insert(ResourceId(WIN), 0x0000_000c); + + // Physical button 1 -> logical 3 (identity for 2/3). + state.pointer_mapping_override = Some(vec![3, 2, 1]); + // Pointer frozen so the release is withheld at the gate. + state.xi1_frozen.insert( + crate::xinput::DEVICEID_XTEST_POINTER, + Xi1Freeze { + state: Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + + let xid_map = backend.xid_map().clone(); + // Drive a PHYSICAL button-1 release through the real fanout: the gate + // withholds it into sync_pending with the physical detail preserved. + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + host_xid: HOST_XID, + detail: 1, + time: 0x2a50, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = crate::core_loop::pointer_fanout::pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + release, + true, + false, + ); + assert_eq!( + state.sync_pending.len(), + 1, + "release must be withheld while frozen" + ); + + // Thaw and replay. + crate::core_loop::pointer_fanout::xi1_thaw_device( + &mut state, + &mut backend, + &xid_map, + crate::xinput::DEVICEID_XTEST_POINTER, + ); + + // The delivered ButtonRelease must carry LOGICAL button 3 (mapped once). + assert!( + peer_saw_event(&mut peer, 5, Some(3)), + "replayed release must map physical 1 -> logical 3 exactly once (not double-mapped)" + ); +} + +/// XI2 mode → core AllowSome mode mapping ([`xi2_allow_mode_to_core`]). +#[test] +fn xi2_allow_mode_to_core_maps_all_modes() { + // Pointer: Async/Sync/Replay → Pointer variants. + assert_eq!(xi2_allow_mode_to_core(0, false), Some(0)); // AsyncDevice → AsyncPointer + assert_eq!(xi2_allow_mode_to_core(1, false), Some(1)); // SyncDevice → SyncPointer + assert_eq!(xi2_allow_mode_to_core(2, false), Some(2)); // ReplayDevice → ReplayPointer + // Keyboard: → Keyboard variants. + assert_eq!(xi2_allow_mode_to_core(0, true), Some(3)); // → AsyncKeyboard + assert_eq!(xi2_allow_mode_to_core(1, true), Some(4)); // → SyncKeyboard + assert_eq!(xi2_allow_mode_to_core(2, true), Some(5)); // → ReplayKeyboard + // paired: AsyncPairedDevice acts on the OTHER device. + assert_eq!(xi2_allow_mode_to_core(3, false), Some(3)); // ptr grab → async keyboard + assert_eq!(xi2_allow_mode_to_core(3, true), Some(0)); // kbd grab → async pointer + assert_eq!(xi2_allow_mode_to_core(4, false), Some(6)); // AsyncPair → AsyncBoth + assert_eq!(xi2_allow_mode_to_core(5, false), Some(7)); // SyncPair → SyncBoth + // touch / unknown → unsupported. + assert_eq!(xi2_allow_mode_to_core(6, false), None); // XIAcceptTouch + assert_eq!(xi2_allow_mode_to_core(7, false), None); // XIRejectTouch +} + +/// Regression: XI2 `XIAllowEvents(XISyncDevice)` (mode 1) must thaw the +/// frozen device and replay the withheld queue. It used to be a no-op +/// ("we're always-async"), so muffin's click-to-focus SYNC path (mutter +/// `events.c` `maybe_unfreeze_pointer_events(EVENTS_UNFREEZE_SYNC)`) +/// could not clear the freeze → `QUEUE-WHILE-FROZEN` piled up → the +/// Cinnamon clicks-and-typing-dead freeze. Now routed through the shared +/// `apply_allow_events` (core SyncPointer). +#[test] +fn xi_allow_events_sync_device_thaws_and_drains_queue() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const GRAB_CLIENT_ID: u32 = 1; + const TARGET_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0071; + const TARGET_WIN: u32 = 0x0020_0072; + const HOST_XID: u32 = 0xCAFE_0007; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer.set_nonblocking(true).expect("nonblocking"); + target_peer.set_nonblocking(true).expect("nonblocking"); + + for (client, win) in [(GRAB_CLIENT_ID, GRAB_WIN), (TARGET_CLIENT_ID, TARGET_WIN)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + state + .clients + .get_mut(&TARGET_CLIENT_ID) + .expect("target") + .event_masks + .insert(ResourceId(TARGET_WIN), 0x0000_000c); + + // Activated SYNC passive grab: held, frozen, activating press stored, + // a release withheld during the freeze. + set_test_pointer_grab(&mut state, GRAB_CLIENT_ID, GRAB_WIN, true, false); + // The activated passive grab's defining record (its mask is what + // the drain-path redirect reports to the grab owner). + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: 0, + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + button: 1, + modifiers: 0x8000, + owner_events: false, + event_mask: 0x0000_000c, // press|release + pointer_mode: 0, // sync + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: false, + }); + state.xi1_frozen.insert( + crate::xinput::DEVICEID_MASTER_POINTER, + crate::server::Xi1Freeze { + state: crate::server::Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x10, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); + } + state + .sync_pending + .push_back(crate::server::PendingSyncEvent { + device: crate::xinput::DEVICEID_MASTER_POINTER, + event: crate::server::QueuedInputEvent::HostPointer(HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 0x20, + ..press + }), + }); + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) + .expect("register host xid"); + + // XIAllowEvents XISyncDevice (mode 1) on master pointer (deviceid 2). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(1); // mode = XISyncDevice + body.push(0); // pad + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + assert!( + !state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .is_some_and(crate::server::Xi1Freeze::frozen), + "XISyncDevice must thaw the frozen pointer (was a no-op → Cinnamon freeze)" + ); + assert!( + !state + .sync_pending + .iter() + .any(|p| p.device == crate::xinput::DEVICEID_MASTER_POINTER), + "withheld queue must be drained on XISyncDevice" + ); + + // XISyncDevice (FREEZE_NEXT_EVENT) thaws WITHOUT deactivating the + // grab (Xorg AllowSome, dix/events.c:1864 — only NOT_GRABBED + // /Replay deactivates). The withheld release replays THROUGH the + // grab (DeliverGrabbedEvent) to the grab owner, then the + // terminating release ends the passive grab; it must NOT leak to + // the foreign natural target (#94). + assert!( + peer_saw_event(&mut grab_peer, 5, None), + "withheld ButtonRelease must replay THROUGH the grab to its owner \ + on XISyncDevice" + ); + assert!( + !peer_saw_event(&mut target_peer, 5, None), + "the grab intercepts the release — it must not leak to the foreign \ + natural target (#94)" + ); +} + +#[test] +fn xi_allow_events_replay_device_releases_active_pointer_grab() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::ActivePointerGrab, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const TARGET_WIN: u32 = 0x0020_0052; + const HOST_XID: u32 = 0xCAFE_0003; + + let mut state = ServerState::new(); + let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(TARGET_WIN)); + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(TARGET_WIN), + event_mask: 0xFFFF, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: true, + implicit: false, + passive: false, + xi2_mask: u64::MAX, + }); + // ReplayDevice only acts on a FROZEN device with a stored event to + // replay (Xorg AllowSome) — engage the sync freeze + activating press. + state.xi1_frozen.insert( + crate::xinput::DEVICEID_MASTER_POINTER, + crate::server::Xi1Freeze { + state: crate::server::Xi1SyncState::FrozenNoEvent, + ..Default::default() + }, + ); + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer( + HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + )); + } + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) + .expect("register host xid"); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(2); // mode = ReplayDevice + body.push(0); // pad + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events replay pointer"); + + assert!(state.active_pointer_grab.is_none()); +} + +#[test] +fn xi_sync_passive_grab_replays_xi2_press_to_target_only_after_allow_events() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::PassiveButtonGrab, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const TARGET_CLIENT_ID: u32 = 2; + const TARGET_WIN: u32 = 0x0020_0052; + const HOST_XID: u32 = 0xCAFE_0002; + const XI2_BUTTON_PRESS_BIT: u32 = 1 << 4; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut target_peer = install_client(&mut state, TARGET_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer + .set_nonblocking(true) + .expect("grab peer nonblocking"); + target_peer + .set_nonblocking(true) + .expect("target peer nonblocking"); + + state.resources.create_window( + ClientId(TARGET_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(TARGET_WIN)); + state + .clients + .get_mut(&GRAB_CLIENT_ID) + .expect("grab client") + .xi2_masks + .insert((ResourceId(TARGET_WIN), 1), u64::from(XI2_BUTTON_PRESS_BIT)); + state + .clients + .get_mut(&TARGET_CLIENT_ID) + .expect("target client") + .xi2_masks + .insert((ResourceId(TARGET_WIN), 1), u64::from(XI2_BUTTON_PRESS_BIT)); + state.button_grabs.push(PassiveButtonGrab { + device_id: 0, + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(TARGET_WIN), + button: 1, + modifiers: 0, + owner_events: false, + event_mask: 0xFFFF_FFFF, + pointer_mode: 0, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: true, + }); + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WIN), HOST_XID) + .expect("register host xid"); + + let event = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x1234, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, event, true, false); + + assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_some() + ); + + let mut buf = [0u8; 128]; + let target_read = target_peer.read(&mut buf); + assert!( + matches!(target_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "sync passive XI2 grab must withhold the initial XI2 press from the target; got {target_read:?}", + ); + let grab_read = grab_peer.read(&mut buf); + assert!( + matches!(grab_read, Ok(n) if n > 0), + "grab owner should receive the grabbed press stream; got {grab_read:?}", + ); + + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0x1234u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.push(2); // mode = ReplayDevice + body.push(0); // pad + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + let target_read = target_peer.read(&mut buf); + assert!( + matches!(target_read, Ok(n) if n >= 32 && buf[0] == 35), + "ReplayDevice must redeliver the XI2 press to the natural target; got {target_read:?}", + ); +} + +#[test] +fn xi_sync_passive_grab_release_during_freeze_queues_for_replay() { + // Regression: in a sync passive grab, a ButtonRelease arriving + // BEFORE the grab owner sends AllowEvents must NOT clear the + // grab nor leak to the natural target — it must queue alongside + // the activating press for replay. Pre-fix, the release cleared + // `frozen_pointer_event` + `pointer_grab_is_passive`, so when + // AllowEvents(ReplayPointer/ReplayDevice) finally arrived there + // was nothing to replay. Visible symptom on MATE: marco's slow + // ~10 round-trip grab handler vs a fast click → app never sees + // the press → menu/titlebar clicks dead. + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::PassiveButtonGrab, + }; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0020_0053; + const HOST_XID: u32 = 0xCAFE_0004; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + state.button_grabs.push(PassiveButtonGrab { + device_id: 0, + owner: ClientId(CLIENT_ID), + grab_window: ResourceId(WINDOW_XID), + button: 1, + modifiers: 0, + owner_events: true, + event_mask: 0xFFFF_FFFF, + pointer_mode: 0, // Synchronous → triggers freeze + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: true, + }); + Backend::register_top_level(&mut backend, None, ResourceId(WINDOW_XID), HOST_XID) + .expect("register host xid"); + + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x1234, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_some() + ); + // No ButtonRelease is withheld yet — it hasn't arrived. (The unified + // queue may already hold the activating press's XI1 form; that is + // expected — Xorg stores the activating event too. We assert on the + // RELEASE specifically, which is what this test is about.) + assert!( + !state + .sync_pending + .iter() + .any(|p| p.device == crate::xinput::DEVICEID_MASTER_POINTER + && matches!( + &p.event, + crate::server::QueuedInputEvent::HostPointer(e) + if e.kind == PointerEventKind::ButtonRelease + )), + "no ButtonRelease must be queued before the release arrives" + ); + + // Release arrives BEFORE AllowEvents (the load-bearing case). + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 0x1280, + ..press + }; + let xid_map = backend.xid_map().clone(); + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + // Grab MUST still be active (waiting for AllowEvents). Press + // is still frozen. Release is in the queue. + assert!( + state.active_pointer_grab.is_some(), + "grab must remain active while frozen — release waits for AllowEvents", + ); + assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_some() + ); + // The withheld release must sit in the global replay queue as a core + // HostPointer event (Xorg syncEvents.pending), not be delivered to the + // natural target. + assert!( + state + .sync_pending + .iter() + .any(|p| p.device == crate::xinput::DEVICEID_MASTER_POINTER + && matches!( + &p.event, + crate::server::QueuedInputEvent::HostPointer(e) + if e.kind == PointerEventKind::ButtonRelease + )), + "release must be queued for replay, not delivered to natural target", + ); +} + +/// Xorg semantics (`DeliverGrabbedEvent`, dix/events.c:4361): the +/// `owner_events=true` natural walk is filtered to the GRAB +/// CLIENT — `TryClientEvents` (dix/events.c:2069) returns -1 for +/// any other client ("not delivered due to grab"), aborting +/// propagation; the press then falls back to the grab window. +/// +/// This test previously pinned the OPPOSITE ("delivers descendant +/// window regardless of owner", from the 2b2680e cinnamon wip) — +/// that leak is what wedged wmaker on HW 2026-06-04: the sync +/// grab froze the queue while the press went to the app client, +/// so the WM never called AllowEvents and clicks died. +#[test] +fn xi_passive_grab_owner_events_redirects_foreign_descendant_press_to_grab_client() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::PassiveButtonGrab, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const CHILD_CLIENT_ID: u32 = 2; + const GRAB_WIN: u32 = 0x0020_0062; + const CHILD_WIN: u32 = 0x0020_0063; + const HOST_XID: u32 = 0xCAFE_0005; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut child_peer = install_client(&mut state, CHILD_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer + .set_nonblocking(true) + .expect("grab peer nonblocking"); + child_peer + .set_nonblocking(true) + .expect("child peer nonblocking"); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + state.resources.create_window( + ClientId(CHILD_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD_WIN), + parent: ResourceId(GRAB_WIN), + x: 10, + y: 10, + width: 40, + height: 40, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + let _ = state.resources.map_window(ResourceId(CHILD_WIN)); + state + .clients + .get_mut(&CHILD_CLIENT_ID) + .expect("child client") + .event_masks + .insert(ResourceId(CHILD_WIN), 0x0000_0004); + state.button_grabs.push(PassiveButtonGrab { + device_id: 0, + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + button: 1, + modifiers: 0, + owner_events: true, + event_mask: 0xFFFF_FFFF, + pointer_mode: 0, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: true, + }); + Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) + .expect("register host xid"); + + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x1234, + root_x: 20, + root_y: 20, + event_x: 20, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + let mut buf = [0u8; 128]; + let grab_read = grab_peer.read(&mut buf); + assert!( + matches!(grab_read, Ok(n) if n >= 32), + "press on a foreign-owned descendant must fall back to grab-window \ + delivery to the GRAB client (Xorg dix/events.c:2069 aborts the \ + natural walk on a foreign subscriber); got {grab_read:?}", + ); + assert_eq!(buf[0], 4, "core ButtonPress to the grab client"); + assert_eq!( + &buf[12..16], + &GRAB_WIN.to_le_bytes(), + "press reported on the grab window", + ); + let child_read = child_peer.read(&mut buf); + let child_got_core_press = + matches!(child_read, Ok(n) if buf[..n.min(128)].chunks(32).any(|c| c[0] == 4)); + assert!( + !child_got_core_press, + "the foreign descendant's owner must NOT see the core press while \ + the grab holds; got {child_read:?}", + ); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_POINTER) + .and_then(|f| f.stored.as_ref()) + .is_some(), + "GrabModeSync activation with a delivery must freeze the queue", + ); +} + +/// During a window move, muffin holds an *active* `XIGrabDevice` on +/// the master pointer. Every master-pointer XI2 event — including the +/// final `XI_ButtonRelease` — must be funnelled to the grab owner, +/// even after the drag has pulled the pointer over another client's +/// window. Regression: the XI2 fanout routed purely by window +/// mask-selection and ignored the active grab, so the release was +/// delivered to the window under the cursor (nemo-desktop) instead of +/// the grab owner (muffin) — leaving muffin stuck in its move loop +/// with the button apparently still held. +#[test] +fn xi_active_device_grab_funnels_button_release_to_grab_owner_not_window_under_cursor() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::ActivePointerGrab, + }; + + const GRAB_CLIENT_ID: u32 = 1; // muffin + const OTHER_CLIENT_ID: u32 = 2; // nemo-desktop + const GRAB_WIN: u32 = 0x0010_0011; // muffin's grab window + const OTHER_WIN: u32 = 0x0025_0003; // nemo-desktop fullscreen window + const OTHER_HOST_XID: u32 = 0xCAFE_0006; + const XI2_BUTTON_RELEASE_BIT: u32 = 1 << 5; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut other_peer = install_client(&mut state, OTHER_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer.set_nonblocking(true).unwrap(); + other_peer.set_nonblocking(true).unwrap(); + + // muffin's grab window — small, off in the corner. The drag pulls + // the pointer away from it onto the desktop. + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + // nemo-desktop's window — covers where the pointer ends up. + state.resources.create_window( + ClientId(OTHER_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(OTHER_WIN), + parent: ROOT_WINDOW, + x: 200, + y: 200, + width: 400, + height: 400, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + let _ = state.resources.map_window(ResourceId(OTHER_WIN)); + + // nemo selects XI2 ButtonRelease on its own window (XIAllDevices=1). + state + .clients + .get_mut(&OTHER_CLIENT_ID) + .expect("other client") + .xi2_masks + .insert( + (ResourceId(OTHER_WIN), 1), + u64::from(XI2_BUTTON_RELEASE_BIT), + ); + + // muffin holds an active master-pointer grab (XIGrabDevice). + // owner_events=false → every event funnels to the grab owner. + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + event_mask: 0xFFFF, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: true, + implicit: false, + passive: false, + xi2_mask: u64::MAX, + }); + + Backend::register_top_level(&mut backend, None, ResourceId(OTHER_WIN), OTHER_HOST_XID) + .expect("register host xid"); + + // Pointer has dragged onto nemo-desktop (200,200..600,600); button 1 + // still held. event_x/y are relative to OTHER_WIN's origin. + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + host_xid: OTHER_HOST_XID, + detail: 1, + time: 0x2000, + root_x: 300, + root_y: 300, + event_x: 100, + event_y: 100, + state: 0x100, // button 1 down + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let press = HostPointerEvent { + kind: PointerEventKind::ButtonPress, + state: 0, + ..release + }; + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let _ = read_all_available(&mut grab_peer); + let _ = read_all_available(&mut other_peer); + grab_peer + .set_nonblocking(true) + .expect("restore grab peer mode"); + other_peer + .set_nonblocking(true) + .expect("restore other peer mode"); + + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let mut buf = [0u8; 256]; + + // The window under the cursor must NOT get the XI2 release — the + // active grab owns the device. + let other_read = other_peer.read(&mut buf); + assert!( + matches!(other_read, Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "active device grab must withhold the XI2 ButtonRelease from the window under the cursor; got {other_read:?}", + ); + + // The grab owner must receive the XI2 ButtonRelease. The grab owner + // also gets the parallel core ButtonRelease (32 bytes) from the + // core redirect, so scan event boundaries for the XI2 GenericEvent. + let n = match grab_peer.read(&mut buf) { + Ok(n) => n, + Err(e) => panic!("grab owner must receive the grabbed XI2 release; got {e:?}"), + }; + let off = (0..n) + .step_by(32) + .find(|&off| off + 10 <= n && buf[off] == 35) + .expect("grab owner must receive an XI2 GenericEvent (got core-only stream)"); + assert_eq!( + u16::from_le_bytes([buf[off + 8], buf[off + 9]]), + 5, + "the grabbed XI2 event must be a ButtonRelease (evtype 5)", + ); +} + +/// A *core* `XGrabPointer` grab must NOT funnel XI2 XGE events to +/// the grab owner — the owner asked for core delivery only (Xorg's +/// `DeliverGrabbedEvent` consults the grab's own xi2mask, which is +/// empty for core grabs). Regression: the XI2 active-grab redirect +/// pushed the grab client unconditionally; a plain-Xlib client that +/// linked libXi without calling XIQueryVersion (every xts5 Xlib11 +/// TCM) NULL-derefs inside libXi's wire handler on the XGE event, +/// and TET's longjmp out of the SIGSEGV poisons the display mutex — +/// the rest of the test case hangs forever (Xlib11/ButtonPress +/// scenario 890-0 on eiger HW, 2026-06-04). +#[test] +fn core_pointer_grab_does_not_send_xi2_to_grab_owner() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + server::ActivePointerGrab, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const GRAB_WIN: u32 = 0x0010_0021; + const HOST_XID: u32 = 0xCAFE_0016; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut backend = RecordingBackend::new(); + grab_peer.set_nonblocking(true).unwrap(); + + state.resources.create_window( + ClientId(GRAB_CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(GRAB_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 50, + height: 50, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(GRAB_WIN)); + // Select core ButtonPress on the grab window so the core + // redirect has a delivery target. + state + .clients + .get_mut(&GRAB_CLIENT_ID) + .expect("grab client") + .event_masks + .insert(ResourceId(GRAB_WIN), 0x0000_0004); + + // Core XGrabPointer, owner_events=false — the xts5 TP10 shape. + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ResourceId(GRAB_WIN), + event_mask: 0xFFFF, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: false, + xi2_mask: 0, + }); + + Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) + .expect("register host xid"); + + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x3000, + root_x: 25, + root_y: 25, + event_x: 25, + event_y: 25, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + let _dropped = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + // The grab owner gets the core ButtonPress (type 4) and nothing + // else — scan every 32-byte event for an XI2 GenericEvent (35). + let mut buf = [0u8; 512]; + let n = match grab_peer.read(&mut buf) { + Ok(n) => n, + Err(e) => panic!("grab owner must receive the core press; got {e:?}"), + }; + let mut saw_core_press = false; + for off in (0..n).step_by(32) { + assert_ne!( + buf[off], 35, + "core grab owner must not receive XI2 GenericEvents", + ); + if buf[off] == 4 { + saw_core_press = true; + } + } + assert!(saw_core_press, "core ButtonPress must reach the grab owner"); +} + +/// `XIQueryPointer` must report currently-held pointer buttons in +/// the XI2 `buttons` bitmask, not only in the legacy KeyButMask +/// `effective_mods`. A GTK4 CSD window move goes through +/// `_NET_WM_MOVERESIZE`: the app sends the request and muffin — which +/// never saw the ButtonPress — queries the pointer to learn whether +/// the initiating button is still held. With an empty `buttons` mask +/// muffin concluded the button was released and aborted the move +/// grab immediately (the window "didn't budge"). Button N maps to +/// bit N (button 1 -> bit 1). +#[test] +fn xi_query_pointer_reports_held_button_in_xi2_button_mask() { + use crate::{backend::Backend, resources::ROOT_VISUAL}; + use yserver_protocol::x11::ClientByteOrder; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0020_0070; + const HOST_XID: u32 = 0xCAFE_0007; + + // Run for both client byte orders. The XI2 button mask is a raw + // byte array indexed by `XIMaskIsSet` (X11/extensions/XI2.h), so it + // must NOT be byte-swapped per client order — a big-endian client + // must still read button 1 in mask byte 0. + for order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + peer.set_nonblocking(true).unwrap(); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = order; + let mut backend = RecordingBackend::new(); + // Model button 1 held (KeyButMask Button1Mask = 0x0100). + backend.query_pointer_mask = 0x0100; + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + Backend::register_top_level(&mut backend, None, ResourceId(WINDOW_XID), HOST_XID) + .expect("register host xid"); + + // XIQueryPointer body: window(4) + deviceid(2) + pad(2). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); // master pointer + body.extend_from_slice(&0u16.to_le_bytes()); // pad + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 40, // XIQueryPointer + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("xi query pointer"); + + let mut buf = [0u8; 128]; + let n = peer.read(&mut buf).expect("reply"); + // Reply: 8-byte header + 24 coord bytes; same_screen@32, pad@33, + // buttons_len@34-35, mods@36-51, group@52-55, button mask@56+. + assert!( + n >= 60, + "{order:?}: XIQueryPointer reply must carry a 1-unit button bitmask (got {n})", + ); + let buttons_len = match order { + ClientByteOrder::LittleEndian => u16::from_le_bytes([buf[34], buf[35]]), + ClientByteOrder::BigEndian => u16::from_be_bytes([buf[34], buf[35]]), + }; + assert_eq!( + buttons_len, 1, + "{order:?}: buttons_len must be 1 so clients can read button state", + ); + // Byte-indexed exactly as `XIMaskIsSet(mask, 1) = mask[1>>3] & + // (1 << (1 & 7)) = mask[0] & 0x02` (the way muffin reads it), + // which is byte-order independent. + assert_ne!( + buf[56] & (1 << 1), + 0, + "{order:?}: button 1 must be held in XI2 button mask byte 0 \ + (raw byte array, not byte-swapped); muffin's \ + _NET_WM_MOVERESIZE move aborts on an empty mask", + ); + } +} + +/// Cinnamon alt-tab regression #2 (2026-06-10): `XIQueryPointer` +/// must report the keyboard modifier state in `ModifierInfo` — +/// Xorg `Xi/xiquerypointer.c:120,139` fills `rep.mods` from the +/// paired MASTER_KEYBOARD's XKB state. The backend mask is a core +/// KeyButMask (modifiers in the low byte, buttons at 0x100+); +/// `base_mods` must carry the modifier bits WITHOUT the button +/// bits. Pre-fix `base_mods` was hardcoded 0 — cinnamon's +/// `global.get_pointer()` (GDK → XIQueryPointer) saw "Alt not +/// held" mid-alt-tab and the switcher took the modifier-already- +/// released branch: `_activateSelected()` + destroy, so the popup +/// never appeared (trace: instant raise+SetInputFocus between the +/// modal grab and ungrab, same server timestamp). +#[test] +fn xi_query_pointer_reports_keyboard_mods_in_modifier_info() { + use yserver_protocol::x11::ClientByteOrder; + + const CLIENT_ID: u32 = 1; + for order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + peer.set_nonblocking(true).unwrap(); + state.clients.get_mut(&CLIENT_ID).unwrap().byte_order = order; + let mut backend = RecordingBackend::new(); + // Alt (Mod1Mask = 0x8) held + button 1 held (Button1Mask = + // 0x100): the reply must separate them. + backend.query_pointer_mask = 0x0108; + + // XIQueryPointer body: window(4) + deviceid(2) + pad(2). + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); // master pointer + body.extend_from_slice(&0u16.to_le_bytes()); // pad + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 40, // XIQueryPointer + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("xi query pointer"); + + let mut buf = [0u8; 128]; + let n = peer.read(&mut buf).expect("reply"); + assert!(n >= 56, "{order:?}: short XIQueryPointer reply ({n})"); + // ModifierInfo at bytes 36..52: base / latched / locked / + // effective (each CARD32, client byte order). + let read_u32 = |b: &[u8]| match order { + ClientByteOrder::LittleEndian => u32::from_le_bytes([b[0], b[1], b[2], b[3]]), + ClientByteOrder::BigEndian => u32::from_be_bytes([b[0], b[1], b[2], b[3]]), + }; + let base_mods = read_u32(&buf[36..40]); + let effective_mods = read_u32(&buf[48..52]); + assert_eq!( + base_mods, 0x8, + "{order:?}: base_mods must carry the held Mod1 (Alt) and \ + not the button bits (Xorg fills it from the paired \ + keyboard's XKB state)", + ); + assert_ne!( + effective_mods & 0x8, + 0, + "{order:?}: effective_mods must include the held Mod1 — \ + GDK reads the effective field for global.get_pointer()", + ); + } +} + +/// Cinnamon alt-tab regression #1 (2026-06-10): a SYNC passive key +/// grab (the muffin keybinding) activates on Alt+Tab and freezes +/// the keyboard; muffin then takes an ASYNC active `XIGrabDevice` +/// (pushModal) and later `XIUngrabDevice`s (popModal). Per Xorg the +/// async activation THAWS the frozen device — `ActivateKeyboardGrab` +/// → `CheckGrabForSyncs` (dix/events.c:1424: async → THAWED) — and +/// deactivation runs `ComputeFreezes` (`DeactivateKeyboardGrab`: +/// sync.state = NOT_GRABBED). The XIAllowEvents muffin sends after +/// the ungrab is then a no-op on an already-thawed device. Pre-fix +/// yserver's XI2 grab/ungrab never touched the sync state, so the +/// freeze outlived the whole modal cycle and EVERY later key event +/// was withheld — one alt-tab permanently killed keyboard input +/// (server log: "AllowEvents no-op ... state=FrozenNoEvent"; +/// trace: zero key events after the alt-tab cluster). +#[test] +fn async_xi2_grab_and_ungrab_thaw_sync_passive_key_freeze() { + use crate::{ + core_loop::key_fanout::key_event_fanout_to_state, host_x11::HostKeyEvent, server::KeyGrab, + xinput::DEVICEID_MASTER_KEYBOARD, + }; + + const APP_WIN: u32 = 0x0030_0001; + const APP: u32 = 9; + const WM: u32 = 7; + let key_event = |pressed: bool, keycode: u8| HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed, + keycode, + time: 1, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + }; + + let mut state = ServerState::new(); + let mut app = install_client(&mut state, APP); + app.set_nonblocking(true).unwrap(); + let _wm = install_client(&mut state, WM); + let mut backend = RecordingBackend::new(); + + // Focused app window with a core KeyPress selection. + state.resources.create_window( + yserver_protocol::x11::ClientId(APP), + CreateWindowRequest { + depth: 24, + window: ResourceId(APP_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(APP_WIN)); + state + .clients + .get_mut(&APP) + .unwrap() + .event_masks + .insert(ResourceId(APP_WIN), 0x1); // KeyPressMask + state.core_focus.raw = APP_WIN; + + // muffin keybinding: SYNC passive key grab on Tab (keycode 23). + state.key_grabs.push(KeyGrab { + device_id: 0, + owner: ClientId(WM), + grab_window: ROOT_WINDOW, + keycode: 23, + modifiers: 0, + owner_events: false, + pointer_mode: 1, + keyboard_mode: 0, // synchronous → freeze + via_xi2: true, + xi2_mask: 0, + }); + + // 1. Alt+Tab press: passive grab activates + keyboard freezes. + let _ = key_event_fanout_to_state(&mut state, &mut backend, key_event(true, 23)); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .and_then(|f| f.stored.as_ref()) + .is_some(), + "sync passive grab must freeze the activating press", + ); + + // 2. pushModal: ASYNC XIGrabDevice on the keyboard. Body per + // xXIGrabDeviceReq: window(4) time(4) cursor(4) deviceid(2) + // mode(1) paired(1) owner_events(1) pad(1) mask_len(2). + let mut grab_body = Vec::with_capacity(18); + grab_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + grab_body.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime + grab_body.extend_from_slice(&0u32.to_le_bytes()); // cursor = None + grab_body.extend_from_slice(&3u16.to_le_bytes()); // master keyboard + grab_body.push(1); // grab_mode = XIGrabModeAsync + grab_body.push(1); // paired_device_mode = Async + grab_body.push(0); // owner_events = false + grab_body.push(0); // pad + grab_body.extend_from_slice(&0u16.to_le_bytes()); // mask_len = 0 + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(WM), + SequenceNumber(2), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, // XIGrabDevice + length_units: 6, + }, + &grab_body, + ) + .expect("xi grab device"); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .and_then(|f| f.stored.as_ref()) + .is_none(), + "CheckGrabForSyncs: an ASYNC active grab must thaw the \ + sync-passive-grab freeze (Xorg dix/events.c:1431)", + ); + assert!( + !state + .xi1_frozen + .get(&DEVICEID_MASTER_KEYBOARD) + .is_some_and(crate::server::Xi1Freeze::frozen), + "keyboard sync state must be THAWED after the async grab", + ); + + // 3. popModal: XIUngrabDevice. Body: time(4) deviceid(2) pad(2). + let mut ungrab_body = Vec::with_capacity(8); + ungrab_body.extend_from_slice(&0u32.to_le_bytes()); + ungrab_body.extend_from_slice(&3u16.to_le_bytes()); + ungrab_body.extend_from_slice(&0u16.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(WM), + SequenceNumber(3), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 52, // XIUngrabDevice + length_units: 3, + }, + &ungrab_body, + ) + .expect("xi ungrab device"); + + // 4. The keyboard must still deliver: a fresh key press reaches + // the focused window's client. + let mut drain = [0u8; 512]; + while app.read(&mut drain).is_ok_and(|n| n > 0) {} + let _ = key_event_fanout_to_state(&mut state, &mut backend, key_event(true, 38)); + let mut buf = [0u8; 64]; + let n = app.read(&mut buf).unwrap_or(0); + assert!( + n >= 32, + "keyboard must keep delivering after the modal grab cycle \ + (got {n} bytes) — a leaked freeze kills all key input", + ); + assert_eq!(buf[0] & 0x7f, 2, "must be a core KeyPress"); +} + +/// `XIGetClientPointer` reply must place `deviceid` at bytes 10-11. +/// Per `xXIGetClientPointerReply` (X11/extensions/XI2proto.h): +/// `set` at byte 8, `pad0` at byte 9, `deviceid` (u16) at bytes +/// 10-11. Regression: the encoder wrote 3 pad bytes after `set`, +/// pushing deviceid to bytes 12-13, so clients read deviceid=0. +/// nemo's desktop rubber-band asks `XIGetClientPointer` for its +/// pointer device, got 0, and queried that for the band anchor — +/// anchoring it at (0,0). caja never calls it, so it was immune. +#[test] +fn xi_get_client_pointer_reply_deviceid_offset() { + const CLIENT_ID: u32 = 1; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + // XIGetClientPointer body: window(4). + let body = 0u32.to_le_bytes().to_vec(); + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 45, // XIGetClientPointer + length_units: 2, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("xi get client pointer"); + + let mut buf = [0u8; 64]; + let n = peer.read(&mut buf).expect("reply"); + assert_eq!(n, 32, "reply must be 32 bytes"); + assert_eq!(buf[8], 1, "byte 8: set = True"); + assert_eq!( + u16::from_le_bytes([buf[10], buf[11]]), + 2, + "deviceid (bytes 10-11 per xXIGetClientPointerReply) must be the \ + master pointer (2); a wrong offset reads as 0 and breaks nemo's \ + pointer-device lookup for the rubber-band anchor", + ); +} + +/// XI2 `FocusIn`/`FocusOut` events share the `xXIEnterEvent` layout +/// and must carry the current pointer position (Xorg populates +/// root_x/root_y/event_x/event_y from it). yserver emits focus events +/// from request handlers that have no backend handle, so it reads the +/// cached `state.pointer_root`. Regression target: focus events +/// shipped at (0,0). +#[test] +fn xi_focus_in_carries_cached_pointer_position() { + use crate::resources::ROOT_VISUAL; + + const CLIENT_ID: u32 = 1; + const FOCUS_WIN: u32 = 0x0010_0007; + const PREV_WIN: u32 = 0x0010_0008; + const XI_FOCUS_IN: u16 = 9; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + peer.set_nonblocking(true).unwrap(); + + for xid in [FOCUS_WIN, PREV_WIN] { + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(xid), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(xid)); + } + // Client selects XI_FocusIn on FOCUS_WIN (keyboard device 3). + state + .clients + .get_mut(&CLIENT_ID) + .unwrap() + .xi2_masks + .insert((ResourceId(FOCUS_WIN), 3), 1 << XI_FOCUS_IN); + + // Cache the pointer position; prior focus is on an unrelated window + // so a Focus crossing actually fires onto FOCUS_WIN. + state.pointer_root = (631, 641); + state.core_focus = crate::server::CoreFocus { + raw: PREV_WIN, + revert_to: 0, + time: 0, + }; + + emit_core_focus_transition(&mut state, PREV_WIN, FOCUS_WIN, 0); + state.core_focus.raw = FOCUS_WIN; + + let mut buf = [0u8; 128]; + let n = peer.read(&mut buf).expect("focus event"); + assert!(n >= 36, "expected an XI2 focus event (got {n} bytes)"); + assert_eq!(buf[0], 35, "must be an XI2 GenericEvent"); + assert_eq!( + u16::from_le_bytes([buf[8], buf[9]]), + XI_FOCUS_IN, + "evtype must be FocusIn", + ); + // root_x is FP1616 at bytes 32-35 (after the 32-byte boundary). + let root_x_fp = u32::from_le_bytes([buf[32], buf[33], buf[34], buf[35]]); + assert_eq!( + root_x_fp, + (631i32 << 16) as u32, + "FocusIn must carry the current pointer X (631), not 0; Xorg \ + populates focus-event coords from the pointer position", + ); +} + +/// A sync passive button grab that also froze the keyboard (dtwm's +/// front panel: GrabModeSync for both) and is let go by +/// `AllowEvents(ReplayPointer)`: Xorg DeactivatePointerGrab clears the +/// keyboard's hold with the grab, so typing works again (measured: +/// tools/vng-scenarios/goldens/passive-grab.txt, last line). +#[test] +fn replay_pointer_of_passive_grab_thaws_keyboard_it_froze() { + const GRAB_CLIENT_ID: u32 = 1; + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + state.set_pointer_grab(crate::server::ActivePointerGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ROOT_WINDOW, + event_mask: 0x0008, + cursor: ResourceId(0), + time: 0, + owner_events: false, + via_xi2: false, + implicit: false, + passive: true, + xi2_mask: 0, + }); + crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( + &mut state, + crate::xinput::DEVICEID_MASTER_POINTER, + ClientId(GRAB_CLIENT_ID), + true, + true, + ); + state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default() + .state = crate::server::Xi1SyncState::FrozenWithEvent; + let kbd_frozen = |state: &ServerState| { + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .is_some_and(crate::server::Xi1Freeze::frozen) + }; + assert!( + kbd_frozen(&state), + "the grab's sync keyboard mode holds the keyboard" + ); + + let header = yserver_protocol::x11::RequestHeader { + opcode: 35, + data: 2, // ReplayPointer + length_units: 2, + }; + handle_allow_events( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &[0u8; 4], + ) + .expect("allow events replay pointer"); + + assert!(state.active_pointer_grab.is_none()); + assert!(!kbd_frozen(&state), "the keyboard thaws with the grab"); +} + +/// Core `AllowEvents(ReplayKeyboard)` (mode 5 — what muffin/mutter +/// calls for a declined key) releases the passive keyboard grab and +/// replays the frozen key to the focused window. This is the +/// dead-`p`-in-wezterm fix end-to-end: a sync passive key grab held +/// `p`, the WM declined it, and ReplayKeyboard hands it to the +/// focused client. +#[test] +fn core_replay_keyboard_releases_grab_and_replays_to_focus() { + use crate::{ + host_x11::HostKeyEvent, + server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const FOCUS_CLIENT_ID: u32 = 2; + const FOCUS_WIN: u32 = 0x0020_0061; + const KEY_PRESS_MASK: u32 = 0x0000_0001; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut focus_peer = install_client(&mut state, FOCUS_CLIENT_ID); + focus_peer.set_nonblocking(true).unwrap(); + + // Focused client selects core KeyPress on its window. + { + let c = state.clients.get_mut(&FOCUS_CLIENT_ID).unwrap(); + c.focused_window = ResourceId(FOCUS_WIN); + c.event_masks.insert(ResourceId(FOCUS_WIN), KEY_PRESS_MASK); + } + state.core_focus.raw = FOCUS_WIN; + + // A sync passive key grab held by the WM is active, with a + // frozen press waiting. + state.active_keyboard_grab = Some(ActiveKeyboardGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ROOT_WINDOW, + owner_events: false, + source: ActiveKeyboardGrabSource::PassiveKey { keycode: 33 }, + via_xi2: true, + xi2_mask: 0, + }); + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_KEYBOARD) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostKey(HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed: true, + keycode: 33, + time: 0x1234, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + })); + } + + let header = yserver_protocol::x11::RequestHeader { + opcode: 35, + data: 5, // ReplayKeyboard + length_units: 2, + }; + handle_allow_events( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &[0u8; 4], + ) + .expect("allow events replay keyboard"); + + assert!( + state.active_keyboard_grab.is_none(), + "ReplayKeyboard must release the passive keyboard grab" + ); + assert!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .and_then(|f| f.stored.as_ref()) + .is_none(), + "the frozen key must be consumed by the replay" + ); + let mut buf = [0u8; 64]; + let n = focus_peer.read(&mut buf).unwrap_or(0); + assert!( + n >= 32 && buf[0] == 2, + "replayed KeyPress (event type 2) must reach the focused client; got n={n} type={}", + buf[0] + ); +} + +/// GH #59 regression (bspwm/sxhkd dead keyboard). sxhkd holds a +/// SYNCHRONOUS core passive key grab; after the activating chord +/// press freezes the keyboard it issues exactly ONE +/// AllowEvents(SyncKeyboard) and waits. The terminating key release +/// must reach `key_route` (device still FreezeNextEvent, NOT +/// re-frozen), deactivate the passive grab, and thaw — so typing +/// reaches the focused window. Pre-fix the SyncKeyboard +/// `FreezeNextEvent` allowance was consumed by replaying the grab's +/// OWN already-delivered activating press (double-booked in the XI1 +/// queue), re-freezing to FrozenWithEvent; the release was then +/// withheld, the grab never deactivated, and the keyboard was dead. +/// Xorg's `ComputeFreezes` only replays the stored event for +/// `Replay*`, not `Sync*` (dix/events.c:1320-1370). +#[test] +fn sync_passive_kbd_grab_synckeyboard_release_thaws() { + use crate::{ + core_loop::key_fanout::key_event_fanout_to_state, + host_x11::HostKeyEvent, + server::{KeyGrab, Xi1SyncState}, + }; + + const GRAB_CLIENT_ID: u32 = 1; // sxhkd + const FOCUS_CLIENT_ID: u32 = 2; // kitty + const FOCUS_WIN: u32 = 0x0020_0091; + const KEY_PRESS_MASK: u32 = 0x0000_0001; + const RETURN_KC: u8 = 36; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + let mut focus_peer = install_client(&mut state, FOCUS_CLIENT_ID); + focus_peer.set_nonblocking(true).unwrap(); + { + let c = state.clients.get_mut(&FOCUS_CLIENT_ID).unwrap(); + c.focused_window = ResourceId(FOCUS_WIN); + c.event_masks.insert(ResourceId(FOCUS_WIN), KEY_PRESS_MASK); + } + state.core_focus.raw = FOCUS_WIN; + + // sxhkd's synchronous core passive grab on the chord key. + state.key_grabs.push(KeyGrab { + device_id: 0, + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ROOT_WINDOW, + keycode: RETURN_KC, + modifiers: 0, + owner_events: true, + pointer_mode: 1, + keyboard_mode: 0, // synchronous → freeze + via_xi2: false, + xi2_mask: 0, + }); + + let key = |pressed, keycode| HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed, + keycode, + time: 1, + root_x: 0, + root_y: 0, + event_x: 0, + event_y: 0, + state: 0, + }; + + // 1) chord press activates the grab and freezes the device. + let _ = key_event_fanout_to_state(&mut state, &mut backend, key(true, RETURN_KC)); + assert!( + state.active_keyboard_grab.is_some(), + "synchronous passive grab must activate on the chord press" + ); + + // 2) sxhkd issues a single AllowEvents(SyncKeyboard) (mode 4). + let header = yserver_protocol::x11::RequestHeader { + opcode: 35, + data: 4, // SyncKeyboard + length_units: 2, + }; + handle_allow_events( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &[0u8; 4], + ) + .expect("allow events sync keyboard"); + + // 3) the terminating release must deactivate the grab and thaw. + let _ = key_event_fanout_to_state(&mut state, &mut backend, key(false, RETURN_KC)); + assert!( + state.active_keyboard_grab.is_none(), + "the matching key release must deactivate the passive grab" + ); + let frozen = state + .xi1_frozen + .get(&crate::xinput::DEVICEID_XTEST_KEYBOARD) + .map_or(Xi1SyncState::Thawed, |f| f.state); + assert_eq!( + frozen, + Xi1SyncState::Thawed, + "the terminating release must thaw the keyboard (not leave it FrozenWithEvent)" + ); + + // 4) typing (an ungrabbed key) must now reach the focused window. + let _ = key_event_fanout_to_state(&mut state, &mut backend, key(true, 38)); + let mut buf = [0u8; 64]; + let n = focus_peer.read(&mut buf).unwrap_or(0); + assert!( + n >= 32 && buf[0] == 2, + "after the grab releases, typing must reach the focused window; got n={n} type={}", + buf[0] + ); +} + +/// Regression (codex review): ReplayKeyboard must release an +/// EXPLICIT GrabKeyboard(GrabModeSync), not just a passive key +/// grab — Xorg NOT_GRABBED calls DeactivateGrab regardless of +/// grab kind (dix/events.c:1898). Pre-fix the grab stayed active +/// after the replay → stuck keyboard. +#[test] +fn core_replay_keyboard_releases_explicit_sync_grab() { + use crate::{ + host_x11::HostKeyEvent, + server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}, + }; + + const GRAB_CLIENT_ID: u32 = 1; + const FOCUS_WIN: u32 = 0x0020_0071; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let _grab_peer = install_client(&mut state, GRAB_CLIENT_ID); + state.core_focus.raw = FOCUS_WIN; + + // Explicit GrabKeyboard(GrabModeSync): active grab + the + // device frozen-no-event, with a key withheld in the freeze + // queue (the "with event" condition for replay). + state.active_keyboard_grab = Some(ActiveKeyboardGrab { + owner: ClientId(GRAB_CLIENT_ID), + grab_window: ROOT_WINDOW, + owner_events: false, + source: ActiveKeyboardGrabSource::Explicit, + via_xi2: false, + xi2_mask: 0, + }); + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_KEYBOARD) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenNoEvent; + state + .sync_pending + .push_back(crate::server::PendingSyncEvent { + device: crate::xinput::DEVICEID_MASTER_KEYBOARD, + event: crate::server::QueuedInputEvent::HostKey(HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed: true, + keycode: 38, + time: 0x2222, + root_x: 1, + root_y: 2, + event_x: 1, + event_y: 2, + state: 0, + }), + }); + } + + let header = yserver_protocol::x11::RequestHeader { + opcode: 35, + data: 5, // ReplayKeyboard + length_units: 2, + }; + handle_allow_events( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT_ID), + SequenceNumber(1), + header, + &[0u8; 4], + ) + .expect("allow events replay keyboard"); + + assert!( + state.active_keyboard_grab.is_none(), + "ReplayKeyboard must deactivate the explicit sync keyboard grab", + ); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi2_grabs.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi2_grabs.rs new file mode 100644 index 000000000..68ec84bb8 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi2_grabs.rs @@ -0,0 +1,3826 @@ +use super::*; + +/// `XIGrabDevice` must wire into the existing core X11 grab +/// state (`state.active_pointer_grab` for +/// the master pointer, `state.active_keyboard_grab` for the +/// master keyboard) so the pointer/key fanout's +/// `active_grab_target` routing kicks in. Pre-fix the handler +/// was a no-op that just sent Success — GTK thought it owned +/// the device but events still went to whatever window the +/// pointer was over, so popups dismissed on the first stray +/// motion and `gtk_window_present` looped re-mapping at ~50 Hz. +#[test] +fn xi_grab_device_sets_active_grab_state() { + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0050; + const CURSOR_XID: u32 = 0x0090_0050; + + let mut state = ServerState::new(); + let _peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + // Pointer grab (deviceid=2) — XIGrabDevice body: window(4) + // time(4) cursor(4) deviceid(2) mode(1) paired(1) + // owner_events(1) pad(1) mask_len(2) ... + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); // window + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&CURSOR_XID.to_le_bytes()); // cursor + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid (pointer) + body.extend_from_slice(&[1, 1, 1, 0]); // mode async, paired async, owner_events=1, pad + body.extend_from_slice(&0u16.to_le_bytes()); // mask_len + body.extend_from_slice(&[0u8; 2]); // pad + + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, // XIGrabDevice + length_units: 7, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("XIGrabDevice pointer"); + + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(CLIENT_ID), ResourceId(WINDOW_XID))), + "XIGrabDevice(pointer) must set active_pointer_grab so \ + pointer_fanout's active_grab_target redirect kicks in", + ); + assert!(state.active_pointer_grab.is_some_and(|grab| !grab.passive)); + let active = state.active_pointer_grab.expect("active_pointer_grab set"); + assert_eq!(active.owner, ClientId(CLIENT_ID)); + assert_eq!(active.grab_window, ResourceId(WINDOW_XID)); + assert_eq!(active.cursor, ResourceId(CURSOR_XID)); + + // Keyboard grab (deviceid=3) — same wire format. + let mut body_kbd = Vec::with_capacity(24); + body_kbd.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body_kbd.extend_from_slice(&0u32.to_le_bytes()); + body_kbd.extend_from_slice(&0u32.to_le_bytes()); + body_kbd.extend_from_slice(&3u16.to_le_bytes()); // keyboard + body_kbd.extend_from_slice(&[1, 1, 1, 0]); + body_kbd.extend_from_slice(&0u16.to_le_bytes()); + body_kbd.extend_from_slice(&[0u8; 2]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(2), + header, + &body_kbd, + ) + .expect("XIGrabDevice keyboard"); + let kgrab = state + .active_keyboard_grab + .expect("active_keyboard_grab set"); + assert_eq!(kgrab.owner, ClientId(CLIENT_ID)); + assert_eq!(kgrab.grab_window, ResourceId(WINDOW_XID)); + + // Ungrab both — XIUngrabDevice body: time(4) deviceid(2) pad(2). + let ungrab_header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 52, + // XIUngrabDevice is Fixed(3): 4 header + time(4) + deviceid(2) + // + pad(2) = 12 bytes = 3 units. (Was 2 — pre-dated the + // XTS-driven REQUEST_SIZE_MATCH length gate, so the malformed + // length slipped through; master now correctly BadLengths it.) + length_units: 3, + }; + let mut ungrab_p = Vec::with_capacity(8); + ungrab_p.extend_from_slice(&0u32.to_le_bytes()); // time + ungrab_p.extend_from_slice(&2u16.to_le_bytes()); // pointer + ungrab_p.extend_from_slice(&[0u8; 2]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(3), + ungrab_header, + &ungrab_p, + ) + .expect("XIUngrabDevice pointer"); + assert!(state.active_pointer_grab.is_none()); + + let mut ungrab_k = Vec::with_capacity(8); + ungrab_k.extend_from_slice(&0u32.to_le_bytes()); + ungrab_k.extend_from_slice(&3u16.to_le_bytes()); + ungrab_k.extend_from_slice(&[0u8; 2]); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(4), + ungrab_header, + &ungrab_k, + ) + .expect("XIUngrabDevice keyboard"); + assert!( + state.active_keyboard_grab.is_none(), + "keyboard grab cleared" + ); +} + +fn process_dynamic_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client_id: ClientId, + sequence: SequenceNumber, + opcode: u8, + data: u8, + body: &[u8], +) { + let wire_bytes = body.len() + 4; + assert_eq!(wire_bytes % 4, 0, "X11 request must be four-byte aligned"); + let length_units = u32::try_from(wire_bytes / 4).expect("request length fits CARD32"); + process_request( + state, + backend, + client_id, + sequence, + RequestHeader { + opcode, + data, + length_units, + }, + body, + None, + ) + .expect("process_request dispatch"); +} + +fn process_xi_dynamic_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client_id: ClientId, + sequence: SequenceNumber, + minor: u8, + body: &[u8], +) { + process_dynamic_request(state, backend, client_id, sequence, 137, minor, body); +} + +fn xi_dynamic_wire_grab_body( + window: u32, + device_id: u16, + grab_mode: u8, + paired_device_mode: u8, + owner_events: bool, + mask: Option, +) -> Vec { + let mut body = Vec::with_capacity(if mask.is_some() { 24 } else { 20 }); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // current time + body.extend_from_slice(&0u32.to_le_bytes()); // no cursor + body.extend_from_slice(&device_id.to_le_bytes()); + body.extend_from_slice(&[grab_mode, paired_device_mode, u8::from(owner_events), 0]); + body.extend_from_slice(&u16::from(mask.is_some()).to_le_bytes()); // mask_len in 4-byte units + if let Some(mask) = mask { + body.extend_from_slice(&mask.to_le_bytes()); + } + body +} + +fn xi_dynamic_select_events_body(window: u32, device_id: u16, mask: u32) -> Vec { + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); // one device mask + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&device_id.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); // one mask word + body.extend_from_slice(&mask.to_le_bytes()); + body +} + +fn xi_dynamic_pointer_event( + origin: crate::core_loop::InputOrigin, + kind: crate::host_x11::PointerEventKind, + detail: u8, + time: u32, +) -> crate::host_x11::HostPointerEvent { + crate::host_x11::HostPointerEvent { + origin, + kind, + host_xid: 0, + detail, + time, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + } +} + +fn xi_dynamic_event_ids(bytes: &[u8]) -> Vec<(u16, u16, u16)> { + let mut result = Vec::new(); + let mut offset = 0; + while offset + 32 <= bytes.len() { + assert_eq!(bytes[offset], 35, "expected GenericEvent"); + let extra = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()); + let evtype = u16::from_le_bytes(bytes[offset + 8..offset + 10].try_into().unwrap()); + let deviceid = u16::from_le_bytes(bytes[offset + 10..offset + 12].try_into().unwrap()); + let source_offset = if matches!(evtype, 13..=17) { 20 } else { 52 }; + let sourceid = u16::from_le_bytes( + bytes[offset + source_offset..offset + source_offset + 2] + .try_into() + .unwrap(), + ); + result.push((evtype, deviceid, sourceid)); + offset += 32 + extra as usize * 4; + } + assert_eq!(offset, bytes.len(), "event stream fully consumed"); + result +} + +#[test] +fn xi_dynamic_grabs_xtest_release_keeps_master_passive_grab_until_master_release() { + use crate::{ + backend::Backend, core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::PointerEventKind, + }; + + const OWNER: u32 = 1; + const SOURCE: u64 = 91; + let mut state = ServerState::new(); + let _owner_peer = install_client(&mut state, OWNER); + let mut backend = RecordingBackend::new(); + let (source_id, pointer_id) = + xi_dynamic_grab_source(&mut state, SOURCE, false, true, "passive-owner-mouse"); + + // Core GrabButton: asynchronous pointer, synchronous paired keyboard. + let mut grab_button = Vec::with_capacity(20); + grab_button.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + grab_button.extend_from_slice(&0x000cu16.to_le_bytes()); // ButtonPress|ButtonRelease + grab_button.extend_from_slice(&[1, 0]); // pointer async, keyboard sync + grab_button.extend_from_slice(&0u32.to_le_bytes()); // no confinement + grab_button.extend_from_slice(&0u32.to_le_bytes()); // no cursor + grab_button.extend_from_slice(&[1, 0]); // button 1, pad + grab_button.extend_from_slice(&0u16.to_le_bytes()); // no modifiers + process_dynamic_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(1), + 28, // GrabButton + 0, // owner_events=false + &grab_button, + ); + assert_eq!(state.button_grabs.len(), 1); + + let xid_map = backend.xid_map().clone(); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + xi_dynamic_pointer_event( + crate::core_loop::InputOrigin::Physical(source_id), + PointerEventKind::ButtonPress, + 1, + 1, + ), + true, + false, + ); + assert!(state.active_pointer_grab.is_some_and(|grab| grab.passive)); + assert_eq!(state.buttons_down, 1); + assert_eq!(state.xi_devices.device(pointer_id).unwrap().buttons_down, 1); + assert_eq!( + state.xi1_frozen[&crate::xinput::DEVICEID_MASTER_KEYBOARD].other, + Some(ClientId(OWNER)), + "the core passive grab holds its paired master keyboard" + ); + + for kind in [ + PointerEventKind::ButtonPress, + PointerEventKind::ButtonRelease, + ] { + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + xi_dynamic_pointer_event( + crate::core_loop::InputOrigin::XTest(crate::xinput::DEVICEID_XTEST_POINTER), + kind, + 1, + 2, + ), + true, + false, + ); + } + + assert!( + state.active_pointer_grab.is_some_and(|grab| grab.passive), + "the XTEST release cannot end a passive grab on the master while a physical button remains down" + ); + assert_eq!( + state.buttons_down, 1, + "the master still holds physical button 1" + ); + assert_eq!(state.xi_devices.device(pointer_id).unwrap().buttons_down, 1); + assert_eq!( + state + .xi_devices + .device(crate::xinput::DEVICEID_XTEST_POINTER) + .unwrap() + .buttons_down, + 0, + "the XTEST source completed its independent click" + ); + assert_eq!( + state.xi1_frozen[&crate::xinput::DEVICEID_MASTER_KEYBOARD].other, + Some(ClientId(OWNER)), + "the paired keyboard remains held until the master grab ends" + ); + assert!(state.sync_pending.is_empty()); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + xi_dynamic_pointer_event( + crate::core_loop::InputOrigin::Physical(source_id), + PointerEventKind::ButtonRelease, + 1, + 3, + ), + true, + false, + ); + assert_eq!(state.buttons_down, 0); + assert_eq!(state.xi_devices.device(pointer_id).unwrap().buttons_down, 0); + assert!(state.active_pointer_grab.is_none()); + assert_eq!( + state.xi1_frozen[&crate::xinput::DEVICEID_MASTER_KEYBOARD].other, + None + ); + assert!(state.sync_pending.is_empty()); +} + +#[test] +fn xi_dynamic_grabs_exact_slave_delivery_uses_grab_mask_without_selection() { + use crate::{ + backend::Backend, core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::PointerEventKind, + }; + + const OWNER: u32 = 1; + const XI_GRAB_DEVICE: u8 = 51; + const XI_UNGRAB_DEVICE: u8 = 52; + const GRAB_MASK: u32 = (1 << 4) | (1 << 5) | (1 << 6); // ButtonPress, ButtonRelease, Motion + + let mut state = ServerState::new(); + let mut owner_peer = install_capture_client(&mut state, OWNER); + let mut backend = RecordingBackend::new(); + let (source_id, pointer_id) = + xi_dynamic_grab_source(&mut state, 92, false, true, "grab-mask-mouse"); + let grab = xi_dynamic_wire_grab_body( + ROOT_WINDOW.0, + pointer_id, + 1, // asynchronous pointer mode + 1, // asynchronous paired-device mode + false, + Some(GRAB_MASK), + ); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(1), + XI_GRAB_DEVICE, + &grab, + ); + let _ = read_all_available(&mut owner_peer); // reply and grab crossings + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None + ); + + let xid_map = backend.xid_map().clone(); + for (kind, detail, time, expected_type) in [ + (PointerEventKind::ButtonPress, 1, 2, 4), + (PointerEventKind::MotionNotify, 0, 3, 6), + (PointerEventKind::ButtonRelease, 1, 4, 5), + ] { + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + xi_dynamic_pointer_event( + crate::core_loop::InputOrigin::Physical(source_id), + kind, + detail, + time, + ), + true, + false, + ); + assert_eq!( + xi_dynamic_event_ids(&read_all_available(&mut owner_peer)), + vec![(expected_type, pointer_id, pointer_id)], + "an exact-device grab uses its XIGrabDevice mask without XISelectEvents" + ); + } + + assert_eq!( + state.xi2_pointer_grabs[&pointer_id].xi2_mask, + u64::from(GRAB_MASK) + ); + assert_eq!(state.xi_devices.device(pointer_id).unwrap().buttons_down, 0); + assert_eq!( + state.buttons_down, 0, + "the floating slave never changes master held state" + ); + assert!(state.xi2_pointer_grabs.contains_key(&pointer_id)); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None + ); + assert!(state.sync_pending.is_empty()); + assert!(!state.xi1_frozen[&pointer_id].frozen()); + + let mut ungrab = Vec::with_capacity(8); + ungrab.extend_from_slice(&0u32.to_le_bytes()); + ungrab.extend_from_slice(&pointer_id.to_le_bytes()); + ungrab.extend_from_slice(&[0u8; 2]); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(2), + XI_UNGRAB_DEVICE, + &ungrab, + ); + assert!(!state.xi2_pointer_grabs.contains_key(&pointer_id)); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER) + ); + assert!(!state.xi2_detached_masters.contains_key(&pointer_id)); + assert!(state.sync_pending.is_empty()); +} + +#[test] +fn xi_dynamic_grabs_floating_slave_does_not_copy_raw_motion_to_masters() { + use crate::{ + backend::Backend, core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::PointerEventKind, + }; + + const FACET_CLIENT: u32 = 1; + const MASTER_CLIENT: u32 = 2; + const ALL_MASTER_CLIENT: u32 = 3; + const GRAB_CLIENT: u32 = 4; + const XI_SELECT_EVENTS: u8 = 46; + const XI_GRAB_DEVICE: u8 = 51; + const RAW_MOTION_MASK: u32 = 1 << 17; + + let mut state = ServerState::new(); + let mut facet_peer = install_capture_client(&mut state, FACET_CLIENT); + let mut master_peer = install_capture_client(&mut state, MASTER_CLIENT); + let mut all_master_peer = install_capture_client(&mut state, ALL_MASTER_CLIENT); + let mut grab_peer = install_capture_client(&mut state, GRAB_CLIENT); + let mut backend = RecordingBackend::new(); + let (source_id, pointer_id) = + xi_dynamic_grab_source(&mut state, 93, false, true, "floating-raw-mouse"); + + for (client, selector) in [ + (FACET_CLIENT, pointer_id), + (MASTER_CLIENT, crate::xinput::DEVICEID_MASTER_POINTER), + (ALL_MASTER_CLIENT, 1), // XIAllMasterDevices + ] { + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(client), + SequenceNumber(1), + XI_SELECT_EVENTS, + &xi_dynamic_select_events_body(ROOT_WINDOW.0, selector, RAW_MOTION_MASK), + ); + } + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT), + SequenceNumber(1), + XI_GRAB_DEVICE, + &xi_dynamic_wire_grab_body(ROOT_WINDOW.0, pointer_id, 1, 1, false, None), + ); + let _ = read_all_available(&mut grab_peer); // reply and grab crossings + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None + ); + + let xid_map = backend.xid_map().clone(); + let mut motion = xi_dynamic_pointer_event( + crate::core_loop::InputOrigin::Physical(source_id), + PointerEventKind::MotionNotify, + 0, + 2, + ); + motion.raw_dx = 8; + motion.raw_dy = -3; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, motion, true, false); + + assert_eq!( + xi_dynamic_event_ids(&read_all_available(&mut facet_peer)), + vec![(17, pointer_id, pointer_id)], + "floating input retains its raw slave event" + ); + assert!( + xi_dynamic_event_ids(&read_all_available(&mut master_peer)).is_empty(), + "a floating slave has no raw master copy" + ); + assert!( + xi_dynamic_event_ids(&read_all_available(&mut all_master_peer)).is_empty(), + "XIAllMasterDevices receives no raw copy from a floating slave" + ); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None + ); + assert!(state.sync_pending.is_empty()); +} + +#[test] +fn xi_slave_switch_device_changed_selection_on_child_window_is_delivered() { + use crate::{core_loop::pointer_fanout::pointer_event_fanout_to_state, host_x11::HostXidMap}; + + const CLIENT: u32 = 94; + const CHILD: u32 = 0x0010_0094; + const XI_SELECT_EVENTS: u8 = 46; + const SOURCE: u64 = 0xB14; + + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(CLIENT), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(CHILD), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let (source_id, pointer_id) = + xi_dynamic_grab_source(&mut state, SOURCE, false, true, "child-switch-mouse"); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + XI_SELECT_EVENTS, + &xi_dynamic_select_events_body( + CHILD, + crate::xinput::DEVICEID_MASTER_POINTER, + crate::xinput::XI2_DEVICE_CHANGED_MASK, + ), + ); + assert!( + read_all_available(&mut peer).is_empty(), + "a child selection does not receive the root-only bootstrap" + ); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(2), + XI_SELECT_EVENTS, + &xi_dynamic_select_events_body( + ROOT_WINDOW.0, + crate::xinput::DEVICEID_MASTER_POINTER, + crate::xinput::XI2_DEVICE_CHANGED_MASK, + ), + ); + let _root_bootstrap = read_all_available(&mut peer); + + let dropped = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &HostXidMap::new(), + xi_dynamic_pointer_event( + crate::core_loop::InputOrigin::Physical(source_id), + crate::host_x11::PointerEventKind::MotionNotify, + 0, + 1, + ), + true, + false, + ); + assert!(dropped.is_empty()); + + let events = read_all_available(&mut peer); + let mut delivered = Vec::new(); + let mut offset = 0; + while offset < events.len() { + assert_eq!(events[offset], 35, "GenericEvent"); + let units = usize::try_from(u32::from_le_bytes( + events[offset + 4..offset + 8].try_into().unwrap(), + )) + .unwrap(); + let event_len = 32 + 4 * units; + assert!( + offset + event_len <= events.len(), + "complete DeviceChanged event" + ); + assert_eq!( + u16::from_le_bytes([events[offset + 8], events[offset + 9]]), + 1, + "XI_DeviceChanged SlaveSwitch" + ); + assert_eq!( + u16::from_le_bytes([events[offset + 10], events[offset + 11]]), + crate::xinput::DEVICEID_MASTER_POINTER + ); + assert_eq!( + u16::from_le_bytes([events[offset + 18], events[offset + 19]]), + pointer_id, + "sourceid is the newly active physical slave" + ); + delivered.push(( + u16::from_le_bytes([events[offset + 10], events[offset + 11]]), + u16::from_le_bytes([events[offset + 18], events[offset + 19]]), + )); + offset += event_len; + } + assert_eq!( + delivered, + [(crate::xinput::DEVICEID_MASTER_POINTER, pointer_id); 2], + "Xorg emits one DeviceChanged for root and one for the selected child" + ); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER) + ); + assert!(state.xi2_pointer_grabs.is_empty()); + assert!(state.active_pointer_grab.is_none()); + assert_eq!(state.buttons_down, 0); + assert!(state.unpublished_pointer_buttons_down.is_empty()); + assert!(state.sync_pending.is_empty()); + assert!(state.xi1_frozen.values().all(|freeze| { + freeze.state == crate::server::Xi1SyncState::Thawed + && freeze.other.is_none() + && freeze.stored.is_none() + })); + assert!(state.clients[&CLIENT].outbound.is_empty()); +} + +fn xi_dynamic_grab_body(window: u32, device_id: u16, mode: u8) -> Vec { + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // current time + body.extend_from_slice(&0u32.to_le_bytes()); // no cursor + body.extend_from_slice(&device_id.to_le_bytes()); + body.extend_from_slice(&[mode, 1, 0, 0]); // mode, paired async, owner_events, pad + body.extend_from_slice(&0u16.to_le_bytes()); // no event-mask words + body.extend_from_slice(&[0u8; 2]); + body +} + +fn xi_dynamic_passive_grab_body( + window: u32, + detail: u32, + device_id: u16, + grab_type: u8, + grab_mode: u8, + paired_device_mode: u8, +) -> Vec { + let mut body = Vec::with_capacity(32); + body.extend_from_slice(&0u32.to_le_bytes()); // current time + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // no cursor + body.extend_from_slice(&detail.to_le_bytes()); + body.extend_from_slice(&device_id.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); // one modifier tuple + body.extend_from_slice(&0u16.to_le_bytes()); // no XI2 event-mask words + body.extend_from_slice(&[grab_type, grab_mode, paired_device_mode, 0, 0, 0]); + body.extend_from_slice(&0u32.to_le_bytes()); // no modifiers + body +} + +fn xi_dynamic_allow_replay_body(device_id: u16) -> Vec { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // current time + body.extend_from_slice(&device_id.to_le_bytes()); + body.extend_from_slice(&[2, 0]); // XIReplayDevice, pad + body +} + +#[test] +fn xi_dynamic_grabs_classify_keyboard_and_keep_slave_grabs_independent() { + const KEY_CLIENT: u32 = 1; + const POINTER_CLIENT_A: u32 = 2; + const POINTER_CLIENT_B: u32 = 3; + const WINDOW: u32 = 0x0010_0057; + + let mut state = ServerState::new(); + let _key_peer = install_client(&mut state, KEY_CLIENT); + let _pointer_peer_a = install_client(&mut state, POINTER_CLIENT_A); + let _pointer_peer_b = install_client(&mut state, POINTER_CLIENT_B); + let mut backend = RecordingBackend::new(); + let (_, keyboard_id) = xi_dynamic_grab_source(&mut state, 11, true, false, "kbd-a"); + let (_, pointer_id_a) = xi_dynamic_grab_source(&mut state, 12, false, true, "ptr-a"); + let (_, pointer_id_b) = xi_dynamic_grab_source(&mut state, 13, false, true, "ptr-b"); + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 7, + }; + + for (client, device_id) in [ + (KEY_CLIENT, keyboard_id), + (POINTER_CLIENT_A, pointer_id_a), + (POINTER_CLIENT_B, pointer_id_b), + ] { + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(client), + SequenceNumber(1), + header, + &xi_dynamic_grab_body(WINDOW, device_id, 1), + ) + .expect("XIGrabDevice for physical facet"); + } + + assert!( + state.active_pointer_grab.is_none(), + "a pointer-slave grab must not occupy the core master-pointer slot" + ); + assert!( + state.active_keyboard_grab.is_none(), + "a keyboard-slave grab must not occupy the core master-keyboard slot" + ); + assert_eq!( + state.xi2_keyboard_grabs.get(&keyboard_id).unwrap().owner, + ClientId(KEY_CLIENT) + ); + assert_eq!( + state.xi2_pointer_grabs.get(&pointer_id_a).unwrap().owner, + ClientId(POINTER_CLIENT_A) + ); + assert_eq!( + state.xi2_pointer_grabs.get(&pointer_id_b).unwrap().owner, + ClientId(POINTER_CLIENT_B) + ); + assert_eq!(state.xi2_keyboard_grabs.len(), 1); + assert_eq!(state.xi2_pointer_grabs.len(), 2); + assert_eq!( + state.xi2_detached_masters.get(&keyboard_id), + Some(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + ); + assert_eq!( + state.xi2_detached_masters.get(&pointer_id_a), + Some(&crate::xinput::DEVICEID_MASTER_POINTER) + ); + assert_eq!( + state.xi2_detached_masters.get(&pointer_id_b), + Some(&crate::xinput::DEVICEID_MASTER_POINTER) + ); + assert_eq!( + state + .xi_devices + .device(keyboard_id) + .unwrap() + .attached_master, + None + ); + assert_eq!( + state + .xi_devices + .device(pointer_id_a) + .unwrap() + .attached_master, + None + ); + assert_eq!( + state + .xi_devices + .device(pointer_id_b) + .unwrap() + .attached_master, + None + ); +} + +#[test] +fn xi_dynamic_grabs_slave_pointer_replay_reattaches_and_replays_to_natural_target() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + + const GRAB_CLIENT: u32 = 1; + const TARGET_CLIENT: u32 = 2; + const TARGET_WINDOW: u32 = 0x0010_005A; + const HOST_XID: u32 = 0xCAFE_005A; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT); + let mut target_peer = install_client(&mut state, TARGET_CLIENT); + let mut backend = RecordingBackend::new(); + let (source_id, pointer_id) = + xi_dynamic_grab_source(&mut state, 41, false, true, "replay-pointer"); + assert!(pointer_id > 5, "test must use a dynamic physical slave ID"); + assert_eq!( + state.xi_devices.role(pointer_id), + Some(crate::xinput::XiDeviceRole::SlavePointer) + ); + state.resources.create_window( + ClientId(TARGET_CLIENT), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WINDOW), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(TARGET_WINDOW)); + state + .clients + .get_mut(&TARGET_CLIENT) + .expect("target client") + .event_masks + .insert(ResourceId(TARGET_WINDOW), 0x0004); // ButtonPressMask + Backend::register_top_level(&mut backend, None, ResourceId(TARGET_WINDOW), HOST_XID) + .expect("register physical input target"); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 54, + length_units: 9, + }, + &xi_dynamic_passive_grab_body( + ROOT_WINDOW.0, + 1, + pointer_id, + 0, // Button + 0, // synchronous pointer mode + 1, // asynchronous paired-device mode + ), + ) + .expect("XIPassiveGrabDevice button"); + let _ = read_all_available(&mut grab_peer); // XIPassiveGrabDevice reply + + let xid_map = backend.xid_map().clone(); + let press = HostPointerEvent { + origin: crate::core_loop::InputOrigin::Physical(source_id), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x1234, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + assert!(state.xi2_pointer_grabs.contains_key(&pointer_id)); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None, + "activating a synchronous physical-slave button grab detaches that slave" + ); + assert!( + state.active_pointer_grab.is_none(), + "a physical-slave XI2 grab must not occupy the core master slot" + ); + assert!(matches!( + state + .xi1_frozen + .get(&pointer_id) + .and_then(|freeze| freeze.stored.as_ref()), + Some(crate::server::QueuedInputEvent::HostPointer(_)) + )); + assert!( + read_all_available(&mut target_peer).is_empty(), + "the natural target waits for XIReplayDevice" + ); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(2), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }, + &xi_dynamic_allow_replay_body(pointer_id), + ) + .expect("XIAllowEvents ReplayDevice"); + + assert!(!state.xi2_pointer_grabs.contains_key(&pointer_id)); + assert!(state.active_pointer_grab.is_some_and(|grab| { + grab.implicit + && grab.owner == ClientId(TARGET_CLIENT) + && grab.grab_window == ResourceId(TARGET_WINDOW) + })); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER), + "ReplayDevice restores the physical slave's original master" + ); + assert!(!state.xi2_detached_masters.contains_key(&pointer_id)); + assert!(!state.xi1_frozen[&pointer_id].frozen()); + assert!(state.xi1_frozen[&pointer_id].stored.is_none()); + + let replay = read_all_or_buffered(&mut state, TARGET_CLIENT, &mut target_peer); + assert!( + replay.len() >= 32, + "expected replayed ButtonPress, got {} bytes", + replay.len() + ); + assert_eq!( + replay[0] & 0x7f, + 4, + "replay reaches the target as ButtonPress" + ); + assert_eq!( + &replay[12..16], + &TARGET_WINDOW.to_le_bytes(), + "XIReplayDevice delivers to the natural target after the passive grab" + ); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + kind: PointerEventKind::ButtonRelease, + time: 0x1235, + state: 0x0100, + ..press + }, + true, + false, + ); + assert!(state.xi2_pointer_grabs.is_empty()); + assert!(state.active_pointer_grab.is_none()); +} + +#[test] +fn xi_dynamic_grabs_slave_keyboard_replay_reattaches_and_replays_to_focus() { + use crate::{ + core_loop::key_fanout::key_event_fanout_to_state, host_x11::HostKeyEvent, + resources::ROOT_VISUAL, + }; + + const GRAB_CLIENT: u32 = 1; + const TARGET_CLIENT: u32 = 2; + const TARGET_WINDOW: u32 = 0x0010_005B; + const KEYCODE: u32 = 38; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT); + let mut target_peer = install_client(&mut state, TARGET_CLIENT); + let mut backend = RecordingBackend::new(); + let (source_id, keyboard_id) = + xi_dynamic_grab_source(&mut state, 42, true, false, "replay-keyboard"); + assert!(keyboard_id > 5, "test must use a dynamic physical slave ID"); + assert_eq!( + state.xi_devices.role(keyboard_id), + Some(crate::xinput::XiDeviceRole::SlaveKeyboard) + ); + state.resources.create_window( + ClientId(TARGET_CLIENT), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WINDOW), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(TARGET_WINDOW)); + state.core_focus.raw = TARGET_WINDOW; + state + .clients + .get_mut(&TARGET_CLIENT) + .expect("target client") + .event_masks + .insert(ResourceId(TARGET_WINDOW), 0x0001); // KeyPressMask + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 54, + length_units: 9, + }, + &xi_dynamic_passive_grab_body( + ROOT_WINDOW.0, + KEYCODE, + keyboard_id, + 1, // Keycode + 0, // synchronous keyboard mode + 1, // asynchronous paired-device mode + ), + ) + .expect("XIPassiveGrabDevice keycode"); + let _ = read_all_available(&mut grab_peer); // XIPassiveGrabDevice reply + + let press = HostKeyEvent { + origin: crate::core_loop::InputOrigin::Physical(source_id), + pressed: true, + keycode: KEYCODE as u8, + time: 0x1234, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + }; + let _ = key_event_fanout_to_state(&mut state, &mut backend, press); + + assert!(state.xi2_keyboard_grabs.contains_key(&keyboard_id)); + assert_eq!( + state + .xi_devices + .device(keyboard_id) + .unwrap() + .attached_master, + None, + "activating a synchronous physical-slave key grab detaches that slave" + ); + assert!(matches!( + state + .xi1_frozen + .get(&keyboard_id) + .and_then(|freeze| freeze.stored.as_ref()), + Some( + crate::server::QueuedInputEvent::HostKey(_) + | crate::server::QueuedInputEvent::HostKeyTransition(_, _) + ) + )); + assert!( + read_all_available(&mut target_peer).is_empty(), + "the focus window waits for XIReplayDevice" + ); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(2), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }, + &xi_dynamic_allow_replay_body(keyboard_id), + ) + .expect("XIAllowEvents ReplayDevice"); + + assert!(!state.xi2_keyboard_grabs.contains_key(&keyboard_id)); + assert!(state.active_keyboard_grab.is_none()); + assert_eq!( + state + .xi_devices + .device(keyboard_id) + .unwrap() + .attached_master, + Some(crate::xinput::DEVICEID_MASTER_KEYBOARD), + "ReplayDevice restores the physical slave's original master" + ); + assert!(!state.xi2_detached_masters.contains_key(&keyboard_id)); + assert!(!state.xi1_frozen[&keyboard_id].frozen()); + assert!(state.xi1_frozen[&keyboard_id].stored.is_none()); + + let replay = read_all_available(&mut target_peer); + assert!( + replay.len() >= 32, + "expected replayed KeyPress, got {} bytes", + replay.len() + ); + assert_eq!(replay[0] & 0x7f, 2, "replay reaches focus as KeyPress"); + assert_eq!( + &replay[12..16], + &TARGET_WINDOW.to_le_bytes(), + "XIReplayDevice delivers to the current focus window" + ); +} + +#[test] +fn xi_dynamic_grabs_slave_keyboard_release_reattaches_for_next_key() { + use crate::{ + core_loop::key_fanout::key_event_fanout_to_state, host_x11::HostKeyEvent, + resources::ROOT_VISUAL, + }; + + const GRAB_CLIENT: u32 = 1; + const TARGET_CLIENT: u32 = 2; + const TARGET_WINDOW: u32 = 0x0010_005C; + const GRABBED_KEYCODE: u32 = 38; + const NEXT_KEYCODE: u8 = 39; + + let mut state = ServerState::new(); + let mut grab_peer = install_client(&mut state, GRAB_CLIENT); + let mut target_peer = install_client(&mut state, TARGET_CLIENT); + let mut backend = RecordingBackend::new(); + let (source_id, keyboard_id) = + xi_dynamic_grab_source(&mut state, 43, true, false, "release-keyboard"); + assert!(keyboard_id > 5, "test must use a dynamic physical slave ID"); + assert_eq!( + state.xi_devices.role(keyboard_id), + Some(crate::xinput::XiDeviceRole::SlaveKeyboard) + ); + state.resources.create_window( + ClientId(TARGET_CLIENT), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(TARGET_WINDOW), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(TARGET_WINDOW)); + state.core_focus.raw = TARGET_WINDOW; + state + .clients + .get_mut(&TARGET_CLIENT) + .expect("target client") + .event_masks + .insert(ResourceId(TARGET_WINDOW), 0x0001); // KeyPressMask + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 54, + length_units: 9, + }, + &xi_dynamic_passive_grab_body( + ROOT_WINDOW.0, + GRABBED_KEYCODE, + keyboard_id, + 1, // Keycode + 1, // asynchronous keyboard mode; release is not frozen + 1, // asynchronous paired-device mode + ), + ) + .expect("XIPassiveGrabDevice keycode"); + let _ = read_all_available(&mut grab_peer); // XIPassiveGrabDevice reply + + let input = |pressed, keycode| HostKeyEvent { + origin: crate::core_loop::InputOrigin::Physical(source_id), + pressed, + keycode, + time: 0x1234, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + }; + let _ = key_event_fanout_to_state(&mut state, &mut backend, input(true, GRABBED_KEYCODE as u8)); + assert!(state.xi2_keyboard_grabs.contains_key(&keyboard_id)); + assert_eq!( + state + .xi_devices + .device(keyboard_id) + .unwrap() + .attached_master, + None, + "the matching passive grab floats the physical keyboard" + ); + + let _ = key_event_fanout_to_state( + &mut state, + &mut backend, + input(false, GRABBED_KEYCODE as u8), + ); + assert!( + !state.xi2_keyboard_grabs.contains_key(&keyboard_id), + "the matching key release auto-deactivates the slave passive grab" + ); + assert_eq!( + state + .xi_devices + .device(keyboard_id) + .unwrap() + .attached_master, + Some(crate::xinput::DEVICEID_MASTER_KEYBOARD), + "matching key release restores the physical slave's original master" + ); + assert!(!state.xi2_detached_masters.contains_key(&keyboard_id)); + + let _ = key_event_fanout_to_state(&mut state, &mut backend, input(true, NEXT_KEYCODE)); + let delivered = read_all_available(&mut target_peer); + assert!( + delivered.len() >= 32, + "expected next core KeyPress, got {} bytes", + delivered.len() + ); + assert_eq!( + delivered[0] & 0x7f, + 2, + "next key returns to core KeyPress delivery" + ); + assert_eq!( + &delivered[12..16], + &TARGET_WINDOW.to_le_bytes(), + "next key from the reattached slave reaches the focused window" + ); + assert_ne!( + state.keys_down[usize::from(NEXT_KEYCODE / 8)] & (1 << (NEXT_KEYCODE % 8)), + 0, + "the reattached key also updates master keyboard state" + ); +} + +#[test] +fn xi_dynamic_grabs_passive_button_is_scoped_to_its_device() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + + const GRAB_CLIENT: u32 = 1; + const WINDOW: u32 = 0x0010_0058; + const HOST_XID: u32 = 0xCAFE_0058; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, GRAB_CLIENT); + let mut backend = RecordingBackend::new(); + let (_, razer_id) = xi_dynamic_grab_source(&mut state, 21, false, true, "razer"); + let (hyperx_source, hyperx_id) = xi_dynamic_grab_source(&mut state, 22, false, true, "hyperx"); + state.resources.create_window( + ClientId(GRAB_CLIENT), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WINDOW)); + + // XIPassiveGrabDevice: one AnyModifier button grab, tied to the Razer + // pointer facet. The button mask is intentionally empty; the passive + // grab still activates and its owner receives the protocol event. + let mut body = Vec::with_capacity(32); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&WINDOW.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&1u32.to_le_bytes()); // button 1 + body.extend_from_slice(&razer_id.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); // one modifier tuple + body.extend_from_slice(&0u16.to_le_bytes()); // no event-mask words + body.extend_from_slice(&[0, 0, 1, 0, 0, 0]); // button, sync, async, owner=false, pad + body.extend_from_slice(&0u32.to_le_bytes()); // AnyModifier is encoded as zero here + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 54, + length_units: 9, + }, + &body, + ) + .expect("XIPassiveGrabDevice"); + + Backend::register_top_level(&mut backend, None, ResourceId(WINDOW), HOST_XID) + .expect("register host window"); + let event = |source, kind, root_x, root_y, state_mask| HostPointerEvent { + origin: crate::core_loop::InputOrigin::Physical(source), + kind, + host_xid: HOST_XID, + detail: 1, + time: 0x1234, + root_x, + root_y, + event_x: root_x, + event_y: root_y, + state: state_mask, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let xid_map = backend.xid_map().clone(); + for kind in [ + PointerEventKind::ButtonPress, + PointerEventKind::ButtonRelease, + ] { + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + event( + hyperx_source, + kind, + 10, + 10, + if kind == PointerEventKind::ButtonRelease { + 0x0100 + } else { + 0 + }, + ), + true, + false, + ); + } + + assert!( + !state.xi2_pointer_grabs.contains_key(&razer_id), + "HyperX press/release must not activate Razer's exact-device passive grab", + ); + assert!( + state.active_pointer_grab.is_none(), + "Razer's exact-device passive grab must not intercept HyperX" + ); + assert_eq!( + state.xi_devices.device(hyperx_id).unwrap().buttons_down, + 0, + "HyperX press/release transitions remain balanced on HyperX" + ); + assert_eq!( + state.xi_devices.device(razer_id).unwrap().buttons_down, + 0, + "Razer's held set is untouched" + ); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + event(hyperx_source, PointerEventKind::ButtonPress, 10, 10, 0), + true, + false, + ); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + event( + crate::xinput::InputSourceId(21), + PointerEventKind::ButtonPress, + 10, + 10, + 0, + ), + true, + false, + ); + assert_eq!( + state + .xi2_pointer_grabs + .get(&razer_id) + .map(|grab| grab.owner), + Some(ClientId(GRAB_CLIENT)), + "Razer's exact XI2 passive grab activates for Razer" + ); + assert_eq!( + state.xi_devices.device(razer_id).unwrap().attached_master, + None, + "the passive grab floats only its exact physical slave" + ); + assert!(state.active_pointer_grab.is_none()); + + // The activating press arrived while attached. A later, separate + // button transition arrives while the Razer facet is floating and + // must change only its per-slave hold state. + let master_buttons = state.buttons_down; + let master_position = state.pointer_root; + let second_press = HostPointerEvent { + detail: 2, + state: 0x0100, + ..event( + crate::xinput::InputSourceId(21), + PointerEventKind::ButtonPress, + 10, + 10, + 0x0100, + ) + }; + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + second_press, + true, + false, + ); + assert_eq!(state.buttons_down, master_buttons); + assert_eq!(state.pointer_root, master_position); + assert_eq!(state.xi_devices.device(razer_id).unwrap().buttons_down, 3); + let second_release = HostPointerEvent { + kind: PointerEventKind::ButtonRelease, + state: 0x0300, + ..second_press + }; + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + second_release, + true, + false, + ); + assert_eq!(state.buttons_down, master_buttons); + assert_eq!(state.xi_devices.device(razer_id).unwrap().buttons_down, 1); + + for kind in [ + PointerEventKind::ButtonPress, + PointerEventKind::ButtonRelease, + ] { + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + event( + hyperx_source, + kind, + 10, + 10, + if kind == PointerEventKind::ButtonRelease { + 0x0100 + } else { + 0 + }, + ), + true, + false, + ); + } + assert!(state.xi2_pointer_grabs.contains_key(&razer_id)); + assert_eq!(state.xi_devices.device(hyperx_id).unwrap().buttons_down, 0); + + let master_position = state.pointer_root; + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + event( + crate::xinput::InputSourceId(21), + PointerEventKind::MotionNotify, + 30, + 40, + 0x0100, + ), + true, + false, + ); + assert_eq!( + state.pointer_root, master_position, + "floating motion leaves the master sprite alone" + ); + assert_eq!( + state.floating_pointer_positions.get(&razer_id), + Some(&(30.0, 40.0)) + ); + + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + event( + crate::xinput::InputSourceId(21), + PointerEventKind::ButtonRelease, + 30, + 40, + 0x0100, + ), + true, + false, + ); + assert!(state.xi2_pointer_grabs.contains_key(&razer_id)); + assert_eq!( + state.xi_devices.device(razer_id).unwrap().attached_master, + None, + "a synchronous activating press stays grabbed until replay" + ); + assert!(!state.sync_pending.is_empty()); + + let mut allow_body = Vec::with_capacity(8); + allow_body.extend_from_slice(&0u32.to_le_bytes()); + allow_body.extend_from_slice(&razer_id.to_le_bytes()); + allow_body.extend_from_slice(&[2, 0]); // XIReplayDevice + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(GRAB_CLIENT), + SequenceNumber(2), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }, + &allow_body, + ) + .expect("XIAllowEvents ReplayDevice"); + assert!( + state.xi2_pointer_grabs.is_empty(), + "passive release ends the exact-device grab" + ); + assert_eq!( + state.xi_devices.device(razer_id).unwrap().attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER), + "passive release restores the original master" + ); + assert_eq!(state.xi_devices.device(razer_id).unwrap().buttons_down, 0); + assert_eq!(state.xi_devices.device(hyperx_id).unwrap().buttons_down, 0); + assert_eq!( + state.buttons_down, 0, + "replay drains the attached master hold" + ); + assert!(!state.xi2_detached_masters.contains_key(&razer_id)); + assert!(!state.floating_pointer_positions.contains_key(&razer_id)); + assert!(!state.xi1_frozen[&razer_id].frozen()); + assert!(state.sync_pending.is_empty()); +} + +#[test] +fn xi_dynamic_grabs_detach_and_reattach_slave_without_pair_freeze() { + const CLIENT: u32 = 1; + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT); + let mut backend = RecordingBackend::new(); + let (source_id, pointer_id) = + xi_dynamic_grab_source(&mut state, 31, false, true, "floating-razer"); + let grab_body = xi_dynamic_wire_grab_body( + ROOT_WINDOW.0, + pointer_id, + 1, // asynchronous pointer mode + 0, // requested synchronous paired-device mode; Xorg forces Async for slaves + false, + None, + ); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(1), + 51, + &grab_body, + ); + let _ = read_all_available(&mut peer); // XIGrabDevice reply and crossings + + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None, + "an explicit XI2 physical-slave grab detaches the slave" + ); + assert!( + state.xi_devices.source(source_id).unwrap().enabled, + "detaching a live slave does not disable its source" + ); + assert_eq!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .and_then(|freeze| freeze.other), + None, + "a slave grab forces its paired mode to Async and leaves the master keyboard unfrozen", + ); + assert!( + !state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .is_some_and(crate::server::Xi1Freeze::frozen) + ); + + // XIAsyncPairedDevice remains a no-op after Xorg coerces the paired + // mode to Async during XIGrabDevice. + let mut allow_body = Vec::with_capacity(8); + allow_body.extend_from_slice(&0u32.to_le_bytes()); + allow_body.extend_from_slice(&pointer_id.to_le_bytes()); + allow_body.extend_from_slice(&[3, 0]); // XIAsyncPairedDevice + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(2), + 53, + &allow_body, + ); + assert_eq!( + state + .xi1_frozen + .get(&crate::xinput::DEVICEID_MASTER_KEYBOARD) + .and_then(|freeze| freeze.other), + None, + "XIAllowEvents does not find a paired master hold to release", + ); + assert!(state.xi2_pointer_grabs.contains_key(&pointer_id)); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + None, + "allowing the paired device leaves the requested slave grab intact", + ); + + let mut ungrab_body = Vec::with_capacity(8); + ungrab_body.extend_from_slice(&0u32.to_le_bytes()); + ungrab_body.extend_from_slice(&pointer_id.to_le_bytes()); + ungrab_body.extend_from_slice(&[0u8; 2]); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(CLIENT), + SequenceNumber(3), + 52, + &ungrab_body, + ); + assert_eq!( + state.xi_devices.device(pointer_id).unwrap().attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER), + "ungrab restores the original master attachment" + ); + assert!(!state.xi2_pointer_grabs.contains_key(&pointer_id)); + assert!(!state.xi2_detached_masters.contains_key(&pointer_id)); + assert!(!state.floating_pointer_positions.contains_key(&pointer_id)); + assert!(!state.xi1_frozen[&pointer_id].frozen()); + assert!(state.sync_pending.is_empty()); +} + +#[test] +fn xi_dynamic_grabs_disconnect_reattaches_only_the_owners_slave() { + use crate::{ + backend::Backend, + core_loop::{message::InputOrigin, pointer_fanout::pointer_event_fanout_to_state}, + host_x11::{HostPointerEvent, PointerEventKind}, + }; + + const OWNER: u32 = 1; + const OTHER_OWNER: u32 = 2; + let mut state = ServerState::new(); + let _owner_peer = install_client(&mut state, OWNER); + let _other_peer = install_client(&mut state, OTHER_OWNER); + let mut backend = RecordingBackend::new(); + let (owner_source, owner_device) = + xi_dynamic_grab_source(&mut state, 41, false, true, "disconnect-pointer"); + let (_other_source, other_device) = + xi_dynamic_grab_source(&mut state, 42, false, true, "unrelated-pointer"); + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 7, + }; + + for (client, device, mode) in [(OWNER, owner_device, 0), (OTHER_OWNER, other_device, 1)] { + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(client), + SequenceNumber(1), + header, + &xi_dynamic_grab_body(ROOT_WINDOW.0, device, mode), + ) + .expect("XIGrabDevice before disconnect"); + } + + assert!(state.xi1_frozen[&owner_device].frozen()); + let xid_map = backend.xid_map().clone(); + let _ = pointer_event_fanout_to_state( + &mut state, + &mut backend, + &xid_map, + HostPointerEvent { + origin: InputOrigin::Physical(owner_source), + kind: PointerEventKind::ButtonPress, + host_xid: 0, + detail: 1, + time: 0x2233, + root_x: 12, + root_y: 13, + event_x: 12, + event_y: 13, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }, + true, + false, + ); + assert_eq!(state.sync_pending.len(), 1, "sync-grab event is queued"); + assert_eq!( + state.xi_devices.device(owner_device).unwrap().buttons_down, + 1 + ); + + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut backend, + ClientId(OWNER), + ); + + assert!(!state.xi2_pointer_grabs.contains_key(&owner_device)); + assert_eq!( + state + .xi2_pointer_grabs + .get(&other_device) + .map(|grab| grab.owner), + Some(ClientId(OTHER_OWNER)), + "disconnect leaves the other client's independent grab intact" + ); + assert_eq!( + state + .xi_devices + .device(owner_device) + .unwrap() + .attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER) + ); + assert_eq!( + state + .xi_devices + .device(other_device) + .unwrap() + .attached_master, + None, + "the unrelated grabbed slave remains floating" + ); + assert!(!state.xi2_detached_masters.contains_key(&owner_device)); + assert!(!state.floating_pointer_positions.contains_key(&owner_device)); + assert!(state.xi2_detached_masters.contains_key(&other_device)); + assert!(!state.xi1_frozen[&owner_device].frozen()); + assert!(state.xi1_frozen[&owner_device].stored.is_none()); + assert!(state.sync_pending.is_empty()); + assert_eq!( + state.xi_devices.device(owner_device).unwrap().buttons_down, + 1, + "disconnect releases the grab and queue, while the still-held physical button remains tracked" + ); + assert!(state.active_pointer_grab.is_none()); +} + +/// On `XIGrabDevice` activation, Xorg synthesises an XI2 crossing +/// event (`XI_Enter`(7) for pointer / `XI_FocusIn`(9) for keyboard) +/// with `mode=NotifyGrab`(1) and `detail=NotifyNonlinear`(3) and +/// delivers it to the grab requester. Without these events, GTK3 +/// popup state machines never engage their hover/click tracking — +/// the menu is visible but items don't highlight or activate. +/// Captured in `mate-xorg.xtrace` (Xi/exevents.c::ActivatePointer +/// Grab / ActivateKeyboardGrab). On `XIUngrabDevice` the symmetric +/// `mode=NotifyUngrab`(2) crossings fire. +#[test] +fn xi_grab_device_emits_grab_activation_crossings() { + use std::io::Read; + + const CLIENT_ID: u32 = 1; + const WINDOW_XID: u32 = 0x0010_0060; + const HOST_XID: u32 = 0x0040_0060; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WINDOW_XID), + parent: ROOT_WINDOW, + x: 100, + y: 200, + width: 300, + height: 200, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(WINDOW_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + let _ = state.resources.map_window(ResourceId(WINDOW_XID)); + + // XIGrabDevice pointer. + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&WINDOW_XID.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.extend_from_slice(&[1, 1, 1, 0]); + body.extend_from_slice(&0u16.to_le_bytes()); // mask_len + body.extend_from_slice(&[0u8; 2]); + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 7, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("XIGrabDevice"); + + // Drain wire and look for the synthesised XI2 Enter event: + // byte 0: 35 (GenericEvent) + // byte 1: 137 (XInputExtension major) + // bytes 8-9: evtype = 7 (XI_Enter) + // byte 18: mode = 1 (NotifyGrab) + // byte 19: detail = 0 (NotifyAncestor — sprite is the ancestor) + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 4096]; + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + // Wire contains both the 32-byte XIGrabDevice reply and the + // synthesised XI2 GenericEvent (76 bytes). Order may vary — + // scan for the GenericEvent signature: type=35, major=137, + // evtype=7 (XI_Enter). + let crossing_offset = (0..wire.len().saturating_sub(76)) + .find(|&i| { + wire[i] == 35 + && wire[i + 1] == 137 + && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 7 + }) + .unwrap_or_else(|| { + panic!( + "no XI_Enter GenericEvent found in {} wire bytes: {:?}", + wire.len(), + &wire[..wire.len().min(140)], + ) + }); + let crossing = &wire[crossing_offset..crossing_offset + 76]; + // Crossing event byte layout (from encode_xi2_crossing_event): + // 0:type=35, 1:major, 2..4:seq, 4..8:length, 8..10:evtype, + // 10..12:deviceid, 12..16:time, 16..18:sourceid, 18:mode, + // 19:detail, 20..24:root, 24..28:event, ... + assert_eq!(crossing[18], 1, "mode = NotifyGrab"); + // The sprite (pointer at (0,0)) is in root, an ancestor of the + // grab window — Xorg's `DeviceEnterLeaveEvents` IsParent(from,to) + // branch emits `XI_Enter(NotifyAncestor)` on the grab window + // (preceded by `XI_Leave(NotifyInferior)` on root). NotifyAncestor + // = 0. (Pre-fix this was a hardcoded NotifyNonlinear = 3.) + assert_eq!(crossing[19], 0, "detail = NotifyAncestor"); + let event_window = u32::from_le_bytes([crossing[24], crossing[25], crossing[26], crossing[27]]); + assert_eq!(event_window, WINDOW_XID); + + // The activation chain also leaves the ancestor (root) the + // sprite was in: an `XI_Leave(NotifyInferior)` precedes the Enter. + let leave = (0..wire.len().saturating_sub(28)).find(|&i| { + wire[i] == 35 && wire[i + 1] == 137 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 8 + }); + let leave = leave.expect("XI_Leave on the ancestor (root) must precede the Enter"); + let leave = &wire[leave..leave + 28]; + assert_eq!(leave[19], 2, "Leave detail = NotifyInferior"); + let leave_window = u32::from_le_bytes([leave[24], leave[25], leave[26], leave[27]]); + assert_eq!(leave_window, ROOT_WINDOW.0, "Leave is on the root ancestor"); +} + +/// XIGrabDevice whose `grab_window` is the very window the pointer +/// already sits in must emit NO pointer crossing — Xorg's +/// `DoEnterLeaveEvents` early-returns when `fromWin == toWin` +/// (dix/enterleave.c). mutter/muffin grabs its own full-screen +/// clutter stage on every button press; the pre-fix code emitted an +/// unconditional `XI_Enter(NotifyGrab)` on the grab window, which +/// desynced cinnamon's XEmbed-systray click-forward state machine — +/// pamac's tray icon became unclickable (HW trace 2026-06-22). The +/// sprite is resolved from the live pointer position, matching the +/// production handler. +#[test] +fn xi_grab_device_self_grab_emits_no_crossing() { + use std::io::Read; + + const CLIENT_ID: u32 = 1; + // Window covering the pointer position (RecordingBackend's + // query_pointer reports (0,0)), so it is the sprite window AND + // the grab window. + const STAGE_XID: u32 = 0x0010_0070; + const HOST_XID: u32 = 0x0040_0070; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, CLIENT_ID); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + yserver_protocol::x11::ClientId(CLIENT_ID), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(STAGE_XID), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 2560, + height: 1440, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + { + let w = state + .resources + .window_mut(ResourceId(STAGE_XID)) + .expect("window installed"); + w.host_xid = Some(crate::backend::WindowHandle::from_raw_for_test(HOST_XID)); + } + let _ = state.resources.map_window(ResourceId(STAGE_XID)); + // Precondition: the pointer (0,0) really does resolve to the + // grab window, otherwise the test would pass trivially. + assert_eq!( + state.root_pointer_target_at(0, 0).map(|h| h.0), + Some(ResourceId(STAGE_XID)), + "sprite must be the grab window for this fixture" + ); + + // XIGrabDevice pointer (device 2) on the stage window. + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&STAGE_XID.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid + body.extend_from_slice(&[1, 1, 1, 0]); // mode, paired, owner_events, pad + body.extend_from_slice(&0u16.to_le_bytes()); // mask_len + body.extend_from_slice(&[0u8; 2]); + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 7, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(CLIENT_ID), + SequenceNumber(1), + header, + &body, + ) + .expect("XIGrabDevice"); + + peer.set_nonblocking(true).unwrap(); + let mut wire = Vec::new(); + let mut tmp = [0u8; 4096]; + loop { + match peer.read(&mut tmp) { + Ok(0) => break, + Ok(n) => wire.extend_from_slice(&tmp[..n]), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + // Scan for any XI2 GenericEvent that is an Enter (evtype 7) or + // Leave (evtype 8) from the XInput extension (major 137). There + // must be none — a self-grab is a no-op transition. + let crossing = (0..wire.len().saturating_sub(10)).find(|&i| { + wire[i] == 35 + && wire[i + 1] == 137 + && matches!(u16::from_le_bytes([wire[i + 8], wire[i + 9]]), 7 | 8) + }); + assert!( + crossing.is_none(), + "self-grab must emit no XI_Enter/XI_Leave crossing; got {} wire bytes: {:?}", + wire.len(), + &wire[..wire.len().min(140)], + ); +} + +/// #94 fast-click acceptance: press withheld by muffin's sync XI2 +/// passive grab; the RELEASE arrives during the freeze and is queued; +/// XIAllowEvents(ReplayDevice) replays the press (installing the +/// implicit grab on the natural recipient) and the queue drain must +/// deliver the release UNDER that grab (Xorg PlayReleasedEvents → +/// DeliverGrabbedEvent) — not re-hit-test it. +#[test] +fn xi_replay_device_then_queued_release_follows_implicit_grab() { + use crate::{ + backend::Backend, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const WM: u32 = 1; + const APP: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0051; + const APP_WIN: u32 = 0x0020_0052; + const HOST_XID: u32 = 0xCAFE_0001; + + let mut state = ServerState::new(); + let _wm_peer = install_client(&mut state, WM); + let mut app_peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + app_peer.set_nonblocking(true).expect("nonblocking"); + + for (client, win) in [(WM, GRAB_WIN), (APP, APP_WIN)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + state + .clients + .get_mut(&APP) + .expect("app client") + .event_masks + .insert(ResourceId(APP_WIN), 0x0000_000c); // press|release + Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_XID) + .expect("register host xid"); + + // Frozen sync passive grab held by the WM, activating press stored, + // and the fast release already QUEUED (it arrived mid-freeze; the + // queue gate decremented buttons_down and withheld it). + set_test_pointer_grab(&mut state, WM, GRAB_WIN, true, false); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 1000, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); + } + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 1010, + state: 0x100, + ..press + }; + state + .sync_pending + .push_back(crate::server::PendingSyncEvent { + device: crate::xinput::DEVICEID_MASTER_POINTER, + event: crate::server::QueuedInputEvent::HostPointer(release), + }); + + // XIAllowEvents(ReplayDevice) from the WM. + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&2u16.to_le_bytes()); // deviceid = master ptr + body.push(2); // mode = ReplayDevice + body.push(0); // pad + let header = yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(WM), + SequenceNumber(1), + header, + &body, + ) + .expect("allow events"); + + // The replayed press delivered to APP + the queued release drained + // UNDER the freshly-installed implicit grab. + let bytes = read_all_available(&mut app_peer); + let (mut saw_press, mut saw_release) = (false, false); + let mut off = 0usize; + while off + 32 <= bytes.len() { + match bytes[off] & 0x7F { + 4 => saw_press = true, + 5 => { + saw_release = true; + assert_eq!( + &bytes[off + 12..off + 16], + &APP_WIN.to_le_bytes(), + "queued release must deliver on the implicit grab window" + ); + } + _ => {} + } + off += 32; + } + assert!(saw_press, "replayed press must reach the natural target"); + assert!( + saw_release, + "queued release must follow the implicit grab owner (fast click)" + ); + assert!( + state.active_pointer_grab.is_none(), + "release completes the click — implicit grab torn down" + ); + assert_eq!( + state.buttons_down, 0, + "the queued release leaves the master clear" + ); + assert_eq!( + state.xi_devices.device(4).unwrap().buttons_down, + 0, + "the queued release leaves XTEST 4 clear" + ); +} + +/// An implicit grab is a REAL grab for request purposes (Xorg shares +/// deviceGrab.grab): another client's GrabPointer during it fails +/// AlreadyGrabbed (events.c:5240-5243); the owner's GrabPointer +/// replaces it; the owner's UngrabPointer releases it (events.c:5155). +#[test] +fn implicit_grab_interacts_with_grab_requests_like_a_real_grab() { + use crate::server::ActivePointerGrab; + const OWNER: u32 = 1; + const INTRUDER: u32 = 2; + const WIN: u32 = 0x0010_0001; + + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut owner_peer = install_client(&mut state, OWNER); + let mut intruder_peer = install_client(&mut state, INTRUDER); + owner_peer.set_nonblocking(true).unwrap(); + intruder_peer.set_nonblocking(true).unwrap(); + state.resources.create_window( + ClientId(OWNER), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WIN)); + + let install_implicit = |state: &mut ServerState| { + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(OWNER), + grab_window: ResourceId(WIN), + event_mask: 0x000c, + cursor: ResourceId(0), + time: 1000, + owner_events: false, + via_xi2: false, + implicit: true, + passive: false, + xi2_mask: 0, + }); + state.last_pointer_grab_time = 1000; + }; + let grab_body = || { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&WIN.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); // event-mask + body.push(1); // pointer-mode async + body.push(1); // keyboard-mode async + body.extend_from_slice(&0u32.to_le_bytes()); // confine-to + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&0u32.to_le_bytes()); // time CurrentTime + body + }; + let header = RequestHeader { + opcode: 26, + data: 0, + length_units: 6, + }; + let grab_status = |peer: &mut std::os::unix::net::UnixStream| -> u8 { + let wire = read_all_available(peer); + assert!(wire.len() >= 32, "expected a GrabPointer reply"); + assert_eq!(wire[0], 1, "reply, not an event/error"); + wire[1] + }; + + // (a) Another client's GrabPointer → AlreadyGrabbed, state untouched. + install_implicit(&mut state); + handle_grab_pointer( + &mut state, + &mut backend, + ClientId(INTRUDER), + SequenceNumber(1), + header, + &grab_body(), + ) + .expect("grab pointer"); + assert_eq!(grab_status(&mut intruder_peer), 1, "AlreadyGrabbed"); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.implicit && g.owner == ClientId(OWNER)), + "implicit grab untouched by the failed request" + ); + + // (b) The owner's GrabPointer replaces its implicit grab. + handle_grab_pointer( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(2), + header, + &grab_body(), + ) + .expect("grab pointer"); + assert_eq!(grab_status(&mut owner_peer), 0, "GrabSuccess"); + assert!( + state.active_pointer_grab.is_some_and(|g| !g.implicit), + "explicit grab replaced the implicit one" + ); + + // (c) Owner's UngrabPointer releases its own implicit grab; a + // non-owner's UngrabPointer is a no-op. + install_implicit(&mut state); + let ungrab_body = 0u32.to_le_bytes(); // time CurrentTime + handle_ungrab_pointer( + &mut state, + &mut backend, + ClientId(INTRUDER), + SequenceNumber(3), + &ungrab_body, + ) + .expect("ungrab pointer"); + assert!( + state.active_pointer_grab.is_some(), + "non-owner UngrabPointer must not touch the implicit grab" + ); + handle_ungrab_pointer( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(4), + &ungrab_body, + ) + .expect("ungrab pointer"); + assert!( + state.active_pointer_grab.is_none(), + "owner UngrabPointer releases the implicit grab (Xorg SameClient)" + ); +} + +/// #94 slow-click acceptance (the traced Cinnamon shape): muffin's +/// sync XI2 passive grab withholds the press; XIAllowEvents( +/// XIReplayDevice) re-delivers it to Steam (XI2-only selector), +/// installing the implicit grab; muffin then MUTATES THE TREE +/// (click-to-focus reparents/restacks) before the user releases. +/// The release must follow the implicit grab to Steam — pre-fix it +/// was re-hit-tested against the mutated tree and lost (steam.xtrace: +/// 164 XI2 presses vs 28 releases → stuck button). +#[test] +fn xi_replay_device_press_then_tree_mutation_release_follows_grab() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const WM: u32 = 1; + const APP: u32 = 2; + const GRAB_WIN: u32 = 0x0010_0051; // WM's passive-grab window + const APP_WIN: u32 = 0x0020_0052; // Steam-like, XI2-only selector + const FRAME_WIN: u32 = 0x0010_0060; // WM frame created mid-click + const COVER_WIN: u32 = 0x0010_0061; // WM window the release re-hits + const HOST_APP: u32 = 0xCAFE_0001; + const HOST_COVER: u32 = 0xCAFE_0002; + const XI2_MASTER: u16 = 2; + + let mut state = ServerState::new(); + let mut wm_peer = install_client(&mut state, WM); + let mut app_peer = install_client(&mut state, APP); + let mut backend = RecordingBackend::new(); + wm_peer.set_nonblocking(true).unwrap(); + app_peer.set_nonblocking(true).unwrap(); + + for (client, win) in [ + (WM, GRAB_WIN), + (APP, APP_WIN), + (WM, FRAME_WIN), + (WM, COVER_WIN), + ] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + // Steam shape: cooked XI2 buttons, NO core mask. + state + .clients + .get_mut(&APP) + .expect("app") + .xi2_masks + .insert((ResourceId(APP_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); + // The WM selects XI2 buttons on the covering window — a re-hit-test + // would deliver the release THERE. + state + .clients + .get_mut(&WM) + .expect("wm") + .xi2_masks + .insert((ResourceId(COVER_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); + Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP) + .expect("register app"); + Backend::register_top_level(&mut backend, None, ResourceId(COVER_WIN), HOST_COVER) + .expect("register cover"); + + // Frozen sync passive grab held by the WM, press stored. + set_test_pointer_grab(&mut state, WM, GRAB_WIN, true, false); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_APP, + detail: 1, + time: 1000, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + { + let f = state + .xi1_frozen + .entry(crate::xinput::DEVICEID_MASTER_POINTER) + .or_default(); + f.state = crate::server::Xi1SyncState::FrozenWithEvent; + f.stored = Some(crate::server::QueuedInputEvent::HostPointer(press)); + } + + // XIAllowEvents(ReplayDevice) from the WM. + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.push(2); // ReplayDevice + body.push(0); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(WM), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }, + &body, + ) + .expect("allow events"); + + let xge_events = |bytes: &[u8]| -> Vec<(u16, u32)> { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(( + u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), + u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), + )); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + assert!( + xge_events(&read_all_available(&mut app_peer)).contains(&(4, APP_WIN)), + "replayed press must reach APP as XI2 on its window" + ); + assert!( + state.active_pointer_grab.is_some_and(|g| g.implicit + && g.via_xi2 + && g.owner == ClientId(APP) + && g.grab_window == ResourceId(APP_WIN)), + "replayed press installs the via_xi2 implicit grab (#94 crux)" + ); + + // muffin-style mutation between press and release: reparent the + // app window into a WM frame and let a WM window cover the spot. + let _ = state + .resources + .reparent_window(yserver_protocol::x11::ReparentWindowRequest { + window: ResourceId(APP_WIN), + parent: ResourceId(FRAME_WIN), + x: 0, + y: 0, + }); + let _ = state.resources.map_window(ResourceId(APP_WIN)); + + // Natural release now resolves over the WM's covering window. + let xid_map = backend.xid_map().clone(); + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + host_xid: HOST_COVER, + time: 1200, + state: 0x100, + ..press + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + assert!( + xge_events(&read_all_available(&mut app_peer)).contains(&(5, APP_WIN)), + "release must follow the implicit grab to APP on the grab window" + ); + assert!( + !xge_events(&read_all_available(&mut wm_peer)) + .iter() + .any(|(evtype, _)| *evtype == 5), + "the grab captures the release away from the re-hit-tested window" + ); + assert!( + state.active_pointer_grab.is_none(), + "click complete — implicit grab torn down" + ); +} + +/// Xorg oracle from `steam-xorg.xtrace` connection 019 — the canonical +/// Steam-webhelper click. The client selects XI2 Button{Press,Release}+ +/// Motion on its window W (`XISelectEvents win=W device=0 mask=0x001c0ff2`), +/// receives the `ButtonPress`, then establishes its OWN grab on the master +/// pointer BEFORE the release (`XIGrabDevice grab_window=W device=2 +/// grab_mode=Async owner_events=true masks=0x001c0070`), and Xorg still +/// delivers the matching `ButtonRelease` to the client on W — press count +/// equals release count — after which the client `XIUngrabDevice`s. +/// +/// This encodes Xorg's observed behavior ONLY. On yserver a delivered +/// press installs an implicit pointer grab, and the client's mid-click +/// `XIGrabDevice` overwrites that slot; the question this pins is whether +/// the release survives that overlap the way it does under Xorg. +#[test] +fn xi_client_grab_device_mid_click_delivers_release_xorg_conn019() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const APP: u32 = 1; + const APP_WIN: u32 = 0x0044_000b; // window id shape from the trace + const HOST_APP: u32 = 0xCAFE_0001; + const XI2_MASTER: u16 = 2; + + let mut state = ServerState::new(); + let mut app_peer = install_client(&mut state, APP); + app_peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(APP_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(APP_WIN)); + // Xorg XISelectEvents mask 0x001c0ff2 → Button{Press,Release}+Motion (+more). + state.clients.get_mut(&APP).expect("app").xi2_masks.insert( + (ResourceId(APP_WIN), XI2_MASTER), + (1 << 4) | (1 << 5) | (1 << 6), + ); + Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP) + .expect("register app"); + let xid_map = backend.xid_map().clone(); + + let xge = |bytes: &[u8]| -> Vec<(u16, u32)> { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(( + u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), + u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), + )); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + + // 1. ButtonPress @ W (Xorg: delivered to the selector on its window). + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_APP, + detail: 1, + time: 1000, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let after_press = xge(&read_all_available(&mut app_peer)); + let presses = after_press.iter().filter(|(t, _)| *t == 4).count(); + assert!( + after_press.contains(&(4, APP_WIN)), + "Xorg: the ButtonPress is delivered to the XI2 selector on its own window" + ); + + // 2. Client's own XIGrabDevice on the master pointer, owner_events=true, + // grab_window=W, mask=Button{Press,Release}+Motion (Xorg masks=0x001c0070). + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&APP_WIN.to_le_bytes()); // grab_window + body.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime + body.extend_from_slice(&0u32.to_le_bytes()); // cursor = None + body.extend_from_slice(&2u16.to_le_bytes()); // device = master pointer + body.extend_from_slice(&[1, 1, 1, 0]); // async, async, owner_events=1, pad + body.extend_from_slice(&1u16.to_le_bytes()); // mask_len (one 4-byte unit) + body.extend_from_slice(&[0u8; 2]); // pad + body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber(2), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, // XIGrabDevice + length_units: 8, + }, + &body, + ) + .expect("XIGrabDevice"); + let _ = read_all_available(&mut app_peer); // drain grab reply, if any + + // 3. ButtonRelease @ W, still over W (Xorg: delivered to the client on W, + // even though the client established its own grab mid-click). + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 1100, + state: 0x100, + ..press + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + let after_release = xge(&read_all_available(&mut app_peer)); + let releases = after_release.iter().filter(|(t, _)| *t == 5).count(); + + assert!( + after_release.contains(&(5, APP_WIN)), + "Xorg: the ButtonRelease must still reach the client on its window even \ + though the client established its own XIGrabDevice mid-click \ + (steam-xorg.xtrace conn 019); got events {after_release:?}" + ); + assert_eq!( + presses, releases, + "Xorg: press count equals release count for the grab client \ + (presses={presses}, releases={releases})" + ); + + // 4. Client XIUngrabDevice(device=2) — grab released. + let mut ungrab = Vec::with_capacity(8); + ungrab.extend_from_slice(&0u32.to_le_bytes()); // time + ungrab.extend_from_slice(&2u16.to_le_bytes()); // device = master pointer + ungrab.extend_from_slice(&[0u8; 2]); // pad + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber(3), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 52, // XIUngrabDevice + length_units: 3, + }, + &ungrab, + ) + .expect("XIUngrabDevice"); + assert!( + state.active_pointer_grab.is_none(), + "after the client ungrabs, no pointer grab remains" + ); +} + +/// Xorg oracle: `steam-xorg.xtrace` conn 019 repeats the grab-dance click +/// (`ButtonPress → XIGrabDevice → ButtonRelease → XIUngrabDevice`) ~40 +/// times, and EVERY click delivers a matched press+release with no residue. +/// The GH #94 report ("several clicks before one registers, growing +/// backlog") is a state-accumulation symptom, so this drives the same +/// cycle N times and asserts each click stays balanced and leaves no +/// stuck grab / lingering pointer-button state behind. +#[test] +fn xi_repeated_grab_dance_clicks_stay_balanced_xorg_conn019() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const APP: u32 = 1; + const APP_WIN: u32 = 0x0044_000b; + const HOST_APP: u32 = 0xCAFE_0001; + const XI2_MASTER: u16 = 2; + + let mut state = ServerState::new(); + let mut app_peer = install_client(&mut state, APP); + app_peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(APP), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(APP_WIN), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(APP_WIN)); + state.clients.get_mut(&APP).expect("app").xi2_masks.insert( + (ResourceId(APP_WIN), XI2_MASTER), + (1 << 4) | (1 << 5) | (1 << 6), + ); + Backend::register_top_level(&mut backend, None, ResourceId(APP_WIN), HOST_APP) + .expect("register app"); + let xid_map = backend.xid_map().clone(); + + let xge = |bytes: &[u8]| -> Vec<(u16, u32)> { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(( + u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), + u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), + )); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + + let grab_body = |window: u32| { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.extend_from_slice(&[1, 1, 1, 0]); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); + body + }; + let ungrab_body = || { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body + }; + + for i in 0..10u32 { + let seq = i * 4; + let base_time = 1000 + i * 100; + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_APP, + detail: 1, + time: base_time, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber((seq + 2) as u16), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 8, + }, + &grab_body(APP_WIN), + ) + .expect("XIGrabDevice"); + + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: base_time + 50, + state: 0x100, + ..press + }; + let _ = + pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber((seq + 3) as u16), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 52, + length_units: 3, + }, + &ungrab_body(), + ) + .expect("XIUngrabDevice"); + + let evs = xge(&read_all_available(&mut app_peer)); + let presses = evs.iter().filter(|(t, _)| *t == 4).count(); + let releases = evs.iter().filter(|(t, _)| *t == 5).count(); + assert!( + evs.contains(&(4, APP_WIN)) && evs.contains(&(5, APP_WIN)), + "click {i}: both press and release must reach the client on its window; \ + got {evs:?}" + ); + assert_eq!( + (presses, releases), + (1, 1), + "click {i}: exactly one press and one release must be delivered — \ + balanced-but-duplicated (e.g. 2/2) is also a bug \ + (presses={presses}, releases={releases})" + ); + assert!( + state.active_pointer_grab.is_none(), + "click {i}: no stuck grab may accumulate between clicks" + ); + assert_eq!( + state.buttons_down, 0, + "click {i}: logical button state must return to 0 after the release" + ); + } +} + +/// Xorg oracle from the FAILING `cinnamon.xtrace` (one Steam click) + +/// `dix/events.c:5240`. The traced sequence that swallows the click: +/// muffin sync-passive-grabs the press, `XIAllowEvents(ReplayDevice)` +/// replays it to Steam; Steam (conn 105) `XIGrabDevice`s the master +/// pointer (device=2, grab_window=its own window, first, never ungrabs); +/// muffin (conn 026) THEN `XIGrabDevice`s the SAME master pointer +/// (device=2, different client); the ButtonRelease is delivered to +/// muffin, and Steam never sees it → the click never completes. +/// +/// Xorg rejects the second grab with `AlreadyGrabbed` +/// (`grab && !SameClient`, dix/events.c:5240), so the first grabber keeps +/// the device and the release follows it. This test encodes that rule: a +/// second client's `XIGrabDevice` while another client holds the pointer +/// grab must NOT steal it, and the release must reach the first grabber. +#[test] +fn xi_grab_device_by_other_client_must_not_steal_held_grab_cinnamon_xtrace() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const STEAM: u32 = 1; + const MUFFIN: u32 = 2; + const STEAM_WIN: u32 = 0x0260_000d; // conn 105 grab_window + const MUFFIN_WIN: u32 = 0x00e0_0011; // conn 026 grab_window + const HOST_STEAM: u32 = 0xCAFE_0001; + const XI2_MASTER: u16 = 2; + + let mut state = ServerState::new(); + let mut steam_peer = install_client(&mut state, STEAM); + let mut muffin_peer = install_client(&mut state, MUFFIN); + steam_peer.set_nonblocking(true).unwrap(); + muffin_peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + for (client, win, x) in [(STEAM, STEAM_WIN, 0i16), (MUFFIN, MUFFIN_WIN, 500i16)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + // Both select XI2 Button{Press,Release} on their own windows, so a + // misrouted release to muffin would be observable on its wire. + state + .clients + .get_mut(&STEAM) + .unwrap() + .xi2_masks + .insert((ResourceId(STEAM_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); + state + .clients + .get_mut(&MUFFIN) + .unwrap() + .xi2_masks + .insert((ResourceId(MUFFIN_WIN), XI2_MASTER), (1 << 4) | (1 << 5)); + Backend::register_top_level(&mut backend, None, ResourceId(STEAM_WIN), HOST_STEAM) + .expect("register steam"); + let xid_map = backend.xid_map().clone(); + + let xge = |bytes: &[u8]| -> Vec<(u16, u32)> { + let mut found = Vec::new(); + let mut off = 0usize; + while off + 32 <= bytes.len() { + let advance = if bytes[off] == 35 { + found.push(( + u16::from_le_bytes([bytes[off + 8], bytes[off + 9]]), + u32::from_le_bytes(bytes[off + 24..off + 28].try_into().unwrap()), + )); + 32 + u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize * 4 + } else { + 32 + }; + off += advance; + } + found + }; + let grab_body = |window: u32, owner_events: u8| { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); // time + body.extend_from_slice(&0u32.to_le_bytes()); // cursor + body.extend_from_slice(&2u16.to_le_bytes()); // device = master pointer + body.extend_from_slice(&[1, 1, owner_events, 0]); + body.extend_from_slice(&1u16.to_le_bytes()); // mask_len + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); + body + }; + let do_grab = |state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + seq: u16, + window: u32, + owner_events: u8| { + handle_xi2_request( + state, + backend, + None, + ClientId(client), + SequenceNumber(seq), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 8, + }, + &grab_body(window, owner_events), + ) + .expect("XIGrabDevice"); + }; + + // Press @ STEAM_WIN (post-ReplayDevice replay to Steam): Steam gets it, + // installs the implicit grab. + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_STEAM, + detail: 1, + time: 0xa040, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + let _ = read_all_available(&mut steam_peer); + + // Steam grabs the master pointer FIRST (conn 105, never ungrabs). + do_grab(&mut state, &mut backend, STEAM, 10, STEAM_WIN, 1); + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(STEAM), ResourceId(STEAM_WIN))), + "precondition: Steam holds the master-pointer grab" + ); + + // Muffin then grabs the SAME master pointer (conn 026). Xorg: + // AlreadyGrabbed → rejected; Steam keeps the grab. + do_grab(&mut state, &mut backend, MUFFIN, 20, MUFFIN_WIN, 0); + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(STEAM), ResourceId(STEAM_WIN))), + "Xorg (dix/events.c:5240): a second client's XIGrabDevice while \ + another client holds the pointer grab must return AlreadyGrabbed \ + and must NOT steal the grab" + ); + // The rejected grab's reply must carry status=1 (AlreadyGrabbed) at + // byte offset 8 (xXIGrabDeviceReply). muffin has received nothing else + // yet (the press went to Steam), so its wire starts with this reply. + let muffin_reply = read_all_available(&mut muffin_peer); + assert!( + muffin_reply.len() >= 9 && muffin_reply[0] == 1 && muffin_reply[8] == 1, + "muffin's contending XIGrabDevice must reply AlreadyGrabbed(1) at \ + offset 8; got {:?}", + &muffin_reply[..muffin_reply.len().min(12)] + ); + + // Release over Steam's window — must reach the grab holder (Steam), + // not muffin. + let release = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonRelease, + time: 0xa0e3, + state: 0x100, + ..press + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, release, true, false); + + let steam_evs = xge(&read_all_available(&mut steam_peer)); + let muffin_evs = xge(&read_all_available(&mut muffin_peer)); + assert!( + steam_evs.iter().any(|(t, _)| *t == 5), + "the ButtonRelease must be delivered to the grab holder (Steam); \ + got steam={steam_evs:?} muffin={muffin_evs:?}" + ); + assert!( + !muffin_evs.iter().any(|(t, _)| *t == 5), + "the release must NOT be stolen by the second (rejected) grabber; \ + muffin={muffin_evs:?}" + ); +} + +/// Cinnamon dialog acceptance pin. The shell activates a synchronous XI2 +/// passive pointer grab, then issues XIReplayDevice. Xorg transitions the +/// device to NOT_GRABBED before replay (`dix/events.c:1898`), so the app's +/// later XIGrabDevice must succeed without superseding a foreign grab. +#[test] +fn xi_dialog_grab_succeeds_over_foreign_passive_grab_cinnamon() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + server::PassiveButtonGrab, + }; + const SHELL: u32 = 1; + const APP: u32 = 2; + const GRAB_WIN: u32 = 0x0070_0003; + const APP_WIN: u32 = 0x0080_0003; // the app dialog's popup + const HOST_XID: u32 = 0xCAFE_0001; + + let mut state = ServerState::new(); + let _shell_peer = install_client(&mut state, SHELL); + let mut app_peer = install_client(&mut state, APP); + app_peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + for (client, win) in [(SHELL, GRAB_WIN), (APP, APP_WIN)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + state.button_grabs.push(PassiveButtonGrab { + device_id: 0, + owner: ClientId(SHELL), + grab_window: ResourceId(GRAB_WIN), + button: 1, + modifiers: 0x8000, + owner_events: false, + event_mask: (1 << 4) | (1 << 5), + pointer_mode: 0, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: true, + }); + Backend::register_top_level(&mut backend, None, ResourceId(GRAB_WIN), HOST_XID) + .expect("register"); + let xid_map = backend.xid_map().clone(); + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_XID, + detail: 1, + time: 0x1c33, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert!( + state + .active_pointer_grab + .is_some_and(|grab| { grab.owner == ClientId(SHELL) && grab.passive && grab.via_xi2 }) + ); + + let mut allow_body = Vec::with_capacity(8); + allow_body.extend_from_slice(&0u32.to_le_bytes()); + allow_body.extend_from_slice(&2u16.to_le_bytes()); + allow_body.push(2); // XIReplayDevice + allow_body.push(0); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(SHELL), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 53, + length_units: 3, + }, + &allow_body, + ) + .expect("XIAllowEvents ReplayDevice"); + assert!( + !state + .active_pointer_grab + .is_some_and(|grab| grab.owner == ClientId(SHELL)), + "ReplayDevice must deactivate the foreign passive pointer grab" + ); + assert!( + !state + .active_keyboard_grab + .is_some_and(|grab| grab.owner == ClientId(SHELL)), + "no foreign keyboard grab is held at grab time" + ); + + let mut grab_body = Vec::with_capacity(28); + grab_body.extend_from_slice(&APP_WIN.to_le_bytes()); + grab_body.extend_from_slice(&0u32.to_le_bytes()); + grab_body.extend_from_slice(&0u32.to_le_bytes()); + grab_body.extend_from_slice(&2u16.to_le_bytes()); + grab_body.extend_from_slice(&[1, 1, 1, 0]); + grab_body.extend_from_slice(&1u16.to_le_bytes()); + grab_body.extend_from_slice(&[0u8; 2]); + grab_body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber(2), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 8, + }, + &grab_body, + ) + .expect("XIGrabDevice"); + let ptr_reply = read_all_available(&mut app_peer); + let reply_start = ptr_reply.len().saturating_sub(32); + assert!( + ptr_reply.len() >= 32 && ptr_reply[reply_start] == 1 && ptr_reply[reply_start + 8] == 0, + "pointer XIGrabDevice must return Success(0), not AlreadyGrabbed(1), \ + over a foreign passive grab; got {:?}", + &ptr_reply[..ptr_reply.len().min(12)] + ); +} + +/// Pure Xorg guard: an implicit grab held by another client is still an +/// active grab and must return AlreadyGrabbed. The real MATE combo works +/// because its deeper XI2 leaf delivery attributes the implicit grab to +/// the app itself, covered by `mate_combo_implicit_grab_attributed_to_app_leaf_xi2`. +#[test] +fn xi_grab_device_over_foreign_implicit_grab_returns_already_grabbed() { + use crate::server::ActivePointerGrab; + const CORE_ANCESTOR: u32 = 13; // implicit-grab owner (core-first) + const APP: u32 = 46; // the GTK app opening the combo + const IMPLICIT_WIN: u32 = 0x0050_069b; + const COMBO_WIN: u32 = 0x0150_0ac3; + + let mut state = ServerState::new(); + let mut app_peer = install_client(&mut state, APP); + let _anc_peer = install_client(&mut state, CORE_ANCESTOR); + app_peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + for (client, win) in [(CORE_ANCESTOR, IMPLICIT_WIN), (APP, COMBO_WIN)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + } + + // A core-first implicit grab attributed to the ancestor's core client. + state.active_pointer_grab = Some(ActivePointerGrab { + owner: ClientId(CORE_ANCESTOR), + grab_window: ResourceId(IMPLICIT_WIN), + event_mask: 0x000c, + cursor: ResourceId(0), + time: 100, + owner_events: false, + via_xi2: false, + implicit: true, + passive: false, + xi2_mask: 0, + }); + + // The app's combo XIGrabDevice on the master pointer. + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&COMBO_WIN.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.extend_from_slice(&[1, 1, 1, 0]); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 8, + }, + &body, + ) + .expect("XIGrabDevice"); + + assert_eq!( + state.active_pointer_grab.map(|grab| grab.owner), + Some(ClientId(CORE_ANCESTOR)), + "the foreign implicit grab must remain untouched" + ); + let reply = read_all_available(&mut app_peer); + let reply_start = reply.len().saturating_sub(32); + assert!( + reply.len() >= 32 && reply[reply_start] == 1 && reply[reply_start + 8] == 1, + "grab over a foreign implicit grab must return AlreadyGrabbed(1); got {:?}", + &reply[..reply.len().min(12)] + ); +} + +/// MATE combo regression: Xorg's `DeliverDeviceEvents` walks from the +/// leaf toward root and tries XI2 before core at each window. An XI2 +/// selector on the app leaf therefore owns the implicit grab instead of +/// a core selector on its ancestor. The app's popup grab is SameClient. +#[test] +fn mate_combo_implicit_grab_attributed_to_app_leaf_xi2() { + use crate::{ + backend::Backend, + core_loop::pointer_fanout::pointer_event_fanout_to_state, + host_x11::{HostPointerEvent, PointerEventKind}, + resources::ROOT_VISUAL, + }; + const CORE_ANCESTOR: u32 = 13; + const APP: u32 = 46; + let parent = ResourceId(0x0050_069b); // core-ancestor selector window + let leaf = ResourceId(0x0150_0007); // the XI2 app's window (hit) + let combo = ResourceId(0x0150_0ac3); // the app's combo popup + const HOST_LEAF: u32 = 0xCAFE_0001; + const XI2_ALL_MASTER: u16 = 1; + + let mut state = ServerState::new(); + let _anc_peer = install_client(&mut state, CORE_ANCESTOR); + let mut app_peer = install_client(&mut state, APP); + app_peer.set_nonblocking(true).unwrap(); + let mut backend = RecordingBackend::new(); + + state.resources.create_window( + ClientId(CORE_ANCESTOR), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: parent, + parent: ROOT_WINDOW, + x: 0, + y: 0, + width: 200, + height: 200, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(parent); + for (client, win, par) in [(APP, leaf, parent), (APP, combo, ROOT_WINDOW)] { + state.resources.create_window( + ClientId(client), + yserver_protocol::x11::CreateWindowRequest { + depth: 24, + window: win, + parent: par, + x: 0, + y: 0, + width: 100, + height: 100, + border_width: 0, + class: 1, + visual: ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(win); + } + // Ancestor: CORE press|release. App leaf: XI2 under XIAllMasterDevices. + state + .clients + .get_mut(&CORE_ANCESTOR) + .unwrap() + .event_masks + .insert(parent, 0x0000_000c); + state + .clients + .get_mut(&APP) + .unwrap() + .xi2_masks + .insert((leaf, XI2_ALL_MASTER), (1 << 4) | (1 << 5)); + Backend::register_top_level(&mut backend, None, leaf, HOST_LEAF).expect("register"); + let xid_map = backend.xid_map().clone(); + + // Real click over the app's leaf. + let press = HostPointerEvent { + origin: crate::core_loop::message::InputOrigin::XTest(4), + kind: PointerEventKind::ButtonPress, + host_xid: HOST_LEAF, + detail: 1, + time: 0x7e1b, + root_x: 10, + root_y: 10, + event_x: 10, + event_y: 10, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + tree_change: false, + }; + let _ = pointer_event_fanout_to_state(&mut state, &mut backend, &xid_map, press, true, false); + assert_eq!( + state.active_pointer_grab.map(|grab| grab.owner), + Some(ClientId(APP)), + "the deeper XI2 leaf delivery must own the implicit grab" + ); + assert!( + state + .active_pointer_grab + .is_some_and(|grab| grab.implicit && grab.via_xi2) + ); + let _ = read_all_available(&mut app_peer); + + // The app opens its combo → XIGrabDevice on the master pointer. + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&combo.0.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&2u16.to_le_bytes()); + body.extend_from_slice(&[1, 1, 1, 0]); + body.extend_from_slice(&1u16.to_le_bytes()); + body.extend_from_slice(&[0u8; 2]); + body.extend_from_slice(&((1u32 << 4) | (1 << 5) | (1 << 6)).to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(APP), + SequenceNumber(1), + yserver_protocol::x11::RequestHeader { + opcode: 131, + data: 51, + length_units: 8, + }, + &body, + ) + .expect("XIGrabDevice"); + + assert_eq!( + state + .active_pointer_grab + .map(|grab| (grab.owner, grab.grab_window)), + Some((ClientId(APP), combo)), + "the app's SameClient XIGrabDevice must replace its implicit grab" + ); + let reply = read_all_available(&mut app_peer); + let reply_start = reply.len().saturating_sub(32); + assert!( + reply.len() >= 32 && reply[reply_start] == 1 && reply[reply_start + 8] == 0, + "combo grab reply must be Success (0), not AlreadyGrabbed (1); got {:?}", + &reply[..reply.len().min(12)] + ); +} + +/// Xorg `ProcXIPassiveGrabDevice` / `ProcXIPassiveUngrabDevice` +/// (Xi/xipassivegrab.c) take `XIAllDevices` and `XIAllMasterDevices` +/// without a device lookup. GH #277 probe V7/V8: a keycode grab on +/// XIAllMasterDevices, owner_events=1, then the matching ungrab — Xorg +/// raises no error, the grab activates on the master keyboard, keeps the +/// requested owner_events, and is gone after the ungrab. +#[test] +fn xi_passive_key_grab_on_all_master_devices_grabs_and_ungrabs() { + use crate::{core_loop::key_fanout::key_event_fanout_to_state, host_x11::HostKeyEvent}; + + const GRAB_CLIENT: u32 = 1; + const ALL_MASTER: u16 = 1; + const KEYCODE: u32 = 38; + const XI_KEY_PRESS_MASK: u32 = 1 << 2; + + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, GRAB_CLIENT); + let mut backend = RecordingBackend::new(); + + let mut grab = Vec::with_capacity(36); + grab.extend_from_slice(&0u32.to_le_bytes()); // current time + grab.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + grab.extend_from_slice(&0u32.to_le_bytes()); // no cursor + grab.extend_from_slice(&KEYCODE.to_le_bytes()); + grab.extend_from_slice(&ALL_MASTER.to_le_bytes()); + grab.extend_from_slice(&1u16.to_le_bytes()); // one modifier tuple + grab.extend_from_slice(&1u16.to_le_bytes()); // one mask word + grab.extend_from_slice(&[1, 1, 1, 1, 0, 0]); // Keycode, async, async, owner_events + grab.extend_from_slice(&XI_KEY_PRESS_MASK.to_le_bytes()); + grab.extend_from_slice(&0u32.to_le_bytes()); // no modifiers + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT), + SequenceNumber(1), + 54, + &grab, + ); + let reply = read_all_available(&mut peer); + assert_eq!( + reply.first(), + Some(&1), + "XIPassiveGrabDevice reply, not an error" + ); + + let press = |pressed| HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed, + keycode: KEYCODE as u8, + time: 1, + root_x: 10, + root_y: 20, + event_x: 10, + event_y: 20, + state: 0, + }; + let _ = key_event_fanout_to_state(&mut state, &mut backend, press(true)); + let grabbed = state + .active_keyboard_grab + .map(|g| (g.owner, g.owner_events)); + assert_eq!(grabbed, Some((ClientId(GRAB_CLIENT), true))); + assert!( + !read_all_available(&mut peer).is_empty(), + "owner got the press" + ); + let _ = key_event_fanout_to_state(&mut state, &mut backend, press(false)); + assert!(state.active_keyboard_grab.is_none()); + let _ = read_all_available(&mut peer); + + let mut ungrab = Vec::with_capacity(20); + ungrab.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); + ungrab.extend_from_slice(&KEYCODE.to_le_bytes()); + ungrab.extend_from_slice(&ALL_MASTER.to_le_bytes()); + ungrab.extend_from_slice(&1u16.to_le_bytes()); // one modifier tuple + ungrab.extend_from_slice(&[1, 0, 0, 0]); // Keycode, pad + ungrab.extend_from_slice(&0u32.to_le_bytes()); // no modifiers + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(GRAB_CLIENT), + SequenceNumber(2), + 55, + &ungrab, + ); + assert_eq!(read_all_available(&mut peer), [], "no BadDevice"); + + let _ = key_event_fanout_to_state(&mut state, &mut backend, press(true)); + assert!( + state.active_keyboard_grab.is_none(), + "the ungrabbed key no longer activates a grab" + ); + assert_eq!( + read_all_available(&mut peer), + [], + "the press is not grabbed" + ); +} + +/// `DeleteWindowFromAnyEvents` deactivates every device's active grab on a +/// dying window, whoever owns it (`dix/events.c:5915-5931`): an XI2 grab on +/// the master pointer and one on a slave, the slave going back to its master +/// (`DeactivatePointerGrab` → `ReattachToOldMaster`). +#[test] +fn destroy_window_releases_xi2_active_grabs_on_it() { + const OWNER: u32 = 1; + const SURVIVOR: u32 = 2; + const XI_GRAB_DEVICE: u8 = 51; + const WIN: u32 = 0x0020_0010; + + let mut state = ServerState::new(); + let _owner = install_capture_client(&mut state, OWNER); + let _survivor = install_capture_client(&mut state, SURVIVOR); + let mut backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(OWNER), + CreateWindowRequest { + depth: 24, + window: ResourceId(WIN), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(WIN)); + let (_source, slave) = xi_dynamic_grab_source(&mut state, 93, false, true, "destroy-grab"); + for (sequence, device) in [(1, slave), (2, crate::xinput::DEVICEID_MASTER_POINTER)] { + let grab = xi_dynamic_wire_grab_body(WIN, device, 1, 1, false, Some(1 << 4)); + process_xi_dynamic_request( + &mut state, + &mut backend, + ClientId(SURVIVOR), + SequenceNumber(sequence), + XI_GRAB_DEVICE, + &grab, + ); + } + assert!(state.xi2_pointer_grabs.contains_key(&slave)); + assert!( + state + .active_pointer_grab + .is_some_and(|g| g.via_xi2 && g.grab_window == ResourceId(WIN)) + ); + assert_eq!( + state.xi_devices.device(slave).unwrap().attached_master, + None + ); + + process_dynamic_request( + &mut state, + &mut backend, + ClientId(OWNER), + SequenceNumber(1), + 4, // DestroyWindow + 0, + &WIN.to_le_bytes(), + ); + + assert!(!state.xi2_pointer_grabs.contains_key(&slave)); + assert!(state.active_pointer_grab.is_none()); + assert_eq!( + state.xi_devices.device(slave).unwrap().attached_master, + Some(crate::xinput::DEVICEID_MASTER_POINTER) + ); +} + +/// A mapped window `win` with a mapped child `win + 1`, both owned by client +/// 1, and client 1's active XI1 grab on the master pointer with the child as +/// grab window, `this_device_mode` Async and `other_devices_mode` Sync. As +/// GrabDevice activates it (`xi1_check_grab_for_syncs(this = false, other = +/// true)`), the paired master keyboard is held on the grab's behalf (Xorg +/// `CheckGrabForSyncs`, `dix/events.c:1424-1450`). A key event withheld by +/// that hold sits in the sync queue. +fn xi1_grab_holding_the_paired_keyboard(win: u32) -> (ServerState, RecordingBackend) { + use crate::{ + host_x11::HostKeyEvent, + server::{PendingSyncEvent, QueuedInputEvent, Xi1ActiveGrab}, + xinput::{DEVICEID_MASTER_KEYBOARD as KBD, DEVICEID_MASTER_POINTER as PTR}, + }; + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let backend = RecordingBackend::new(); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(win), + parent: ROOT_WINDOW, + width: 100, + height: 100, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win)); + state.resources.create_window( + ClientId(1), + CreateWindowRequest { + depth: 24, + window: ResourceId(win + 1), + parent: ResourceId(win), + width: 50, + height: 50, + class: 1, + visual: crate::resources::ROOT_VISUAL, + ..Default::default() + }, + ); + let _ = state.resources.map_window(ResourceId(win + 1)); + state.xi1_active_grabs.insert( + PTR, + Xi1ActiveGrab { + owner: ClientId(1), + deviceid: PTR, + grab_window: ResourceId(win + 1), + owner_events: false, + this_mode: 1, + other_mode: 0, + passive_detail: None, + }, + ); + crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( + &mut state, + PTR, + ClientId(1), + false, + true, + ); + assert!( + state.xi1_frozen[&KBD].frozen(), + "precondition: keyboard held" + ); + state.sync_pending.push_back(PendingSyncEvent { + device: KBD, + event: QueuedInputEvent::HostKey(HostKeyEvent { + origin: crate::core_loop::InputOrigin::NestedHost, + pressed: false, + keycode: 38, + time: 0x1000, + root_x: 5, + root_y: 5, + event_x: 5, + event_y: 5, + state: 0, + }), + }); + (state, backend) +} + +fn assert_xi1_grab_and_paired_hold_released(state: &ServerState) { + use crate::xinput::{DEVICEID_MASTER_KEYBOARD as KBD, DEVICEID_MASTER_POINTER as PTR}; + assert!(!state.xi1_active_grabs.contains_key(&PTR), "grab released"); + assert!( + !state.xi1_frozen.get(&KBD).is_some_and(|f| f.frozen()), + "the paired keyboard is thawed" + ); + assert!( + state.sync_pending.is_empty(), + "the withheld key event is replayed" + ); +} + +/// Destroying the grab window's parent: `UnrealizeTree` runs +/// `DeleteWindowFromAnyEvents` on every realized window of the subtree +/// (`dix/window.c:2806`), which deactivates the XI1 grab on the child +/// through the device's `DeactivateGrab` (`dix/events.c:5927-5931`). That +/// clears every `sync.other` naming the grab and calls `ComputeFreezes` +/// (`dix/events.c:1697-1700`, `:1819`): the paired keyboard thaws. +#[test] +fn destroy_window_releases_an_xi1_grabs_paired_device_hold() { + const WIN: u32 = 0x0010_0131; + let (mut state, mut backend) = xi1_grab_holding_the_paired_keyboard(WIN); + process_dynamic_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + 4, // DestroyWindow + 0, + &WIN.to_le_bytes(), + ); + assert!(state.resources.window(ResourceId(WIN)).is_none()); + assert!(state.resources.window(ResourceId(WIN + 1)).is_none()); + assert_xi1_grab_and_paired_hold_released(&state); +} + +/// Unmapping the grab window's parent unrealizes the child and takes the same +/// `DeleteWindowFromAnyEvents` path (`dix/window.c:2806`). +#[test] +fn unmap_window_releases_an_xi1_grabs_paired_device_hold() { + const WIN: u32 = 0x0010_0132; + let (mut state, mut backend) = xi1_grab_holding_the_paired_keyboard(WIN); + process_dynamic_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + 10, // UnmapWindow + 0, + &WIN.to_le_bytes(), + ); + assert!(state.resources.window(ResourceId(WIN)).is_some()); + assert_xi1_grab_and_paired_hold_released(&state); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi_config.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi_config.rs new file mode 100644 index 000000000..c2a9f8add --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi_config.rs @@ -0,0 +1,3538 @@ +use super::*; +use crate::xinput::XI2_PROPERTY_EVENT_MASK; +use yserver_protocol::x11::AtomId; + +// ----------------------------------------------------------------- +// XI 1.x device-property dispatch (minors 36/37/38/39) — byte-level. +// These are the path MATE's settings daemon actually uses +// (OpenDevice + GetDeviceProperty), distinct from the XI2 path above. +// ----------------------------------------------------------------- + +/// Build an `xGetDevicePropertyReq` body (bytes after the 4-byte +/// generic header): property(4), type(4), longOffset(4), longLength(4), +/// deviceid(1, CARD8), delete(1), pad(2). +fn xi1_get_property_body( + property: u32, + type_atom: u32, + offset: u32, + len: u32, + deviceid: u8, + delete: u8, +) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&property.to_le_bytes()); + body.extend_from_slice(&type_atom.to_le_bytes()); + body.extend_from_slice(&offset.to_le_bytes()); + body.extend_from_slice(&len.to_le_bytes()); + body.push(deviceid); + body.push(delete); + body.extend_from_slice(&0u16.to_le_bytes()); + body +} + +#[test] +fn xi1_get_xtest_marker_property_wire() { + // Reads the XTEST Device INTEGER/8/[1] marker from virtual XTEST pointer 4. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let marker_atom = state + .atoms + .intern(crate::xinput::PROP_XTEST_DEVICE, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi1_get_property_body(marker_atom, 0 /* AnyPropertyType */, 0, 100, 4, 0); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(0x1234), + xi2_header(39), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + // 32-byte header + 1 data byte padded to 4 → 36. + assert_eq!(wire.len(), 36); + assert_eq!(wire[0], 1, "X_Reply"); + assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 0x1234, "sequence"); + assert_eq!( + u32::from_le_bytes(wire[4..8].try_into().unwrap()), + 1, + "length = ceil(1/4)" + ); + assert_eq!( + u32::from_le_bytes(wire[8..12].try_into().unwrap()), + integer_atom, + "type = INTEGER" + ); + assert_eq!( + u32::from_le_bytes(wire[12..16].try_into().unwrap()), + 0, + "bytes_after = 0" + ); + assert_eq!( + u32::from_le_bytes(wire[16..20].try_into().unwrap()), + 1, + "num_items = 1" + ); + assert_eq!(wire[20], 8, "format = 8"); + assert_eq!(wire[21], 4, "deviceid echoed (XI1-specific byte)"); + assert!(wire[22..32].iter().all(|&b| b == 0), "pad1..pad3 zero"); + assert_eq!(wire[32], 1, "value = XTEST marker"); + assert_eq!(&wire[33..36], &[0, 0, 0], "value padding"); +} + +#[test] +fn xi1_get_device_property_absent_returns_none() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // XTEST pointer 4 exists but has no property at atom 999. The atom + // ITSELF must be valid (T3 BadAtom guard); the test checks the + // distinct case where the atom is interned but the device has + // no value for it. + state.atoms.register_for_test(AtomId(999), "test-prop-999"); + let body = xi1_get_property_body(999, 0, 0, 100, 4, 0); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(3), + xi2_header(39), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "no data for absent property"); + assert_eq!(wire[0], 1, "X_Reply (not error)"); + assert_eq!( + u32::from_le_bytes(wire[8..12].try_into().unwrap()), + 0, + "type = None" + ); + assert_eq!( + u32::from_le_bytes(wire[12..16].try_into().unwrap()), + 0, + "bytes_after = 0" + ); + assert_eq!(wire[20], 0, "format = 0"); + assert_eq!(wire[21], 4, "deviceid still echoed"); +} + +#[test] +fn xi1_get_device_property_type_mismatch_metadata_only() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Seed an INTEGER/8 prop at atom 100, then ask for STRING. + seed_one_prop(&mut state, 100, 8, vec![0xAB]); + let string_atom = crate::xinput::XA_STRING.0; + let body = xi1_get_property_body(100, string_atom, 0, 100, 4, 0); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(4), + xi2_header(39), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "no value bytes on mismatch"); + assert_eq!( + u32::from_le_bytes(wire[8..12].try_into().unwrap()), + crate::xinput::XA_INTEGER.0, + "type = stored INTEGER" + ); + assert_eq!( + u32::from_le_bytes(wire[12..16].try_into().unwrap()), + 1, + "bytes_after = stored item count" + ); + assert_eq!( + u32::from_le_bytes(wire[16..20].try_into().unwrap()), + 0, + "num_items = 0" + ); + assert_eq!(wire[20], 8, "format = stored"); + assert_eq!(wire[21], 4, "deviceid echoed"); +} + +#[test] +fn xi1_get_device_property_bad_device() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Pre-register atom 100 so the BadAtom guard doesn't fire before + // the bad-device check the test is exercising. + state.atoms.register_for_test(AtomId(100), "test-prop-100"); + let body = xi1_get_property_body(100, 0, 0, 100, 99, 0); // device 99 absent + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(9), + xi2_header(39), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "error is 32 bytes"); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!( + wire[1], XI2_FIRST_ERROR, + "BadDevice = XI2_FIRST_ERROR (157)" + ); + assert_eq!(u16::from_le_bytes([wire[2], wire[3]]), 9, "sequence"); +} + +#[test] +fn xi1_get_device_property_bad_delete_value() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.atoms.register_for_test(AtomId(100), "test-prop-100"); + let body = xi1_get_property_body(100, 0, 0, 1, 4, 2); // delete = 2 (illegal) + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(11), + xi2_header(39), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!(wire[1], 2, "BadValue"); +} + +#[test] +fn xi1_list_device_properties_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + seed_one_prop(&mut state, 200, 8, vec![2]); + + // xListDevicePropertiesReq body: deviceid(1), pad0(1), pad1(2). + let body = [4u8, 0, 0, 0]; + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(36), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!( + wire.len(), + 32 + 16, + "32 header + XTEST marker + Device Enabled + 2 client atoms" + ); + assert_eq!(wire[0], 1, "X_Reply"); + assert_eq!( + u32::from_le_bytes(wire[4..8].try_into().unwrap()), + 4, + "length = nAtoms including the XTEST marker and Device Enabled" + ); + assert_eq!(u16::from_le_bytes([wire[8], wire[9]]), 4, "nAtoms"); + assert!(wire[10..32].iter().all(|&b| b == 0), "pad zero"); + let mut atoms = wire[32..] + .chunks_exact(4) + .map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap())) + .collect::>(); + let mut expected = vec![ + state.xtest_device_atom.0, + state.xi_device_enabled_atom.0, + 100, + 200, + ]; + atoms.sort_unstable(); + expected.sort_unstable(); + assert_eq!(atoms, expected, "the virtual XTEST Device marker is listed"); +} + +#[test] +fn xi1_list_device_properties_bad_device() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let body = [99u8, 0, 0, 0]; // device 99 absent + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header(36), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!(wire[1], XI2_FIRST_ERROR, "BadDevice"); +} + +#[test] +fn xi1_change_then_get_roundtrip_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Pre-register atom 100 (T3 BadAtom guard). + state.atoms.register_for_test(AtomId(100), "test-prop-100"); + + // xChangeDevicePropertyReq body: property(4)=100, type(4)=INTEGER, + // deviceid(1)=4, format(1)=8, mode(1)=Replace, pad(1), + // nUnits(4)=3, value=[7,8,9]+pad. + let mut body = Vec::new(); + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&crate::xinput::XA_INTEGER.0.to_le_bytes()); + body.push(4); // deviceid (CARD8) + body.push(8); // format + body.push(crate::xinput::XI_PROP_MODE_REPLACE); // mode + body.push(0); // pad + body.extend_from_slice(&3u32.to_le_bytes()); + body.extend_from_slice(&[7, 8, 9, 0]); // 3 data bytes + 1 pad + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(37), + &body, + ) + .unwrap(); + // ChangeDeviceProperty has no reply. + assert!(read_all_available(&mut peer).is_empty()); + + // Read it back via XI1 GetDeviceProperty. + let gbody = xi1_get_property_body(100, 0, 0, 100, 4, 0); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header(39), + &gbody, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!( + u32::from_le_bytes(wire[16..20].try_into().unwrap()), + 3, + "num_items" + ); + assert_eq!(wire[21], 4, "deviceid echoed"); + assert_eq!(&wire[32..35], &[7, 8, 9], "value round-trips"); +} + +#[test] +fn xi1_change_device_property_bad_device_outranks_format() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let mut body = Vec::new(); + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&crate::xinput::XA_INTEGER.0.to_le_bytes()); + body.push(99); // deviceid (CARD8) absent + body.push(7); // format 7 (illegal) + body.push(0); // mode + body.push(0); // pad + body.extend_from_slice(&0u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(5), + xi2_header(37), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32); + assert_eq!(wire[0], 0, "error packet"); + assert_eq!(wire[1], XI2_FIRST_ERROR, "BadDevice outranks BadValue"); +} + +#[test] +fn xi1_delete_device_property_wire() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + + // xDeleteDevicePropertyReq body: property(4)=100, deviceid(1)=4, + // pad0(1), pad1(2). + let mut body = Vec::new(); + body.extend_from_slice(&100u32.to_le_bytes()); + body.push(4); // deviceid (CARD8) + body.push(0); + body.extend_from_slice(&0u16.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(38), + &body, + ) + .unwrap(); + assert!(read_all_available(&mut peer).is_empty(), "no reply"); + let dev = state + .xi_devices + .device(crate::xinput::DEVICEID_XTEST_POINTER) + .unwrap(); + assert!( + !dev.properties.contains_key(&AtomId(100)), + "property removed" + ); +} + +fn parse_t3_xi2_config_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + deviceid: u16, + property_name: &str, + mode: u8, + format: u8, + data: &[u8], +) -> crate::core_loop::message::XiConfigRequest { + let property = state.atoms.intern(property_name, false).0; + let type_atom = if property_name == "libinput Accel Speed" { + state.float_atom.0 + } else { + crate::xinput::XA_INTEGER.0 + }; + let body = xi2_change_property_body(deviceid, mode, format, property, type_atom, data); + match handle_xi2_request( + state, + backend, + None, + ClientId(client), + SequenceNumber(sequence), + xi2_header(57), + &body, + ) + .expect("parse XI2 property request") + { + RequestOutcome::PendingXiConfig(request) => request, + outcome => panic!("recognized physical write must be pending, got {outcome:?}"), + } +} + +fn parse_t3_xi1_config_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + deviceid: u16, + data: &[u8], +) -> crate::core_loop::message::XiConfigRequest { + let property = state.atoms.intern("libinput Accel Speed", false).0; + let body = xi1_change_property_body( + property, + state.float_atom.0, + u8::try_from(deviceid).expect("physical XI1 id fits CARD8"), + 32, + crate::xinput::XI_PROP_MODE_REPLACE, + data, + ); + match handle_xi2_request( + state, + backend, + None, + ClientId(client), + SequenceNumber(sequence), + xi2_header(37), + &body, + ) + .expect("parse XI1 property request") + { + RequestOutcome::PendingXiConfig(request) => request, + outcome => panic!("recognized physical XI1 write must be pending, got {outcome:?}"), + } +} + +/// Run the real HostInput lifecycle dispatcher while one write occupies +/// the lane and another targets the source being removed or suspended. +/// RecordingBackend does not own XI topology, so prepare the state change +/// performed by the production KMS `on_host_input` before dispatching. +fn assert_t3_host_lifecycle_cancels_queued_write(removed: bool, xi1_request: bool) { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer_a = install_capture_client(&mut state, 1); + let mut peer_b = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let source = state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .source_id + .unwrap(); + let source_info = state.xi_devices.source(source).unwrap().clone(); + let accel_atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + let source_property_before = state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&accel_atom] + .data + .clone(); + + let mut live_info = source_info.clone(); + live_info.source_id = crate::xinput::InputSourceId(source.0 + 1); + live_info.device_node = "/dev/input/event78".into(); + live_info.sysname = "event78".into(); + let live_ids = state.xi_register_source(&live_info); + let live_device = *live_ids + .iter() + .find(|id| *id != &TEST_PHYSICAL_POINTER_ID) + .expect("second pointer facet"); + let live_source = live_info.source_id; + let mut inventory = crate::core_loop::input_inventory::InputInventory::new(); + inventory.add(source_info); + inventory.add(live_info); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(207)))); + + // B submits a write on the other, still-enabled source. + let request_b = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 2, + 4, + live_device, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.75_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_b, + ); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(!lane.is_empty(), "B's backend operation remains in flight"); + assert!(pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(2))); + + // A's source-specific request queues behind B and retains its XI + // minor opcode and sequence for an immediate lifecycle error. + let request_a = if xi1_request { + parse_t3_xi1_config_request( + &mut state, + &mut backend, + 1, + 9, + TEST_PHYSICAL_POINTER_ID, + &0.25_f32.to_le_bytes(), + ) + } else { + parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 9, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.25_f32.to_le_bytes(), + ) + }; + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_a, + ); + assert!(pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(1))); + assert!(read_all_available(&mut peer_a).is_empty()); + assert!(read_all_available(&mut peer_b).is_empty()); + + // This mirrors the registry transition made by the production KMS + // backend in handle_host_input; the shared run_core dispatcher below + // performs inventory maintenance, calls handle_host_input, and + // cancels the queued XI write. + let lifecycle_event = if removed { + state.xi_unregister_source(source); + crate::core_loop::HostInputEvent::DeviceRemoved { source_id: source } + } else { + let mut disabled = state.xi_devices.source(source).unwrap().clone(); + disabled.enabled = false; + state.xi_devices.register(&disabled); + crate::core_loop::HostInputEvent::DeviceSuspended { source_id: source } + }; + crate::core_loop::run::dispatch_host_input( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + lifecycle_event, + crate::core_loop::generation::Generation::default(), + ); + + let expected_error = if removed { + XI2_FIRST_ERROR + } else { + x11::error::BAD_MATCH + }; + let minor_opcode = if xi1_request { 37 } else { 57 }; + let cancelled = read_all_available(&mut peer_a); + assert_xi_config_error(&cancelled, expected_error, 9, minor_opcode); + assert!( + !pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(1)), + "lifecycle cancellation unblocks A immediately" + ); + assert!(pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(2))); + assert!(!lane.is_empty(), "B remains in flight after A is cancelled"); + assert_eq!(backend.started_device_configs.len(), 1, "A never starts"); + assert!(read_all_available(&mut peer_b).is_empty()); + + if removed { + assert!(state.xi_devices.source(source).is_none()); + assert!(inventory.get(source).is_none()); + assert!(state.xi_devices.device(TEST_PHYSICAL_POINTER_ID).is_none()); + } else { + assert!(!state.xi_devices.source(source).unwrap().enabled); + assert!(!inventory.get(source).unwrap().enabled); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&accel_atom] + .data, + source_property_before, + "suspension leaves source S's property unchanged" + ); + } + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(207), + source: live_source, + result: Ok(()), + }, + crate::core_loop::generation::Generation::default(), + ); + + assert_eq!( + backend.started_device_configs, + [(live_source, DeviceConfigChange::AccelSpeed(0.75))], + "only B's enabled-source write reaches the backend" + ); + assert_eq!( + state.xi_devices.device(live_device).unwrap().properties[&accel_atom].data, + 0.75_f32.to_le_bytes(), + "B's completion commits normally" + ); + assert_eq!( + inventory.get(live_source).unwrap().config.accel.current, + 0.75 + ); + if removed { + assert!(state.xi_devices.source(source).is_none()); + assert!(inventory.get(source).is_none()); + } else { + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&accel_atom] + .data, + source_property_before, + "S's property remains unchanged after B completes" + ); + } + assert!(lane.is_empty()); + assert!(pending.is_empty()); + assert!(read_all_available(&mut peer_a).is_empty()); + assert!(read_all_available(&mut peer_b).is_empty()); +} + +#[test] +fn xi_config_completion_writable_descriptor_commits_to_registry() { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + // Write `[0]` (disable tap) to a writable Bool descriptor. + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "successful XIChangeProperty has no reply" + ); + // Registry now holds the new value. + let dev = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap(); + let prop = dev.properties.get(&AtomId(tap_atom)).expect("tap stored"); + assert_eq!(prop.format, 8); + assert_eq!(prop.data, vec![0], "tap toggled off"); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert!(!inventory.get(source).unwrap().config.tap.current); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +// ----------------------------------------------------------------- +// T3 B1 (review round): `dispatch_change_property` must pin the +// request's `format`/`type_atom` to the descriptor's before running +// `validate_value`/`decode_change` — the latter's fixed-width +// decoders (`float32`, `card32`) index the value slice assuming +// `validate_value` already enforced the descriptor's real width. +// Before the fix, a request lying about `format` slipped a +// too-short value past `validate_value` (which derived its expected +// length from the *request's* format) and then panicked on +// out-of-bounds indexing in `decode_change` — a client-reachable +// server crash. These tests drive the real dispatch path (not +// `validate_value` in isolation) so a regression shows up as either +// a wrong error or a test-thread panic. +// ----------------------------------------------------------------- + +/// Build an `xChangeDevicePropertyReq` body (after the 4-byte +/// generic header): property(4), type(4), deviceid(1), format(1), +/// mode(1), pad(1), num_items(4), value(num_items * format/8, +/// padded to 4 bytes) — mirrors `xi2_change_property_body` for the +/// XI1 wire layout (XIproto.h:1462-1473). +fn xi1_change_property_body( + property: u32, + type_atom: u32, + deviceid: u8, + format: u8, + mode: u8, + data: &[u8], +) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&property.to_le_bytes()); + body.extend_from_slice(&type_atom.to_le_bytes()); + body.push(deviceid); + body.push(format); + body.push(mode); + body.push(0); // pad + let num_items = data.len() / usize::from(format / 8); + body.extend_from_slice(&(num_items as u32).to_le_bytes()); + body.extend_from_slice(data); + while body.len() % 4 != 0 { + body.push(0); + } + body +} + +#[test] +fn xi_config_completion_b1_xi2_format8_scalar_float_mismatch_is_badmatch_no_panic() { + // `libinput Accel Speed` is Scalar/Float, descriptor format 32. + // A `format=8, num_items=1` write used to pass `validate_value` + // (which computed its expected length from the request's + // format) and then panic in `decode_change`'s `float32(&[7])` + // (`b[1]` out of bounds). + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, _) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let properties_before = xi_property_snapshot(&state); + let accel_speed_atom = state.atoms.intern("libinput Accel Speed", false).0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + accel_speed_atom, + crate::xinput::XA_INTEGER.0, + &[7], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, x11::error::BAD_MATCH, 1, 57); + assert_eq!(xi_property_snapshot(&state), properties_before); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_b1_xi2_format16_scalar_float_mismatch_is_badmatch() { + // Same target, format=16 (still not the descriptor's 32). + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, _) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let properties_before = xi_property_snapshot(&state); + let accel_speed_atom = state.atoms.intern("libinput Accel Speed", false).0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 16, + accel_speed_atom, + crate::xinput::XA_INTEGER.0, + &[7, 0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, x11::error::BAD_MATCH, 1, 57); + assert_eq!(xi_property_snapshot(&state), properties_before); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_b1_xi2_format8_card32_mismatch_is_badmatch_no_panic() { + // `libinput Button Scrolling Button` is Scalar/Card32, + // descriptor format 32. Same crash shape via `card32(&[7])`. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, _) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let properties_before = xi_property_snapshot(&state); + let scroll_button_atom = state + .atoms + .intern("libinput Button Scrolling Button", false) + .0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + scroll_button_atom, + crate::xinput::XA_INTEGER.0, + &[7], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, x11::error::BAD_MATCH, 1, 57); + assert_eq!(xi_property_snapshot(&state), properties_before); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +/// The short-write relaxation is per-descriptor, not blanket. +/// +/// `xf86-input-libinput` gates every 8-bit multi-slot property on an +/// exact `val->size` except `Accel Profile Enabled`, whose width grew +/// from 2 to 3 with libinput 1.23's custom-accel slot +/// (`LibinputSetPropertyAccelProfile`, xf86libinput.c:4622 — +/// `val->size < 2 || val->size > 3`; compare `ScrollMethods` :4884 +/// `!= 3`, `ClickMethod` :4988 `!= 2`). +/// +/// Accepting a short `Scroll Method Enabled` and zero-padding it +/// would silently commit "two-finger on, edge off, button off" — a +/// configuration the client never expressed, and BadMatch on Xorg. +#[test] +fn xi_config_completion_short_write_only_for_ranged_accel_profile_descriptor() { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let scroll_atom = state + .atoms + .intern("libinput Scroll Method Enabled", false) + .0; + + // Two bytes against a 3-wide exact descriptor → BadMatch. + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + scroll_atom, + crate::xinput::XA_INTEGER.0, + &[0, 1], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, x11::error::BAD_MATCH, 1, 57); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); + + // The same two-byte shape against Accel Profile Enabled is the + // write mate-settings-daemon emits, and must be accepted. + let accel_atom = state + .atoms + .intern("libinput Accel Profile Enabled", false) + .0; + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + accel_atom, + crate::xinput::XA_INTEGER.0, + &[0, 1], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 2, + xi2_header(57), + &body, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "two-item accel-profile write must succeed (no error packet)", + ); + assert_eq!(backend.started_device_configs.len(), 1); + assert_eq!( + inventory.get(source).unwrap().config.accel_profile.current, + Some(1) + ); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&AtomId(accel_atom)] + .data, + [0, 1, 0] + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_b1_xi1_format_mismatch_is_badmatch_no_panic() { + // Same crash shape, XI1 wire arm (minor 37) — the path MATE's + // settings daemon actually uses. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, _) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let properties_before = xi_property_snapshot(&state); + let accel_speed_atom = state.atoms.intern("libinput Accel Speed", false).0; + + let body = xi1_change_property_body( + accel_speed_atom, + crate::xinput::XA_INTEGER.0, + u8::try_from(TEST_PHYSICAL_POINTER_ID).unwrap(), + 8, + crate::xinput::XI_PROP_MODE_REPLACE, + &[7], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(37), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, x11::error::BAD_MATCH, 1, 37); + assert_eq!(xi_property_snapshot(&state), properties_before); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +// ----------------------------------------------------------------- +// T3 B2 (review round): merge-then-validate. `Append`/`Prepend` +// must be merged with the existing stored value BEFORE +// `validate_value` runs, or a short *fragment* (legal on its own +// since Task 1) can pass validation, decode to a value the client +// never wrote, and reach `apply_device_config`. The commit must +// also store the *normalised* merged value, not the raw request +// bytes, or a short Replace silently narrows the property's +// advertised width for the next reader. +// ----------------------------------------------------------------- + +#[test] +fn xi_config_completion_t3_b2_xi2_two_item_accel_profile_commits_normalized_bytes() { + // The headline vector: msd writes exactly 2 bytes; the merged + // (here: unmerged, since Replace) value must validate, decode + // to AccelProfile(Some(1)) — flat — and the STORED property + // must be normalised to the full 3-byte descriptor width, not + // the 2 raw bytes the client sent. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let atom = state + .atoms + .intern("libinput Accel Profile Enabled", false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + atom, + integer_atom, + &[0, 1], + ); + let outcome = handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(57), + &body, + ) + .unwrap(); + let crate::core_loop::process_request::RequestOutcome::PendingXiConfig(request) = outcome + else { + panic!("recognized XI2 write must enter the core config lane") + }; + assert!( + read_all_available(&mut peer).is_empty(), + "no X error for a short write" + ); + assert!( + backend.started_device_configs.is_empty(), + "request parsing does not start the backend" + ); + let dev = state.xi_devices.device(TEST_PHYSICAL_POINTER_ID).unwrap(); + assert_eq!( + dev.properties.get(&AtomId(atom)).unwrap().data, + vec![1, 0, 0], + "request parsing leaves the seeded property unchanged" + ); + + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert_eq!( + backend.started_device_configs, + vec![( + source, + crate::xinput::libinput_props::DeviceConfigChange::AccelProfile(Some(1)), + )], + "reaches the backend as AccelProfile(Some(1)) — flat" + ); + assert!(lane.is_empty(), "synchronous confirmation drains the lane"); + assert!( + pending.is_empty(), + "synchronous confirmation unblocks the client" + ); + assert_eq!( + inventory.get(source).unwrap().config.accel_profile.current, + Some(1), + "confirmed value is retained in the process-lifetime inventory" + ); + + let dev = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap(); + let prop = dev + .properties + .get(&AtomId(atom)) + .expect("accel profile stored"); + assert_eq!( + prop.data, + vec![0, 1, 0], + "stored property is exactly 3 bytes, zero-padded" + ); +} + +#[test] +fn xi_config_completion_t3_b2_xi1_two_item_accel_profile_commits_normalized_bytes() { + // Same assertions, XI1 wire arm (minor 37). + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let atom = state + .atoms + .intern("libinput Accel Profile Enabled", false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi1_change_property_body( + atom, + integer_atom, + u8::try_from(TEST_PHYSICAL_POINTER_ID).unwrap(), + 8, + crate::xinput::XI_PROP_MODE_REPLACE, + &[0, 1], + ); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let outcome = handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(37), + &body, + ) + .unwrap(); + let crate::core_loop::process_request::RequestOutcome::PendingXiConfig(request) = outcome + else { + panic!("recognized XI1 write must enter the core config lane") + }; + assert!( + read_all_available(&mut peer).is_empty(), + "no X error for a short write" + ); + assert!( + backend.started_device_configs.is_empty(), + "request parsing does not start the backend" + ); + let dev = state.xi_devices.device(TEST_PHYSICAL_POINTER_ID).unwrap(); + assert_eq!( + dev.properties.get(&AtomId(atom)).unwrap().data, + vec![1, 0, 0], + "request parsing leaves the seeded property unchanged" + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert_eq!( + backend.started_device_configs, + vec![( + source, + crate::xinput::libinput_props::DeviceConfigChange::AccelProfile(Some(1)), + )], + "reaches the backend as AccelProfile(Some(1)) — flat" + ); + assert!(lane.is_empty(), "synchronous confirmation drains the lane"); + assert!( + pending.is_empty(), + "synchronous confirmation unblocks the client" + ); + assert_eq!( + inventory.get(source).unwrap().config.accel_profile.current, + Some(1), + "confirmed value is retained in the process-lifetime inventory" + ); + + let dev = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap(); + let prop = dev + .properties + .get(&AtomId(atom)) + .expect("accel profile stored"); + assert_eq!( + prop.data, + vec![0, 1, 0], + "stored property is exactly 3 bytes, zero-padded" + ); +} + +#[test] +fn xi_config_completion_t3_b2_full_width_accel_profile_append_is_badvalue_and_untouched() { + // Append [1] onto an already-full-width (3-byte) stored value: + // the merged length is 4 > n=3, so this must be BadValue with + // BOTH the stored property and the libinput config untouched — + // in particular, `apply_device_config` must NOT be called a + // second time with the wrong fragment-decoded value. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let atom = state + .atoms + .intern("libinput Accel Profile Enabled", false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + // Seed a full-width value first (Replace [1, 0, 0] = adaptive). + let seed_body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + atom, + integer_atom, + &[1, 0, 0], + ); + let outcome = handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(57), + &seed_body, + ) + .unwrap(); + let crate::core_loop::process_request::RequestOutcome::PendingXiConfig(seed_request) = outcome + else { + panic!("setup write must enter the core config lane") + }; + assert!(backend.started_device_configs.is_empty()); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .get(&AtomId(atom)) + .unwrap() + .data, + vec![1, 0, 0], + "the setup request has not committed before lane processing" + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + seed_request, + ); + assert!(read_all_available(&mut peer).is_empty()); + assert_eq!(backend.started_device_configs.len(), 1); + assert_eq!( + inventory.get(source).unwrap().config.accel_profile.current, + Some(0) + ); + + // Append [1] → merged length 4 > n=3 → BadValue, untouched. + let append_body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_APPEND, + 8, + atom, + integer_atom, + &[1], + ); + let outcome = handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + xi2_header(57), + &append_body, + ) + .unwrap(); + let crate::core_loop::process_request::RequestOutcome::PendingXiConfig(append_request) = + outcome + else { + panic!("recognized append must enter the core config lane") + }; + assert_eq!( + backend.started_device_configs.len(), + 1, + "append has not started" + ); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .get(&AtomId(atom)) + .unwrap() + .data, + vec![1, 0, 0], + "request parsing leaves the confirmed full-width value untouched" + ); + assert!( + read_all_available(&mut peer).is_empty(), + "no reply or event before validation" + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + append_request, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, x11::error::BAD_VALUE, 2, 57); + + let dev = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap(); + let prop = dev.properties.get(&AtomId(atom)).unwrap(); + assert_eq!( + prop.data, + vec![1, 0, 0], + "stored property untouched by the rejected append" + ); + assert_eq!( + backend.started_device_configs.len(), + 1, + "only the seeding Replace reached start_device_config, not the rejected Append" + ); +} + +#[test] +fn xi_config_completion_immediate_success_updates_registry_and_inventory() { + use crate::xinput::libinput_props::DeviceConfigChange; + + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let request = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.5_f32.to_le_bytes(), + ); + let atom = request.property; + + assert!(backend.started_device_configs.is_empty()); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + 0.0_f32.to_le_bytes(), + "request parsing has not changed the XI property" + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.5))] + ); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + 0.5_f32.to_le_bytes() + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.5); + assert!(lane.is_empty()); + assert!(pending.is_empty()); + assert!(read_all_available(&mut peer).is_empty()); +} + +#[test] +fn xi_config_completion_pending_success_commits_only_after_message() { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + select_xi2_property_event_on_root(&mut state, 1, TEST_PHYSICAL_POINTER_ID); + let original = 0.0_f32.to_le_bytes(); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(201)))); + let request = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.5_f32.to_le_bytes(), + ); + let atom = request.property; + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.5))] + ); + assert!( + !lane.is_empty(), + "submitted write holds the lane until acknowledgment" + ); + assert!(!pending.is_empty(), "originating client remains blocked"); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + original, + "XI value remains old until the input thread confirms success" + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.0); + assert!( + read_all_available(&mut peer).is_empty(), + "no notification before success" + ); + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(201), + source, + result: Ok(()), + }, + crate::core_loop::generation::Generation::default(), + ); + + let wire = read_all_available(&mut peer); + let event = find_xi2_property_event(&wire).expect("success emits XI_PropertyEvent"); + assert_eq!(event[20], crate::xinput::PropWhat::Modified as u8); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + 0.5_f32.to_le_bytes() + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.5); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_start_and_async_errors_leave_values_untouched() { + use crate::xinput::libinput_props::{ + DeviceConfigError as ConfigError, DeviceConfigStart, DeviceConfigToken, + }; + + for (start_result, async_error, expected_error) in [ + (Err(ConfigError::Unsupported), None, x11::error::BAD_MATCH), + (Err(ConfigError::Invalid), None, x11::error::BAD_VALUE), + // Xorg's libinput property handler returns BadMatch when the + // shared handle is absent (xf86libinput.c:4392-4409, 4579-4607). + (Err(ConfigError::SourceGone), None, x11::error::BAD_MATCH), + ( + Ok(DeviceConfigStart::Pending(DeviceConfigToken(203))), + Some(ConfigError::Invalid), + x11::error::BAD_VALUE, + ), + ( + Ok(DeviceConfigStart::Pending(DeviceConfigToken(203))), + Some(ConfigError::Unsupported), + x11::error::BAD_MATCH, + ), + ( + Ok(DeviceConfigStart::Pending(DeviceConfigToken(203))), + Some(ConfigError::SourceGone), + x11::error::BAD_MATCH, + ), + ] { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let request = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 3, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.5_f32.to_le_bytes(), + ); + let atom = request.property; + let old_property = state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .clone(); + backend.device_config_start_results.push_back(start_result); + + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert_eq!(backend.started_device_configs.len(), 1); + if let Some(error) = async_error { + assert!(!lane.is_empty()); + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(203), + source, + result: Err(error), + }, + crate::core_loop::generation::Generation::default(), + ); + } + + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, expected_error, 3, 57); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom], + old_property + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.0); + assert!(lane.is_empty()); + assert!(pending.is_empty()); + } +} + +#[test] +fn xi_config_completion_merges_ordered_writes_at_dequeue_time() { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer_a = install_capture_client(&mut state, 1); + let mut peer_b = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + select_xi2_property_event_on_root(&mut state, 1, TEST_PHYSICAL_POINTER_ID); + select_xi2_property_event_on_root(&mut state, 2, TEST_PHYSICAL_POINTER_ID); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(204)))); + + let request_a = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.5_f32.to_le_bytes(), + ); + let atom = request_a.property; + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_a, + ); + let request_b = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 2, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_APPEND, + 32, + &[], + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_b, + ); + + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.5))], + "B remains queued behind A" + ); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + 0.0_f32.to_le_bytes() + ); + assert!(read_all_available(&mut peer_a).is_empty()); + assert!(read_all_available(&mut peer_b).is_empty()); + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(204), + source, + result: Ok(()), + }, + crate::core_loop::generation::Generation::default(), + ); + + assert_eq!( + backend.started_device_configs, + [ + (source, DeviceConfigChange::AccelSpeed(0.5)), + (source, DeviceConfigChange::AccelSpeed(0.5)), + ], + "B's empty Append merges with A's confirmed 0.5 at dequeue" + ); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + 0.5_f32.to_le_bytes() + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.5); + for peer in [&mut peer_a, &mut peer_b] { + let wire = read_all_available(peer); + let event = find_xi2_property_event(&wire).expect("confirmed write notification"); + assert_eq!(event[20], crate::xinput::PropWhat::Modified as u8); + } + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_removal_cancels_queued_write_before_id_reuse() { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer_a = install_capture_client(&mut state, 1); + let mut peer_b = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let original_info = state.xi_devices.source(source).unwrap().clone(); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(205)))); + + let request_a = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.25_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_a, + ); + let request_b = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 2, + 2, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.75_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_b, + ); + assert_eq!(backend.started_device_configs.len(), 1); + + state.xi_unregister_source(source); + inventory.remove(source); + crate::core_loop::run::cancel_queued_xi_configs_for_source( + &mut state, + &mut backend, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + source, + crate::core_loop::generation::Generation::default(), + ); + let mut replacement = original_info; + replacement.source_id = crate::xinput::InputSourceId(source.0 + 1); + replacement.device_node = "/dev/input/event88".into(); + replacement.sysname = "event88".into(); + let replacement_ids = state.xi_register_source(&replacement); + inventory.add(replacement.clone()); + assert!(replacement_ids.contains(&TEST_PHYSICAL_POINTER_ID)); + + // B's device has already been unregistered, so ProcXIChangeProperty's + // dixLookupDevice returns BadDevice (Xi/xiproperty.c:1140-1142; + // dix/devices.c:1259-1274). + let error_b = read_all_available(&mut peer_b); + assert_xi_config_error(&error_b, XI2_FIRST_ERROR, 2, 57); + assert_eq!( + backend.started_device_configs.len(), + 1, + "B never reached the backend" + ); + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(205), + source, + result: Err(crate::xinput::libinput_props::DeviceConfigError::SourceGone), + }, + crate::core_loop::generation::Generation::default(), + ); + // A's backend result is SourceGone while its request still names the + // in-flight device; libinput maps the missing shared handle to + // BadMatch (xf86libinput.c:4392-4409, 4579-4607). + let error_a = read_all_available(&mut peer_a); + assert_xi_config_error(&error_a, x11::error::BAD_MATCH, 1, 57); + + let replacement_device = state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .expect("replacement reused the physical XI id"); + let replacement_atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + assert_eq!(replacement_device.source_id, Some(replacement.source_id)); + assert_eq!( + replacement_device.properties[&replacement_atom].data, + replacement.config.accel.current.to_le_bytes() + ); + assert_eq!( + inventory + .get(replacement.source_id) + .unwrap() + .config + .accel + .current, + 0.0 + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.25))] + ); +} + +#[test] +fn xi_config_completion_disconnect_discards_replies_but_keeps_submitted_change() { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer_a = install_capture_client(&mut state, 1); + let mut peer_b = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(206)))); + + let request_a = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.5_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_a, + ); + let request_b = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 2, + 2, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.75_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_b, + ); + + let mut reset_trigger = + crate::core_loop::reset::ResetTrigger::new(crate::core_loop::reset::ResetPolicy::NoReset); + crate::core_loop::run::disconnect_with_pending_cleanup( + &mut state, + &mut backend, + &mut pending, + &mut lane, + &mut reset_trigger, + ClientId(2), + ); + assert!(read_all_available(&mut peer_b).is_empty()); + assert_eq!(backend.started_device_configs.len(), 1); + crate::core_loop::run::disconnect_with_pending_cleanup( + &mut state, + &mut backend, + &mut pending, + &mut lane, + &mut reset_trigger, + ClientId(1), + ); + assert!(read_all_available(&mut peer_a).is_empty()); + assert!(pending.is_empty()); + assert!( + !lane.is_empty(), + "submitted backend work survives disconnect" + ); + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut reset_trigger, + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(206), + source, + result: Ok(()), + }, + crate::core_loop::generation::Generation::default(), + ); + + let atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&atom] + .data, + 0.5_f32.to_le_bytes() + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.5); + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.5))] + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_reset_keeps_submitted_change_and_uses_current_atoms() { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer_a = install_capture_client(&mut state, 1); + let mut peer_b = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let info = inventory.get(source).unwrap().clone(); + let old_atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(207)))); + + let request = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.5_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + let queued = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 2, + 1, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.75_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + queued, + ); + assert_eq!(backend.started_device_configs.len(), 1); + crate::core_loop::run::cancel_unsubmitted_xi_configs(&mut lane, &mut pending); + assert!(!lane.is_empty(), "reset retains the submitted operation"); + assert!( + pending.is_empty(), + "reset releases old client blocking state" + ); + assert!(read_all_available(&mut peer_a).is_empty()); + assert!(read_all_available(&mut peer_b).is_empty()); + + let mut reset_state = ServerState::new(); + let _ = reset_state.atoms.intern("reset atom allocation", false); + reset_state.xi_register_source(&info); + let current_atom = reset_state.atoms.id_for("libinput Accel Speed").unwrap(); + assert_ne!( + current_atom, old_atom, + "reset replay gives the descriptor a fresh atom id" + ); + let generation = crate::core_loop::generation::GenerationCounter::new(); + let current_generation = generation.bump(); + crate::core_loop::run::dispatch_device_config_result( + &mut reset_state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(207), + source, + result: Ok(()), + }, + current_generation, + ); + + let device = reset_state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .expect("replayed source has its pointer facet"); + assert_eq!(device.properties[¤t_atom].data, 0.5_f32.to_le_bytes()); + assert_eq!(device.source_id, Some(source)); + assert_eq!( + reset_state + .xi_devices + .source(source) + .unwrap() + .config + .accel + .current, + 0.5 + ); + assert_eq!(inventory.get(source).unwrap().config.accel.current, 0.5); + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.5))] + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_recreates_get_deleted_property_after_success() { + use crate::xinput::libinput_props::{DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let property = state.atoms.intern("libinput Accel Profile Enabled", false); + select_xi2_property_event_on_root(&mut state, 1, TEST_PHYSICAL_POINTER_ID); + + let mut delete_body = TEST_PHYSICAL_POINTER_ID.to_le_bytes().to_vec(); + delete_body.extend_from_slice(&[1, 0]); + delete_body.extend_from_slice(&property.0.to_le_bytes()); + delete_body.extend_from_slice(&0u32.to_le_bytes()); // type = AnyPropertyType + delete_body.extend_from_slice(&0u32.to_le_bytes()); // offset + delete_body.extend_from_slice(&3u32.to_le_bytes()); // full three-byte read + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(59), + &delete_body, + ) + .expect("GetProperty(delete)"); + let deletion_wire = read_all_available(&mut peer); + assert!(find_xi2_property_event(&deletion_wire).is_some()); + assert!( + !state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .contains_key(&property), + "GetProperty(delete) removes the seeded property" + ); + + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(208)))); + let request = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 2, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Profile Enabled", + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + &[0, 1], + ); + assert!(backend.started_device_configs.is_empty()); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert!( + !state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .contains_key(&property), + "a submitted write does not recreate the property before success" + ); + assert!( + read_all_available(&mut peer).is_empty(), + "no Created event before success" + ); + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(208), + source, + result: Ok(()), + }, + crate::core_loop::generation::Generation::default(), + ); + let wire = read_all_available(&mut peer); + assert_eq!( + find_xi2_property_event(&wire).unwrap()[20], + crate::xinput::PropWhat::Created as u8 + ); + let recreated = &state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&property]; + assert_eq!(recreated.data, [0, 1, 0]); + assert!( + recreated.deletable, + "recreated Xorg property uses default deletable flag" + ); + assert_eq!( + inventory.get(source).unwrap().config.accel_profile.current, + Some(1) + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_suspended_source_rejects_without_blocking_other_source() { + use crate::xinput::libinput_props::{DeviceConfigChange, DeviceConfigStart, DeviceConfigToken}; + + let mut state = ServerState::new(); + let mut peer_suspended = install_capture_client(&mut state, 1); + let mut peer_live = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let source_suspended = state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .source_id + .unwrap(); + let mut suspended_info = state.xi_devices.source(source_suspended).unwrap().clone(); + suspended_info.enabled = false; + state.xi_devices.register(&suspended_info); + let mut live_info = suspended_info.clone(); + live_info.source_id = crate::xinput::InputSourceId(source_suspended.0 + 1); + live_info.enabled = true; + live_info.device_node = "/dev/input/event77".into(); + live_info.sysname = "event77".into(); + let live_ids = state.xi_register_source(&live_info); + let live_device = *live_ids + .iter() + .find(|id| *id != &TEST_PHYSICAL_POINTER_ID) + .expect("second pointer facet"); + let source_live = live_info.source_id; + let mut inventory = crate::core_loop::input_inventory::InputInventory::new(); + inventory.add(suspended_info); + inventory.add(live_info); + inventory.suspend(source_suspended); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + backend + .device_config_start_results + .push_back(Ok(DeviceConfigStart::Pending(DeviceConfigToken(206)))); + + // Client B's enabled-source write occupies the global lane while its + // backend completion remains pending. + let request_live = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 2, + 1, + live_device, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.75_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_live, + ); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(!lane.is_empty(), "client B's write is still in flight"); + assert!(pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(2))); + + // Client A's write targets the suspended source and must fail before + // it can wait behind B's in-flight write. + let request_suspended = parse_t3_xi2_config_request( + &mut state, + &mut backend, + 1, + 2, + TEST_PHYSICAL_POINTER_ID, + "libinput Accel Speed", + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + &0.25_f32.to_le_bytes(), + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request_suspended, + ); + + let rejected = read_all_available(&mut peer_suspended); + assert_xi_config_error(&rejected, x11::error::BAD_MATCH, 2, 57); + assert!( + !pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(1)), + "client A is rejected without joining the pending lane" + ); + assert!(pending.xi_config_client_is_blocked_for_test(yserver_protocol::x11::ClientId(2))); + assert!(!lane.is_empty(), "client B remains in flight"); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(read_all_available(&mut peer_live).is_empty()); + + let accel_atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + assert_eq!( + state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties[&accel_atom] + .data, + 0.0_f32.to_le_bytes(), + "the rejected suspended-source write leaves its property unchanged" + ); + assert_eq!( + inventory + .get(source_suspended) + .unwrap() + .config + .accel + .current, + 0.0 + ); + + crate::core_loop::run::dispatch_device_config_result( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + &mut crate::core_loop::reset::ResetTrigger::new( + crate::core_loop::reset::ResetPolicy::NoReset, + ), + crate::core_loop::message::Message::DeviceConfigResult { + token: DeviceConfigToken(206), + source: source_live, + result: Ok(()), + }, + crate::core_loop::generation::Generation::default(), + ); + + let live_atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + assert_eq!( + backend.started_device_configs, + [(source_live, DeviceConfigChange::AccelSpeed(0.75))] + ); + assert_eq!( + state.xi_devices.device(live_device).unwrap().properties[&live_atom].data, + 0.75_f32.to_le_bytes() + ); + assert_eq!( + inventory.get(source_live).unwrap().config.accel.current, + 0.75 + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); + assert!(read_all_available(&mut peer_live).is_empty()); + assert!(read_all_available(&mut peer_suspended).is_empty()); +} + +#[test] +fn xi_libinput_write_uses_enabled_sibling_facets() { + use crate::xinput::libinput_props::DeviceConfigChange; + + // Mutation killed: restore the per-facet `!device.enabled` BadMatch + // gate in the XI config path. The pointer write below must reach + // libinput while its keyboard sibling remains enabled. + // Xorg's shared handle stays open until every facet is disabled + // (xf86libinput.c:416-432), and property checks fail only when that + // shared handle is null (xf86libinput.c:4392-4410). + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let baseline_device_ids: Vec<_> = state + .xi_devices + .devices() + .iter() + .map(|device| device.id) + .collect(); + let baseline_source_ids = state.xi_devices.source_ids(); + let baseline_properties = xi_property_snapshot(&state); + let baseline_pointer_buttons = state.buttons_down; + let baseline_device_buttons: Vec<_> = state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down)) + .collect(); + let baseline_key_holds = state.key_down_by_device.clone(); + let baseline_detached_masters = state.xi2_detached_masters.clone(); + let baseline_floating_positions = state.floating_pointer_positions.clone(); + let baseline_selections = { + let client = &state.clients[&1]; + ( + client.xi2_masks.clone(), + client.xi1_event_classes.clone(), + client.xi1_window_event_classes.clone(), + ) + }; + let core_xi2_header = |minor, body: &[u8]| { + let mut header = xi2_header_for_body(minor, body); + header.opcode = 137; + header + }; + + let source = crate::xinput::InputSourceId(u64::from(line!())); + let info = crate::core_loop::DeviceInfo { + source_id: source, + enabled: true, + resume_key: None, + capabilities: crate::xinput::InputCapabilities { + keyboard: true, + pointer: true, + touch: false, + }, + name: "Mixed keyboard and pointer".into(), + device_node: "/dev/input/event88".into(), + sysname: "event88".into(), + vendor_id: 0x046d, + product_id: 0xc52f, + is_touchpad: false, + config: crate::core_loop::message::LibinputConfigSnapshot { + accel: crate::core_loop::message::FloatSetting { + available: true, + current: 0.0, + default: 0.0, + }, + ..Default::default() + }, + }; + let ids = state.xi_register_source(&info); + let pointer = state + .xi_devices + .facet(source, crate::xinput::XiFacetKind::PointerTouch) + .expect("mixed source pointer facet"); + let keyboard = state + .xi_devices + .facet(source, crate::xinput::XiFacetKind::Keyboard) + .expect("mixed source keyboard facet"); + let mut inventory = crate::core_loop::input_inventory::InputInventory::new(); + inventory.add(info); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + + // Match the post-EnableDevice property value before exercising the + // client disable transition (the fixture registered the source). + let enabled_atom = state.xi_device_enabled_atom.0; + let enabled_write = xi2_change_property_body( + pointer, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + enabled_atom, + crate::xinput::XA_INTEGER.0, + &[1], + ); + assert!(matches!( + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(1), + core_xi2_header(57, &enabled_write), + &enabled_write, + None, + ) + .unwrap(), + RequestOutcome::Handled + )); + + let disable_pointer = xi2_change_property_body( + pointer, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + enabled_atom, + crate::xinput::XA_INTEGER.0, + &[0], + ); + assert!(matches!( + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(2), + core_xi2_header(57, &disable_pointer), + &disable_pointer, + None, + ) + .unwrap(), + RequestOutcome::Handled + )); + assert!(state.xi_devices.device(pointer).unwrap().client_disabled); + assert!(!state.xi_devices.device(pointer).unwrap().enabled); + assert!(state.xi_devices.device(keyboard).unwrap().enabled); + + let accel_atom = state.atoms.id_for("libinput Accel Speed").unwrap(); + let accel_body = xi2_change_property_body( + pointer, + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + accel_atom.0, + state.float_atom.0, + &0.75_f32.to_le_bytes(), + ); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(3), + core_xi2_header(57, &accel_body), + &accel_body, + None, + ) + .unwrap(); + let RequestOutcome::PendingXiConfig(request) = outcome else { + panic!("recognized libinput write must enter the config lane: {outcome:?}"); + }; + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert_eq!( + backend.started_device_configs, + [(source, DeviceConfigChange::AccelSpeed(0.75))], + "a disabled pointer facet can configure the still-open shared source" + ); + assert_eq!( + inventory.get(source).unwrap().config.accel.current, + 0.75, + "the applied setting reaches the source inventory" + ); + assert_eq!( + f32::from_le_bytes( + state.xi_devices.device(pointer).unwrap().properties[&accel_atom].data[..4] + .try_into() + .unwrap() + ), + 0.75, + "the confirmed value is committed to the disabled facet property" + ); + + let disable_keyboard = xi2_change_property_body( + keyboard, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + enabled_atom, + crate::xinput::XA_INTEGER.0, + &[0], + ); + assert!(matches!( + process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(4), + core_xi2_header(57, &disable_keyboard), + &disable_keyboard, + None, + ) + .unwrap(), + RequestOutcome::Handled + )); + assert!( + state + .xi_devices + .devices() + .iter() + .filter(|device| device.source_id == Some(source)) + .all(|device| !device.enabled) + ); + + let accel_body = xi2_change_property_body( + pointer, + crate::xinput::XI_PROP_MODE_REPLACE, + 32, + accel_atom.0, + state.float_atom.0, + &0.25_f32.to_le_bytes(), + ); + let outcome = process_request( + &mut state, + &mut backend, + ClientId(1), + SequenceNumber(5), + core_xi2_header(57, &accel_body), + &accel_body, + None, + ) + .unwrap(); + let RequestOutcome::PendingXiConfig(request) = outcome else { + panic!("recognized libinput write must enter the config lane: {outcome:?}"); + }; + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert_xi_config_error(&read_all_available(&mut peer), x11::error::BAD_MATCH, 5, 57); + assert_eq!( + backend.started_device_configs.len(), + 1, + "no config reaches the backend once every facet is disabled" + ); + assert_eq!( + inventory.get(source).unwrap().config.accel.current, + 0.75, + "a rejected write does not alter source settings" + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); + + let removed = state.xi_unregister_source(source); + assert_eq!(removed, ids); + assert_eq!( + state.take_xi_removed_device_descriptors().len(), + ids.len(), + "the source removal publisher owns every removed descriptor" + ); + inventory.remove(source); + assert!(inventory.is_empty()); + assert_eq!( + state + .xi_devices + .devices() + .iter() + .map(|device| device.id) + .collect::>(), + baseline_device_ids, + "registry returns to its original device set" + ); + assert_eq!(state.xi_devices.source_ids(), baseline_source_ids); + assert!(state.xi_devices.source(source).is_none()); + assert_eq!(xi_property_snapshot(&state), baseline_properties); + assert_eq!(state.buttons_down, baseline_pointer_buttons); + assert_eq!( + state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down)) + .collect::>(), + baseline_device_buttons + ); + assert_eq!(state.key_down_by_device, baseline_key_holds); + assert_eq!(state.xi2_detached_masters, baseline_detached_masters); + assert_eq!( + state.floating_pointer_positions, + baseline_floating_positions + ); + let client = &state.clients[&1]; + assert_eq!( + ( + &client.xi2_masks, + &client.xi1_event_classes, + &client.xi1_window_event_classes, + ), + ( + &baseline_selections.0, + &baseline_selections.1, + &baseline_selections.2, + ) + ); + assert!(read_all_available(&mut peer).is_empty()); +} + +#[test] +fn xi_config_completion_removal_cancels_queued_write_on_host_input_for_xi1_and_xi2() { + for xi1_request in [true, false] { + assert_t3_host_lifecycle_cancels_queued_write(true, xi1_request); + } +} + +#[test] +fn xi_config_completion_suspension_cancels_queued_write_on_host_input_for_xi1_and_xi2() { + for xi1_request in [true, false] { + assert_t3_host_lifecycle_cancels_queued_write(false, xi1_request); + } +} + +#[test] +fn xi_config_completion_t3_b2_append_onto_absent_profile_behaves_like_replace() { + // Model a client-deleted supported property. Append [0, 1, 0] + // then behaves exactly like Replace and stores three bytes. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + let atom = state + .atoms + .intern("libinput Accel Profile Enabled", false) + .0; + + // Delete through the same XIGetProperty(delete) path a client uses. + let mut delete_body = TEST_PHYSICAL_POINTER_ID.to_le_bytes().to_vec(); + delete_body.extend_from_slice(&[1, 0]); + delete_body.extend_from_slice(&atom.to_le_bytes()); + delete_body.extend_from_slice(&0u32.to_le_bytes()); + delete_body.extend_from_slice(&0u32.to_le_bytes()); + delete_body.extend_from_slice(&3u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(59), + &delete_body, + ) + .unwrap(); + let deleted_reply = read_all_available(&mut peer); + assert_eq!( + deleted_reply.len(), + 36, + "GetProperty reply includes the full value" + ); + assert_eq!(deleted_reply[0], 1, "GetProperty returns a reply"); + assert!( + !state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .contains_key(&AtomId(atom)) + ); + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_APPEND, + 8, + atom, + integer_atom, + &[0, 1, 0], + ); + let outcome = handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(57), + &body, + ) + .unwrap(); + let crate::core_loop::process_request::RequestOutcome::PendingXiConfig(request) = outcome + else { + panic!("recognized Append must enter the core config lane") + }; + assert!(backend.started_device_configs.is_empty()); + assert!( + !state + .xi_devices + .device(TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .contains_key(&AtomId(atom)), + "request parsing leaves the deleted property absent" + ); + route_t3_config_request( + &mut state, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + request, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "no error: absent property + Append behaves like Replace" + ); + + let dev = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap(); + let prop = dev.properties.get(&AtomId(atom)).unwrap(); + assert_eq!(prop.data, vec![0, 1, 0]); + assert!( + prop.deletable, + "recreated property uses Xorg's default flag" + ); + assert_eq!( + backend.started_device_configs, + [( + source, + crate::xinput::libinput_props::DeviceConfigChange::AccelProfile(Some(1)) + )] + ); + assert_eq!( + inventory.get(source).unwrap().config.accel_profile.current, + Some(1) + ); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_t5_xi2_modified_property_event_to_selecting_client() { + // Selecting client receives an XI2 XI_PropertyEvent with + // what=Modified after a successful XIChangeProperty against an + // already-seeded libinput property ("libinput Tapping Enabled" + // is set by `seed_pointer_properties`, so the write is a Modify). + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + select_xi2_property_event_on_root(&mut state, 1, TEST_PHYSICAL_POINTER_ID); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + // No reply for XIChangeProperty; the only bytes on the wire + // must be the 32-byte XI_PropertyEvent. + assert_eq!(wire.len(), 32, "exactly one 32-byte event, no reply"); + let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); + assert_eq!(ev[0], 35, "GenericEvent"); + assert_eq!(ev[1], 137, "extension = XInputExtension major"); + assert_eq!(u16::from_le_bytes([ev[8], ev[9]]), 12, "evtype"); + assert_eq!( + u16::from_le_bytes([ev[10], ev[11]]), + TEST_PHYSICAL_POINTER_ID, + "deviceid" + ); + assert_eq!( + u32::from_le_bytes([ev[16], ev[17], ev[18], ev[19]]), + tap_atom, + "property atom" + ); + assert_eq!(ev[20], 2, "what = Modified (property already seeded)"); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn t5_xi2_change_property_emits_property_event_created_for_new_atom() { + // Writing a property the device has never carried before + // (atom 0x4242 — a synthetic test atom, no descriptor table + // entry, so the dispatch falls through to the bare commit step) + // reports `Created`. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // No touchpad → the descriptor path is bypassed and any atom + // commits straight into the registry. + state.atoms.register_for_test(AtomId(0x4242), "T5 created"); + select_xi2_property_event_on_root(&mut state, 1, 4); + + let body = xi2_change_property_body( + 4, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + 0x4242, + crate::xinput::XA_INTEGER.0, + &[7], + ); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(57), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); + assert_eq!(ev[20], 1, "what = Created"); + assert_eq!( + u32::from_le_bytes([ev[16], ev[17], ev[18], ev[19]]), + 0x4242, + "property atom" + ); +} + +#[test] +fn t5_xi2_delete_property_emits_property_event_deleted() { + // XIDeleteProperty against a seeded property fans out + // what=Deleted. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + select_xi2_property_event_on_root(&mut state, 1, 4); + + let mut body = Vec::new(); + body.extend_from_slice(&4u16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(58), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "exactly one 32-byte event, no reply"); + let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); + assert_eq!(ev[20], 0, "what = Deleted"); + assert_eq!( + u32::from_le_bytes([ev[16], ev[17], ev[18], ev[19]]), + 100, + "property atom" + ); +} + +#[test] +fn t5_xi2_delete_property_absent_is_silent() { + // Redundant delete of an absent property must NOT emit an + // event (mirror of xiproperty.c, which only calls + // `send_property_event` when the registry actually shrank). + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + // Atom must exist for the BadAtom guard, but the property is + // not seeded onto device 4. + state.atoms.register_for_test(AtomId(100), "T5 absent prop"); + select_xi2_property_event_on_root(&mut state, 1, 4); + + let mut body = Vec::new(); + body.extend_from_slice(&4u16.to_le_bytes()); + body.extend_from_slice(&0u16.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(58), + &body, + ) + .unwrap(); + assert!( + read_all_available(&mut peer).is_empty(), + "no event for a no-op delete" + ); +} + +#[test] +fn t5_xi2_get_property_delete_emits_property_event_deleted() { + // `XIGetProperty(delete=1)` removes the property after a full + // read and the dispatch arm fans out what=Deleted to selecting + // clients. Both the GetProperty reply (36 bytes: 32 header + + // 1 data byte padded to 4) and the 32-byte XI_PropertyEvent + // end up on the same socket — the X protocol leaves the order + // unspecified (clients reorder by sequence), so the test + // searches for the event payload rather than anchoring on its + // wire position. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + select_xi2_property_event_on_root(&mut state, 1, 4); + + // body: deviceid(2)=4, delete(1)=1, pad(1), property(4)=100, + // type(4)=0, offset(4)=0, len(4)=100. + let mut body = Vec::new(); + body.extend_from_slice(&4u16.to_le_bytes()); + body.push(1); // delete = true + body.push(0); // pad + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(59), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 36 + 32, "GetProperty reply + PropertyEvent"); + let ev = find_xi2_property_event(&wire).expect("XI_PropertyEvent present"); + assert_eq!(ev[20], 0, "what = Deleted"); + // Independently confirm the reply is somewhere in the buffer. + // The reply starts with X_Reply = 1, which the 32-byte event + // (starts with GenericEvent = 35) can't impersonate. + assert!(wire.contains(&1), "GetProperty reply is on the wire"); + // The registry must have actually shrunk. + let dev = state.xi_devices.iter().find(|d| d.id == 4).unwrap(); + assert!( + !dev.properties.contains_key(&AtomId(100)), + "delete=1 consumed the property" + ); +} + +#[test] +fn t5_xi2_get_property_no_delete_does_not_emit() { + // The non-deleting read path must not emit anything. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_one_prop(&mut state, 100, 8, vec![1]); + select_xi2_property_event_on_root(&mut state, 1, 4); + + let mut body = Vec::new(); + body.extend_from_slice(&4u16.to_le_bytes()); + body.push(0); // delete = false + body.push(0); // pad + body.extend_from_slice(&100u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + xi2_header(59), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert!( + find_xi2_property_event(&wire).is_none(), + "no XI_PropertyEvent on a non-deleting read" + ); +} + +#[test] +fn xi_config_completion_t5_xi2_not_selected_client_gets_nothing() { + // A client that did NOT select `XI_PropertyEventMask` for + // this physical device must not receive the event, even if it has other + // XI2 selections on the same window. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + // Selecting `XI_DeviceChanged` only — the + // `XI2_PROPERTY_EVENT_MASK` bit is NOT set, so this client + // must be skipped. + state.clients.get_mut(&1).unwrap().xi2_masks.insert( + (ROOT_WINDOW, TEST_PHYSICAL_POINTER_ID), + u64::from(crate::xinput::XI2_DEVICE_CHANGED_MASK), + ); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "client without the property-event bit gets nothing" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_t5_xi2_other_device_does_not_match() { + // Selecting `XI_PropertyEvent` for device 3 (master keyboard) + // must NOT route a physical pointer property change to that client. + // The wildcards `XIAllDevices(0)` / `XIAllMasterDevices(1)` are + // followed by `xi2mask_isset` (xserver dix/inpututils.c:1153), + // but device 3 is neither, so this client stays unselected. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + // Client subscribes to property events on device 3, not the physical pointer. + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 3), u64::from(XI2_PROPERTY_EVENT_MASK)); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + assert!( + read_all_available(&mut peer).is_empty(), + "device-3 selection must not see physical pointer events" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_t5_xi2_all_devices_wildcard_matches() { + // Regression for the bug `xinput watch-props 4` exposed on + // M1/Asahi: every realworld client (xinput, MATE, etc.) calls + // XISelectEvents with `deviceid = XIAllDevices = 0`, not the + // specific slave id. xserver's `xi2mask_isset` + // (dix/inpututils.c:1153) ORs the wildcard mask with the + // specific mask; without that OR the client silently received + // nothing. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + // Select on the wildcard, NOT on the physical pointer directly. + state + .clients + .get_mut(&1) + .unwrap() + .xi2_masks + .insert((ROOT_WINDOW, 0), u64::from(XI2_PROPERTY_EVENT_MASK)); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + let ev = find_xi2_property_event(&wire) + .expect("XIAllDevices selection must receive the property event"); + assert_eq!(ev[20], 2, "what byte = Modified"); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_t5_xi1_write_also_emits_xi2_property_event() { + // The XI1 write path (minor 37) must trigger the same XI2 + // fan-out — xserver's `send_property_event` fires from both + // protocol paths so an XI2-listening client sees its tap + // toggle even when an XI1 caller (e.g. an older xset variant) + // wrote the property. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + select_xi2_property_event_on_root(&mut state, 1, TEST_PHYSICAL_POINTER_ID); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + // xChangeDevicePropertyReq body layout (XIproto.h:1467-1479): + // property(4), type(4), deviceid(1), format(1), mode(1), pad(1), + // num_items(4), value(num_items * format/8 padded to 4). + let mut body = Vec::new(); + body.extend_from_slice(&tap_atom.to_le_bytes()); + body.extend_from_slice(&integer_atom.to_le_bytes()); + body.push(u8::try_from(TEST_PHYSICAL_POINTER_ID).unwrap()); // deviceid + body.push(8); // format + body.push(crate::xinput::XI_PROP_MODE_REPLACE); + body.push(0); // pad + body.extend_from_slice(&1u32.to_le_bytes()); // num_items = 1 + body.extend_from_slice(&[0u8, 0, 0, 0]); // value=[0] + 3 pad + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(37), + &body, + ); + let wire = read_all_available(&mut peer); + let ev = find_xi2_property_event(&wire).expect("XI1 write must also fan-out XI_PropertyEvent"); + assert_eq!(ev[20], 2, "what = Modified"); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn xi_config_completion_t5_property_event_selected_on_any_window_still_delivers() { + // SendEventToAllWindows: a client that selected + // `XI_PropertyEvent` for the device on ANY window (here a + // synthetic non-root xid) must still receive the event. The + // event has no event-window field, so per-window distinctions + // only affect delivery. + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, source) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + // Subscribe via a non-root window — anything keyed by the + // device id wins. + state.clients.get_mut(&1).unwrap().xi2_masks.insert( + (ResourceId(0xdead_beef), TEST_PHYSICAL_POINTER_ID), + u64::from(XI2_PROPERTY_EVENT_MASK), + ); + let tap_atom = state + .atoms + .intern(crate::xinput::PROP_TAPPING_ENABLED, false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + tap_atom, + integer_atom, + &[0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 1, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert!( + find_xi2_property_event(&wire).is_some(), + "non-root selection must still deliver" + ); + assert_confirmed_tap_write(&state, &inventory, source, AtomId(tap_atom)); + assert_eq!(backend.started_device_configs.len(), 1); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} + +#[test] +fn t3_xi2_get_property_uninterned_atom_yields_bad_atom() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + // Atom 0xdeadbeef has never been interned → BadAtom. + let bogus_atom = 0xdead_beefu32; + assert!(!state.atoms.exists(AtomId(bogus_atom)), "precondition"); + // XIGetProperty body: physical deviceid(2), delete(1)=0, pad(1), + // property(4), type(4)=0, offset(4)=0, len(4)=100. + let mut body = Vec::new(); + body.extend_from_slice(&TEST_PHYSICAL_POINTER_ID.to_le_bytes()); + body.push(0); // delete + body.push(0); // pad + body.extend_from_slice(&bogus_atom.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&0u32.to_le_bytes()); + body.extend_from_slice(&100u32.to_le_bytes()); + handle_xi2_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(3), + xi2_header(59), + &body, + ) + .unwrap(); + let wire = read_all_available(&mut peer); + assert_eq!(wire.len(), 32, "error packet"); + assert_eq!(wire[0], 0, "X_Error"); + assert_eq!(wire[1], 5, "BadAtom"); + // The error's bad-value field should echo the offending atom. + assert_eq!( + u32::from_le_bytes(wire[4..8].try_into().unwrap()), + bogus_atom, + "BadAtom echoes property" + ); +} + +#[test] +fn xi_config_completion_invalid_value_yields_bad_value_without_mutation() { + let mut state = ServerState::new(); + let mut peer = install_capture_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + seed_pointer_for_t3(&mut state); + let (mut inventory, _) = inventory_for_t3_source(&state); + let mut pending = crate::core_loop::run::PendingBackendRequests::default(); + let mut lane = crate::core_loop::run::XiConfigLane::default(); + // Scroll Method Enabled is `OneHotOrNone { n: 3 }` — two bits set is illegal. + let scroll_atom = state + .atoms + .intern("libinput Scroll Method Enabled", false) + .0; + let integer_atom = crate::xinput::XA_INTEGER.0; + let before = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .get(&AtomId(scroll_atom)) + .cloned() + .expect("scroll method seeded"); + let properties_before = xi_property_snapshot(&state); + + let body = xi2_change_property_body( + TEST_PHYSICAL_POINTER_ID, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + scroll_atom, + integer_atom, + &[1, 1, 0], + ); + drive_t3_config_wire_request( + &mut state, + &mut peer, + &mut backend, + &mut inventory, + &mut pending, + &mut lane, + 1, + 4, + xi2_header(57), + &body, + ); + let wire = read_all_available(&mut peer); + assert_xi_config_error(&wire, 2, 4, 57); + + let after = state + .xi_devices + .iter() + .find(|d| d.id == TEST_PHYSICAL_POINTER_ID) + .unwrap() + .properties + .get(&AtomId(scroll_atom)) + .cloned() + .expect("scroll method still present"); + assert_eq!( + before.data, after.data, + "registry untouched when validation rejects the value" + ); + assert_eq!(xi_property_snapshot(&state), properties_before); + assert!(backend.started_device_configs.is_empty()); + assert!(lane.is_empty()); + assert!(pending.is_empty()); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi_hotplug.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi_hotplug.rs new file mode 100644 index 000000000..5cd011264 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi_hotplug.rs @@ -0,0 +1,457 @@ +use super::*; +use yserver_protocol::x11::AtomId; + +// ----------------------------------------------------------------- +// XI 1.x `SelectExtensionEvent` + `DevicePropertyNotify` fan-out. +// ----------------------------------------------------------------- + +const XI1_DEVICE_PRESENCE_CLASS: u32 = 256 << 8; +const XI1_DEVICE_PRESENCE_EVENT_TYPE: u8 = + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_PRESENCE_NOTIFY_OFFSET; + +fn xi2_hierarchy_wire_event_type() -> u8 { + u8::try_from(crate::xinput::XI2_HIERARCHY_CHANGED_EVENT_TYPE) + .expect("XI2 event types fit in u8") +} + +fn xi_hotplug_hierarchy_selection_body(window: ResourceId, selected: bool) -> Vec { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&window.0.to_le_bytes()); + body.extend_from_slice(&1u16.to_le_bytes()); // num_masks + body.extend_from_slice(&0u16.to_le_bytes()); // pad + body.extend_from_slice(&0u16.to_le_bytes()); // XIAllDevices + body.extend_from_slice(&1u16.to_le_bytes()); // four-byte mask + body.extend_from_slice(&[0, if selected { 0x08 } else { 0 }, 0, 0]); + body +} + +fn xi_hotplug_select_hierarchy( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + window: ResourceId, + selected: bool, +) { + let body = xi_hotplug_hierarchy_selection_body(window, selected); + xi_hotplug_dispatch(state, backend, client, sequence, 137, 46, &body); +} + +fn xi_hotplug_select_presence( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + window: ResourceId, +) { + let body = xi1_select_extension_event_body(window.0, &[XI1_DEVICE_PRESENCE_CLASS]); + xi_hotplug_dispatch(state, backend, client, sequence, 137, 6, &body); +} + +fn xi_hotplug_set_enabled( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + device_id: u16, + enabled: bool, +) { + let body = xi2_change_property_body( + device_id, + crate::xinput::XI_PROP_MODE_REPLACE, + 8, + state.xi_device_enabled_atom.0, + crate::xinput::XA_INTEGER.0, + &[u8::from(enabled)], + ); + xi_hotplug_dispatch(state, backend, client, sequence, 137, 57, &body); +} + +fn xi_hotplug_device_events(wire: &[u8], event_type: u8) -> Vec<&[u8]> { + let mut events = Vec::new(); + let mut offset = 0; + while wire.len().saturating_sub(offset) >= 32 { + let event_size = if wire[offset] == 35 { + let length = + u32::from_le_bytes(wire[offset + 4..offset + 8].try_into().unwrap()) as usize; + 32usize.saturating_add(length.saturating_mul(4)) + } else { + 32 + }; + if event_size > wire.len() - offset { + break; + } + let matches = if event_type == XI1_DEVICE_PRESENCE_EVENT_TYPE { + wire[offset] == XI1_DEVICE_PRESENCE_EVENT_TYPE + } else { + wire[offset] == 35 + && u16::from_le_bytes([wire[offset + 8], wire[offset + 9]]) == u16::from(event_type) + }; + if matches { + events.push(&wire[offset..offset + event_size]); + } + offset += event_size; + } + events +} + +#[derive(Debug, PartialEq)] +struct XiHotplugDeviceSnapshot { + id: u16, + role: crate::xinput::XiDeviceRole, + source_id: Option, + facet: Option, + enabled: bool, + attachment: Option, +} + +#[derive(Debug, PartialEq)] +struct XiHotplugInputStateSnapshot { + device: u16, + keys_down: [u8; 32], + buttons_down: [u8; 32], + valuator_mode: u8, + valuators: [i32; 4], +} + +#[derive(Debug, PartialEq)] +struct XiHotplugClientSelectionsSnapshot { + client: u32, + xi2: Vec<((ResourceId, u16), u64)>, + xi1: Vec<(ResourceId, Vec)>, +} + +#[derive(Debug, PartialEq)] +struct XiHotplugStateSnapshot { + registry: Vec, + source_ids: Vec, + properties: Vec<( + u16, + std::collections::BTreeMap, + )>, + buttons_down: u16, + device_buttons_down: Vec<(u16, u16)>, + key_down_by_device: Vec<(u16, Vec<(u8, crate::core_loop::InputOrigin)>)>, + xi1_input_state: Vec, + detached_masters: HashMap, + floating_pointer_positions: HashMap, + client_selections: Vec, + selections: HashMap, +} + +fn xi_hotplug_state_snapshot(state: &ServerState) -> XiHotplugStateSnapshot { + let registry = state + .xi_devices + .devices() + .iter() + .map(|device| XiHotplugDeviceSnapshot { + id: device.id, + role: state.xi_devices.role(device.id).expect("registered role"), + source_id: device.source_id, + facet: device.facet, + enabled: device.enabled, + attachment: state.xi_devices.attachment(device.id), + }) + .collect(); + let mut key_down_by_device = state + .key_down_by_device + .iter() + .map(|(device, keys)| { + let mut keys: Vec<_> = keys.iter().map(|(key, origin)| (*key, *origin)).collect(); + keys.sort_unstable_by_key(|(key, _)| *key); + (*device, keys) + }) + .collect::>(); + key_down_by_device.sort_unstable_by_key(|(device, _)| *device); + let mut xi1_input_state = state + .xi1_device_input_state + .iter() + .map(|(device, input)| XiHotplugInputStateSnapshot { + device: *device, + keys_down: input.keys_down, + buttons_down: input.buttons_down, + valuator_mode: input.valuator_mode, + valuators: input.valuators, + }) + .collect::>(); + xi1_input_state.sort_unstable_by_key(|input| input.device); + let mut client_selections = state + .clients + .iter() + .filter_map(|(client_id, client)| { + let mut xi2: Vec<_> = client + .xi2_masks + .iter() + .map(|(key, mask)| (*key, *mask)) + .collect(); + xi2.sort_unstable_by_key(|((window, device), _)| (window.0, *device)); + let mut xi1: Vec<_> = client + .xi1_window_event_classes + .iter() + .map(|(window, classes)| { + let mut classes: Vec<_> = classes.iter().copied().collect(); + classes.sort_unstable(); + (*window, classes) + }) + .collect(); + xi1.sort_unstable_by_key(|(window, _)| window.0); + (!xi2.is_empty() || !xi1.is_empty()).then_some(XiHotplugClientSelectionsSnapshot { + client: *client_id, + xi2, + xi1, + }) + }) + .collect::>(); + client_selections.sort_unstable_by_key(|client| client.client); + XiHotplugStateSnapshot { + registry, + source_ids: state.xi_devices.source_ids(), + properties: xi_property_snapshot(state), + buttons_down: state.buttons_down, + device_buttons_down: state + .xi_devices + .devices() + .iter() + .map(|device| (device.id, device.buttons_down)) + .collect(), + key_down_by_device, + xi1_input_state, + detached_masters: state.xi2_detached_masters.clone(), + floating_pointer_positions: state.floating_pointer_positions.clone(), + client_selections, + selections: state.selections.clone(), + } +} + +fn xi_hotplug_create_child( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + child: ResourceId, +) { + let body = xi_hotplug_create_window_body(child.0, ROOT_WINDOW.0); + xi_hotplug_dispatch(state, backend, client, sequence, 1, 0, &body); +} + +fn xi_hotplug_destroy_child( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + sequence: u16, + child: ResourceId, +) { + xi_hotplug_dispatch( + state, + backend, + client, + sequence, + 4, + 0, + &child.0.to_le_bytes(), + ); +} + +fn xi_hotplug_finish_clients( + state: &mut ServerState, + backend: &mut RecordingBackend, + client_ids: &[u32], +) { + for client_id in client_ids { + crate::core_loop::process_disconnect::process_disconnect( + state, + backend, + ClientId(*client_id), + ); + } +} + +#[test] +fn xi_hotplug_per_window_hierarchy_selection_delivers_each_window_copy() { + // Mutation killed: collect XI_HierarchyChanged targets once per + // client instead of once per selected window. Xorg walks the root + // and descendants and delivers separately at each one + // (Xi/exevents.c:3279-3312; Xi/xichangehierarchy.c:119). + let mut state = ServerState::new(); + let mut peer1 = install_capture_client(&mut state, 1); + let mut peer2 = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let device_id = seed_pointer_for_t3(&mut state); + // The registry fixture constructs an enabled source directly, so + // mirror the Device Enabled=1 write that completes production add. + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 1, device_id, true); + let before = xi_hotplug_state_snapshot(&state); + let child = ResourceId(0x10_0001); + + xi_hotplug_create_child(&mut state, &mut backend, 1, 2, child); + xi_hotplug_select_hierarchy(&mut state, &mut backend, 1, 3, ROOT_WINDOW, true); + xi_hotplug_select_hierarchy(&mut state, &mut backend, 1, 4, child, true); + xi_hotplug_select_hierarchy(&mut state, &mut backend, 2, 1, ROOT_WINDOW, true); + assert!(read_all_available(&mut peer1).is_empty()); + assert!(read_all_available(&mut peer2).is_empty()); + + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 5, device_id, false); + let disabled1 = read_all_available(&mut peer1); + let disabled2 = read_all_available(&mut peer2); + let events1 = xi_hotplug_device_events(&disabled1, xi2_hierarchy_wire_event_type()); + let events2 = xi_hotplug_device_events(&disabled2, xi2_hierarchy_wire_event_type()); + assert_eq!(events1.len(), 2, "client 1 selected root and child"); + assert_eq!(events2.len(), 1, "client 2 selected only the root"); + assert_eq!(events1[0], events1[1], "copies carry no window field"); + + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 6, device_id, true); + let enabled1 = read_all_available(&mut peer1); + let enabled2 = read_all_available(&mut peer2); + let events1 = xi_hotplug_device_events(&enabled1, xi2_hierarchy_wire_event_type()); + let events2 = xi_hotplug_device_events(&enabled2, xi2_hierarchy_wire_event_type()); + assert_eq!(events1.len(), 2); + assert_eq!(events2.len(), 1); + assert_eq!(events1[0], events1[1]); + assert_eq!( + state.xi_devices.device(device_id).unwrap().properties[&state.xi_device_enabled_atom].data, + [1], + "reenabling restores the Device Enabled property" + ); + + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(1)); + assert_eq!( + state.xi_devices.device(device_id).unwrap().properties[&state.xi_device_enabled_atom].data, + [1], + "client disconnect does not change Device Enabled" + ); + crate::core_loop::process_disconnect::process_disconnect(&mut state, &mut backend, ClientId(2)); + assert!(state.clients.is_empty()); + assert!(state.resources.window(child).is_none()); + assert_eq!(xi_hotplug_state_snapshot(&state), before); +} + +#[test] +fn xi_hotplug_per_window_presence_selection_delivers_each_window_copy() { + // Mutation killed: fan out XI1 DevicePresenceNotify once per client + // using the global class set. Xorg records the presence mask on a + // window (Xi/selectev.c:69-111, 141-180) and walks each window + // (dix/devices.c:333-346; Xi/exevents.c:3279-3312). + let mut state = ServerState::new(); + let mut peer1 = install_capture_client(&mut state, 1); + let mut peer2 = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let device_id = seed_pointer_for_t3(&mut state); + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 1, device_id, true); + let before = xi_hotplug_state_snapshot(&state); + let child = ResourceId(0x10_0002); + + xi_hotplug_create_child(&mut state, &mut backend, 1, 2, child); + xi_hotplug_select_presence(&mut state, &mut backend, 1, 3, ROOT_WINDOW); + xi_hotplug_select_presence(&mut state, &mut backend, 1, 4, child); + xi_hotplug_select_presence(&mut state, &mut backend, 2, 1, ROOT_WINDOW); + assert!(read_all_available(&mut peer1).is_empty()); + assert!(read_all_available(&mut peer2).is_empty()); + + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 5, device_id, false); + let disabled1 = read_all_available(&mut peer1); + let disabled2 = read_all_available(&mut peer2); + let events1 = xi_hotplug_device_events(&disabled1, XI1_DEVICE_PRESENCE_EVENT_TYPE); + let events2 = xi_hotplug_device_events(&disabled2, XI1_DEVICE_PRESENCE_EVENT_TYPE); + assert_eq!(events1.len(), 2, "client 1 selected root and child"); + assert_eq!(events2.len(), 1, "client 2 selected only the root"); + assert_eq!(events1[0], events1[1], "copies carry no window field"); + + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 6, device_id, true); + let enabled1 = read_all_available(&mut peer1); + let enabled2 = read_all_available(&mut peer2); + let events1 = xi_hotplug_device_events(&enabled1, XI1_DEVICE_PRESENCE_EVENT_TYPE); + let events2 = xi_hotplug_device_events(&enabled2, XI1_DEVICE_PRESENCE_EVENT_TYPE); + assert_eq!(events1.len(), 2); + assert_eq!(events2.len(), 1); + assert_eq!(events1[0], events1[1]); + + xi_hotplug_finish_clients(&mut state, &mut backend, &[1, 2]); + assert!(state.clients.is_empty()); + assert!(state.resources.window(child).is_none()); + assert_eq!(xi_hotplug_state_snapshot(&state), before); +} + +#[test] +fn xi_hotplug_per_window_destroyed_child_selection_is_removed() { + // Mutation killed: retain XI1/XI2 selections when DestroyWindow + // tears down a selected child. The event before destruction has two + // copies; afterward only the still-selected root gets one. Xorg + // removes a window's extension selections during teardown + // (dix/window.c:998-1000; Xi/exevents.c:3103-3123). + let mut state = ServerState::new(); + let mut peer1 = install_capture_client(&mut state, 1); + let mut peer2 = install_capture_client(&mut state, 2); + let mut backend = RecordingBackend::new(); + let device_id = seed_pointer_for_t3(&mut state); + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 1, device_id, true); + let before = xi_hotplug_state_snapshot(&state); + let child = ResourceId(0x10_0003); + + xi_hotplug_create_child(&mut state, &mut backend, 1, 2, child); + for (sequence, window) in [(3, ROOT_WINDOW), (4, child)] { + xi_hotplug_select_hierarchy(&mut state, &mut backend, 1, sequence, window, true); + xi_hotplug_select_presence(&mut state, &mut backend, 1, sequence + 2, window); + } + xi_hotplug_select_hierarchy(&mut state, &mut backend, 2, 1, ROOT_WINDOW, true); + xi_hotplug_select_presence(&mut state, &mut backend, 2, 2, ROOT_WINDOW); + assert!(read_all_available(&mut peer1).is_empty()); + assert!(read_all_available(&mut peer2).is_empty()); + + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 7, device_id, false); + let disabled1 = read_all_available(&mut peer1); + let disabled2 = read_all_available(&mut peer2); + for (wire, expected) in [(&disabled1, 2), (&disabled2, 1)] { + assert_eq!( + xi_hotplug_device_events(wire, xi2_hierarchy_wire_event_type()).len(), + expected, + "hierarchy copies match the selected window count" + ); + assert_eq!( + xi_hotplug_device_events(wire, XI1_DEVICE_PRESENCE_EVENT_TYPE).len(), + expected, + "presence copies match the selected window count" + ); + } + let hierarchy_copies = xi_hotplug_device_events(&disabled1, xi2_hierarchy_wire_event_type()); + let presence_copies = xi_hotplug_device_events(&disabled1, XI1_DEVICE_PRESENCE_EVENT_TYPE); + assert_eq!(hierarchy_copies[0], hierarchy_copies[1]); + assert_eq!(presence_copies[0], presence_copies[1]); + + xi_hotplug_destroy_child(&mut state, &mut backend, 1, 8, child); + assert!(state.resources.window(child).is_none()); + assert!( + !state.clients[&1] + .xi2_masks + .keys() + .any(|(window, _)| *window == child), + "DestroyWindow drops the child's XI2 selection" + ); + assert!( + !state.clients[&1] + .xi1_window_event_classes + .contains_key(&child), + "DestroyWindow drops the child's XI1 selection" + ); + assert!(read_all_available(&mut peer1).is_empty()); + assert!(read_all_available(&mut peer2).is_empty()); + + xi_hotplug_set_enabled(&mut state, &mut backend, 1, 9, device_id, true); + let enabled1 = read_all_available(&mut peer1); + let enabled2 = read_all_available(&mut peer2); + for wire in [&enabled1, &enabled2] { + assert_eq!( + xi_hotplug_device_events(wire, xi2_hierarchy_wire_event_type()).len(), + 1, + "only the root selection remains" + ); + assert_eq!( + xi_hotplug_device_events(wire, XI1_DEVICE_PRESENCE_EVENT_TYPE).len(), + 1, + "only the root selection remains" + ); + } + + xi_hotplug_finish_clients(&mut state, &mut backend, &[1, 2]); + assert!(state.clients.is_empty()); + assert_eq!(xi_hotplug_state_snapshot(&state), before); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xkb.rs b/crates/yserver-core/src/core_loop/process_request/tests/xkb.rs new file mode 100644 index 000000000..e13a254ac --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/xkb.rs @@ -0,0 +1,384 @@ +use super::*; + +#[test] +fn xkb_get_kbd_by_name_also_broadcasts_legacy_mapping_notify() { + // Real `setxkbmap` loads a layout via XkbGetKeyboardByName (minor + // 23), not by writing `_XKB_RULES_NAMES`. A plain-X11 client (any + // WM that never calls XkbSelectEvents and only understands core + // events — e.g. one resolving keybinds via XKeysymToKeycode once + // at startup) relies on the legacy MappingNotify event to know + // when to re-resolve its keysym-based key grabs. Without it, the + // WM's shortcuts stay bound to the pre-switch keycodes forever + // even though per-keystroke translation (and thus typing) already + // reflects the new layout. + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + // Stale ChangeKeyboardMapping row from before the switch — must + // not keep shadowing the freshly loaded keymap either. + state.keymap_overrides.insert(38, vec![0x0071]); + + let mut reply = vec![0u8; 32]; + reply[0] = 1; // X_Reply + assert!(crate::core_loop::xkb_select::use_extension( + &mut state, + ClientId(1), + &[1, 0, 0, 0] + )); + let mut backend = RecordingBackend::new().with_kbd_by_name_result( + reply, + Some(crate::backend::XkbNewKeyboardInfo { + min_keycode: 8, + max_keycode: 255, + old_min_keycode: 8, + old_max_keycode: 255, + changed: 0x0001, + }), + ); + + handle_xkb_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(1), + RequestHeader { + opcode: 136, + data: 23, + length_units: 2, + }, + &[], + ) + .expect("XkbGetKbdByName"); + + assert!( + state.keymap_overrides.is_empty(), + "a full XkbGetKeyboardByName load must drop stale ChangeKeyboardMapping rows too" + ); + + let bytes = read_all_available(&mut peer); + let mapping_notify_count = bytes + .chunks(32) + .filter( + |chunk| chunk.len() == 32 && chunk[0] == 34, /* MappingNotify */ + ) + .count(); + assert!( + mapping_notify_count >= 2, + "expected legacy MappingNotify(Keyboard) + MappingNotify(Modifier) \ + alongside XkbNewKeyboardNotify, got {mapping_notify_count} in {bytes:02x?}" + ); + let keyboard_mapping_notify = bytes + .chunks(32) + .find(|chunk| chunk.len() == 32 && chunk[0] == 34 && chunk[4] == 1); + assert!( + keyboard_mapping_notify.is_some(), + "expected a MappingNotify with request=Keyboard(1): {bytes:02x?}" + ); +} + +fn xkb_request( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + minor: u8, + body: &[u8], +) { + handle_xkb_request( + state, + backend, + None, + ClientId(client), + SequenceNumber(1), + RequestHeader { + opcode: 136, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).unwrap(), + }, + body, + ) + .expect("XKB request"); +} + +/// Xvfb 21.1.24, XkbUseExtension(1, 0) at sequence 2 from a +/// little-endian client: `01010200 00000000 01000000 00…` +/// (supported, server 1.0). +#[test] +fn xkb_use_extension_replies_like_xorg() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + handle_xkb_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 136, + data: 0, + length_units: 2, + }, + &[1, 0, 0, 0], + ) + .expect("XkbUseExtension"); + let reply = read_all_available(&mut peer); + let mut expected = [0u8; 32]; + expected[..10].copy_from_slice(&[1, 1, 2, 0, 0, 0, 0, 0, 1, 0]); + assert_eq!(reply, expected); + assert!(crate::core_loop::xkb_select::xkb_initialized( + &state, + ClientId(1) + )); +} + +/// yserver's XKB request parsers and reply encoders are little-endian +/// only, so a big-endian client is refused the way Xorg refuses a +/// client it can't serve: XkbUseExtension answers supported=False +/// (the bytes are Xvfb's big-endian answer to an unsupported version, +/// `01000002 00000000 00010000 00…`), and every other XKB request is +/// then BadAccess, as Xorg answers an uninitialised client (Xvfb: +/// GetState → BadAccess, value 0, minor 4). All of it in the client's +/// byte order. +#[test] +fn xkb_refuses_big_endian_clients_cleanly() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + state.clients.get_mut(&1).unwrap().byte_order = ClientByteOrder::BigEndian; + // XKB request bodies are not swapped: wantedMajor=1, wantedMinor=0 + // as a big-endian client sends them. + handle_xkb_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(2), + RequestHeader { + opcode: 136, + data: 0, + length_units: 2, + }, + &[0, 1, 0, 0], + ) + .expect("XkbUseExtension"); + let reply = read_all_available(&mut peer); + let mut expected = [0u8; 32]; + expected[..10].copy_from_slice(&[1, 0, 0, 2, 0, 0, 0, 0, 0, 1]); + assert_eq!(reply, expected); + assert!(!crate::core_loop::xkb_select::xkb_initialized( + &state, + ClientId(1) + )); + handle_xkb_request( + &mut state, + &mut backend, + None, + ClientId(1), + SequenceNumber(3), + RequestHeader { + opcode: 136, + data: 4, + length_units: 2, + }, + &[1, 0, 0, 0], + ) + .expect("XkbGetState"); + let err = read_all_available(&mut peer); + assert_eq!(err.len(), 32); + assert_eq!((err[0], err[1]), (0, x11::error::BAD_ACCESS)); + assert_eq!(&err[2..4], &[0, 3], "big-endian sequence"); + assert_eq!(&err[8..10], &[0, 4], "big-endian minor opcode"); +} + +/// Golden (`xorg-xkb-setmap-errors.txt`, Xvfb 21.1.24: `access`, +/// `access-getmap`, `access-selectevents`): an XKB request from a client +/// that never called XkbUseExtension answers BadAccess (value 0, minor = +/// the request's), and changes nothing; after UseExtension the same +/// requests go through. +#[test] +fn xkb_requests_need_use_extension() { + let mut state = ServerState::new(); + let mut peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + let select_all = [0x00, 0x01, 0xff, 0x0f, 0, 0, 0xff, 0x0f, 0xff, 0, 0xff, 0]; + for (minor, body) in [ + (8u8, vec![0u8; 24]), + (1, select_all.to_vec()), + (9, vec![0; 32]), + ] { + xkb_request(&mut state, &mut backend, 1, minor, &body); + let err = read_all_available(&mut peer); + assert_eq!(err.len(), 32, "minor {minor}: one error"); + assert_eq!( + (err[0], err[1], &err[4..8], err[8], err[10]), + (0, x11::error::BAD_ACCESS, &[0u8, 0, 0, 0][..], minor, 136), + "minor {minor}" + ); + } + assert!( + state + .xkb_clients + .get(&1) + .is_none_or(|c| c.map_notify_mask == 0) + ); + xkb_request(&mut state, &mut backend, 1, 0, &[1, 0, 0, 0]); + assert!(crate::core_loop::xkb_select::xkb_initialized( + &state, + ClientId(1) + )); + let _ = read_all_available(&mut peer); + xkb_request(&mut state, &mut backend, 1, 1, &select_all); + assert!( + read_all_available(&mut peer).is_empty(), + "SelectEvents: no error" + ); + assert_eq!(state.xkb_clients[&1].map_notify_mask, 0xff); +} + +/// `ProcXkbUseExtension`: an unsupported version (2.0) leaves the client +/// uninitialised. +#[test] +fn xkb_use_extension_unsupported_version_stays_uninitialised() { + let mut state = ServerState::new(); + let _peer = install_client(&mut state, 1); + let mut backend = RecordingBackend::new(); + xkb_request(&mut state, &mut backend, 1, 0, &[2, 0, 0, 0]); + assert!(!crate::core_loop::xkb_select::xkb_initialized( + &state, + ClientId(1) + )); +} + +/// `XkbSendLegacyMapNotify` (xkb/xkbEvents.c): a MapNotify's core +/// MappingNotify goes to non-XKB clients and to XKB clients whose map +/// details include a change; a NewKeyboardNotify's only to non-XKB +/// clients. +#[test] +fn legacy_map_notify_filters_xkb_clients() { + use crate::core_loop::xkb_select::{ + LegacyCause, send_legacy_core_map_notify, xkb_select_events, + }; + let mut state = ServerState::new(); + let mut plain = install_client(&mut state, 1); + let mut xkb_keysyms = install_client(&mut state, 2); + let mut xkb_none = install_client(&mut state, 3); + xkb_select_events(&mut state, 2, 0x100, 0x0002); + xkb_select_events(&mut state, 3, 0x100, 0x0004); + let _ = send_legacy_core_map_notify(&mut state, LegacyCause::MapNotify, 0x0002, 8, 248); + let count = |b: Vec| b.chunks(32).filter(|e| e[0] == 34).count(); + assert_eq!(count(read_all_available(&mut plain)), 1); + assert_eq!(count(read_all_available(&mut xkb_keysyms)), 1); + assert_eq!(count(read_all_available(&mut xkb_none)), 0); + let _ = send_legacy_core_map_notify(&mut state, LegacyCause::NewKeyboardNotify, 0x0001, 8, 248); + assert_eq!( + count(read_all_available(&mut plain)), + 2, + "Keyboard + Modifier" + ); + assert_eq!(count(read_all_available(&mut xkb_keysyms)), 0); + assert_eq!(count(read_all_available(&mut xkb_none)), 0); +} + +/// XkbUseExtension, then SelectEvents for StateNotify with `details` only +/// (affectState = state = `details`, nothing else selected). +fn select_state_details( + state: &mut ServerState, + backend: &mut RecordingBackend, + client: u32, + details: u16, +) { + xkb_request(state, backend, client, 0, &[1, 0, 0, 0]); + let [lo, hi] = details.to_le_bytes(); + let body = [ + 0x00, 0x01, 0x04, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, lo, hi, lo, hi, + ]; + xkb_request(state, backend, client, 1, &body); +} + +/// LatchLockState body locking (affect, values) and nothing else. +fn lock_mods_body(affect: u8, values: u8) -> [u8; 12] { + [0x00, 0x01, affect, values, 0, 0, 0, 0, 0, 0, 0, 0] +} + +/// `XkbSendStateNotify`: a client gets the event only when its selected +/// StateNotify details intersect `changed`. Locking Mod2 changes ModifierLock +/// and ModifierState, so a GroupState-only selector stays silent; repeating +/// the request changes nothing and nobody hears about it. +#[test] +fn latch_lock_mods_state_notify_respects_selected_details() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut group_only = install_client(&mut state, 1); + let mut lock_only = install_client(&mut state, 2); + let mut all = install_client(&mut state, 3); + select_state_details(&mut state, &mut backend, 1, 0x0010); + select_state_details(&mut state, &mut backend, 2, 0x0008); + select_state_details(&mut state, &mut backend, 3, 0x3fff); + for peer in [&mut group_only, &mut lock_only, &mut all] { + let _ = read_all_available(peer); + } + // RecordingBackend has no XKB event base: StateNotify is code 0, xkbType 2. + let notifies = |b: Vec| b.chunks(32).filter(|e| e[0] == 0 && e[1] == 2).count(); + + xkb_request(&mut state, &mut backend, 3, 5, &lock_mods_body(0x10, 0x10)); + assert_eq!(backend.xkb_mods, (0x10, 0, 0, 0x10)); + assert_eq!(notifies(read_all_available(&mut group_only)), 0); + assert_eq!(notifies(read_all_available(&mut lock_only)), 1); + assert_eq!(notifies(read_all_available(&mut all)), 1); + + xkb_request(&mut state, &mut backend, 3, 5, &lock_mods_body(0x10, 0x10)); + assert_eq!(notifies(read_all_available(&mut group_only)), 0); + assert_eq!(notifies(read_all_available(&mut lock_only)), 0); + assert_eq!(notifies(read_all_available(&mut all)), 0); +} + +/// `ProcXkbLatchLockState` validates before applying: values outside the +/// affect mask are BadMatch (`_XkbErrCode2(0x01, bad bits)`), a wrong-size +/// request BadLength, and neither touches the modifier state. +#[test] +fn latch_lock_mods_rejects_invalid_requests_without_change() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + xkb_request(&mut state, &mut backend, 1, 0, &[1, 0, 0, 0]); + let _ = read_all_available(&mut peer); + + xkb_request(&mut state, &mut backend, 1, 5, &lock_mods_body(0x10, 0x11)); + let err = read_all_available(&mut peer); + assert_eq!( + (err[0], err[1], &err[4..8]), + (0, x11::error::BAD_MATCH, &[1u8, 0, 0, 1][..]) + ); + assert_eq!(backend.xkb_mods, (0, 0, 0, 0)); + + xkb_request( + &mut state, + &mut backend, + 1, + 5, + &lock_mods_body(0x10, 0x10)[..4], + ); + let err = read_all_available(&mut peer); + assert_eq!((err[0], err[1]), (0, x11::error::BAD_LENGTH)); + assert_eq!(backend.xkb_mods, (0, 0, 0, 0)); +} + +/// Xorg checks `REQUEST_SIZE_MATCH` before the XkbUseExtension check: a +/// short LatchLockState from an uninitialised client is BadLength, not +/// BadAccess. +#[test] +fn latch_lock_short_request_is_bad_length_before_bad_access() { + let mut state = ServerState::new(); + let mut backend = RecordingBackend::new(); + let mut peer = install_client(&mut state, 1); + xkb_request( + &mut state, + &mut backend, + 1, + 5, + &lock_mods_body(0x10, 0x10)[..4], + ); + let err = read_all_available(&mut peer); + assert_eq!((err[0], err[1], err[8]), (0, x11::error::BAD_LENGTH, 5)); + assert_eq!(backend.xkb_mods, (0, 0, 0, 0)); +} diff --git a/crates/yserver-core/src/core_loop/process_request/vidmode.rs b/crates/yserver-core/src/core_loop/process_request/vidmode.rs new file mode 100644 index 000000000..fd04e590e --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/vidmode.rs @@ -0,0 +1,670 @@ +use crate::{ + backend::{ + Backend, + gamma::{VIDMODE_GAMMA_ENTRIES, VidModeGammaTable}, + }, + core_loop::process_request::{ + CurrentVidModeOutput, RequestOutcome, emit_x11_error_with_minor, write_to_client, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, SequenceNumber}, +}; + +pub(super) fn current_vidmode_output(state: &ServerState) -> Option { + use yserver_protocol::x11::xf86vidmode::ModeLine; + + // Xwayland's VidMode shim uses its fixed output, or otherwise the first + // output. Yserver's configured primary is the closest equivalent; if it + // is off, fall back to the first enabled output. + let output = state + .randr + .outputs + .iter() + .find(|output| output.output_id == state.randr.primary_output && output.mode_id != 0) + .or_else(|| { + state + .randr + .outputs + .iter() + .find(|output| output.mode_id != 0) + })?; + + // Same resolved timing RANDR's ModeInfo reports, so the two extensions + // can never describe the same mode differently. VidMode carries the + // pixel clock in whole kHz rather than RANDR's Hz. + let timing = output.effective_timing(); + // A zero clock would make Mesa derive a zero MSC rate; Xorg's + // VidModeGetCurrentModeline fails the same way and yields BadValue. + if timing.dot_clock_hz == 0 { + return None; + } + Some(CurrentVidModeOutput { + output_id: output.output_id, + crtc_id: output.crtc_id, + connector: output.name.clone(), + mode: ModeLine { + dot_clock: timing.dot_clock_khz(), + hdisplay: output.width, + hsync_start: timing.hsync_start, + hsync_end: timing.hsync_end, + htotal: timing.htotal, + hskew: timing.hskew, + vdisplay: output.height, + vsync_start: timing.vsync_start, + vsync_end: timing.vsync_end, + vtotal: timing.vtotal, + flags: timing.mode_flags, + }, + }) +} + +#[cfg(test)] +pub(super) fn current_vidmode_mode_line( + state: &ServerState, +) -> Option { + current_vidmode_output(state).map(|output| output.mode) +} + +fn vidmode_timing_order_is_valid(mode: yserver_protocol::x11::xf86vidmode::ModeLine) -> bool { + mode.hdisplay <= mode.hsync_start + && mode.hsync_start <= mode.hsync_end + && mode.hsync_end <= mode.htotal + && mode.vdisplay <= mode.vsync_start + && mode.vsync_start <= mode.vsync_end + && mode.vsync_end <= mode.vtotal +} + +/// Derive VidMode's old monitor strings from the same raw EDID RANDR exposes. +/// A missing/invalid EDID leaves the vendor empty and uses the connector name +/// as the model, which is more useful than inventing an identity. +pub(super) fn vidmode_monitor_identity(edid: &[u8], connector: &str) -> (Vec, Vec) { + let vendor = edid + .get(8..10) + .and_then(|bytes| { + let code = u16::from_be_bytes(bytes.try_into().ok()?); + let letters = [ + u8::try_from((code >> 10) & 0x1f).ok()?, + u8::try_from((code >> 5) & 0x1f).ok()?, + u8::try_from(code & 0x1f).ok()?, + ]; + letters + .iter() + .all(|letter| (1..=26).contains(letter)) + .then(|| { + letters + .into_iter() + .map(|letter| b'A' + letter - 1) + .collect() + }) + }) + .unwrap_or_default(); + + let model = [54usize, 72, 90, 108] + .into_iter() + .filter_map(|offset| edid.get(offset..offset + 18)) + .find_map(|descriptor| { + if descriptor.get(..5) != Some(&[0, 0, 0, 0xfc, 0]) { + return None; + } + let name = descriptor.get(5..18)?; + let end = name + .iter() + .rposition(|byte| !matches!(byte, 0 | b'\n' | b'\r' | b' ')) + .map_or(0, |index| index + 1); + (end != 0 + && name[..end] + .iter() + .all(|byte| byte.is_ascii_graphic() || *byte == b' ')) + .then(|| name[..end].to_vec()) + }) + .unwrap_or_else(|| connector.as_bytes().to_vec()); + (vendor, model) +} + +fn vidmode_sync_ranges(mode: yserver_protocol::x11::xf86vidmode::ModeLine) -> ([u32; 1], [u32; 1]) { + fn rounded_hundredths(numerator: u64, denominator: u64) -> u16 { + if denominator == 0 { + return 0; + } + let value = numerator.saturating_add(denominator / 2) / denominator; + u16::try_from(value).unwrap_or(u16::MAX) + } + fn singleton_range(value: u16) -> u32 { + u32::from(value) | (u32::from(value) << 16) + } + + // Horizontal range is kHz * 100. Vertical range is Hz * 100. + let hsync = rounded_hundredths( + u64::from(mode.dot_clock).saturating_mul(100), + u64::from(mode.htotal), + ); + let vsync = rounded_hundredths( + u64::from(mode.dot_clock).saturating_mul(100_000), + u64::from(mode.htotal).saturating_mul(u64::from(mode.vtotal)), + ); + ([singleton_range(hsync)], [singleton_range(vsync)]) +} + +/// Validate the `screen(u16) + pad(u16)` body shared by VidMode's +/// read-only requests. `Err` carries `(error code, errorValue)`. +/// +/// Xorg checks `screen >= screenInfo.numScreens => BadValue`; yserver +/// drives exactly one X screen, so anything but 0 is out of range. +fn vidmode_screen_number(screen: u32) -> Result<(), (u8, u32)> { + if screen != 0 { + return Err((x11::error::BAD_VALUE, screen)); + } + Ok(()) +} + +fn vidmode_screen(body: &[u8]) -> Result<(), (u8, u32)> { + let screen = yserver_protocol::x11::xf86vidmode::parse_screen(body) + .ok_or((x11::error::BAD_LENGTH, 0))?; + vidmode_screen_number(u32::from(screen)) +} + +fn write_vidmode_reply( + state: &mut ServerState, + client_id: ClientId, + reply: &[u8], +) -> io::Result { + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, reply)) +} + +pub(super) fn handle_xf86vidmode_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use crate::nested::{XF86VIDMODE_FIRST_ERROR, XF86VIDMODE_MAJOR_OPCODE}; + use yserver_protocol::x11::{ClientByteOrder, xf86vidmode as x11vm}; + + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |client| client.byte_order); + let is_local = state + .clients + .get(&client_id.0) + .is_none_or(|client| client.is_local); + let version_2 = state + .vidmode_client_versions + .get(&client_id) + .is_some_and(|(major, _)| *major >= 2); + + match header.data { + x11vm::QUERY_VERSION => { + if !body.is_empty() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + let reply = x11vm::encode_query_version_reply(byte_order, sequence); + return write_vidmode_reply(state, client_id, &reply); + } + x11vm::SET_CLIENT_VERSION => { + let Some(version) = x11vm::parse_client_version(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + state + .vidmode_client_versions + .insert(client_id, (version.major, version.minor)); + debug!( + "client {} #{} XFree86-VidMode::SetClientVersion {}.{}", + client_id.0, sequence.0, version.major, version.minor + ); + } + x11vm::VALIDATE_MODE_LINE => { + let Some(request) = + x11vm::parse_validate_mode_line_request(byte_order, body, version_2) + else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + if let Err((code, bad_value)) = vidmode_screen_number(request.screen) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + let Some(current) = current_vidmode_output(state) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + + // Xorg rejects inverted timing order before invoking the monitor + // and driver validators. Yserver exposes only the active mode, so + // that exact advertised line is the only one its read-only + // VidMode surface can truthfully validate. Legacy clients cannot + // carry hskew, matching the legacy GetModeLine reply. + let mut advertised = current.mode; + if !version_2 { + advertised.hskew = 0; + } + let status = + if vidmode_timing_order_is_valid(request.mode) && request.mode == advertised { + x11vm::MODE_OK + } else { + x11vm::MODE_BAD + }; + let reply = x11vm::encode_validate_mode_line_reply(byte_order, sequence, status); + return write_vidmode_reply(state, client_id, &reply); + } + x11vm::GET_GAMMA => { + let Some(screen) = x11vm::parse_gamma_screen(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + if let Err((code, bad_value)) = vidmode_screen_number(u32::from(screen)) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + let gamma = state.vidmode_gamma.map(vidmode_gamma_to_wire); + let reply = x11vm::encode_get_gamma_reply(byte_order, sequence, gamma); + return write_vidmode_reply(state, client_id, &reply); + } + x11vm::GET_GAMMA_RAMP => { + let Some(request) = x11vm::parse_gamma_ramp_request(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + if let Err((code, bad_value)) = vidmode_screen_number(u32::from(request.screen)) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + let Some(current) = current_vidmode_output(state) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + let expected = vidmode_gamma_ramp_size(backend, current.crtc_id); + if request.size != expected { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(request.size), + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + // xf86GetGammaRamp: the VidMode table, not a CRTC's RANDR ramp. + let (red, green, blue) = if expected == 0 { + (Vec::new(), Vec::new(), Vec::new()) + } else { + state + .vidmode_gamma_table + .clone() + .unwrap_or_else(VidModeGammaTable::identity) + .ramp() + }; + let reply = + x11vm::encode_get_gamma_ramp_reply(byte_order, sequence, &red, &green, &blue); + return write_vidmode_reply(state, client_id, &reply); + } + // The ordinary read-only screen-scoped requests all carry + // `screen(u16) + pad(u16)`. + x11vm::GET_MODE_LINE + | x11vm::GET_MONITOR + | x11vm::GET_ALL_MODE_LINES + | x11vm::GET_VIEW_PORT + | x11vm::GET_DOT_CLOCKS + | x11vm::GET_GAMMA_RAMP_SIZE + | x11vm::GET_PERMISSIONS => { + if let Err((code, bad_value)) = vidmode_screen(body) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + let reply = match header.data { + x11vm::GET_PERMISSIONS => { + x11vm::encode_get_permissions_reply(byte_order, sequence, is_local) + } + x11vm::GET_VIEW_PORT => { + x11vm::encode_get_view_port_reply(byte_order, sequence, 0, 0) + } + x11vm::GET_DOT_CLOCKS => x11vm::encode_get_dot_clocks_reply(byte_order, sequence), + _ => { + let Some(current) = current_vidmode_output(state) else { + // Xorg: VidModeGetCurrentModeline failure => BadValue. + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + }; + match header.data { + x11vm::GET_GAMMA_RAMP_SIZE => x11vm::encode_get_gamma_ramp_size_reply( + byte_order, + sequence, + vidmode_gamma_ramp_size(backend, current.crtc_id), + ), + x11vm::GET_MONITOR => { + let edid = backend + .output_identity(current.output_id) + .map_or_else(Vec::new, |(edid, _)| edid); + let (vendor, model) = + vidmode_monitor_identity(&edid, ¤t.connector); + let (hsync, vsync) = vidmode_sync_ranges(current.mode); + x11vm::encode_get_monitor_reply( + byte_order, sequence, &vendor, &model, &hsync, &vsync, + ) + } + x11vm::GET_MODE_LINE | x11vm::GET_ALL_MODE_LINES => { + debug!( + "client {} #{} XFree86-VidMode::{} \ + {}x{} clock={}kHz totals={}x{} flags=0x{:x}", + client_id.0, + sequence.0, + if header.data == x11vm::GET_MODE_LINE { + "GetModeLine" + } else { + "GetAllModeLines" + }, + current.mode.hdisplay, + current.mode.vdisplay, + current.mode.dot_clock, + current.mode.htotal, + current.mode.vtotal, + current.mode.flags + ); + if header.data == x11vm::GET_MODE_LINE { + x11vm::encode_get_mode_line_reply( + byte_order, + sequence, + current.mode, + version_2, + ) + } else { + x11vm::encode_get_all_mode_lines_reply( + byte_order, + sequence, + current.mode, + version_2, + ) + } + } + _ => unreachable!("screen-scoped VidMode read"), + } + } + }; + return write_vidmode_reply(state, client_id, &reply); + } + // A local client, told it may write (GetPermissions), has its gamma + // and lock writes applied as Xorg applies them. + x11vm::SET_GAMMA | x11vm::SET_GAMMA_RAMP | x11vm::LOCK_MODE_SWITCH if is_local => { + return handle_vidmode_local_write( + state, + backend, + client_id, + sequence, + header.data, + body, + ); + } + // Mode setting stays RANDR's, so it fails with the extension's + // ClientNotLocal error even for a local client; so does every write + // from a remote one, as in Xorg's dispatch. + x11vm::MOD_MODE_LINE + | x11vm::SWITCH_MODE + | x11vm::LOCK_MODE_SWITCH + | x11vm::ADD_MODE_LINE + | x11vm::DELETE_MODE_LINE + | x11vm::SWITCH_TO_MODE + | x11vm::SET_VIEW_PORT + | x11vm::SET_GAMMA + | x11vm::SET_GAMMA_RAMP => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XF86VIDMODE_FIRST_ERROR + x11vm::CLIENT_NOT_LOCAL, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(header.data), + XF86VIDMODE_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// A `SetGamma` value as Xorg holds it: `((float) value) / 10000.`, a +/// double narrowed to the float `SetGamma` takes. +fn vidmode_gamma_from_wire(value: u32) -> f32 { + #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)] + let gamma = (f64::from(value as f32) / 10_000.0) as f32; + gamma +} + +/// `GetGamma`'s `(CARD32) (gamma * 10000.)`, truncated. +fn vidmode_gamma_to_wire(gamma: f32) -> u32 { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let value = (f64::from(gamma) * 10_000.0) as u32; + value +} + +/// VidMode's gamma ramp size, as modesetting reports it: the CMap table's +/// `gammaElements`, whatever the hardware LUT's size; 0 when the CRTC has +/// no gamma, so a backend without gamma advertises no ramp. +fn vidmode_gamma_ramp_size(backend: &dyn Backend, crtc: u32) -> u16 { + if backend.crtc_gamma_size(crtc) == 0 { + 0 + } else { + VIDMODE_GAMMA_ENTRIES + } +} + +/// Make `table` the screen's VidMode gamma and hand it to the backend, +/// which loads it under every CRTC's RANDR ramp. +fn install_vidmode_gamma_table( + state: &mut ServerState, + backend: &mut dyn Backend, + table: VidModeGammaTable, +) { + if let Err(e) = backend.set_vidmode_gamma(Some(&table)) { + log::warn!("XF86VidMode gamma apply failed: {e}"); + } + state.vidmode_gamma_table = Some(table); +} + +/// Rebuild the screen's VidMode gamma table after a server reset, from +/// the gamma values the new generation carried over, and hand it to the +/// backend. Xorg keeps `pScrn->gamma` across regeneration (set once in +/// PreInit by `xf86SetGamma`) and `xf86HandleColormaps` rebuilds the CMap +/// table from it in ScreenInit, so a ramp set only by `SetGammaRamp` falls +/// back to the gamma curve, and gamma 1.0 leaves the RANDR ramps alone. +pub(crate) fn reinstall_vidmode_gamma(state: &mut ServerState, backend: &mut dyn Backend) { + #[allow(clippy::float_cmp)] + let table = (state.vidmode_gamma != [1.0; 3]) + .then(|| VidModeGammaTable::from_gamma(state.vidmode_gamma)); + if let Err(e) = backend.set_vidmode_gamma(table.as_ref()) { + log::warn!("XF86VidMode gamma reapply after reset failed: {e}"); + } + state.vidmode_gamma_table = table; +} + +/// A local client's `SetGamma`, `SetGammaRamp` and `LockModeSwitch`, as +/// Xorg's modesetting server answers them: Xext/vidmode.c's checks, then +/// hw/xfree86's `CMapChangeGamma` (`ComputeGamma`) for the gamma, +/// `xf86ChangeGammaRamp` (`ComputeGammaRamp`) for the ramp, both loaded +/// through `xf86RandR12LoadPalette` under every CRTC's RANDR ramp, and +/// `xf86VidModeLockZoom` for the lock. +fn handle_vidmode_local_write( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + minor: u8, + body: &[u8], +) -> io::Result { + use crate::nested::XF86VIDMODE_MAJOR_OPCODE; + use yserver_protocol::x11::xf86vidmode as x11vm; + + let error = |state: &mut ServerState, code: u8, bad_value: u32| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + u16::from(minor), + XF86VIDMODE_MAJOR_OPCODE, + ) + }; + match minor { + x11vm::LOCK_MODE_SWITCH => { + let Some(screen) = x11vm::parse_lock_mode_switch_screen(body) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if let Err((code, bad_value)) = vidmode_screen_number(u32::from(screen)) { + return error(state, code, bad_value); + } + // xf86VidModeLockZoom fails only under the DontZoom option, + // which yserver has no counterpart of. + } + x11vm::SET_GAMMA => { + let Some(request) = x11vm::parse_set_gamma(body) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if let Err((code, bad_value)) = vidmode_screen_number(u32::from(request.screen)) { + return error(state, code, bad_value); + } + let gamma = [request.red, request.green, request.blue].map(vidmode_gamma_from_wire); + // CMapChangeGamma: each within [GAMMA_MIN, GAMMA_MAX], 1/10 to 10. + if gamma + .iter() + .any(|&g| f64::from(g) < 1.0 / 10.0 || f64::from(g) > 10.0) + { + return error(state, x11::error::BAD_VALUE, 0); + } + state.vidmode_gamma = gamma; + install_vidmode_gamma_table(state, backend, VidModeGammaTable::from_gamma(gamma)); + } + x11vm::SET_GAMMA_RAMP => { + let Some(request) = x11vm::parse_set_gamma_ramp_header(body) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if let Err((code, bad_value)) = vidmode_screen_number(u32::from(request.screen)) { + return error(state, code, bad_value); + } + let Some(current) = current_vidmode_output(state) else { + return error(state, x11::error::BAD_VALUE, 0); + }; + // The size GetGammaRampSize reports, then exactly that ramp. + // It replaces the table; GetGamma's values stay as they were. + let size = vidmode_gamma_ramp_size(backend, current.crtc_id); + if request.size != size { + return error(state, x11::error::BAD_VALUE, u32::from(request.size)); + } + let Some((red, green, blue)) = x11vm::parse_set_gamma_ramp_channels(body, size) else { + return error(state, x11::error::BAD_LENGTH, 0); + }; + if size > 0 { + let table = VidModeGammaTable::from_ramp(&red, &green, &blue); + install_vidmode_gamma_table(state, backend, table); + } + } + _ => unreachable!("not a VidMode gamma or lock write"), + } + Ok(RequestOutcome::Handled) +} diff --git a/crates/yserver-core/src/core_loop/process_request/window_destroy.rs b/crates/yserver-core/src/core_loop/process_request/window_destroy.rs new file mode 100644 index 000000000..48ba81210 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/window_destroy.rs @@ -0,0 +1,319 @@ +//! The window-destroy executor: Xorg `DeleteWindow` (`dix/window.c:1070`) +//! over one [`PreparedDestroy`], every side effect in Xorg's order. + +use std::{collections::HashSet, io}; + +use yserver_protocol::x11::{self, ClientId, ResourceId, xfixes::SELECTION_NOTIFY_WINDOW_DESTROY}; + +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::{fanout_event_to_clients, subscribers_by_id}, + process_request::{ + focus_pointer::revert_core_focus_from, + grabs::{deactivate_core_keyboard_grab, deactivate_core_pointer_grab}, + present_ext::fire_present_window_destroyed, + selection::drop_selections_owned_by_windows, + windows::{ + free_pictures_on_destroyed_windows, purge_present_for_destroyed_windows, + release_dropped_cursors, release_redirects_on_destroyed_windows, + release_xi1_active_grab, send_exposures, + }, + xi::deactivate_xi2_device_grab, + }, + }, + resources::{COMPOSITE_OVERLAY_WINDOW, MapState, PreparedDestroy, ROOT_WINDOW}, + server::ServerState, +}; + +/// What one executed plan destroyed, for the caller's cleanup that is not +/// window-scoped. +pub(crate) struct DestroyOutcome { + /// Exactly the plan's windows, CrushTree order. + pub windows: Vec, + /// Background/border host pixmaps the destroyed windows held; candidates + /// for the orphan gate, not yet freed. + pub attr_pixmaps: Vec, +} + +/// One planned window as it was before the teardown began. +struct Captured { + window: ResourceId, + parent: ResourceId, + host_xid: Option, + on_window: Vec, + on_parent: Vec, +} + +/// Run one prepared destroy plan to completion. +pub(crate) fn execute_destroy( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + prepared: PreparedDestroy, +) -> DestroyOutcome { + let plan = prepared.plan(); + let windows: Vec = plan.windows().collect(); + let top = plan.top(); + + // 1. Capture, while the tree is intact. + let captured: Vec = windows + .iter() + .map(|&window| { + let (parent, host_xid) = state + .resources + .window(window) + .map_or((ROOT_WINDOW, None), |w| (w.parent, w.host_xid)); + Captured { + window, + parent, + host_xid, + on_window: subscribers_by_id(state, window, 0x0002_0000), + on_parent: subscribers_by_id(state, parent, 0x0008_0000), + } + }) + .collect(); + let top_map_state = state + .resources + .window(top) + .map_or(MapState::Unmapped, |w| w.map_state); + // `ProcDestroyWindow`'s `FreeResource(id, RT_NONE)` frees the newer + // resources on the top's id first (`dix/resource.c:907`, `:829-833`): its + // XFIXES selection inputs go before `DeleteWindow` runs. + drop_xfixes_selection_inputs_on(state, top); + + // 2-4. `UnmapWindow(T, FALSE)` (`dix/window.c:2844-2875`). + let mut unrealized: HashSet = HashSet::new(); + if top_map_state != MapState::Unmapped { + let top_entry = captured.last().expect("a plan has its top window"); + let parent = top_entry.parent; + let _dropped = fanout_event_to_clients(state, &top_entry.on_window, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, top, top, false); + }); + let _dropped = fanout_event_to_clients(state, &top_entry.on_parent, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, parent, top, false); + }); + let realized = top_map_state == MapState::Viewable; + let clips_before = if realized { + crate::core_loop::clip_list::clip_entries_under(state, top) + } else { + Vec::new() + }; + if realized { + // `UnrealizeTree` (`:2780-2820`). + for w in unrealize_tree_order(state, top) { + delete_window_from_any_events(state, backend, origin, w, &windows, top); + unrealized.insert(w); + } + } + let _ = state.resources.unmap_window(top); + if realized { + // HandleExposures, then WindowsRestructured (`:2864-2872`). + let after = crate::core_loop::clip_list::clip_entries_under(state, top); + send_exposures( + state, + backend, + origin, + crate::core_loop::clip_list::newly_exposed(&clips_before, after, None), + None, + ); + backend.windows_restructured(state); + } + } + + // 5. `CrushTree`, then the top (`:1023-1086`): DestroyNotify, then + // `FreeWindowResources` (`:994-1018`). + for entry in &captured { + let (window, parent) = (entry.window, entry.parent); + let _dropped = fanout_event_to_clients(state, &entry.on_window, |buf, seq, order| { + x11::encode_destroy_notify_event(buf, seq, order, window, window); + }); + let _dropped = fanout_event_to_clients(state, &entry.on_parent, |buf, seq, order| { + x11::encode_destroy_notify_event(buf, seq, order, parent, window); + }); + // CrushTree's `FreeResource(id, RT_WINDOW)` (`:1043`) frees the + // inferior's other same-id resources before `FreeWindowResources`. + drop_xfixes_selection_inputs_on(state, window); + // `DeleteWindowFromAnySaveSet`, `DeleteWindowFromAnySelections`. + for client in state.clients.values_mut() { + client.save_set.remove(&window); + } + drop_selections_owned_by_windows(state, &[window], SELECTION_NOTIFY_WINDOW_DESTROY); + crate::rootless::selection::forget_window(state, window); + // `DeleteWindowFromAnyEvents(w, TRUE)` (`dix/events.c:5905-6002`). + if !unrealized.contains(&window) { + delete_window_from_any_events(state, backend, origin, window, &windows, top); + } + state.button_grabs.retain(|g| g.grab_window != window); + state.key_grabs.retain(|g| g.grab_window != window); + state.xi1_passive_grabs.retain(|g| g.grab_window != window); + state.drop_window_subscriptions(&[window]); + // `(*pScreen->DestroyWindow)` (`dix/window.c:1018`): `present_destroy_window` + // (`present/present_screen.c:89-120`) sends PresentWindowDestroyed, + // then frees the window's selections. The purge can trigger idle + // fences, and a fired SYNC await sends CounterNotify. + fire_present_window_destroyed(state, window); + purge_present_for_destroyed_windows(state, backend, &[window]); + } + + // 6. Resource-level cleanup; nothing here reaches the wire. + free_pictures_on_destroyed_windows(state, backend, origin, &windows); + release_redirects_on_destroyed_windows(state, backend, origin, &windows); + let attr_pixmaps = state.resources.collect_attribute_pixmap_host_xids(top); + state.resources.apply_destroy(plan); + if plan.contains_cow() { + state.destroy_cow_input_shape(); + } + for entry in &captured { + // CrushTree order puts the COW's children first, so they are torn + // down while the backend COW still exists. + if entry.window == COMPOSITE_OVERLAY_WINDOW && prepared.retires_overlay() { + if let Some(xid) = entry.host_xid { + backend.unregister_host_window(xid.as_raw()); + } + backend.retire_overlay_window(origin); + continue; + } + if let Some(xid) = entry.host_xid { + backend.unregister_host_window(xid.as_raw()); + let _ = backend.update_host_event_mask( + origin, + xid.as_raw(), + crate::host_x11::POINTER_EVENT_MASK, + false, + ); + let _ = backend.update_host_event_mask( + origin, + xid.as_raw(), + crate::host_x11::SUBWINDOW_EVENT_MASK, + false, + ); + let _ = backend.destroy_subwindow(origin, xid.as_raw()); + } + } + backend.sync_top_level_order(state); + release_dropped_cursors(state, backend, origin); + DestroyOutcome { + windows, + attr_pixmaps, + } +} + +/// Plan, prepare and execute the destroy of `window`, then free its orphaned +/// attribute pixmaps. Root and unknown ids are a no-op. `Err`: preparation +/// failed and nothing changed. +pub(crate) fn destroy_window_subtree( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, +) -> io::Result<()> { + let Some(plan) = state.resources.plan_destroy(window) else { + return Ok(()); + }; + let prepared = plan.prepare(backend)?; + finish_destroy(state, backend, origin, prepared); + Ok(()) +} + +/// Execute an explicit destroy and free its orphaned attribute pixmaps. +pub(super) fn finish_destroy( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + prepared: PreparedDestroy, +) { + let outcome = execute_destroy(state, backend, origin, prepared); + crate::core_loop::process_disconnect::free_orphaned_host_pixmaps( + state, + backend, + outcome.attr_pixmaps, + &[], + None, + ); +} + +/// The realized windows of `top`'s subtree in `UnrealizeTree` order +/// (`dix/window.c:2780-2820`): `top` first, then depth-first, topmost child +/// first, descending only into realized windows. +fn unrealize_tree_order(state: &ServerState, top: ResourceId) -> Vec { + fn walk(state: &ServerState, w: ResourceId, out: &mut Vec) { + let Some(win) = state.resources.window(w) else { + return; + }; + if win.map_state != MapState::Viewable { + return; + } + out.push(w); + for child in win.children.iter().rev() { + walk(state, *child, out); + } + } + let mut out = Vec::new(); + walk(state, top, &mut out); + out +} + +/// The input half of `DeleteWindowFromAnyEvents(w, …)` (`dix/events.c:5905-5985`, +/// `Xi/exevents.c:3027-3100`): every device's active grab on `w` (window or +/// confine-to), whoever owns it, deactivates; then every keyboard focus on +/// `w` reverts. `dying` is the whole plan, `dying_root` its top. +fn delete_window_from_any_events( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + w: ResourceId, + dying: &[ResourceId], + dying_root: ResourceId, +) { + if let Some(grab) = state.active_pointer_grab + && (grab.grab_window == w || state.pointer_confine_to == w) + { + deactivate_core_pointer_grab(state, backend, grab.owner); + } + if let Some(grab) = state.active_keyboard_grab + && grab.grab_window == w + { + deactivate_core_keyboard_grab(state, grab.owner); + } + let mut pointer_grabs: Vec<(u16, ClientId)> = state + .xi2_pointer_grabs + .iter() + .filter(|(_, g)| g.grab_window == w) + .map(|(dev, g)| (*dev, g.owner)) + .collect(); + pointer_grabs.sort_unstable_by_key(|(dev, _)| *dev); + for (dev, owner) in pointer_grabs { + deactivate_xi2_device_grab(state, backend, origin, owner, dev, false, false); + } + let mut keyboard_grabs: Vec<(u16, ClientId)> = state + .xi2_keyboard_grabs + .iter() + .filter(|(_, g)| g.grab_window == w) + .map(|(dev, g)| (*dev, g.owner)) + .collect(); + keyboard_grabs.sort_unstable_by_key(|(dev, _)| *dev); + for (dev, owner) in keyboard_grabs { + deactivate_xi2_device_grab(state, backend, origin, owner, dev, true, false); + } + let mut xi1_grabs: Vec = state + .xi1_active_grabs + .iter() + .filter(|(_, g)| g.grab_window == w) + .map(|(dev, _)| *dev) + .collect(); + xi1_grabs.sort_unstable(); + for dev in xi1_grabs { + release_xi1_active_grab(state, backend, dev); + } + revert_core_focus_from(state, w, dying); + crate::core_loop::xi1_focus::revert_focus_on_dying_window(state, w, dying_root); +} + +/// Every client's XFIXES SelectSelectionInput on `window` (Xorg +/// `SelectionFreeWindow`, `xfixes/select.c:244`). +fn drop_xfixes_selection_inputs_on(state: &mut ServerState, window: ResourceId) { + state + .xfixes_selection_masks + .retain(|(_, w, _), _| *w != window); +} diff --git a/crates/yserver-core/src/core_loop/process_request/windows.rs b/crates/yserver-core/src/core_loop/process_request/windows.rs new file mode 100644 index 000000000..9ddb623ff --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/windows.rs @@ -0,0 +1,3629 @@ +use crate::{ + access::{AccessMode, Creation, RequestOpcodes, ResourceKind, ResourceTarget}, + backend::{Backend, OriginContext}, + core_loop::{ + damage_fanout::{ + accumulate_damage_border_to_state, accumulate_damage_full_to_state, + accumulate_damage_region_to_state, + }, + fanout::{ + emit_visibility_unobscured_subtree_to_state, emit_window_event_to_state, + fanout_event_to_clients, subscribers_by_id, + }, + process_request::{ + RequestOutcome, emit_x11_error, + focus_pointer::revert_core_focus_if_unviewable, + glx::glx_fbconfig_depth, + grabs::{confine_pointer_now, release_core_grabs_for_unviewable}, + present_ext::{discard_stale_present_event, fire_present_configure_notify_for_window}, + redirect::{ + BackingDamage, apply_viewability_delta_to_redirects, + effective_redirect_mode_for_window, finish_redirected_backing_rotate, + has_redirected_ancestor, realize_storage_for_delta, + reapply_redirect_mode_after_map, release_storage_for_delta, + rotate_redirected_backing_on_resize, sync_redirect_backing, + }, + window_destroy::finish_destroy, + write_to_client, + }, + }, + resources::{ + BorderSource, COMPOSITE_OVERLAY_WINDOW, MapState, Pixmap, ROOT_WINDOW, ViewabilityDelta, + Window, + }, + server::ServerState, +}; +use log::debug; +use std::{collections::HashSet, io}; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +fn resolve_host_subwindow_visual_to_state( + state: &ServerState, + window: ResourceId, +) -> crate::host_x11::HostSubwindowVisual { + use crate::host_x11::HostSubwindowVisual; + let Some(window) = state.resources.window(window) else { + return HostSubwindowVisual::CopyFromParent; + }; + if window.visual == crate::resources::ROOT_VISUAL { + return HostSubwindowVisual::CopyFromParent; + } + let Some(visual) = state.resources.visual(window.visual) else { + return HostSubwindowVisual::CopyFromParent; + }; + let Some(visual_xid) = visual.host_visual_xid else { + return HostSubwindowVisual::DepthOnly { + depth: window.depth, + }; + }; + let Some(colormap) = state.resources.colormap_for_visual(window.visual) else { + return HostSubwindowVisual::DepthOnly { + depth: window.depth, + }; + }; + let Some(colormap_xid) = colormap.host_colormap_xid else { + return HostSubwindowVisual::DepthOnly { + depth: window.depth, + }; + }; + HostSubwindowVisual::Explicit { + depth: visual.depth, + visual_xid: visual_xid.as_raw(), + colormap_xid: colormap_xid.as_raw(), + } +} + +/// Xorg's `miWindowExposures` (`mi/miexpose.c:375-410`) for `region` of +/// `window` (its content space): its background over the region when +/// `paint` (unless None or inhibited, `miPaintWindow`), and Expose events +/// to the clients that selected them, one per rect with the count still +/// to follow, or the extents alone past `RECTLIMIT` rects. +pub(crate) fn send_window_exposures( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + region: &[x11::xfixes::RegionRect], + paint: bool, +) { + if region.is_empty() { + return; + } + if paint { + let _ = paint_window_background(state, backend, origin, window, region); + } + if subscribers_by_id(state, window, 0x0000_8000).is_empty() { + return; + } + let extents; + let events = if region.len() > crate::core_loop::clip_list::RECTLIMIT { + extents = [crate::nested::region_extents(region)]; + &extents[..] + } else { + region + }; + let last = events.len() - 1; + for (i, r) in events.iter().enumerate() { + let count = u16::try_from(last - i).unwrap_or(u16::MAX); + let r = *r; + let _dropped = emit_window_event_to_state(state, window, 0x0000_8000, |buf, seq, order| { + x11::encode_expose_event( + buf, + seq, + order, + window, + u16::try_from(r.x).unwrap_or(0), + u16::try_from(r.y).unwrap_or(0), + r.width, + r.height, + count, + ); + }); + } +} + +/// `miHandleValidateExposures` (`mi/miwindow.c:211-240`): per window, its +/// exposed border painted (`PW_BORDER`), then `miWindowExposures`. The +/// border of `skip_border` is left alone. +pub(crate) fn send_exposures( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + exposures: Vec, + skip_border: Option, +) { + for e in exposures { + if Some(e.window) != skip_border { + paint_window_border_region(state, backend, origin, e.window, &e.border); + } + send_window_exposures(state, backend, origin, e.window, &e.region, true); + } +} + +/// `miPaintWindow(PW_BORDER)` over `region` of `window`'s border (its +/// content space), and its DAMAGE. Nothing at `bw == 0`. +pub(crate) fn paint_window_border_region( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + region: &[x11::xfixes::RegionRect], +) { + if region.is_empty() { + return; + } + let Some(host) = state + .resources + .window(window) + .filter(|w| w.border_width > 0) + .and_then(|w| w.host_xid) + else { + return; + }; + if backend + .paint_window_border_rects(origin, host.as_raw(), region) + .is_ok() + { + let _dropped = accumulate_damage_region_to_state(state, window, region); + } +} + +/// Xorg's `miPaintWindow(PW_BACKGROUND)` (`mi/miexpose.c:398-436`) over +/// `region` of `window` (its content space, already clipped): nothing when +/// the background resolves to None or is inhibited, else the fill and its +/// DAMAGE. A failed fill stops the paint; only the rects already filled are +/// damaged. +pub(crate) fn paint_window_background( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + region: &[x11::xfixes::RegionRect], +) -> io::Result<()> { + if region.is_empty() { + return Ok(()); + } + let Some(bg) = state.resources.window_resolved_background(window) else { + return Ok(()); + }; + if background_paint_inhibited(state, window) { + return Ok(()); + } + let Some(host) = state + .resources + .host_drawable_target(window) + .map(|t| t.host_xid()) + else { + return Ok(()); + }; + let mut result = Ok(()); + let mut painted = 0; + for r in region { + result = backend.clear_area( + origin, + host, + bg.background_pixel, + bg.background_pixmap_host_xid.map(|h| h.as_raw()), + r.x, + r.y, + r.width, + r.height, + bg.tile_origin_offset, + ); + if result.is_err() { + break; + } + painted += 1; + } + let _dropped = accumulate_damage_region_to_state(state, window, ®ion[..painted]); + result +} + +/// The Expose events of windows becoming viewable: each of `tops`, then +/// its inferiors, a window before its children and children top-most +/// first, each for its whole clip list (`miHandleValidateExposures`, +/// `mi/miwindow.c`, after `miComputeClips` gives a newly viewable window +/// its clip list as exposed). Their borders and backgrounds are painted on +/// realize; the DAMAGE for those paints goes out here, after the caller's +/// MapNotify: each window's border ring, then its background over the clip +/// list unless None or inhibited (`miPaintWindow`, `mi/miexpose.c`). +fn send_map_exposures( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + tops: &[ResourceId], +) { + for (w, region) in crate::core_loop::clip_list::subtrees_clip_lists(state, tops) { + let _dropped = accumulate_damage_border_to_state(state, w); + if state.resources.window_resolved_background(w).is_some() + && !background_paint_inhibited(state, w) + { + let _dropped = accumulate_damage_region_to_state(state, w, ®ion); + } + send_window_exposures(state, backend, origin, w, ®ion, false); + } +} + +/// Xorg `inhibitBGPaint`: the window whose background `window` paints with +/// (itself, or the ancestor its ParentRelative chain resolves to) has a +/// Manual `RedirectSubwindows`, so `miPaintWindow` skips the background +/// (`composite/compalloc.c:411`, `mi/miexpose.c:435`). +pub(crate) fn background_paint_inhibited(state: &ServerState, window: ResourceId) -> bool { + let mut current = window; + while let Some(w) = state.resources.window(current) { + let parent_relative = matches!(w.background_pixmap, Some(bg) if bg.0 == 1); + if !parent_relative || w.parent == current { + break; + } + current = w.parent; + } + state.composite_redirects.subwindows_mode(current) + == Some(crate::server::CompositeRedirectMode::Manual) +} + +/// Of `parents`, those on which `owner` holds the Manual +/// `RedirectSubwindows`, each with its clip list taken while its children +/// are still Manual and so transparent: Xorg's `compFreeClientSubwindows` +/// clears the background before it unredirects them +/// (`composite/compalloc.c:436-455`). +pub(crate) fn manual_subwindows_release_regions( + state: &ServerState, + owner: ClientId, + parents: &[ResourceId], +) -> Vec<(ResourceId, Vec)> { + parents + .iter() + .filter(|p| { + state + .composite_redirects + .subwindows_records(**p) + .iter() + .any(|r| r.owner == owner && r.mode == crate::server::CompositeRedirectMode::Manual) + }) + .map(|p| (*p, crate::core_loop::clip_list::clip_list(state, *p))) + .collect() +} + +/// Once the Manual records of [`manual_subwindows_release_regions`] are +/// gone: `ClearToBackground(pWin, 0, 0, 0, 0, TRUE)`, the background over +/// the clip list and Expose events for it (`mi/miwindow.c:63-117`). +pub(crate) fn clear_after_manual_subwindows_release( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + released: &[(ResourceId, Vec)], +) { + for (parent, region) in released { + if state.resources.window(*parent).is_some() { + send_window_exposures(state, backend, origin, *parent, region, true); + } + } +} + +/// Purge every core-visible Present population targeting a destroyed window +/// subtree. Backend-hidden GPU/direct events cannot be cancelled here; the +/// removed window generation makes their later drain discard wire delivery and +/// release only at a safe retirement (direct sources wait for retired-idle). +/// Shared by explicit/COW destruction and both disconnect/zombie paths so +/// numeric XID reuse always starts with fresh CRTC/MSC state. +pub(crate) fn purge_present_for_destroyed_windows( + state: &mut ServerState, + backend: &mut dyn Backend, + windows: &[ResourceId], +) { + let destroyed: HashSet = windows.iter().map(|window| window.0).collect(); + if destroyed.is_empty() { + return; + } + + state + .present_pending_msc + .retain(|pending| !destroyed.contains(&pending.window)); + state + .present_window_msc + .retain(|window, _| !destroyed.contains(window)); + state + .present_window_generations + .retain(|window, _| !destroyed.contains(window)); + state + .present_event_selections + .retain(|_, selection| !destroyed.contains(&selection.window.0)); + + let stale_present_ids: Vec = state + .present_pending_exec + .iter() + .filter_map(|(&pid, entry)| { + destroyed + .contains(&entry.pending.request.window()) + .then_some(pid) + }) + .collect(); + for pid in stale_present_ids { + let Some(entry) = state.present_pending_exec.remove(&pid) else { + continue; + }; + match &entry.pending.wake { + crate::backend::PresentWake::Pixmap { idle_fence_xid } if *idle_fence_xid != 0 => { + if let Err(error) = backend.dri3_trigger_fence(*idle_fence_xid) { + log::warn!( + "PRESENT teardown: trigger idle fence 0x{idle_fence_xid:x} failed: {error}" + ); + } + crate::core_loop::sync_await::fence_triggered(state, *idle_fence_xid); + } + crate::backend::PresentWake::PixmapSynced { + release, + release_value, + release_syncobj, + } => { + if let Err(error) = release.signal(*release_value) { + log::warn!( + "PRESENT teardown: signal release syncobj 0x{release_syncobj:x}@\ + {release_value} failed: {error}" + ); + } + } + _ => {} + } + if let Some(wait_id) = entry.wait_id { + backend.finish_present_source_wait(wait_id); + state.present_wait_to_id.remove(&wait_id); + } + if let Some(pin) = entry.pin { + backend.release_present_source(pin); + } + } + + let stale_completions: Vec<_> = state + .present_pending_complete + .iter() + .filter(|pending| destroyed.contains(&pending.event.dst_host_xid)) + .map(|pending| pending.event.clone()) + .collect(); + for event in &stale_completions { + // Copy completions (`emit_idle=true`) have already retired their GPU + // read and may release now. Direct completions deliberately remain + // busy until their later retired-idle event; releasing them here could + // hand a still-scanned buffer back to the client. + discard_stale_present_event(state, backend, event, false); + } + state + .present_pending_complete + .retain(|pending| !destroyed.contains(&pending.event.dst_host_xid)); + + let stale_gate_ids: Vec = state + .present_complete_gate + .iter() + .filter_map(|(&id, gate)| destroyed.contains(&gate.dst_window_xid).then_some(id)) + .collect(); + for id in stale_gate_ids { + // The backend completion is still in flight. It is not safe to release + // either a copy source (GPU may still read it) or a direct source + // (scanout may still own it). The generation check in the backend-event + // drain discards its eventual wire event and releases at the matching + // retirement instead. + state.present_complete_gate.remove(&id); + } +} + +/// Free every Picture on the doomed `windows`, whichever client owns it, while the +/// window records still exist (Xorg `PictureDestroyWindow`, `render/picture.c:67`). +pub(crate) fn free_pictures_on_destroyed_windows( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + windows: &[ResourceId], +) { + for (pic_xid, owned_pix) in state.resources.remove_pictures_on_windows(windows) { + let _ = backend.render_free_picture(origin, pic_xid); + if let Some(pix_xid) = owned_pix { + let _ = backend.free_pixmap(origin, pix_xid); + } + } +} + +/// Release each doomed window's redirect backing and drop every redirect record keyed on it, +/// while the window records still exist (Xorg `compDestroyWindow`, `composite/compwindow.c:600`). +/// Surviving `NameWindowPixmap` aliases keep the backing alive until their `FreePixmap`. +pub(crate) fn release_redirects_on_destroyed_windows( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + windows: &[ResourceId], +) { + for window in windows { + crate::core_loop::process_disconnect::unrealize_redirect_backing( + state, backend, origin, *window, + ); + } + state.composite_redirects.forget_windows(windows); +} + +/// Free on the backend each host cursor a window let go of that nothing +/// references any more — a cursor freed while a window still used it goes +/// when that window changes cursor or dies (Xorg `FreeCursor` on +/// `refcnt == 0`, `dix/window.c:968`/`:1559`). +pub(crate) fn release_dropped_cursors( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, +) { + for host in state.resources.take_unreferenced_cursor_hosts() { + let _ = backend.free_cursor(origin, host); + } +} + +pub(super) fn handle_reparent_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(request) = x11::reparent_window_request(body) else { + return Ok(RequestOutcome::Handled); + }; + if state.resources.window(request.window).is_some() { + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::MANAGE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 7); + } + if state.resources.window(request.parent).is_some() + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.parent, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::ADD, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 7); + } + } + let valid = state.resources.check_reparent_window(request).is_ok(); + let mapped = valid.then(|| { + state.resources.window(request.window).and_then(|w| { + (w.map_state != MapState::Unmapped).then_some(( + w.parent, + w.map_state, + w.override_redirect, + )) + }) + }); + let mapped = mapped.flatten(); + let remap_denied = if valid + && mapped.is_some() + && super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SHOW, + access_request, + ) + .is_err() + { + // XLibre's denied MapWindow is Success. Reuse the client + // UnmapWindow transition once, then reparent without remapping. + unmap_window(state, backend, origin, request.window, false); + true + } else { + false + }; + // Xorg ReparentWindow unmaps a mapped window first (`dix/window.c:2519`): + // UnmapNotify, and the pointer leaves it while it is still in the old + // place. Its map state is only hidden for that hit-test; the reparent + // below keeps the window mapped, and the MapNotify after ReparentNotify + // stands for Xorg's MapWindow. + let unmapped = if valid && !remap_denied { mapped } else { None }; + let unmapped_host = unmapped + .and_then(|_| state.resources.window(request.window)) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()); + if let Some((old_parent, map_state, _)) = unmapped { + let window = request.window; + // The backend too, before the repaint below: a window it still + // holds mapped clips the background fill of what it covered in a + // shared backing. + if let Some(host) = unmapped_host { + let _ = backend.unmap_subwindow(origin, host); + } + let clips_before = if map_state == MapState::Viewable { + crate::core_loop::clip_list::clip_entries_under(state, window) + } else { + Vec::new() + }; + let _dropped = emit_window_event_to_state(state, window, 0x0002_0000, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, window, window, false); + }); + let _dropped = + emit_window_event_to_state(state, old_parent, 0x0008_0000, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, old_parent, window, false); + }); + if let Some(w) = state.resources.window_mut(window) { + w.map_state = MapState::Unmapped; + } + // What it covered in the old place is exposed (`UnmapWindow`, + // `dix/window.c:2856-2866`). + if map_state == MapState::Viewable { + let after = crate::core_loop::clip_list::clip_entries_under(state, window); + send_exposures( + state, + backend, + origin, + crate::core_loop::clip_list::newly_exposed(&clips_before, after, None), + None, + ); + } + backend.windows_restructured(state); + if let Some(w) = state.resources.window_mut(window) { + w.map_state = map_state; + } + } + let result = match state.resources.reparent_window(request) { + Ok(result) => result, + Err(crate::resources::ReparentWindowError::BadWindow) => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + request.window.0, + 7, + ); + } + Err(crate::resources::ReparentWindowError::BadMatch) => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + request.window.0, + 7, + ); + } + }; + // compReparentWindow → compSetPixmap (`composite/compwindow.c:470-472`). + crate::core_loop::damage_fanout::move_window_damage_to_list_head(state, result.window); + let on_window = subscribers_by_id(state, result.window, 0x0002_0000); + let on_old_parent = subscribers_by_id(state, result.old_parent, 0x0008_0000); + let on_new_parent = if result.old_parent == result.new_parent { + Vec::new() + } else { + subscribers_by_id(state, result.new_parent, 0x0008_0000) + }; + debug!( + "client {} #{} ReparentWindow 0x{:x}: 0x{:x}->0x{:x} pos=({},{}) host_xid={:?} map_state={:?}->{:?} viewable+{} viewable-{}", + client_id.0, + sequence.0, + result.window.0, + result.old_parent.0, + result.new_parent.0, + result.x, + result.y, + result.host_xid, + result.old_map_state, + result.new_map_state, + result.delta.became_viewable.len(), + result.delta.became_unviewable.len(), + ); + if let Some(xid) = result.host_xid { + let new_host_parent = if result.new_parent == ROOT_WINDOW { + Some(backend.window_id()) + } else { + state + .resources + .window(result.new_parent) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()) + }; + if let Some(host_parent) = new_host_parent { + let child = xid.as_raw(); + if let Err(e) = + backend.reparent_subwindow(origin, child, host_parent, result.x, result.y) + { + panic!( + "reparent_subwindow failed after protocol validation: child=0x{child:x} \ + parent=0x{host_parent:x}: {e}" + ); + } + } + if result.old_parent == ROOT_WINDOW && result.new_parent != ROOT_WINDOW { + let _ = backend.update_host_event_mask( + origin, + xid.as_raw(), + crate::host_x11::POINTER_EVENT_MASK, + false, + ); + if let Err(err) = backend.register_subwindow(origin, result.window, xid.as_raw()) { + log::warn!( + "client {} register_subwindow for 0x{:x} on reparent failed: {err}", + client_id.0, + result.window.0 + ); + } + } + if result.old_parent != ROOT_WINDOW && result.new_parent == ROOT_WINDOW { + let _ = backend.update_host_event_mask( + origin, + xid.as_raw(), + crate::host_x11::SUBWINDOW_EVENT_MASK, + false, + ); + if let Err(err) = backend.register_top_level(origin, result.window, xid.as_raw()) { + log::warn!( + "client {} register_top_level for 0x{:x} on reparent failed: {err}", + client_id.0, + result.window.0 + ); + } else { + backend.on_window_became_top_level(state, xid.as_raw()); + } + } + // Step 2 (DRIFT 2): a reparent across the root boundary changes + // root's child set; reproject the backend top-level order from core. + if result.old_parent == ROOT_WINDOW || result.new_parent == ROOT_WINDOW { + backend.sync_top_level_order(state); + } + } + // Xorg's MapWindow in the new place (`dix/window.c:2587-2588`), before + // storage and redirect reconcile as in `handle_map_window`. + if let Some(host) = unmapped_host { + let _ = backend.map_subwindow(origin, host); + } + // Before the reconcile below, so a GRANT backing finds the leaf that carries its route. + realize_storage_for_delta(state, backend, origin, &result.delta); + let window = result.window; + let new_parent = result.new_parent; + let old_parent = result.old_parent; + let rx = result.x; + let ry = result.y; + let override_redirect = result.override_redirect; + // Xorg compReparentWindow (composite/compwindow.c:453-454): the old + // parent's subwindows records leave the window, the new parent's join + // it; its own RedirectWindow records stay. A root child that leaves + // muffin's RedirectSubwindows(root, Manual) for a frame is no longer + // redirected, so no stale inner backing keeps its paints from the + // compositor (nm-applet into mate-panel's tray socket; Warframe + // fullscreen -> windowed: black). + let before = state.composite_redirects.window_mode(window); + state + .composite_redirects + .reparent_subwindow(old_parent, new_parent, window); + log::debug!( + "reparent reconcile: window=0x{:x} old_parent=0x{:x} new_parent=0x{:x} \ + mode {before:?} -> {:?}", + window.0, + old_parent.0, + new_parent.0, + state.composite_redirects.window_mode(window), + ); + if backend.supports_redirect_activation() { + sync_redirect_backing( + state, + backend, + origin, + window, + before, + BackingDamage::MapExposures, + ); + } + // After the reconcile, so a revoke still sees the backing it tears down. + apply_viewability_delta_to_redirects(state, backend, origin, &result.delta); + release_storage_for_delta(state, backend, origin, &result.delta); + if unmapped_host.is_some() { + reapply_redirect_mode_after_map(state, backend, origin, window); + } + let _dropped = fanout_event_to_clients(state, &on_window, |buf, seq, order| { + x11::encode_reparent_notify_event( + buf, + seq, + order, + window, + window, + new_parent, + rx, + ry, + override_redirect, + ); + }); + let _dropped = fanout_event_to_clients(state, &on_old_parent, |buf, seq, order| { + x11::encode_reparent_notify_event( + buf, + seq, + order, + old_parent, + window, + new_parent, + rx, + ry, + override_redirect, + ); + }); + let _dropped = fanout_event_to_clients(state, &on_new_parent, |buf, seq, order| { + x11::encode_reparent_notify_event( + buf, + seq, + order, + new_parent, + window, + new_parent, + rx, + ry, + override_redirect, + ); + }); + if let Some((_, _, override_redirect)) = unmapped { + let _dropped = emit_window_event_to_state(state, window, 0x0002_0000, |buf, seq, order| { + x11::encode_map_notify_event(buf, seq, order, window, window, override_redirect); + }); + let _dropped = + emit_window_event_to_state(state, new_parent, 0x0008_0000, |buf, seq, order| { + x11::encode_map_notify_event( + buf, + seq, + order, + new_parent, + window, + override_redirect, + ); + }); + // MapWindow exposes it in the new place, its background painted + // there: the storage it kept is not what Xorg shows. + for (w, region) in crate::core_loop::clip_list::subtree_clip_lists(state, window) { + let _dropped = accumulate_damage_border_to_state(state, w); + send_window_exposures(state, backend, origin, w, ®ion, true); + } + } + // The window moved in the tree; Xorg's ReparentWindow re-evaluates the + // pointer through its MapWindow (`dix/window.c:2695`). + backend.windows_restructured(state); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_create_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let Some(request) = x11::create_window_request(header.data, body) else { + return Ok(RequestOutcome::Handled); + }; + let access_request = RequestOpcodes::for_request(header); + debug!( + "client {} create window 0x{:x} parent=0x{:x} pos=({},{}) size={}x{} mask=0x{:x}", + client_id.0, + request.window.0, + request.parent.0, + request.x, + request.y, + request.width, + request.height, + request.event_mask.unwrap_or(0) + ); + let new_id = request.window.0; + let mask = request.event_mask.unwrap_or(0); + let window_id = request.window; + let parent = request.parent; + let geometry = (request.x, request.y, request.width, request.height); + // Xorg `dix/dispatch.c::ProcCreateWindow` calls dixLookupWindow on + // the parent first; BadWindow if the parent xid is stale. xts5 + // Xlib4 probes XCreateWindow / XCreateSimpleWindow with + // parent=badwin() and expects the protocol error. + if state.resources.window(parent).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + parent.0, + 1, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: parent, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::ADD, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 1); + } + // Xorg `dix/window.c::CreateWindow:769-786` resolves + // `class == CopyFromParent` against the parent, then enforces: + // - class must be InputOutput or InputOnly → BadValue. + // - parent class InputOnly + child class != InputOnly → BadMatch. + // - class InputOnly + (border_width != 0 || depth != 0) → BadMatch. + // xts5 Xlib4: XCreateSimpleWindow-10 (parent InputOnly path), + // XCreateWindow-31 (InputOnly+border_width), XCreateWindow-43 + // (parent InputOnly + InputOutput child), XCreateWindow-44 + // (InputOnly + non-zero depth). + let parent_class = state + .resources + .window(parent) + .map(|w| w.class) + .expect("parent existence verified above"); + let parent_class_value = parent_class.protocol_value(); + let effective_class = match request.class { + 0 => parent_class_value, // CopyFromParent → parent's class + v => v, + }; + if effective_class != 1 && effective_class != 2 { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(request.class), + 1, + ); + } + if matches!(parent_class, crate::resources::WindowClass::InputOnly) && effective_class != 2 { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); + } + if effective_class == 2 && (request.border_width != 0 || request.depth != 0) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); + } + // InputOnly value-mask check, same legal-mask as + // ChangeWindowAttributes — xts5 Xlib4 XCreateWindow-24 cycles + // every illegal bit through value_mask and expects BadMatch. + if effective_class == 2 { + const INPUTONLY_LEGAL_MASK: u32 = 0x0020 // CWWinGravity + | 0x0200 // CWOverrideRedirect + | 0x0800 // CWEventMask + | 0x1000 // CWDontPropagate + | 0x4000; // CWCursor + if (request.value_mask & !INPUTONLY_LEGAL_MASK) != 0 { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); + } + } + // BadIdChoice / BadMatch validation. The server creates its own + // windows (the screensaver's) under `SERVER_OWNER`, with no client. + let validation_failed = client_id != crate::resources::SERVER_OWNER && { + let handle = state.clients.get(&client_id.0).expect("client registered"); + let owned = crate::server::IdAllocator::validate_owned( + new_id, + handle.resource_id_base, + handle.resource_id_mask, + ); + let in_use = state.xid_occupied(request.window.0); + !owned || in_use + }; + if validation_failed { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + new_id, + 1, + ); + } + let visual_known = request.visual.0 == 0 || state.resources.is_known_visual(request.visual); + if !visual_known { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + request.visual.0, + 1, + ); + } + // Attribute value-id validation, matching Xorg's + // `dix/window.c::CreateWindow`. CWBackPixmap values 0/1 are + // reserved (None / ParentRelative); CWColormap value 0 in the + // typed enum is CopyFromParent. + if let Some(bg_pixmap) = request.background_pixmap + && bg_pixmap.0 > 1 + { + if state.resources.pixmap(bg_pixmap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + bg_pixmap.0, + 1, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: bg_pixmap, + kind: ResourceKind::Pixmap, + creation: None, + }, + AccessMode::READ, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 1); + } + } + if let Some(Some(colormap)) = request.colormap { + if state.resources.colormap(colormap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + colormap.0, + 1, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: colormap, + kind: ResourceKind::Colormap, + creation: None, + }, + AccessMode::USE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 1); + } + } + if let Some(cursor) = request.cursor + && cursor.0 != 0 + { + if !state.resources.cursor_exists(cursor) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + 1, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::USE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 1); + } + } + // Border validation. The effective depth resolves CopyFromParent + // (depth 0) against the parent, matching + // `ResourceTable::create_window`. + let parent_depth = state + .resources + .window(parent) + .map(|w| w.depth) + .expect("parent existence verified above"); + let effective_depth = if request.depth == 0 { + parent_depth + } else { + request.depth + }; + // Xorg `dix/window.c:818`: a window whose depth differs from its + // parent's MUST supply a border attribute, because the inherited + // border (`:879`) would otherwise carry the parent's depth. InputOnly + // has no border at all and is exempt. + const CW_BORDER_PIXMAP: u32 = 0x0004; + const CW_BORDER_PIXEL: u32 = 0x0008; + if (request.value_mask & (CW_BORDER_PIXMAP | CW_BORDER_PIXEL)) == 0 + && effective_class != 2 + && effective_depth != parent_depth + { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); + } + // `dix/window.c:1251` CWBorderPixmap. CWBorderPixel overrides it and + // clears the bit before the pixmap is ever resolved (`:1298`), so a + // request carrying both is not validated against the pixmap. + if request.border_pixel.is_none() + && let Some(border_pixmap) = request.border_pixmap + { + if border_pixmap.0 == 0 { + // CopyFromParent: BadMatch unless the depths match. (The + // no-parent case cannot arise here — the parent xid was + // validated above.) + if effective_depth != parent_depth { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 1); + } + } else { + match state.resources.pixmap(border_pixmap) { + None => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + border_pixmap.0, + 1, + ); + } + Some(pixmap) => { + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: border_pixmap, + kind: ResourceKind::Pixmap, + creation: None, + }, + AccessMode::READ, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 1); + } + if pixmap.depth != effective_depth { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + 1, + ); + } + } + } + } + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window_id, + kind: ResourceKind::Window, + creation: Some(Creation { + parent: Some(parent), + owner: client_id, + }), + }, + AccessMode::CREATE | AccessMode::SET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 1); + } + state.resources.create_window(client_id, request); + if mask != 0 + && let Some(client) = state.clients.get_mut(&client_id.0) + { + client.event_masks.insert(window_id, mask); + } + let needs_host_xid = state + .resources + .window(window_id) + .is_some_and(|w| w.class != crate::resources::WindowClass::InputOnly); + if needs_host_xid { + let host_visual = resolve_host_subwindow_visual_to_state(state, window_id); + let host_parent: Option = if parent == ROOT_WINDOW { + crate::backend::WindowHandle::from_raw(backend.window_id()) + } else { + state.resources.window(parent).and_then(|w| w.host_xid) + }; + let local = state.resources.window(window_id); + let resolved_bg = state.resources.window_resolved_background(window_id); + // `window_resolved_background` returning None is MEANINGFUL: it + // says this window has no background, so the server paints + // nothing (X11 §CreateWindow — background-pixmap defaults to + // None). It returns None in exactly four cases, and a stored + // pixel is the wrong answer in all of them: a ParentRelative + // cycle; the window absent from the map (then `local` is None + // too); a ParentRelative chain that resolved to no background; + // and `background_none` itself. + // + // So DO NOT fall back to `w.background_pixel` here. For a + // background-None window that field holds the 0x00ffffff + // PLACEHOLDER `create_window` stores when the request carries no + // background attribute, and passing it on painted every such + // window's fresh storage WHITE — the storage half of + // `window_storage_init_covers_the_whole_allocation`, and the + // reason `default_window_init_color`'s None branch was dead for + // client windows. None reaches that safe default instead. + let host_bg_pixel = resolved_bg.map(|bg| bg.background_pixel); + let host_bg_pixmap = resolved_bg + .and_then(|bg| bg.background_pixmap_host_xid) + .map(|h| h.as_raw()) + .or_else(|| { + local + .and_then(|w| w.background_pixmap_host_xid) + .map(|h| h.as_raw()) + }); + let allocated = host_parent.and_then(|host_parent| { + match backend.create_subwindow( + origin, + host_parent, + geometry.0, + geometry.1, + geometry.2, + geometry.3, + request.border_width, + host_visual, + host_bg_pixel, + host_bg_pixmap, + ) { + Ok(handle) => Some(handle), + Err(err) => { + log::warn!( + "client {} create_subwindow for 0x{:x} failed: {err}", + client_id.0, + new_id + ); + None + } + } + }); + if let Some(host_handle) = allocated { + if let Some(w) = state.resources.window_mut(window_id) { + w.host_xid = Some(host_handle); + } + let host_xid = host_handle.as_raw(); + // #133 step 2 (P3): `create_subwindow` carries `border_width` + // on the wire but not the border SOURCE, so forward it now + // through the generic attribute route. Without this a window + // created with a border pixel that is never changed again + // would leave the backend mirror with no source at all — + // and CreateWindow inherits the parent's border + // (`dix/window.c:879`), so even a client that supplies no + // border attribute can start out with a non-default one. + if let Some(border) = state.resources.window(window_id).map(|w| w.border) { + let (value_mask, values) = border_source_cwa_values(border); + let _ = backend.change_subwindow_attributes(origin, host_xid, value_mask, &values); + } + // CWCursor on CreateWindow, as ChangeWindowAttributes forwards it. + if let Some(cursor_host) = request + .cursor + .filter(|c| c.0 != 0) + .and_then(|c| state.resources.cursor_host_xid(c)) + { + let _ = backend.define_cursor(origin, host_xid, cursor_host); + } + let result = if parent == ROOT_WINDOW { + backend.register_top_level(origin, window_id, host_xid) + } else { + backend.register_subwindow(origin, window_id, host_xid) + }; + if let Err(err) = result { + log::warn!( + "client {} register host window for 0x{:x} failed: {err}", + client_id.0, + new_id + ); + } else if parent == ROOT_WINDOW { + backend.on_window_became_top_level(state, host_xid); + // Step 2 (DRIFT 2): a new root child changes the top-level + // set; reproject the backend order from core so the new + // window lands where core put it (e.g. below the COW). + backend.sync_top_level_order(state); + } + } + } + // Xorg compCreateWindow (composite/compwindow.c:579-589): a child of a + // RedirectSubwindows parent gets that client's record. It is unmapped, + // so the backing waits for realize. + state + .composite_redirects + .redirect_new_subwindow(parent, window_id); + // CreateNotify on parent (SubstructureNotify subscribers). + let create_notify_targets = subscribers_by_id(state, parent, 0x0008_0000); + if !create_notify_targets.is_empty() { + let geometry_opt = state.resources.window(window_id).map(window_geometry); + if let Some(geometry) = geometry_opt { + let override_redir = request.override_redirect.unwrap_or(false); + let _dropped = + fanout_event_to_clients(state, &create_notify_targets, |buf, seq, order| { + x11::encode_create_notify_event( + buf, + seq, + order, + parent, + window_id, + geometry, + override_redir, + ); + }); + } + } + debug!("client {} #{} CreateWindow", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_change_window_attributes( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let Some(mut request) = x11::change_window_attributes_request(body) else { + return Ok(RequestOutcome::Handled); + }; + let access_request = RequestOpcodes::for_request(header); + if state.resources.window(request.window).is_none() { + // Xorg `dix/dispatch.c::ProcChangeWindowAttributes` returns + // BadWindow via dixLookupWindow before applying any attribute + // changes. xts5 Xlib4 probes XChangeWindowAttributes and its + // wrappers (XSetWindowBackground / *BorderPixmap / *Colormap / + // XDefineCursor / XUndefineCursor / …) on badwin() and expects + // the protocol error. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + request.window.0, + 2, + ); + } + let event_mask = request.value_mask & 0x0800 != 0; + let other_attributes = request.value_mask & !0x0800 != 0; + let window_mode = match (event_mask, other_attributes) { + (true, true) => Some(AccessMode::RECEIVE | AccessMode::SET_ATTR), + (true, false) => Some(AccessMode::RECEIVE), + (false, true) => Some(AccessMode::SET_ATTR), + (false, false) => None, + }; + if let Some(mode) = window_mode + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.window, + kind: ResourceKind::Window, + creation: None, + }, + mode, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 2); + } + // Xorg `dix/window.c::ChangeWindowAttributes:1174`: an InputOnly + // window may only carry the `INPUTONLY_LEGAL_MASK` bits + // (CWWinGravity, CWEventMask, CWDontPropagate, CWOverrideRedirect, + // CWCursor); any other bit → BadMatch. xts5 Xlib4 + // XChangeWindowAttributes-26 cycles every illegal bit through the + // value_mask and expects BadMatch from each. + const INPUTONLY_LEGAL_MASK: u32 = 0x0020 // CWWinGravity + | 0x0200 // CWOverrideRedirect + | 0x0800 // CWEventMask + | 0x1000 // CWDontPropagate + | 0x4000; // CWCursor + let target_class = state + .resources + .window(request.window) + .map(|w| w.class) + .expect("window existence verified above"); + if matches!(target_class, crate::resources::WindowClass::InputOnly) + && (request.value_mask & !INPUTONLY_LEGAL_MASK) != 0 + { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 2); + } + let refused = crate::rootless::refuse_root_redirect(state, &mut request) + || exclusive_event_mask_conflict(state, client_id, &request); + if refused { + request.truncate_at_event_mask(); + } + // Resource-id validation of attribute values, mirroring Xorg's + // `dix/window.c::ChangeWindowAttributes` per-attribute + // `dixLookupResource`. Values 0 and 1 on CWBackPixmap are reserved + // (None / ParentRelative); colormap value 0 in the typed enum + // means CopyFromParent and is resolved against the parent. + if let Some(bg_pixmap) = request.background_pixmap + && bg_pixmap.0 > 1 + { + if state.resources.pixmap(bg_pixmap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + bg_pixmap.0, + 2, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: bg_pixmap, + kind: ResourceKind::Pixmap, + creation: None, + }, + AccessMode::READ, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 2); + } + } + if let Some(Some(colormap)) = request.colormap { + if state.resources.colormap(colormap).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_COLORMAP, + colormap.0, + 2, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: colormap, + kind: ResourceKind::Colormap, + creation: None, + }, + AccessMode::USE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 2); + } + } + if let Some(cursor) = request.cursor + && cursor.0 != 0 + { + if !state.resources.cursor_exists(cursor) { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + 2, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: cursor, + kind: ResourceKind::Cursor, + creation: None, + }, + AccessMode::USE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 2); + } + } + // `dix/window.c:1251` CWBorderPixmap. CWBorderPixel overrides it and + // clears the bit before the pixmap is resolved (`:1298`), so a + // request carrying both is never validated against the pixmap. + if request.border_pixel.is_none() + && let Some(border_pixmap) = request.border_pixmap + { + let (own_depth, parent_depth) = { + let window = state + .resources + .window(request.window) + .expect("window existence verified above"); + let parent_depth = if request.window == ROOT_WINDOW { + None + } else { + state.resources.window(window.parent).map(|p| p.depth) + }; + (window.depth, parent_depth) + }; + if border_pixmap.0 == 0 { + // CopyFromParent: BadMatch with no parent, or when the + // depths differ — the parent's border would carry the wrong + // depth for this window. + if parent_depth != Some(own_depth) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 2); + } + } else { + match state.resources.pixmap(border_pixmap) { + None => { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_PIXMAP, + border_pixmap.0, + 2, + ); + } + Some(pixmap) => { + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: border_pixmap, + kind: ResourceKind::Pixmap, + creation: None, + }, + AccessMode::READ, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 2); + } + if pixmap.depth != own_depth { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + 2, + ); + } + } + } + } + } + if let Some(bg_pixmap) = request.background_pixmap { + debug!( + "client {} CWA bg_pixmap: window 0x{:x} ← 0x{:x} ({})", + client_id.0, + request.window.0, + bg_pixmap.0, + match bg_pixmap.0 { + 0 => "None", + 1 => "ParentRelative", + _ => "pixmap", + }, + ); + } + if let Some(event_mask) = request.event_mask { + debug!( + "client {} attrs window 0x{:x} mask=0x{:x}", + client_id.0, request.window.0, event_mask + ); + let entry = state + .clients + .get_mut(&client_id.0) + .expect("client registered"); + if event_mask == 0 { + entry.event_masks.remove(&request.window); + } else { + entry.event_masks.insert(request.window, event_mask); + } + } + let target_window = request.window; + let cursor_id = request.cursor; + let released = state.resources.change_window_attributes(request); + // Release a replaced bg / border pixmap on the host ONLY if it is + // fully orphaned: no other window background OR border references it + // AND the client no longer owns it (FreePixmap already happened — at + // which point handle_free_pixmap skipped the host free because the + // attribute reference was still live). Freeing while the client still + // owns the pixmap destroyed it server-side: e16 menu items blanked on + // hover because the bg swap to the hilite pixmap host-freed the kept + // "normal" pixmap the un-hover restore then pointed back at. + // + // Both reference checks gate BOTH releases: one host handle can be a + // background on one window and a border on another (nothing stops a + // client naming the same pixmap for both), so testing only the + // matching attribute would free storage the other kind still samples. + // + // DEDUPLICATED: one request can replace both attributes at once, and if + // both named the same tile then `background` and `border` hand back the + // SAME handle. Freeing it twice happens to be inert on KMS (the store + // entry is gone by the second call) but it is still a broken backend + // contract, and a recording or host-X11 backend sees the duplicate. + let mut released_hosts = [released.background, released.border] + .into_iter() + .flatten() + .collect::>(); + released_hosts.dedup_by_key(|h| h.as_raw()); + for old_host_xid in released_hosts { + if !state.resources.host_xid_still_referenced(old_host_xid) { + let _ = backend.free_pixmap(origin, old_host_xid.as_raw()); + state.resources.host_pixmap_freed(old_host_xid.as_raw()); + } + } + + if target_window == ROOT_WINDOW { + let root_bg = state.resources.window_resolved_background(ROOT_WINDOW); + let root_bg_host_xid = root_bg.and_then(|bg| bg.background_pixmap_host_xid); + debug!( + "client {} CWA(root) bg_pixmap={:?} bg_pixel={:?} root_bg_host_xid={:?}", + client_id.0, request.background_pixmap, request.background_pixel, root_bg_host_xid, + ); + if request.background_pixmap.is_some() { + if let Some(host_bg) = root_bg_host_xid { + let _ = backend.set_container_background_pixmap(origin, host_bg.as_raw()); + } else if let Some(bg_pixel) = root_bg.map(|bg| bg.background_pixel) { + let _ = backend.set_container_background_pixel(origin, bg_pixel); + } + } else if let Some(pixel) = request.background_pixel { + let _ = backend.set_container_background_pixel(origin, pixel); + } + } + + // Only a CWA that (re)selects input may promote focus — i.e. a + // window "advertising input later" by adding key events to its event + // mask. A CWA changing an unrelated attribute (cursor, background, + // ...) must never move the input focus; in X11 focus changes only + // via SetInputFocus / grabs. Without this gate, muffin setting the + // "fleur" move cursor on its guard window during a + // `_NET_WM_MOVERESIZE` drag stole focus to that window, which then + // turned the dragged app's own child-focus move into a + // `FocusOut(Nonlinear)` (GTK4 backdrop) and broke the drag. + + if target_window != ROOT_WINDOW + && (request.background_pixel.is_some() || request.background_pixmap.is_some()) + { + let host_xid = state + .resources + .window(target_window) + .and_then(|w| w.host_xid); + let resolved_bg = state.resources.window_resolved_background(target_window); + if let Some(host_xid) = host_xid { + let mut value_mask: u32 = 0; + let mut values: Vec = Vec::with_capacity(1); + if request.background_pixmap.is_some() { + if let Some(bg_pixmap_host_xid) = + resolved_bg.and_then(|bg| bg.background_pixmap_host_xid) + { + value_mask |= 1 << 0; + values.push(bg_pixmap_host_xid.as_raw()); + } else { + value_mask |= 1 << 1; + values.push(resolved_bg.map(|bg| bg.background_pixel).unwrap_or(0)); + } + } else if request.background_pixel.is_some() { + value_mask |= 1 << 1; + values.push(resolved_bg.map(|bg| bg.background_pixel).unwrap_or(0)); + } + let _ = + backend.change_subwindow_attributes(origin, host_xid.as_raw(), value_mask, &values); + } + } + + // #133 step 2 (P3): the border source needs its OWN forward. The + // background block above fires only on a background change, so + // before this a `CWBorderPixel` / `CWBorderPixmap` reached the + // backend by no route at all — awesome's focus recolour (its only + // border request shape) was dropped on the floor. Read the window's + // CURRENT `border` rather than the request fields: the resource + // layer has already applied CopyFromParent resolution and + // pixel-overrides-pixmap, so this sends the state that actually + // took effect. Unhosted / InputOnly windows have no host xid and + // are silently skipped, same as the background path. + if target_window != ROOT_WINDOW + && (request.border_pixel.is_some() || request.border_pixmap.is_some()) + { + let host_xid = state + .resources + .window(target_window) + .and_then(|w| w.host_xid); + let border = state.resources.window(target_window).map(|w| w.border); + if let (Some(host_xid), Some(border)) = (host_xid, border) { + let (value_mask, values) = border_source_cwa_values(border); + let _ = + backend.change_subwindow_attributes(origin, host_xid.as_raw(), value_mask, &values); + } + // #143 — report protocol DAMAGE for the ring the forward above + // just repainted. Xorg does exactly this, in + // `ChangeWindowAttributes` itself and on the same condition + // (`(vmaskCopy & (CWBorderPixel | CWBorderPixmap)) && pWin->viewable + // && HasBorder(pWin)`, `dix/window.c:1581-1589`): it subtracts + // `winSize` from `borderClip` and `PaintWindow(..., PW_BORDER)`s the + // difference, which lands as a `PolyFillRect` on the window's + // (composite backing) pixmap and so goes through `damagePolyFillRect` + // (`miext/damage/damage.c:1194`). Xorg does NOT compare old-vs-new + // border source, and neither does our backend forward + // (`backend.rs:20110` repaints on any `value_mask & 0x0c`), so the + // damage has to fire on exactly the same trigger or the reported + // region and the painted region drift apart. + // + // Without this, awesome's focus recolour repainted our backing + // correctly but told no compositor: picom, on `EXT_buffer_age` + // partial repaint, kept one ring colour per back buffer and + // alternated between them at frame rate (#143's border flicker). + // + // No-op for unbordered windows, for the root and for a + // non-viewable window. + let _dropped = accumulate_damage_border_to_state(state, target_window); + } + + if let Some(cid) = cursor_id { + let host_window_raw = if target_window == ROOT_WINDOW { + Some(backend.window_id()) + } else { + state + .resources + .window(target_window) + .and_then(|w| w.host_xid) + .map(|w| w.as_raw()) + }; + // X11 `cursor = None` (xid 0) means "clear the per-window + // cursor so the effective cursor inherits from the parent + // chain." Match Xorg `dix/window.c:1487-1491`, which sets + // `pCursor = (CursorPtr) None` in that case. Pre-fix, we + // silently dropped CWA cursor=0 because `cursor_host_xid(0)` + // returns None and the (Some, Some) match below failed — + // marco's resize-frame XDefineCursor(frame, None) reset never + // propagated to the backend, so the resize cursor sprite + // stayed visible after the pointer moved off the edge into + // the frame interior. + let cursor_host_xid = if cid.0 == 0 { + Some(0u32) + } else { + state.resources.cursor_host_xid(cid) + }; + if let (Some(hw), Some(ch)) = (host_window_raw, cursor_host_xid) { + let _ = backend.define_cursor(origin, hw, ch); + } else if host_window_raw.is_none() { + // No backend window (InputOnly): the backend reads the cursor + // from the tree when it re-resolves the window under the + // pointer. + backend.windows_restructured(state); + } + release_dropped_cursors(state, backend, origin); + } + debug!( + "client {} #{} ChangeWindowAttributes", + client_id.0, sequence.0 + ); + if refused { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + target_window.0, + 2, + ); + } + Ok(RequestOutcome::Handled) +} + +/// Xorg `dix/events.c:4528` `AtMostOneClient`: SubstructureRedirect, +/// ResizeRedirect and ButtonPress may each be selected on a window by one +/// client only. `EventSelectForWindow` (:4624-4636) refuses a bit another +/// client already holds; re-selecting your own is fine. +fn exclusive_event_mask_conflict( + state: &ServerState, + client_id: ClientId, + request: &x11::ChangeWindowAttributesRequest, +) -> bool { + const AT_MOST_ONE_CLIENT: u32 = 0x0010_0000 | 0x0004_0000 | 0x0004; + let Some(check) = request.event_mask.map(|m| m & AT_MOST_ONE_CLIENT) else { + return false; + }; + check != 0 + && state.clients.iter().any(|(&id, c)| { + id != client_id.0 + && c.event_masks.get(&request.window).copied().unwrap_or(0) & check != 0 + }) +} + +/// #133 step 2 (P3): flatten a window's border source into the +/// `(value_mask, values)` pair `Backend::change_subwindow_attributes` +/// takes. The mask uses real X11 CW bit numbering — `0x04` +/// CWBorderPixmap, `0x08` CWBorderPixel — because the host-X11 backend +/// forwards mask and values verbatim to a real X server +/// (`host_x11/request.rs:1046`), so the correct bits make the nested +/// path work with no translation. +/// +/// A border is an either/or in Xorg (`PixUnion border` + +/// `borderIsPixel`, `include/windowstr.h:146`), so exactly one bit is +/// ever set. `Window::border` already has CopyFromParent resolved +/// eagerly (`dix/window.c:1251`), so this is a plain read with no +/// ParentRelative-style walk — unlike a background, a border has no +/// inherit-at-paint-time sentinel. +/// +/// A tile pixmap with no host storage degrades to the pixel bit with +/// value 0, mirroring the background block's "no host pixmap → send a +/// pixel" shape: a backend that cannot sample the tile is better off +/// with a defined solid colour than with a dangling xid. +fn border_source_cwa_values(border: BorderSource) -> (u32, Vec) { + match border { + BorderSource::Pixmap { + host_xid: Some(host), + .. + } => (0x04, vec![host.as_raw()]), + BorderSource::Pixmap { host_xid: None, .. } => (0x08, vec![0]), + BorderSource::Pixel(pixel) => (0x08, vec![pixel]), + } +} + +pub(super) fn handle_configure_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(request) = x11::configure_window_request(body) else { + return Ok(RequestOutcome::Handled); + }; + configure_window_apply( + state, + backend, + origin, + client_id, + sequence, + request, + crate::rootless::ConfigureSource::Client, + Some(access_request), + ) +} + +/// ConfigureWindow after parsing; `source` feeds rootless acks (spec §4.2.1). +pub(crate) fn configure_window_apply( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + request: x11::ConfigureWindowRequest, + source: crate::rootless::ConfigureSource, + access_request: Option, +) -> io::Result { + log::trace!( + target: "yserver::input::restack", + "CONFIGURE-REQ client={} win={} stack_mode={:?} sibling={}", + state.debug_client_label(client_id), + state.debug_window_label(request.window), + request.stack_mode, + request + .sibling + .map_or_else(|| "None".to_string(), |s| state.debug_window_label(s)), + ); + // X11 spec / Xorg `dix/window.c::ConfigureWindow`: ConfigureWindow + // on the root window is accepted (no error) but has no visible + // effect — root geometry is owned by the screen/RandR, not by the + // client. Without this short-circuit we apply the client's + // width/height to `state.resources.window(ROOT_WINDOW)` and every + // subsequent on-screen check (e.g. GetImage's BadMatch validation) + // breaks because root reports the client's tiny dimensions instead + // of the KMS scanout dims. xts5 produced a 70x61 root resize that + // cascaded into ~1000 UNRES. + if request.window == ROOT_WINDOW { + if let Some(access_request) = access_request + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::MANAGE | AccessMode::SET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 12); + } + debug!( + "client {} #{} ConfigureWindow on root — dropped (matches Xorg semantics)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + if state.resources.window(request.window).is_none() { + // Xorg `dix/dispatch.c::ProcConfigureWindow` returns BadWindow + // via dixLookupWindow before applying any geometry change. + // xts5 Xlib4 probes XConfigureWindow and its Xlib wrappers + // (XMoveWindow / XResizeWindow / XMoveResizeWindow / + // XRaiseWindow / XLowerWindow / XMapRaised — Xlib9 XRestack / + // XSetWindowBorderWidth) on badwin() and expects the protocol + // error. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + request.window.0, + 12, + ); + } + if let Some(access_request) = access_request + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: request.window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::MANAGE | AccessMode::SET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 12); + } + // Xorg `dix/window.c::ConfigureWindow` checks (in order, before + // any geometry change or SubstructureRedirect dispatch): + // 1. InputOnly + CWBorderWidth → BadMatch (xts5 Xlib4 + // XConfigureWindow-33 / XSetWindowBorderWidth-6). + // 2. CWSibling without CWStackMode → BadMatch (XConfigureWindow-30). + // 3. CWStackMode value > 4 → BadValue. + // 4. CWSibling: sibling xid unknown → BadWindow; sibling not + // actually a sibling of `window` or sibling==window → BadMatch + // (XConfigureWindow-31). + // 5. CWWidth=0 or CWHeight=0 → BadValue (XConfigureWindow-32). + const CW_BORDER_WIDTH: u16 = 0x0010; + const CW_SIBLING: u16 = 0x0020; + const CW_STACK_MODE: u16 = 0x0040; + let window_class = state + .resources + .window(request.window) + .map(|w| w.class) + .expect("window existence verified above"); + let window_parent = state + .resources + .window(request.window) + .map(|w| w.parent) + .expect("window existence verified above"); + if matches!(window_class, crate::resources::WindowClass::InputOnly) + && (request.value_mask & CW_BORDER_WIDTH) != 0 + { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 12); + } + if (request.value_mask & CW_SIBLING) != 0 && (request.value_mask & CW_STACK_MODE) == 0 { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 12); + } + if let Some(mode) = request.stack_mode + && mode > 4 + { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mode), + 12, + ); + } + if let Some(sibling) = request.sibling { + let sibling_window = state.resources.window(sibling); + if sibling_window.is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + sibling.0, + 12, + ); + } + if let Some(access_request) = access_request + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: sibling, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 12); + } + let sibling_parent = sibling_window.map(|w| w.parent); + if sibling_parent != Some(window_parent) || sibling == request.window { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, 12); + } + } + if request.width == Some(0) || request.height == Some(0) { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, 12); + } + let pre = state + .resources + .window(request.window) + .map(|w| (w.parent, w.override_redirect)); + let redirect_targets: Vec = if let Some((parent, false)) = pre { + let requester_has = state + .clients + .get(&client_id.0) + .and_then(|c| c.event_masks.get(&parent).copied()) + .is_some_and(|m| m & 0x0010_0000 != 0); + if requester_has { + Vec::new() + } else { + subscribers_by_id(state, parent, 0x0010_0000) + } + } else { + Vec::new() + }; + if !redirect_targets.is_empty() { + let parent = pre.map(|(p, _)| p).unwrap_or(ROOT_WINDOW); + let _dropped = fanout_event_to_clients(state, &redirect_targets, |buf, seq, order| { + x11::encode_configure_request_event(buf, seq, order, parent, request.window, &request); + }); + return Ok(RequestOutcome::Handled); + } + crate::rootless::note_configure(state, &request, source); + let old_size = state + .resources + .window(request.window) + .map(|w| (w.width, w.height)); + // X11 dix/window.c::ConfigureWindow: a ConfigureNotify is emitted + // only when the window is *actually* reconfigured. Snapshot the + // fields the event reports (geometry + above-sibling) before the + // change so we can suppress the notify for a no-op (e.g. a + // stacking-only request that doesn't reorder, or a same-value + // geometry). Emitting on a no-op restack makes Enlightenment + // re-restack forever (~8000 req/s). + let before_geom = state + .resources + .window(request.window) + .map(|w| (w.x, w.y, w.width, w.height, w.border_width)); + let before_above = state + .resources + .configure_notify_above_sibling(request.window); + let sibling_host_xid = request + .sibling + .and_then(|sibling| state.resources.window(sibling)) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()); + // The clip lists the change can alter, for its exposures below. + let tree_change = before_geom.and_then(|(x, y, w, h, bw)| { + let bw2 = request.border_width.unwrap_or(bw).saturating_mul(2); + let reach = x11::xfixes::RegionRect { + x: request.x.unwrap_or(x), + y: request.y.unwrap_or(y), + width: request.width.unwrap_or(w).saturating_add(bw2), + height: request.height.unwrap_or(h).saturating_add(bw2), + }; + crate::core_loop::clip_list::TreeChange::begin(state, request.window, Some(reach)) + }); + let configure = state + .resources + .configure_window(request) + .map(|w| (w.id, window_geometry(w), w.override_redirect)); + let host_xid = configure + .as_ref() + .and_then(|(id, _, _)| state.resources.window(*id).and_then(|w| w.host_xid)); + let parent = configure + .as_ref() + .and_then(|(id, _, _)| state.resources.window(*id).map(|w| w.parent)); + debug!( + "client {} #{} ConfigureWindow 0x{:x} mask=0x{:x} x={:?} y={:?} w={:?} h={:?} host_xid={:?}", + client_id.0, + sequence.0, + request.window.0, + request.value_mask, + request.x, + request.y, + request.width, + request.height, + host_xid, + ); + if let Some(xid) = host_xid { + let _ = backend.configure_subwindow( + origin, + xid.as_raw(), + crate::host_x11::HostSubwindowConfig { + x: request.x, + y: request.y, + width: request.width, + height: request.height, + border_width: request.border_width, + sibling: sibling_host_xid, + stack_mode: request.stack_mode, + }, + ); + } + // Step 2 (DRIFT 2): a stack_mode restack changed root's child order in + // the core tree (with full occlusion + COW cap). Reproject the + // backend's top-level z-order from core so the two cannot drift. + if request.stack_mode.is_some() { + backend.sync_top_level_order(state); + } + if let Some((window_id, geometry, override_redirect)) = configure { + let above_sibling = state.resources.configure_notify_above_sibling(window_id); + // Only emit ConfigureNotify when the window was actually + // reconfigured (geometry or stacking changed), per Xorg + // dix/window.c::ConfigureWindow. A stacking-only request that + // doesn't reorder, or a configure to identical geometry, is a + // no-op and must stay silent — otherwise a WM that re-applies its + // stacking policy on every ConfigureNotify (Enlightenment) spins + // forever. + let after_geom = state + .resources + .window(window_id) + .map(|w| (w.x, w.y, w.width, w.height, w.border_width)); + let configure_changed = before_geom != after_geom || before_above != above_sibling; + if configure_changed { + // Xorg calls the screen's ConfigNotify hook before it delivers + // the core ConfigureNotify (dix/window.c::ConfigureWindow). + // Present wraps that hook, so a client selecting both events + // observes Present::ConfigureNotify first. Keep this wire order: + // Mesa/CEF consume both streams for the same DRI3 window, and + // reversing them briefly left Steam's popup surface with its + // parent-relative coordinates while the native root child had + // already moved. + fire_present_configure_notify_for_window(state, window_id, geometry); + let _dropped = + emit_window_event_to_state(state, window_id, 0x0002_0000, |buf, seq, order| { + x11::encode_configure_notify_event( + buf, + seq, + order, + window_id, + window_id, + above_sibling, + geometry, + override_redirect, + ); + }); + if let Some(parent) = parent { + let _dropped = + emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { + x11::encode_configure_notify_event( + buf, + seq, + order, + parent, + window_id, + above_sibling, + geometry, + override_redirect, + ); + }); + } + } + // X11 window gravity: resizing a window repositions its children + // per each child's `win_gravity` (Xorg dix ResizeChildrenWinSize). + // Reposition in the host mirror and send GravityNotify. fvwm's + // window-shade relies on this — it parks a South-gravity client + // above the fold and reveals it by growing the client's holder; + // without gravity the client stays parked and renders as a black + // rectangle over the frame (air/silence HW 2026-07-02). + let resized = + old_size.is_some_and(|(ow, oh)| geometry.width != ow || geometry.height != oh); + // A viewable window whose size changes unmaps its UnmapGravity + // children first, top-most first, after its ConfigureNotify and + // before any GravityNotify (`miResizeWindow`, `mi/miwindow.c:389-398`; + // `UnmapWindow(pChild, TRUE)`). A move or border change is not a + // resize (`dix/window.c:2331-2338`). + if resized + && state + .resources + .window(window_id) + .is_some_and(|w| w.map_state == MapState::Viewable) + { + let unmap_gravity: Vec = state + .resources + .children(window_id) + .iter() + .rev() + .copied() + .filter(|c| { + state + .resources + .window(*c) + .is_some_and(|w| w.win_gravity == 0 && w.map_state != MapState::Unmapped) + }) + .collect(); + for child in unmap_gravity { + unmap_window(state, backend, origin, child, true); + } + } + let moved = old_size.map_or_else(Vec::new, |(ow, oh)| { + state + .resources + .apply_win_gravity(window_id, ow, oh, geometry.width, geometry.height) + }); + let old_border_width = before_geom.map_or(geometry.border_width, |g| g.4); + // `miResizeWindow` (mi/miwindow.c:342-620): the realloc happens + // first, then each gravity group is copied from the OLD pixmap + // (`compCopyWindow`, composite/compwindow.c:489-528). + let old_backing = if resized || old_border_width != geometry.border_width { + rotate_redirected_backing_on_resize( + state, + backend, + origin, + window_id, + geometry.width, + geometry.height, + false, + old_border_width, + ) + } else { + None + }; + if !moved.is_empty() { + let host_moves: Vec<(u32, i16, i16)> = moved + .iter() + .filter_map(|&(child, nx, ny)| { + state + .resources + .window(child) + .and_then(|w| w.host_xid) + .map(|h| (h.as_raw(), nx, ny)) + }) + .collect(); + let _ = backend.move_subwindows_for_gravity(origin, &host_moves, old_backing); + } + finish_redirected_backing_rotate(backend, origin, old_backing); + for (child, nx, ny) in moved { + // GravityNotify → child (StructureNotify) and its parent + // (SubstructureNotify), mirroring ConfigureNotify delivery. + let _dropped = + emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { + x11::encode_gravity_notify_event(buf, seq, order, child, child, nx, ny); + }); + let _dropped = + emit_window_event_to_state(state, window_id, 0x0008_0000, |buf, seq, order| { + x11::encode_gravity_notify_event(buf, seq, order, window_id, child, nx, ny); + }); + } + // NOTE (Issue 2 — 2026-07-01): a pure move MUST NOT rotate the + // redirected backing. picom glx holds a one-time `NameWindowPixmap` + // alias to the original backing (its GLX texture never re-binds + // on move), so any swap breaks the alias: the live client content + // starts landing in a new backing picom never samples, and the + // frame visually freezes ("btop stops animating when dragged"). + // The WIP `else if moved { rotate(..., true) }` that briefly lived + // here in commit bb3cc70d was this regression — reverted. + // X11 Composite + DAMAGE interaction: configuring a redirected + // window (move / resize / border / stack-order) changes its + // screen-space presentation. The pixel content of the + // redirected backing doesn't change, but the compositor MUST + // recomposite the moved-from + moved-to regions. Xorg + // signals this by emitting a `DamageNotify` on the window + // for the full window-local extent at the new geometry + // (xserver/composite/compwindow.c). Measured divergence on a + // mate-with-compositing drag: Xephyr emitted 776 DamageNotify + // events to marco over the run; yserver emitted 0. Without + // these events marco's compositor never marked the moved + // window dirty, its SetPictureClipRectangles excluded the + // window's region, and composites against the redirected + // backing no-op'd — producing the "CC disappears on drag / + // muddy bands on caja-redraw" symptom. + // + // Apply to the window itself. `accumulate_damage_full_to_state` + // walks the ancestor chain so any compositor subscribed + // higher in the tree also gets a translated rect. Only fires + // when a damage object exists on the drawable (the helper + // filters on `damage_object.drawable == this`), so cost is + // zero for unredirected/uncomposited windows. + // Xorg's Composite wakeup on ConfigureWindow is about visible + // geometry changes of redirected windows. Pure restacks + // (CWSibling/CWStackMode only) do affect stacking order, but + // they are not modeled as "whole window damaged" events. Doing + // that here seeds bogus fullscreen damage on marco's desktop + // window (0x01300005), which then collapses the compositor's + // update region before later dialog composites run. + const CONFIGURE_DAMAGE_GEOMETRY_MASK: u16 = 0x001f; // x|y|w|h|border + let geometry_changed = (request.value_mask & CONFIGURE_DAMAGE_GEOMETRY_MASK) != 0; + // Gate on Viewable, mirroring the Expose path below. Xorg + // damages a redirected window on configure only when it is + // realized/viewable (compWindowUpdateAutomatic runs on realized + // windows). i3's floating-drag creates a "floatingcon" root + // child, sizes/moves it during the drag, but never maps it — + // under an inherited RedirectSubwindows this path would emit + // full-window DamageNotify for that unmapped window, and the + // compositor (fastcompmgr) NameWindowPixmaps it and composites + // its stale backing at the drag position (the smear trail). + let viewable = state + .resources + .window(window_id) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + if geometry_changed + && viewable + && let Some(mode) = effective_redirect_mode_for_window(state, window_id) + { + log::trace!( + target: "yserver_core::core_loop::damage_fanout", + "configure_damage_emit: window=0x{:x} geom=({},{} {}x{}) old_size={:?} resized={} mode={:?} mask=0x{:x}", + window_id.0, + geometry.x, + geometry.y, + geometry.width, + geometry.height, + old_size, + resized, + mode, + request.value_mask, + ); + let _dropped = accumulate_damage_full_to_state(state, window_id); + } else if viewable + && !resized + && let Some((old_x, old_y, _, _, _)) = before_geom + && (old_x, old_y) != (geometry.x, geometry.y) + && (has_redirected_ancestor(state, window_id) + || parent.is_some_and(|p| p != crate::resources::ROOT_WINDOW)) + { + // A pure move of an UNREDIRECTED subwindow (inside a + // redirected ancestor, the backend also carries its pixels to the new + // position in the ancestor's backing, Xorg `fbCopyWindow`): + // Xorg reports that copy through `damageCopyWindow` + // (`miext/damage/damage.c`); a damage object on any ancestor + // sees it, since window damage includes inferiors. (The + // vacated area is reported by its exposure paint below.) + // Without this the compositor's damage region is just the + // parent's own ClipByChildren repaint, which excludes the + // moved window — MATE's notification area stayed blank after + // a panel drag until something else damaged that spot. + log::trace!( + target: "yserver_core::core_loop::damage_fanout", + "configure_damage_emit_inferior_move: window=0x{:x} ({},{}) -> ({},{})", + window_id.0, + old_x, + old_y, + geometry.x, + geometry.y, + ); + let _dropped = accumulate_damage_full_to_state(state, window_id); + } else { + log::trace!( + target: "yserver_core::core_loop::damage_fanout", + "configure_damage_skip: window=0x{:x} geom=({},{} {}x{}) old_size={:?} resized={} geometry_changed={} mask=0x{:x}", + window_id.0, + geometry.x, + geometry.y, + geometry.width, + geometry.height, + old_size, + resized, + geometry_changed, + request.value_mask, + ); + } + // Xorg validates the tree after a move, resize, restack or border + // change and exposes what each window shows that it did not + // (`miMoveWindow`, `miResizeWindow`, `ReflectStackChange`): its + // background painted there, unless None, and Expose sent + // (`miWindowExposures`, `mi/miexpose.c:375-410`). A resized window + // gets its whole clip list: "the entire window is trashed unless + // bitGravity recovers portions of it" (`mi/miwindow.c:466-472`); + // this server keeps no bit-gravity bits, so its window is exposed + // whole for every gravity. A top-level that is raised from under + // another is exposed like any other window (#213: awesome maps + // mpv's frame under the terminal, then raises it). + if let Some(change) = tree_change { + // A reallocated backing already had its whole ring repainted and + // damaged; Xorg reports it a second time, we keep one report. + let ring_repainted = old_backing.is_some().then_some(window_id); + send_exposures( + state, + backend, + origin, + change.exposed(state, resized.then_some(window_id)), + ring_repainted, + ); + } + } + // Xorg miMoveWindow / miResizeWindow / ReflectStackChange end in + // WindowsRestructured (`mi/miwindow.c:302,620`, `dix/window.c:2179`). + backend.windows_restructured(state); + // A confined pointer follows its confine window — re-clamp after + // any geometry change (Xorg ConfineCursorToWindow on configure; + // XGrabButton-25 moves confine_to and expects the pointer pulled + // along). + if state.pointer_confine_to.0 != 0 { + confine_pointer_now(state, backend); + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_destroy_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if let Some(window) = x11::free_resource_id(body) { + // Xorg `dix/dispatch.c::ProcDestroyWindow` returns BadWindow + // via dixLookupWindow before tearing the subtree down. xts5 + // Xlib4 probes XDestroyWindow on badwin() and expects the + // protocol error. + if state.resources.window(window).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 4, + ); + } + let access_request = RequestOpcodes::for_request(header); + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::DESTROY, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 4); + } + if window != ROOT_WINDOW { + let parent = state + .resources + .window(window) + .expect("window existence verified above") + .parent; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: parent, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::REMOVE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 4); + } + } + // `ProcDestroyWindow` frees only a window with a parent: root plans + // nothing and is a successful no-op (#297). + if let Some(plan) = state.resources.plan_destroy(window) { + let Ok(prepared) = plan.prepare(backend) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 4); + }; + finish_destroy(state, backend, origin, prepared); + } + } + debug!("client {} #{} DestroyWindow", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_destroy_subwindows( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if body.len() >= 4 { + let parent = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + // Xorg `dix/dispatch.c::ProcDestroySubwindows` returns + // BadWindow for an unknown parent xid. + if state.resources.window(parent).is_none() { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + parent.0, + 5, + ); + } + let access_request = RequestOpcodes::for_request(header); + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: parent, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::REMOVE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 5); + } + // Every child is planned and prepared before anything changes, so a + // failed preparation leaves the request undone. + let mut prepared = Vec::new(); + for child in state.resources.children(parent).to_vec() { + let Some(plan) = state.resources.plan_destroy(child) else { + continue; + }; + let Ok(ready) = plan.prepare(backend) else { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_ALLOC, 0, 5); + }; + prepared.push(ready); + } + // Xorg unmaps them all first, so all UnmapNotifies and one exposure + // of the parent precede the DestroyNotifies (`dix/window.c:1104-1124`). + unmap_subwindows_with_delta(state, backend, origin, client_id, sequence, body, None)?; + for ready in prepared { + let child = ready.plan().top(); + if super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: child, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::DESTROY, + access_request, + ) + .is_err() + { + break; + } + finish_destroy(state, backend, origin, ready); + } + } + debug!("client {} #{} DestroySubwindows", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_get_geometry( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let drawable = x11::drawable_request_id(body).unwrap_or(ROOT_WINDOW); + let (geometry, kind) = if let Some(window) = state.resources.window(drawable) { + (window_geometry(window), ResourceKind::Window) + } else if let Some(pixmap) = state.resources.pixmap(drawable) { + (pixmap_geometry(pixmap), ResourceKind::Pixmap) + } else if let Some(geometry) = glx_pbuffer_geometry(state, drawable) { + (geometry, ResourceKind::GlxDrawable) + } else { + // Spec: BadDrawable on unknown drawable. xts probes + // destroyed/stale IDs and expects the protocol error. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + drawable.0, + 14, + ); + }; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: drawable, + kind, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 14); + } + debug!( + "client {} #{} GetGeometry 0x{:x} -> root=0x{:x} pos=({},{}) size=({}x{}) border={} depth={}", + client_id.0, + sequence.0, + drawable.0, + geometry.root.0, + geometry.x, + geometry.y, + geometry.width, + geometry.height, + geometry.border_width, + geometry.depth, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_get_geometry_reply(&mut buf, byte_order, sequence, geometry)?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_query_tree( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let window = x11::drawable_request_id(body).unwrap_or(ROOT_WINDOW); + debug!( + "client {} #{} QueryTree 0x{:x}", + client_id.0, sequence.0, window.0 + ); + let Some(window_state) = state.resources.window(window) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 15, + ); + }; + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::LIST, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 15); + } + // X11 spec: the root window's parent is None. Internally we store + // root.parent = root (self) and other code relies on that invariant, so + // translate the self-parent to None only here on the QueryTree wire reply. + // Reporting the root as its own parent makes Chromium/Ozone's GeometryCache + // recurse forever (infinite QueryTree(root)+GetGeometry(root)), so Electron + // apps (VS Code) spin and never map their window. + let parent = if window_state.parent == window { + ResourceId(0) + } else { + window_state.parent + }; + // Xorg's QueryTree stops at RealChildHead (dix/dispatch.c:1078), which + // Composite points at the overlay window while it tops the root + // (composite/compwindow.c:762): the COW is a root child nobody lists. + let mut children = window_state.children.clone(); + if window == ROOT_WINDOW { + children.retain(|child| *child != COMPOSITE_OVERLAY_WINDOW); + } + debug!( + "client {} #{} QueryTree reply 0x{:x}: parent=0x{:x} children={}", + client_id.0, + sequence.0, + window.0, + parent.0, + children.len(), + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(64); + x11::write_query_tree_reply( + &mut buf, + byte_order, + sequence, + ROOT_WINDOW, + parent, + &children, + )?; + Ok(write_to_client(client, client_id, &buf)) +} + +pub(super) fn handle_map_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(window) = x11::map_window_id(body) else { + return Ok(RequestOutcome::Handled); + }; + let Some((parent, override_redirect, current_map_state)) = state + .resources + .window(window) + .map(|w| (w.parent, w.override_redirect, w.map_state)) + else { + // Xorg `dix/dispatch.c::ProcMapWindow` does `dixLookupWindow` + // first and returns BadWindow on lookup failure. xts5 Xlib4 + // probes XMapWindow on a freed xid (badwin()) and expects the + // protocol error. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 8, + ); + }; + + if super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SHOW, + request, + ) + .is_err() + { + return Ok(RequestOutcome::Handled); + } + + // Per X11 protocol (Xorg `dix/window.c:2661`): "If the window is + // already mapped, this request has no effect." This MUST guard + // the MapRequest dispatch below, not just the local mapping — + // otherwise (a) the root window, which is permanently + // `Viewable` and whose `parent` field points to itself, fans a + // phantom MapRequest(parent=root, window=root) to any WM with + // SubstructureRedirect on root (mate-screensaver hits this on + // activation; marco's panic-response drops its substructure + // subscription and breaks compositing of every subsequent + // top-level); and (b) brisk-menu's ~50 Hz + // `gtk_window_present`/`XMapRaised` loop on its already-viewable + // popup re-fans MapNotify → Expose → full-extent damage, + // triggering marco's per-MapNotify `COMPOSITE::NameWindowPixmap` + // + recomposite (visible as menu flicker on KMS). + if current_map_state != MapState::Unmapped { + debug!( + "client {} #{} MapWindow 0x{:x} (already mapped — no-op)", + client_id.0, sequence.0, window.0 + ); + return Ok(RequestOutcome::Handled); + } + + // SubstructureRedirect on the parent: forward MapRequest to the + // first subscriber that isn't the requester (the WM), and skip + // mapping locally. + let redirect_targets: Vec = if !override_redirect { + let requester_has = state + .clients + .get(&client_id.0) + .and_then(|c| c.event_masks.get(&parent).copied()) + .is_some_and(|m| m & 0x0010_0000 != 0); + if requester_has { + Vec::new() + } else { + subscribers_by_id(state, parent, 0x0010_0000) + } + } else { + Vec::new() + }; + + if !redirect_targets.is_empty() { + debug!( + "client {} MapWindow 0x{:x} -> MapRequest to WM", + client_id.0, window.0 + ); + let _dropped = fanout_event_to_clients(state, &redirect_targets, |buf, seq, order| { + x11::encode_map_request_event(buf, seq, order, parent, window); + }); + return Ok(RequestOutcome::Handled); + } + + let transition = state.resources.map_window(window); + debug_assert!( + transition.mapping_changed, + "current_map_state == Unmapped guard above was checked; \ + map_window should now transition", + ); + let host_xid = state.resources.window(window).and_then(|w| w.host_xid); + let map_info = state + .resources + .window(window) + .map(|w| (w.parent, w.override_redirect)); + if let Some(xid) = host_xid { + let _ = backend.map_subwindow(origin, xid.as_raw()); + } + realize_storage_for_delta(state, backend, origin, &transition.delta); + // Every window that became viewable under a redirect (its own, or its + // parent's RedirectSubwindows) gets a backing, as Xorg allocates on + // realize (`compwindow.c:274`). AFTER `map_subwindow` per the plan's + // codex-round-6 ordering fix — `map_subwindow` blindly flips + // `scene_participating = true`, so the Manual participation flip + // inside `activate_redirect_backing_for` must land last. + apply_viewability_delta_to_redirects(state, backend, origin, &transition.delta); + if host_xid.is_some() { + reapply_redirect_mode_after_map(state, backend, origin, window); + } + + if let Some((parent, override_redir)) = map_info { + let _dropped = emit_window_event_to_state(state, window, 0x0002_0000, |buf, seq, order| { + x11::encode_map_notify_event(buf, seq, order, window, window, override_redir); + }); + let _dropped = emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { + x11::encode_map_notify_event(buf, seq, order, parent, window, override_redir); + }); + // Emit VisibilityNotify(Unobscured) then Expose on the window + // itself when it becomes viewable. Subscribed clients want the + // newly-viewable window to redraw. + let viewable = state + .resources + .window(window) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + if viewable { + // VisibilityNotify(Unobscured) for clients selecting + // VisibilityChangeMask (0x10000). Under yserver's compositor + // model every viewable top-level is effectively unobscured. + // Without this, GTK3 leaves the window in a non-paintable + // visibility state and suppresses all frame-clock paints + // after the first expose-driven frame — the + // cinnamon-settings "title changes but content never + // repaints" freeze. Xorg sends Unobscured on map; we mirror + // that. (We never send Obscured: a composited top-level is + // always paintable, and unmap is signalled by UnmapNotify + // per spec, not VisibilityNotify.) + let _dropped = + emit_window_event_to_state(state, window, 0x0001_0000, |buf, seq, order| { + x11::encode_visibility_notify_event(buf, seq, order, window, 0); + }); + // Descendants that were MapWindow'd while this window was + // still unmapped were Unviewable; mapping this window + // transitions them to Viewable. Xorg fires + // VisibilityNotify(Unobscured) on every such descendant + // (mate-xorg.xtrace seq 0x0147 shows VisibilityNotify on + // both the FF main window and its child 0x02400010). + // yserver previously only notified the directly-mapped + // window, so GTK3's frame clock for the child never woke + // and the profile chooser stayed blank — the "empty shadow" + // FF bug on bee. Order with the Expose subtree walk below + // doesn't matter; both are subtree-wide and idempotent. + let _dropped = emit_visibility_unobscured_subtree_to_state(state, window); + send_map_exposures(state, backend, origin, &[window]); + } + } + // Xorg MapWindow ends in WindowsRestructured (`dix/window.c:2695`): the + // pointer's crossings follow MapNotify and Expose within the request. + backend.windows_restructured(state); + debug!( + "client {} #{} MapWindow 0x{:x} viewable+{}", + client_id.0, + sequence.0, + window.0, + transition.delta.became_viewable.len() + ); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_map_subwindows( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + map_subwindows_with_delta( + state, + backend, + origin, + client_id, + sequence, + access_request, + body, + ) + .map(|(outcome, _delta)| outcome) +} + +/// MapSubwindows; also returns the union of the children's viewability deltas. +pub(super) fn map_subwindows_with_delta( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result<(RequestOutcome, ViewabilityDelta)> { + let mut delta = ViewabilityDelta::default(); + let Some(parent) = x11::map_window_id(body) else { + return Ok((RequestOutcome::Handled, delta)); + }; + if state.resources.window(parent).is_none() { + // Xorg `dix/dispatch.c::ProcMapSubwindows` returns BadWindow + // for an unknown parent xid. xts5 Xlib4 probes XMapSubwindows + // on badwin() and expects the protocol error. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + parent.0, + 9, + ) + .map(|outcome| (outcome, delta)); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: parent, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::LIST, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 9) + .map(|outcome| (outcome, delta)); + } + // Xorg walks firstChild→nextSib, top-most first, mapping, notifying and + // realizing each in turn (`dix/window.c:2739-2758`). + let children: Vec = state + .resources + .children(parent) + .iter() + .rev() + .copied() + .collect(); + let mut newly_viewable = Vec::new(); + for child in children { + if super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: child, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::SHOW, + access_request, + ) + .is_err() + { + continue; + } + let transition = state.resources.map_window(child); + let was_unmapped = transition.mapping_changed; + let host_xid = state.resources.window(child).and_then(|w| w.host_xid); + let override_redirect = state + .resources + .window(child) + .is_some_and(|w| w.override_redirect); + if let Some(xid) = host_xid { + let _ = backend.map_subwindow(origin, xid.as_raw()); + } + realize_storage_for_delta(state, backend, origin, &transition.delta); + // Same post-hook as `handle_map_window`: AFTER `map_subwindow`. + apply_viewability_delta_to_redirects(state, backend, origin, &transition.delta); + delta.extend(transition.delta); + if host_xid.is_some() { + reapply_redirect_mode_after_map(state, backend, origin, child); + } + if was_unmapped { + let _dropped = + emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { + x11::encode_map_notify_event(buf, seq, order, child, child, override_redirect); + }); + let _dropped = + emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { + x11::encode_map_notify_event(buf, seq, order, parent, child, override_redirect); + }); + } + // Only a child now Viewable (its parent mapped too) is exposed, + // with the descendants that mapping it promoted to Viewable. + let viewable = state + .resources + .window(child) + .is_some_and(|w| w.map_state == MapState::Viewable); + if was_unmapped && viewable { + newly_viewable.push(child); + } + } + // Xorg maps them all, then validates and exposes once: top-most first, + // each clipped by the siblings mapped with it (`dix/window.c:2760-2775`). + send_map_exposures(state, backend, origin, &newly_viewable); + // Xorg MapSubwindows: one WindowsRestructured after the batch + // (`dix/window.c:2775`). + backend.windows_restructured(state); + debug!( + "client {} #{} MapSubwindows viewable+{}", + client_id.0, + sequence.0, + delta.became_viewable.len() + ); + Ok((RequestOutcome::Handled, delta)) +} + +pub(super) fn handle_unmap_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + if let Some(window) = x11::map_window_id(body) { + if state.resources.window(window).is_none() { + // Xorg `dix/dispatch.c::ProcUnmapWindow` returns BadWindow + // via dixLookupWindow before unmapping. xts5 Xlib4 probes + // XUnmapWindow on badwin() and expects the protocol error. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + 10, + ); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::HIDE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 10); + } + unmap_window(state, backend, origin, window, false); + } + debug!("client {} #{} UnmapWindow", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +/// Xorg `UnmapWindow(pWin, fromConfigure)` (`dix/window.c:2844-2875`) on a +/// window that exists: UnmapNotify with `from_configure`, the backend and +/// storage let go, focus and grabs on the unviewable subtree dropped. Not +/// from a configure, it also exposes what the window covered and ends in +/// WindowsRestructured; from one (`miResizeWindow`'s UnmapGravity children) +/// the resize validates and exposes, and restructures once. +pub(super) fn unmap_window( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + window: ResourceId, + from_configure: bool, +) { + let host_xid = state.resources.window(window).and_then(|w| w.host_xid); + let viewable_before = state + .resources + .window(window) + .is_some_and(|w| w.map_state == MapState::Viewable); + let clips_before = if viewable_before && !from_configure { + crate::core_loop::clip_list::clip_entries_under(state, window) + } else { + Vec::new() + }; + let transition = state.resources.unmap_window(window); + let was_mapped = transition.mapping_changed; + let parent = if was_mapped { + state + .resources + .window(window) + .map_or(ROOT_WINDOW, |w| w.parent) + } else { + ROOT_WINDOW + }; + if let Some(xid) = host_xid { + let _ = backend.unmap_subwindow(origin, xid.as_raw()); + } + // Xorg frees each redirect pixmap at unrealize (`compwindow.c:291`). + apply_viewability_delta_to_redirects(state, backend, origin, &transition.delta); + release_storage_for_delta(state, backend, origin, &transition.delta); + // XI1: an active device grab is released automatically when its + // grab window becomes not viewable (XTS XGrabDeviceKey-9; Xorg + // DeactivateGrabsOnWindowUnmap shape). + if was_mapped { + let released: Vec = state + .xi1_active_grabs + .iter() + .filter(|(_, g)| { + state + .resources + .window(g.grab_window) + .is_none_or(|w| w.map_state != crate::resources::MapState::Viewable) + }) + .map(|(d, _)| *d) + .collect(); + for dev in released { + release_xi1_active_grab(state, backend, dev); + } + } + if was_mapped { + let _dropped = emit_window_event_to_state(state, window, 0x0002_0000, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, window, window, from_configure); + }); + let _dropped = emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, parent, window, from_configure); + }); + // What it covered is exposed: its parent's and lower + // siblings' backgrounds painted there, and Expose sent + // (`UnmapWindow`, `dix/window.c:2856-2866`). From a configure the + // caller's validation exposes it. + if viewable_before && !from_configure { + let after = crate::core_loop::clip_list::clip_entries_under(state, window); + send_exposures( + state, + backend, + origin, + crate::core_loop::clip_list::newly_exposed(&clips_before, after, None), + None, + ); + } + // XI1: a device focus on a window that just became + // unviewable reverts per its revert_to, emitting + // DeviceFocusIn/Out (Xi/exevents.c + // DeleteDeviceFromAnyExtEvents). After UnmapNotify, matching + // Xorg's UnmapWindow → UnrealizeTree ordering. + crate::core_loop::xi1_focus::revert_unviewable_focus(state); + // Core focus likewise (Xorg UnrealizeTree → + // DeleteWindowFromAnyEvents): covers the focus window + // itself or any unmapped ancestor. + revert_core_focus_if_unviewable(state); + // Active grabs on a window that just became unviewable + // deactivate too (same Xorg path). + release_core_grabs_for_unviewable(state, backend); + // Then WindowsRestructured (`dix/window.c:2870-2872`). + if !from_configure { + backend.windows_restructured(state); + } + } +} + +/// Deactivate `dev`'s XI1 active grab when its window stops being viewable +/// or is destroyed, as UngrabDevice does: thaw the device, release the +/// paired device held on the grab's behalf, then replay what the freeze +/// withheld (Xorg `DeactivateGrab`, `dix/events.c:1694-1700`, `:1819`). +pub(super) fn release_xi1_active_grab( + state: &mut ServerState, + backend: &mut dyn Backend, + dev: u16, +) { + crate::core_loop::pointer_fanout::xi1_deactivate_device_grab(state, dev); + let xid_map = backend.xid_map().clone(); + crate::core_loop::pointer_fanout::xi1_compute_freezes(state, backend, &xid_map); +} + +pub(super) fn handle_unmap_subwindows( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let Some(parent) = x11::map_window_id(body) else { + return Ok(RequestOutcome::Handled); + }; + let Some(mut children) = state.resources.mapped_children_bottom_to_top(parent) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + parent.0, + 11, + ); + }; + if parent == ROOT_WINDOW { + children.retain(|child| *child != COMPOSITE_OVERLAY_WINDOW); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: parent, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::LIST, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 11); + } + let denied_children = children + .into_iter() + .filter(|child| { + super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: *child, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::HIDE, + access_request, + ) + .is_err() + }) + .collect::>(); + unmap_subwindows_with_delta( + state, + backend, + origin, + client_id, + sequence, + body, + Some(&denied_children), + ) + .map(|(outcome, _delta)| outcome) +} + +/// UnmapSubwindows; also returns the union of the children's viewability deltas. +pub(super) fn unmap_subwindows_with_delta( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + denied_children: Option<&HashSet>, +) -> io::Result<(RequestOutcome, ViewabilityDelta)> { + let mut delta = ViewabilityDelta::default(); + let Some(parent) = x11::map_window_id(body) else { + return Ok((RequestOutcome::Handled, delta)); + }; + struct PendingUnmap { + child: ResourceId, + host_xid: Option, + } + let Some(mut children) = state.resources.mapped_children_bottom_to_top(parent) else { + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + parent.0, + 11, + ) + .map(|outcome| (outcome, delta)); + }; + // UnmapSubwindows stops at RealChildHead too (dix/window.c:2897): the + // overlay window stays mapped. + if parent == ROOT_WINDOW { + children.retain(|child| *child != COMPOSITE_OVERLAY_WINDOW); + } + if let Some(denied_children) = denied_children { + children.retain(|child| !denied_children.contains(child)); + } + let clip_before = crate::core_loop::clip_list::clip_list(state, parent); + // Snapshot mapping order + collect host xids; unmap each in the + // resource table. + let mut pending: Vec = Vec::new(); + for child in children { + let host_xid = state.resources.window(child).and_then(|w| w.host_xid); + let transition = state.resources.unmap_window(child); + delta.extend(transition.delta); + if transition.mapping_changed { + pending.push(PendingUnmap { child, host_xid }); + } + } + for item in pending { + if let Some(xid) = item.host_xid { + let _ = backend.unmap_subwindow(origin, xid.as_raw()); + } + let child = item.child; + let _dropped = emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, child, child, false); + }); + let _dropped = emit_window_event_to_state(state, parent, 0x0008_0000, |buf, seq, order| { + x11::encode_unmap_notify_event(buf, seq, order, parent, child, false); + }); + } + // Xorg frees each redirect pixmap at unrealize (`compwindow.c:291`). + apply_viewability_delta_to_redirects(state, backend, origin, &delta); + release_storage_for_delta(state, backend, origin, &delta); + // The parent is exposed where its children were (`dix/window.c:2925-2933`). + let gained = crate::core_loop::clip_list::subtract( + &crate::core_loop::clip_list::clip_list(state, parent), + &clip_before, + ); + send_window_exposures(state, backend, origin, parent, &gained, true); + crate::core_loop::xi1_focus::revert_unviewable_focus(state); + revert_core_focus_if_unviewable(state); + release_core_grabs_for_unviewable(state, backend); + // Xorg UnmapSubwindows: one WindowsRestructured (`dix/window.c:2939`). + backend.windows_restructured(state); + debug!( + "client {} #{} UnmapSubwindows viewable-{}", + client_id.0, + sequence.0, + delta.became_unviewable.len() + ); + Ok((RequestOutcome::Handled, delta)) +} + +pub(super) fn handle_get_window_attributes( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let id = x11::drawable_request_id(body).unwrap_or(ROOT_WINDOW); + debug!( + "client {} #{} GetWindowAttributes 0x{:x}", + client_id.0, sequence.0, id.0, + ); + // Spec: BadWindow on unknown window ID. Don't silently fall back to + // ROOT_WINDOW — xts probes stale/destroyed XIDs and expects the + // protocol error. + if state.resources.window(id).is_none() { + return emit_x11_error(state, client_id, sequence, x11::error::BAD_WINDOW, id.0, 3); + } + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + RequestOpcodes::for_request(header), + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 3); + } + let target = id; + let your_event_mask = state + .clients + .get(&client_id.0) + .and_then(|c| c.event_masks.get(&target).copied()) + .unwrap_or(0); + let all_event_masks: u32 = state + .clients + .values() + .filter_map(|c| c.event_masks.get(&target).copied()) + .fold(0u32, |a, b| a | b); + let attrs = window_attributes( + state.resources.window(target), + all_event_masks, + your_event_mask, + ); + if let Some(window) = state.resources.window(target) { + debug!( + "client {} #{} GetWindowAttributes reply 0x{:x}: parent=0x{:x} map_state={} override_redirect={}", + client_id.0, + sequence.0, + target.0, + window.parent.0, + attrs.map_state, + attrs.override_redirect, + ); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(48); + x11::write_get_window_attributes_reply(&mut buf, byte_order, sequence, attrs)?; + Ok(write_to_client(client, client_id, &buf)) +} + +fn window_attributes( + window: Option<&Window>, + all_event_masks: u32, + your_event_mask: u32, +) -> x11::WindowAttributes { + let window = window.expect("root window exists"); + x11::WindowAttributes { + visual: window.visual, + class: window.class.protocol_value(), + bit_gravity: window.bit_gravity, + win_gravity: window.win_gravity, + backing_store: window.backing_store, + backing_planes: window.backing_planes, + backing_pixel: window.backing_pixel, + save_under: window.save_under, + map_is_installed: true, + map_state: window.map_state.protocol_value(), + override_redirect: window.override_redirect, + colormap: window.colormap, + all_event_masks, + your_event_mask, + do_not_propagate_mask: window.do_not_propagate_mask, + } +} + +pub(super) fn handle_circulate_window( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if body.len() < 4 { + debug!( + "client {} #{} CirculateWindow (short body)", + client_id.0, sequence.0 + ); + return Ok(RequestOutcome::Handled); + } + let container = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let direction = header.data; + if state.resources.window(container).is_none() { + // Xorg `dix/dispatch.c::ProcCirculateWindow` returns BadWindow + // via dixLookupWindow on an unknown xid. xts5 Xlib4 probes + // XCirculateSubwindows{,Up,Down} on badwin() and expects it. + return emit_x11_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + container.0, + 13, + ); + } + let access_request = RequestOpcodes::for_request(header); + if let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: container, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::MANAGE, + access_request, + ) { + return emit_x11_error(state, client_id, sequence, code, bad_value, 13); + } + let Some(child) = state.circulate_candidate(container, direction) else { + return Ok(RequestOutcome::Handled); + }; + if super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: child, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::MANAGE | AccessMode::SET_ATTR, + access_request, + ) + .is_err() + { + return Ok(RequestOutcome::Handled); + } + // SubstructureRedirect on the container by another client turns it into + // a CirculateRequest (Xorg MaybeDeliverEventsToClient skips the + // requester). + let redirect_target = subscribers_by_id(state, container, 0x0010_0000) + .into_iter() + .find(|c| *c != client_id); + if let Some(target) = redirect_target { + let _dropped = fanout_event_to_clients(state, &[target], |buf, seq, order| { + let _ = + x11::write_circulate_request_event(buf, order, seq, container, child, direction); + }); + } else { + let tree_change = crate::core_loop::clip_list::TreeChange::begin(state, child, None); + state.resources.circulate_child(child, direction == 0); + if let Some(xid) = state.resources.window(child).and_then(|w| w.host_xid) { + let _ = backend.configure_subwindow( + None, + xid.as_raw(), + crate::host_x11::HostSubwindowConfig { + x: None, + y: None, + width: None, + height: None, + border_width: None, + sibling: None, + stack_mode: Some(if direction == 0 { 0 } else { 1 }), + }, + ); + } + backend.sync_top_level_order(state); + // CirculateNotify to the window's StructureNotify and the parent's + // SubstructureNotify selectors, each with its own event window; the + // place (OnTop 0 / OnBottom 1) equals the direction. + let _dropped = emit_window_event_to_state(state, child, 0x0002_0000, |buf, seq, order| { + let _ = x11::write_circulate_notify_event(buf, order, seq, child, child, direction); + }); + let _dropped = + emit_window_event_to_state(state, container, 0x0008_0000, |buf, seq, order| { + let _ = + x11::write_circulate_notify_event(buf, order, seq, container, child, direction); + }); + // Then ReflectStackChange validates and exposes (`dix/window.c:2149-2176`). + if let Some(change) = tree_change { + send_exposures(state, backend, None, change.exposed(state, None), None); + } + // Xorg ReflectStackChange (`dix/window.c:2179`). + backend.windows_restructured(state); + } + debug!("client {} #{} CirculateWindow", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_change_save_set( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + if body.len() >= 4 { + let win = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + if state.resources.window(win).is_some() + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: win, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::MANAGE, + RequestOpcodes::for_request(header), + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 6); + } + if let Some(c) = state.clients.get_mut(&client_id.0) { + match header.data { + 0 => { + c.save_set.insert(win); + } + 1 => { + c.save_set.remove(&win); + } + _ => {} + } + } + } + debug!("client {} #{} ChangeSaveSet", client_id.0, sequence.0); + Ok(RequestOutcome::Handled) +} + +fn window_geometry(window: &Window) -> x11::Geometry { + x11::Geometry { + root: ROOT_WINDOW, + x: window.x, + y: window.y, + width: window.width, + height: window.height, + border_width: window.border_width, + depth: window.depth, + } +} + +fn pixmap_geometry(pixmap: &Pixmap) -> x11::Geometry { + x11::Geometry { + root: ROOT_WINDOW, + x: 0, + y: 0, + width: pixmap.width, + height: pixmap.height, + border_width: 0, + depth: pixmap.depth, + } +} + +/// Geometry of a GLX pbuffer (#96). Pbuffers are tracked in `glx_drawables` +/// with their `CreatePbuffer` size but are absent from the core resource +/// store, so `GetGeometry` must resolve them here. A 0×0 pbuffer returns +/// `None` (size guard preserved): the caller then falls through to the +/// backing pixmap clamped to 1×1 by `CREATE_PBUFFER`, and a missing +/// drawable stays `BadDrawable` instead of becoming a Success(0×0). +fn glx_pbuffer_geometry(state: &ServerState, drawable: ResourceId) -> Option { + let d = state.glx_drawables.get(&drawable.0)?; + if d.kind != crate::server::GlxDrawableKind::Pbuffer || (d.width == 0 && d.height == 0) { + return None; + } + Some(x11::Geometry { + root: ROOT_WINDOW, + x: 0, + y: 0, + width: u16::try_from(d.width).unwrap_or(u16::MAX), + height: u16::try_from(d.height).unwrap_or(u16::MAX), + border_width: 0, + depth: glx_fbconfig_depth(d.fbconfig), + }) +} + +#[allow(clippy::cast_possible_truncation)] +pub(super) fn handle_translate_coordinates( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + access_request: RequestOpcodes, + body: &[u8], +) -> io::Result { + let (child, dst_x, dst_y, log_src, log_dst, log_src_xy) = if body.len() >= 12 { + let src_window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let dst_window = ResourceId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let src_x = i16::from_le_bytes([body[8], body[9]]); + let src_y = i16::from_le_bytes([body[10], body[11]]); + if state.resources.window(src_window).is_some() + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: src_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 40); + } + if state.resources.window(dst_window).is_some() + && let Err((code, bad_value)) = super::validate_resource_access( + state, + client_id, + ResourceTarget { + id: dst_window, + kind: ResourceKind::Window, + creation: None, + }, + AccessMode::GET_ATTR, + access_request, + ) + { + return emit_x11_error(state, client_id, sequence, code, bad_value, 40); + } + let (src_abs_x, src_abs_y) = state.resources.window_absolute_position(src_window); + let abs_x = src_abs_x + i32::from(src_x); + let abs_y = src_abs_y + i32::from(src_y); + let (dst_abs_x, dst_abs_y) = state.resources.window_absolute_position(dst_window); + let dst_x = (abs_x - dst_abs_x) as i16; + let dst_y = (abs_y - dst_abs_y) as i16; + // Xorg ProcTranslateCoords checks both bounding and input shapes + // while walking the destination's direct children. Reuse the + // server's shape-aware hit test so the Composite Overlay Window's + // empty input shape does not hide a mapped popup beneath it. + let child = state + .direct_child_at(dst_window, dst_x, dst_y) + .unwrap_or(ResourceId(0)); + ( + child, + dst_x, + dst_y, + src_window.0, + dst_window.0, + (src_x, src_y), + ) + } else { + (ResourceId(0), 0i16, 0i16, 0u32, 0u32, (0i16, 0i16)) + }; + debug!( + "client {} #{} TranslateCoordinates src=0x{:x} dst=0x{:x} src_xy=({},{}) -> dst_xy=({},{}) child=0x{:x}", + client_id.0, + sequence.0, + log_src, + log_dst, + log_src_xy.0, + log_src_xy.1, + dst_x, + dst_y, + child.0, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let mut buf: Vec = Vec::with_capacity(32); + x11::write_translate_coordinates_reply(&mut buf, byte_order, sequence, child, dst_x, dst_y)?; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch.rs new file mode 100644 index 000000000..b3294a1fb --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch.rs @@ -0,0 +1,271 @@ +//! XInput requests, XI 1.x and XI2 on the one major opcode: +//! `handle_xi2_request` checks the request length and hands each minor to +//! its own `handle_xi1_*` / `handle_xi_*` fn; replies go out through +//! `xi_write_reply`. XIWarpPointer lives in `focus_pointer`, XISetFocus and +//! XIChangeHierarchy in `xi/mod.rs`. The per-minor fns live in: +//! +//! - `devices`: versions (1, 47), device lists (2, 48), open/close/mode +//! (3–5), keyboard/pointer device change (11, 12), client pointer +//! (44, 45). +//! - `control`: motion history (10), feedback (22, 23), key/modifier/button +//! mappings (24–29), device state (30), bell (32), valuators (33), device +//! controls (34, 35). +//! - `events`: XI1 selection (6, 7), don't-propagate lists (8, 9), +//! SendExtensionEvent (31), XI2 selection (46, 60). +//! - `grabs`: XI1 grabs and AllowDeviceEvents (13–19), XI2 grabs and +//! XIAllowEvents (51–55). +//! - `props`: XI1 (36–39) and XI2 (56–59) device properties. +//! - `focus`: device focus (20, 21, 50), XIQueryPointer (40), +//! XIChangeCursor (42), barrier release (61). + +mod control; +mod devices; +mod events; +mod focus; +mod grabs; +mod props; + +pub(in crate::core_loop::process_request) use grabs::deactivate_xi2_device_grab; + +use crate::{ + backend::{Backend, OriginContext}, + core_loop::process_request::{ + RequestOutcome, XINPUT_LAST_REQUEST, emit_x11_error_with_minor, + focus_pointer::handle_xi_warp_pointer, + write_to_client, + xi::{ + dispatch::{ + control::{ + handle_xi1_change_device_control, handle_xi1_change_device_key_mapping, + handle_xi1_change_feedback_control, handle_xi1_device_bell, + handle_xi1_get_device_button_mapping, handle_xi1_get_device_control, + handle_xi1_get_device_key_mapping, handle_xi1_get_device_modifier_mapping, + handle_xi1_get_device_motion_events, handle_xi1_get_feedback_control, + handle_xi1_query_device_state, handle_xi1_set_device_button_mapping, + handle_xi1_set_device_modifier_mapping, handle_xi1_set_device_valuators, + }, + devices::{ + handle_xi_get_client_pointer, handle_xi_query_device, handle_xi_query_version, + handle_xi_set_client_pointer, handle_xi1_change_keyboard_device, + handle_xi1_change_pointer_device, handle_xi1_close_device, + handle_xi1_get_extension_version, handle_xi1_list_input_devices, + handle_xi1_open_device, handle_xi1_set_device_mode, + }, + events::{ + handle_xi_get_selected_events, handle_xi_select_events, + handle_xi1_change_device_dont_propagate_list, + handle_xi1_get_device_dont_propagate_list, + handle_xi1_get_selected_extension_events, handle_xi1_select_extension_event, + handle_xi1_send_extension_event, + }, + focus::{ + handle_xi_barrier_release_pointer, handle_xi_change_cursor, + handle_xi_get_focus, handle_xi_query_pointer, handle_xi1_get_device_focus, + handle_xi1_set_device_focus, + }, + grabs::{ + handle_xi_allow_events, handle_xi_grab_device, handle_xi_passive_grab_device, + handle_xi_passive_ungrab_device, handle_xi_ungrab_device, + handle_xi1_allow_device_events, handle_xi1_grab_device, + handle_xi1_grab_device_button, handle_xi1_grab_device_key, + handle_xi1_ungrab_device, handle_xi1_ungrab_device_button, + handle_xi1_ungrab_device_key, + }, + props::{ + handle_xi_change_property, handle_xi_delete_property, handle_xi_get_property, + handle_xi_list_properties, handle_xi1_change_device_property, + handle_xi1_delete_device_property, handle_xi1_get_device_property, + handle_xi1_list_device_properties, + }, + }, + handle_xi_change_hierarchy, handle_xi_set_focus, xi2_request_has_complete_dynamic_tail, + }, + }, + server::ServerState, +}; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}, +}; + +pub(in crate::core_loop::process_request) fn handle_xi2_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let byte_order = state + .clients + .get(&client_id.0) + .map_or(ClientByteOrder::LittleEndian, |c| c.byte_order); + let minor = header.data; + // Per-minor length validation mirroring Xorg's `REQUEST_SIZE_MATCH` / + // `REQUEST_AT_LEAST_SIZE` macros invoked at the top of each `ProcX*` + // handler in `xserver/Xi/*.c`. xts5 XIproto probes under-/over-length + // headers for every XI minor and expects core `BadLength` (code 16), + // not the extension-level `BadDevice` the handlers would otherwise + // produce after mis-parsing the truncated/extended body. The XI + // `minor_opcode` is also stamped into the error reply so the test + // harness can attribute the failure. + if !x11::request_lengths::validate_xi_request_length(minor, header.length_units) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + // Content-derived exact-length check for variable-length minors. + // xts5 probes both `length-1` and `length+1`; the AtLeast gate + // catches the under-length case while this gate catches the + // over-length one. + if !x11::request_lengths::validate_xi_exact_request_length(minor, header.length_units, body) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + // Xorg's XI swap/dispatch path checks these content-derived tails before + // handling any selection or grab records. The request swapper has already + // converted the dynamic length fields to LE, while mask bytes remain + // opaque. Keep this check ahead of all state changes so a truncated later + // record cannot leave earlier selections or grabs installed. + if !xi2_request_has_complete_dynamic_tail(minor, body) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + match minor { + 1 => handle_xi1_get_extension_version(state, client_id, sequence, header, body, byte_order), + 42 => handle_xi_change_cursor(state, backend, origin, client_id, sequence, body), + 44 => handle_xi_set_client_pointer(client_id, sequence), + 45 => handle_xi_get_client_pointer(state, client_id, sequence, byte_order), + 46 => handle_xi_select_events(state, backend, origin, client_id, sequence, header, body), + 47 => handle_xi_query_version(state, client_id, sequence, body, byte_order), + 48 => handle_xi_query_device(state, client_id, sequence, body, byte_order), + 56 => handle_xi_list_properties(state, client_id, sequence, body, byte_order), + 57 => handle_xi_change_property(state, backend, client_id, sequence, body, byte_order), + 58 => handle_xi_delete_property(state, client_id, sequence, body), + 59 => handle_xi_get_property(state, client_id, sequence, body, byte_order), + 60 => handle_xi_get_selected_events(state, client_id, sequence, body, byte_order), + 40 => handle_xi_query_pointer( + state, backend, origin, client_id, sequence, body, byte_order, + ), + 51 => handle_xi_grab_device( + state, backend, origin, client_id, sequence, body, byte_order, + ), + 52 => handle_xi_ungrab_device(state, backend, origin, client_id, sequence, body), + 53 => handle_xi_allow_events(state, backend, client_id, sequence, body), + 54 => handle_xi_passive_grab_device(state, client_id, sequence, body, byte_order), + 55 => handle_xi_passive_ungrab_device(state, client_id, sequence, body), + 2 => handle_xi1_list_input_devices(state, client_id, sequence, byte_order), + 6 => handle_xi1_select_extension_event(state, client_id, sequence, body, minor), + 36 => handle_xi1_list_device_properties(state, client_id, sequence, body, byte_order), + 37 => { + handle_xi1_change_device_property(state, backend, client_id, sequence, body, byte_order) + } + 38 => handle_xi1_delete_device_property(state, client_id, sequence, body), + 39 => handle_xi1_get_device_property(state, client_id, sequence, body, byte_order), + 3 => handle_xi1_open_device(state, client_id, sequence, body, byte_order, minor), + 4 => handle_xi1_close_device(state, client_id, sequence, body, minor), + 5 => handle_xi1_set_device_mode(state, client_id, sequence, body, byte_order, minor), + 7 => handle_xi1_get_selected_extension_events( + state, client_id, sequence, body, byte_order, minor, + ), + 8 => handle_xi1_change_device_dont_propagate_list(state, client_id, sequence, body, minor), + 9 => handle_xi1_get_device_dont_propagate_list( + state, client_id, sequence, body, byte_order, minor, + ), + 10 => { + handle_xi1_get_device_motion_events(state, client_id, sequence, body, byte_order, minor) + } + 11 => { + handle_xi1_change_keyboard_device(state, client_id, sequence, body, byte_order, minor) + } + 12 => handle_xi1_change_pointer_device(state, client_id, sequence, minor), + 13 => handle_xi1_grab_device(state, client_id, sequence, body, byte_order, minor), + 14 => handle_xi1_ungrab_device(state, client_id, sequence, body, minor), + 15 => handle_xi1_grab_device_key(state, client_id, sequence, body, minor), + 16 => handle_xi1_ungrab_device_key(state, client_id, sequence, body, minor), + 17 => handle_xi1_grab_device_button(state, client_id, sequence, body, minor), + 18 => handle_xi1_ungrab_device_button(state, client_id, sequence, body, minor), + 19 => handle_xi1_allow_device_events(state, backend, client_id, sequence, body, minor), + 20 => handle_xi1_get_device_focus(state, client_id, sequence, body, byte_order, minor), + 21 => handle_xi1_set_device_focus(state, client_id, sequence, body, minor), + 22 => handle_xi1_get_feedback_control(state, client_id, sequence, body, byte_order, minor), + 23 => handle_xi1_change_feedback_control(state, client_id, sequence, body, minor), + 24 => handle_xi1_get_device_key_mapping( + state, backend, origin, client_id, sequence, body, byte_order, minor, + ), + 25 => handle_xi1_change_device_key_mapping( + state, backend, client_id, sequence, body, byte_order, minor, + ), + 26 => handle_xi1_get_device_modifier_mapping( + state, backend, origin, client_id, sequence, body, byte_order, minor, + ), + 27 => handle_xi1_set_device_modifier_mapping( + state, backend, origin, client_id, sequence, body, byte_order, minor, + ), + 28 => handle_xi1_get_device_button_mapping( + state, client_id, sequence, body, byte_order, minor, + ), + 29 => handle_xi1_set_device_button_mapping( + state, client_id, sequence, body, byte_order, minor, + ), + 30 => handle_xi1_query_device_state(state, client_id, sequence, body, byte_order, minor), + 31 => handle_xi1_send_extension_event(state, client_id, sequence, body, byte_order, minor), + 32 => handle_xi1_device_bell(state, client_id, sequence, body, minor), + 33 => handle_xi1_set_device_valuators(state, client_id, sequence, body, byte_order, minor), + 34 => handle_xi1_get_device_control(state, client_id, sequence, body, byte_order, minor), + 35 => handle_xi1_change_device_control(state, client_id, sequence, body, byte_order, minor), + 50 => handle_xi_get_focus(state, client_id, sequence, body, byte_order, minor), + 61 => handle_xi_barrier_release_pointer(state, client_id, sequence, body), + 41 => handle_xi_warp_pointer(state, backend, origin, client_id, sequence, body), + 43 => handle_xi_change_hierarchy(state, client_id, sequence, byte_order, body), + 49 => handle_xi_set_focus(state, client_id, sequence, body), + // Every minor in 1..=XINPUT_LAST_REQUEST has an arm above; like + // Xorg's ProcIDispatch, anything else is BadRequest. + _ => { + debug_assert!(minor == 0 || minor > XINPUT_LAST_REQUEST); + emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(minor), + header.opcode, + ) + } + } +} + +fn xi_write_reply( + state: &mut ServerState, + client_id: ClientId, + buf: Vec, +) -> io::Result { + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let _byte_order = client.byte_order; + Ok(write_to_client(client, client_id, &buf)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/control.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/control.rs new file mode 100644 index 000000000..fc7685b0a --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/control.rs @@ -0,0 +1,1333 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::fanout_event_to_clients, + process_request::{ + RequestOutcome, + input_ctl::{ + ModmapChangeOutcome, apply_keymap_change, change_modifier_mapping, + fetch_merged_keymap, legacy_keyboard_mapping_notify, + }, + motion_history_range, + xi::{ + XI1_ERROR_BAD_DEVICE, XI1_KEY_MAX, XI1_KEY_MIN, dispatch::xi_write_reply, + xi1_device_button_count, xi1_device_has_buttons, xi1_device_has_keys, + xi1_device_has_valuators, xi1_device_valid, xi1_device_valuator_count, xi1_error, + xi1_zero_reply, + }, + }, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, SequenceNumber}, +}; + +// GetDeviceMotionEvents: { start, stop, deviceid }. Motion +// history needs valuators; the reply axis count comes from the live +// class (`Xi/gtmotion.c:107-120`). +pub(super) fn handle_xi1_get_device_motion_events( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.get(8).unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_valuators(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let start = u32::from_le_bytes(body[0..4].try_into().expect("four bytes")); + let stop = u32::from_le_bytes(body[4..8].try_into().expect("four bytes")); + let history = motion_history_range(state, start, stop); + const XI_ABSOLUTE: u8 = 1; + let axis_count = + xi1_device_valuator_count(&state.xi_devices, dev).expect("validated valuator class"); + let words_per_event = 1 + u32::from(axis_count); + let length_words = u32::try_from(history.len()) + .unwrap_or(u32::MAX) + .saturating_mul(words_per_event); + let mut reply = x11::fixed_reply(byte_order, sequence, minor, length_words); + x11::write_u32( + byte_order, + &mut reply, + u32::try_from(history.len()).unwrap_or(u32::MAX), + ); + reply.push(axis_count); + reply.push(XI_ABSOLUTE); + reply.extend_from_slice(&[0u8; 18]); + for record in history { + x11::write_u32(byte_order, &mut reply, record.time); + x11::write_u32( + byte_order, + &mut reply, + i32::from(record.root_x).cast_unsigned(), + ); + x11::write_u32( + byte_order, + &mut reply, + i32::from(record.root_y).cast_unsigned(), + ); + for _ in 2..axis_count { + x11::write_u32(byte_order, &mut reply, 0); + } + } + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// GetFeedbackControl: { deviceid }. yserver models one keyboard +// control + one pointer control (the same state core +// GetKeyboardControl/GetPointerControl expose). Report the device +// class's single default feedback (id 0): a KbdFeedbackState for +// key devices, a PtrFeedbackState for pointer devices — mirroring +// Xorg Xi/getfctl.c, where the KbdFeedback ctrl *is* the keyboard +// control. +pub(super) fn handle_xi1_get_feedback_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + let feedbacks = if xi1_device_has_keys(&state.xi_devices, dev) { + let kc = &state.keyboard_control; + x11::encode_kbd_feedback_state( + byte_order, + 0, + kc.bell_pitch, + kc.bell_duration, + kc.led_mask, + kc.global_auto_repeat, + kc.key_click_percent, + kc.bell_percent, + &kc.auto_repeats, + ) + } else { + let pc = &state.pointer_control; + x11::encode_ptr_feedback_state( + byte_order, + 0, + pc.accel_numerator, + pc.accel_denominator, + pc.threshold, + ) + }; + x11::write_get_feedback_control_reply(&mut buf, byte_order, sequence, 1, &feedbacks)?; + } + xi_write_reply(state, client_id, buf) +} + +// ChangeFeedbackControl (void): { mask, deviceid, feedbackclass } +// followed by the class-specific control. Yserver advertises one +// KbdFeedback (class 0/id 0) on key devices and one PtrFeedback +// (class 1/id 0) on pointer devices. Both alias the shared core +// keyboard/pointer control, just like Xorg. +pub(super) fn handle_xi1_change_feedback_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + let dev = u16::from(*body.get(4).unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + let mask = u32::from_le_bytes([ + *body.first().unwrap_or(&0), + *body.get(1).unwrap_or(&0), + *body.get(2).unwrap_or(&0), + *body.get(3).unwrap_or(&0), + ]); + let feedback_class = *body.get(5).unwrap_or(&u8::MAX); + match feedback_class { + 0 => { + if body.len() != 28 { + return xi1_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, minor); + } + if !xi1_device_has_keys(&state.xi_devices, dev) || body[9] != 0 { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let mut control = state.keyboard_control.clone(); + let mut bad_value = |value: i32| { + xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + value.cast_unsigned(), + minor, + ) + }; + if mask & (1 << 0) != 0 { + let value = body[14] as i8; + control.key_click_percent = match value { + -1 => crate::server::KeyboardControlState::new().key_click_percent, + 0..=100 => value.cast_unsigned(), + _ => return bad_value(i32::from(value)), + }; + } + if mask & (1 << 1) != 0 { + let value = body[15] as i8; + control.bell_percent = match value { + -1 => crate::server::KeyboardControlState::new().bell_percent, + 0..=100 => value.cast_unsigned(), + _ => return bad_value(i32::from(value)), + }; + } + if mask & (1 << 2) != 0 { + let value = i16::from_le_bytes([body[16], body[17]]); + control.bell_pitch = match value { + -1 => crate::server::KeyboardControlState::new().bell_pitch, + 0.. => value.cast_unsigned(), + _ => return bad_value(i32::from(value)), + }; + } + if mask & (1 << 3) != 0 { + let value = i16::from_le_bytes([body[18], body[19]]); + control.bell_duration = match value { + -1 => crate::server::KeyboardControlState::new().bell_duration, + 0.. => value.cast_unsigned(), + _ => return bad_value(i32::from(value)), + }; + } + if mask & (1 << 4) != 0 { + let led_mask = u32::from_le_bytes(body[20..24].try_into().expect("four bytes")); + let led_values = + u32::from_le_bytes(body[24..28].try_into().expect("four bytes")); + control.led_mask = (control.led_mask & !led_mask) | (led_values & led_mask); + } + let key = body[12]; + if mask & (1 << 6) != 0 { + if !(XI1_KEY_MIN..=XI1_KEY_MAX).contains(&key) { + return bad_value(i32::from(key)); + } + if mask & (1 << 7) == 0 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_MATCH, + 0, + minor, + ); + } + } + if mask & (1 << 7) != 0 { + let mode = body[13]; + if mask & (1 << 6) == 0 { + control.global_auto_repeat = match mode { + 0 => false, + 1 => true, + 2 => crate::server::KeyboardControlState::new().global_auto_repeat, + _ => return bad_value(i32::from(mode)), + }; + } else { + let index = usize::from(key >> 3); + let bit = 1 << (key & 7); + match mode { + 0 => control.auto_repeats[index] &= !bit, + 1 => control.auto_repeats[index] |= bit, + 2 => { + control.auto_repeats[index] = (control.auto_repeats[index] & !bit) + | (crate::server::DEFAULT_AUTO_REPEATS[index] & bit); + } + _ => return bad_value(i32::from(mode)), + } + } + } + state.keyboard_control = control; + } + 1 => { + if body.len() != 20 { + return xi1_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, minor); + } + if !xi1_device_has_valuators(&state.xi_devices, dev) || body[9] != 0 { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let mut control = state.pointer_control.clone(); + let defaults = crate::server::PointerControlState::new(); + for (bit, offset, target, default, denominator) in [ + ( + 0, + 14, + &mut control.accel_numerator, + defaults.accel_numerator, + false, + ), + ( + 1, + 16, + &mut control.accel_denominator, + defaults.accel_denominator, + true, + ), + (2, 18, &mut control.threshold, defaults.threshold, false), + ] { + if mask & (1 << bit) == 0 { + continue; + } + let value = i16::from_le_bytes([body[offset], body[offset + 1]]); + if value == -1 { + *target = default; + } else if value < 0 || (denominator && value == 0) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + i32::from(value).cast_unsigned(), + minor, + ); + } else { + *target = value.cast_unsigned(); + } + } + state.pointer_control = control; + } + _ => { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + } + debug!( + "client {} #{} XI1 ChangeFeedbackControl device={dev} class={feedback_class} mask=0x{mask:x}", + client_id.0, sequence.0, + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// GetDeviceKeyMapping: { deviceid, firstKeyCode, count }. Range +// checks against the advertised 8..=255 keycode space. +pub(super) fn handle_xi1_get_device_key_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + let first = *body.get(1).unwrap_or(&0); + let count = *body.get(2).unwrap_or(&0); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_keys(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + if first < XI1_KEY_MIN { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(first), + minor, + ); + } + if u16::from(first) + u16::from(count) > 256 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(count), + minor, + ); + } + // The XI1 keyboard devices (3 master, 5 slave) share the + // server's single physical keymap — Xorg's XkbGetCoreMap is + // per-device, but yserver models one keyboard. Reuse the core + // GetKeyboardMapping path so the device map matches what the + // client sees via opcode 101. + let (kpc, keysyms) = fetch_merged_keymap(state, backend, origin, first, count); + x11::write_get_device_key_mapping_reply(&mut buf, byte_order, sequence, kpc, &keysyms)?; + } + xi_write_reply(state, client_id, buf) +} + +// ChangeDeviceKeyMapping (void): { deviceid, firstKeyCode, +// keySymsPerKeyCode, keyCodes }. +pub(super) fn handle_xi1_change_device_key_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + let first = *body.get(1).unwrap_or(&0); + let count = *body.get(3).unwrap_or(&0); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if first < XI1_KEY_MIN || u16::from(first) + u16::from(count) > 256 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(first), + minor, + ); + } + // Write the keysym rows into the shared override store the + // read paths (minor 24 / core opcode 101) merge over the + // backend keymap. Body: deviceid(1) firstKeyCode(1) + // keySymsPerKeyCode(1) keyCodes(1) then keyCodes×kpk CARD32s. + // Without this the round-trip silently dropped the change + // (XTS XChangeDeviceKeyMapping-3). + let kpk = *body.get(2).unwrap_or(&0); + // Xorg XkbApplyMappingChange changes and notifies nothing for + // zero keys. + let xkb_change = if count == 0 { + None + } else { + apply_keymap_change( + state, + backend, + first, + kpk, + count, + &body[4.min(body.len())..], + ) + }; + // Same XKB notifications as the core request (Xorg: both reach + // XkbApplyMappingChange): MapNotify first, ControlsNotify last. + let xkb_event_base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); + if let Some(change) = &xkb_change { + crate::core_loop::xkb_layout::send_xkb_map_notify( + state, + xkb_event_base, + change.map_notify, + ); + } + // The core MappingNotify only when the master keyboard changed + // (Xorg XkbSendLegacyMapNotify → XIShouldNotify), as for + // SetDeviceModifierMapping. + if count != 0 && dev == crate::xinput::DEVICEID_MASTER_KEYBOARD { + legacy_keyboard_mapping_notify(state, xkb_change.as_ref(), first, count); + } + // ChangeDeviceKeyMapping is void (no reply), so the event + // ordering question is moot: send to originator + others. + // request_kind=1 = MappingKeyboard. + if crate::core_loop::xi1_focus::xi1_client_wants_device_mapping_notify( + state, client_id, dev, + ) { + let time = state.timestamp_now(); + #[allow(clippy::cast_possible_truncation)] + let device_byte = dev as u8; + crate::xinput::encode_xi1_device_mapping_notify( + &mut buf, + byte_order, + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MAPPING_NOTIFY_OFFSET, + device_byte, + sequence, + time, + 1, + first, + count, + ); + } + crate::core_loop::xi1_focus::emit_device_mapping_notify( + state, + Some(client_id), + dev, + 1, + first, + count, + ); + if let Some(change) = &xkb_change { + crate::core_loop::xkb_layout::send_keyboard_mapping_followups( + state, + xkb_event_base, + change, + (crate::core_loop::xkb_layout::X_CHANGE_KEYBOARD_MAPPING, 0), + ); + } + debug!( + "client {} #{} XI1 ChangeDeviceKeyMapping device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, buf) +} + +// GetDeviceModifierMapping: { deviceid }. Keyboard devices +// share the core keymap, so the reply is the same +// modifier→keycode table the core GetModifierMapping handler +// serves (Xorg Xi/getmmap.c reads the per-device key class — +// ours all alias the core keyboard). +// +// This MUST be real data, not a zero stub: XTS's +// Setup_Extension_DeviceInfo only treats a device as +// modifier-capable when `max_keypermod > 0`, and a zero reply +// silently knocked out every ModMask-gated test (GrabDeviceButton, +// SetDeviceModifierMapping, UngrabDeviceKey-2, ... → UNTESTED). +// +// Wire layout (xGetDeviceModifierMappingReply, XIproto.h:1031): +// numKeyPerModifier lives at byte 8 — NOT the core reply's +// byte-1 data slot — followed by 8*numKeyPerModifier keycodes. +pub(super) fn handle_xi1_get_device_modifier_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_keys(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // Prefer the per-device override stored by + // `XSetDeviceModifierMapping`; fall back to the backend's + // shared core map. xts5 SetDeviceModifierMapping-1 sets + // the map and immediately reads it back. + let (kpm, keycodes) = state + .xi1_modifier_map + .get(&dev) + .cloned() + .unwrap_or_else(|| { + backend + .get_modifier_mapping(origin) + .unwrap_or((0, Vec::new())) + }); + debug_assert_eq!(keycodes.len(), 8 * usize::from(kpm)); + let length_words = u32::from(kpm) * 2; // 8*kpm bytes / 4 + // Byte 1 = RepType = X_GetDeviceModifierMapping (Xi/getmmap.c). + let mut reply = x11::fixed_reply(byte_order, sequence, minor, length_words); + reply.push(kpm); // byte 8: numKeyPerModifier + reply.extend_from_slice(&[0u8; 23]); // bytes 9..=31: pad + reply.extend_from_slice(&keycodes); + debug!( + "client {} #{} XI1 GetDeviceModifierMapping device={dev} kpm={kpm}", + client_id.0, sequence.0 + ); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// SetDeviceModifierMapping: { deviceid, numKeyPerModifier, +// pad1, 8 × numKeyPerModifier keycodes }. +pub(super) fn handle_xi1_set_device_modifier_mapping( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + let kpm = *body.get(1).unwrap_or(&0); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_keys(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let need = 8usize * usize::from(kpm); + let keycodes: Vec = (0..need).filter_map(|i| body.get(4 + i).copied()).collect(); + if keycodes.len() != need { + return xi1_error(state, client_id, sequence, x11::error::BAD_LENGTH, 0, minor); + } + // Xorg ProcXSetDeviceModifierMapping → change_modmap, the core + // request's path: a keycode outside the keycode range (xts5 + // SetDeviceModifierMapping-8 probes MinKeyCode-1) or listed + // twice is BadValue; a held modifier key is MappingBusy. + // Busy changed nothing and notifies nothing (Xi/setmmap.c). On + // success the DeviceMappingNotify goes out before the XKB and + // core notifications: to the requester (xts5 does + // `Expect_Event` then `Expect_Reply`, so ahead of the reply too) + // and to every other client that selected it. + // request_kind=0 = MappingModifier. + let notify_device = |state: &mut ServerState| { + if crate::core_loop::xi1_focus::xi1_client_wants_device_mapping_notify( + state, client_id, dev, + ) { + let time = state.timestamp_now(); + #[allow(clippy::cast_possible_truncation)] + let device_byte = dev as u8; + let _dropped = fanout_event_to_clients(state, &[client_id], |buf, seq, order| { + crate::xinput::encode_xi1_device_mapping_notify( + buf, + order, + crate::server::XI_FIRST_EVENT + + crate::xinput::XI_DEVICE_MAPPING_NOTIFY_OFFSET, + device_byte, + seq, + time, + 0, + 0, + 0, + ); + }); + } + crate::core_loop::xi1_focus::emit_device_mapping_notify( + state, + Some(client_id), + dev, + 0, + 0, + 0, + ); + }; + let status = match change_modifier_mapping( + state, + backend, + origin, + kpm, + &keycodes, + Some(dev), + notify_device, + ) { + ModmapChangeOutcome::Success => 0, + ModmapChangeOutcome::Busy => 1, + ModmapChangeOutcome::BadValue(value) => { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + value, + minor, + ); + } + }; + // xSetDeviceModifierMappingReply: RepType @1, success @8. + let mut reply = x11::fixed_reply(byte_order, sequence, minor, 0); + reply.push(status); + reply.extend_from_slice(&[0u8; 23]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// GetDeviceButtonMapping: { deviceid }. The map length follows the +// device's current ButtonClass, including masters whose shape was +// copied from their last slave; Xorg returns b->numButtons and +// b->map (`Xi/getbmap.c:107-115`). +pub(super) fn handle_xi1_get_device_button_mapping( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_buttons(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let button_count = usize::from( + xi1_device_button_count(&state.xi_devices, dev).expect("validated button class"), + ); + // nElts lives at byte 8 (first byte after the reply header); + // map bytes follow the 32-byte header, padded to 4 bytes. + // Use the device's stored map if set (xts5 + // SetDeviceButtonMapping-1 verifies that a custom map + // round-trips); otherwise identity. + let mut reply = x11::fixed_reply( + byte_order, + sequence, + 0, + u32::try_from(button_count.div_ceil(4)).unwrap_or(u32::MAX), + ); + reply.push(u8::try_from(button_count).expect("XI ButtonClass fits XI1 nElts")); + reply.extend_from_slice(&[0u8; 23]); + let stored = state.xi1_button_map.get(&dev).cloned(); + for i in 0..button_count { + let mapped = stored + .as_ref() + .and_then(|m| m.get(i).copied()) + .unwrap_or_else(|| u8::try_from(i + 1).expect("XI ButtonClass fits XI1")); + reply.push(mapped); + } + while !reply.len().is_multiple_of(4) { + reply.push(0); + } + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// SetDeviceButtonMapping: { deviceid, map_length }. Xorg passes the +// supplied length directly to ApplyPointerMapping; it is not capped +// by ButtonClass count (`Xi/setbmap.c:111-121`). +pub(super) fn handle_xi1_set_device_button_mapping( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + let map_length = *body.get(1).unwrap_or(&0); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_buttons(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // Read the map bytes from the body (after the 4-byte + // header that holds deviceid/map_length/pad). Xorg's + // ApplyPointerMapping only checks device access and whether a + // changed held button makes the mapping busy, then copies the + // supplied bytes (`dix/inpututils.c:43-124`). + let map_bytes: Vec = (0..usize::from(map_length)) + .filter_map(|i| body.get(4 + i).copied()) + .collect(); + let current_map = state.xi1_button_map.get(&dev); + let buttons_down = state + .xi1_device_input_state + .get(&dev) + .map(|device_state| &device_state.buttons_down); + let mapping_busy = map_bytes.iter().enumerate().any(|(index, new_mapping)| { + let button = index + 1; + let previous_mapping = current_map + .and_then(|mapping| mapping.get(index)) + .copied() + .unwrap_or_else(|| u8::try_from(button).unwrap_or(u8::MAX)); + let button_is_down = buttons_down.is_some_and(|down| { + down.get(button / 8) + .is_some_and(|byte| byte & (1 << (button % 8)) != 0) + }); + previous_mapping != *new_mapping && button_is_down + }); + if mapping_busy { + // Xorg ApplyPointerMapping returns MappingBusy before copying + // the map or emitting MappingNotify (`dix/inpututils.c:62-65`). + let mut reply = xi1_zero_reply(byte_order, sequence); + reply[8] = 1; // MappingBusy + buf.extend_from_slice(&reply); + } else { + // Xorg copies exactly the supplied prefix into the device's + // existing map (`dix/inpututils.c:78-80`). Seed an implicit + // identity map from the current ButtonClass, then retain any + // tail when a shorter prefix is written. + let button_count = usize::from( + xi1_device_button_count(&state.xi_devices, dev).expect("validated button class"), + ); + let mut updated = state.xi1_button_map.get(&dev).cloned().unwrap_or_else(|| { + (1..=button_count) + .map(|button| u8::try_from(button).unwrap_or(u8::MAX)) + .collect() + }); + while updated.len() < map_bytes.len() { + updated.push(u8::try_from(updated.len() + 1).unwrap_or(u8::MAX)); + } + updated[..map_bytes.len()].copy_from_slice(&map_bytes); + state.xi1_button_map.insert(dev, updated); + // Reply first, then DeviceMappingNotify event in the same + // outbound write. request_kind=2 = MappingPointer. + buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); + if crate::core_loop::xi1_focus::xi1_client_wants_device_mapping_notify( + state, client_id, dev, + ) { + let time = state.timestamp_now(); + #[allow(clippy::cast_possible_truncation)] + let device_byte = dev as u8; + crate::xinput::encode_xi1_device_mapping_notify( + &mut buf, + byte_order, + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MAPPING_NOTIFY_OFFSET, + device_byte, + sequence, + time, + 2, + 0, + 0, + ); + } + crate::core_loop::xi1_focus::emit_device_mapping_notify( + state, + Some(client_id), + dev, + 2, + 0, + 0, + ); + } + } + xi_write_reply(state, client_id, buf) +} + +// QueryDeviceState: { deviceid }. Snapshot of the device's +// key / button / valuator state (Xorg reads current classes at +// `Xi/queryst.c:131-157`) — the same +// source data DeviceStateNotify reports, in the request-reply +// envelope: num_classes at reply byte 8, then xKeyState / +// xButtonState (36 bytes each: class, length, count, pad, +// 32-byte down-bitmask) and xValuatorState (4 bytes + one +// INT32 per axis). `xinput query-state` consumes this. +// +// num_keys here is max_key_code - min_key_code + 1 (248) — +// ONE MORE than the deviceStateNotify event's max-min (247); +// Xorg is inconsistent between the two and clients are built +// against that, so mirror it. +pub(super) fn handle_xi1_query_device_state( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + let dev_state = state + .xi1_device_input_state + .get(&dev) + .copied() + .unwrap_or_default(); + let class_shape = state + .xi_devices + .device(dev) + .expect("validated XI device") + .class_shape; + let mut data: Vec = Vec::new(); + let mut num_classes = 0u8; + if xi1_device_has_keys(&state.xi_devices, dev) { + // xKeyState: keycodes 8..=255 → num_keys = 248. + data.push(0); // class = KeyClass + data.push(36); // length + data.push(248); // num_keys (max - min + 1) + data.push(0); // pad + data.extend_from_slice(&dev_state.keys_down); + num_classes += 1; + } + if xi1_device_has_buttons(&state.xi_devices, dev) { + data.push(1); // class = ButtonClass + data.push(36); // length + data.push(class_shape.button_count()); // num_buttons + data.push(0); // pad + data.extend_from_slice(&dev_state.buttons_down); + num_classes += 1; + } + if xi1_device_has_valuators(&state.xi_devices, dev) { + let valuator_count = usize::from(class_shape.valuator_count()); + let valuator_length = 4 + 4 * valuator_count; + data.push(2); // class = ValuatorClass + data.push(u8::try_from(valuator_length).expect("XI valuator block fits XI1")); + data.push(class_shape.valuator_count()); // num_valuators + data.push(dev_state.valuator_mode); // mode (in-proximity) + // Stored axis values (Xorg axisVal): axes 0/1 track + // the sprite under real motion; fakes write their + // explicit payload. + for value in dev_state.valuators.iter().take(valuator_count) { + x11::write_u32(byte_order, &mut data, value.cast_unsigned()); + } + num_classes += 1; + } + debug_assert_eq!(data.len() % 4, 0); + let length_words = u32::try_from(data.len() / 4).unwrap_or(u32::MAX); + let mut reply = x11::fixed_reply(byte_order, sequence, 0, length_words); + reply.push(num_classes); // byte 8 + reply.extend_from_slice(&[0u8; 23]); // bytes 9..=31: pad + reply.extend_from_slice(&data); + debug!( + "client {} #{} XI1 QueryDeviceState device={dev} classes={num_classes}", + client_id.0, sequence.0 + ); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// DeviceBell (void): { deviceid, feedbackid, feedbackclass, +// percent }. Yserver exposes KbdFeedback id 0 on key devices but has +// no bell procedure, and exposes no BellFeedback. Xorg +// `Xi/devbell.c::ProcXDeviceBell` returns BadValue for both cases; +// unlike core Bell, this is not a successful bell-less no-op. +#[allow(clippy::needless_return)] +pub(super) fn handle_xi1_device_bell( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + let dev = u16::from(*body.first().unwrap_or(&0)); + let feedback_id = *body.get(1).unwrap_or(&0); + let feedback_class = *body.get(2).unwrap_or(&0); + #[allow(clippy::cast_possible_wrap)] + let percent = *body.get(3).unwrap_or(&0) as i8; + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + // Xorg validates percent before looking up the feedback. + if !(-100..=100).contains(&percent) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(*body.get(3).unwrap_or(&0)), + minor, + ); + } + if !matches!(feedback_class, 0 | 5) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(feedback_class), + minor, + ); + } + let feedback_exists = + feedback_class == 0 && feedback_id == 0 && xi1_device_has_keys(&state.xi_devices, dev); + if !feedback_exists { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(feedback_id), + minor, + ); + } + // The feedback exists, but its BellProc is absent. + return xi1_error(state, client_id, sequence, x11::error::BAD_VALUE, 0, minor); +} + +// SetDeviceValuators: { deviceid, first_valuator, num_valuators, +// pad1, INT32 values[num_valuators] }. Body layout follows +// `xSetDeviceValuatorsReq` (XIproto.h:1144-1153). +pub(super) fn handle_xi1_set_device_valuators( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + let first = *body.get(1).unwrap_or(&0); + let num = *body.get(2).unwrap_or(&0); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_valuators(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // `IsXTestDevice` rejects the XTEST pointer with BadMatch, + // ahead of the axis-range check (`Xi/setdval.c:113-114`). + if dev == crate::xinput::DEVICEID_XTEST_POINTER { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let axis_count = + xi1_device_valuator_count(&state.xi_devices, dev).expect("validated valuator class"); + if u16::from(first) + u16::from(num) > u16::from(axis_count) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(num), + minor, + ); + } + // Xorg checks against `dev->valuator->numAxes` + // (`Xi/setdval.c:110-117`) and + // `ProcXSetDeviceValuators` returns + // `AlreadyGrabbed` when another client holds an active + // grab on the device. `xSetDeviceValuatorsReply.status` + // sits at byte 8 (right after the 8-byte standard reply + // header) — XIproto.h:1249-1261. + const ALREADY_GRABBED: u8 = 1; + let grabbed_elsewhere = state + .xi1_active_grabs + .get(&dev) + .is_some_and(|g| g.owner != client_id); + if grabbed_elsewhere { + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.push(ALREADY_GRABBED); // byte 8: status + reply.extend_from_slice(&[0u8; 23]); // bytes 9-31: pad + buf.extend_from_slice(&reply); + } else { + // Persist the new axis values into + // `xi1_device_input_state` so the next + // DeviceStateNotify / QueryDeviceState reports them. + // xts5 XSetDeviceValuators 1 / 2 read each axis back + // immediately after the set and expect the supplied + // value verbatim. + let entry = state.xi1_device_input_state.entry(dev).or_default(); + for i in 0..usize::from(num) { + let off = 4 + i * 4; + let Some(slice) = body.get(off..off + 4) else { + break; + }; + let value = i32::from_le_bytes(slice.try_into().expect("4-byte slice")); + let idx = usize::from(first) + i; + if let Some(slot) = entry.valuators.get_mut(idx) { + *slot = value; + } + } + buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); + } + } + xi_write_reply(state, client_id, buf) +} + +// GetDeviceControl: { control, deviceid }. DEVICE_RESOLUTION(1) +// is the only control defined for XI 1.x core; it needs +// valuators. Reply layout (`xGetDeviceControlReply` + +// `xDeviceResolutionState`, XIproto.h): +// bytes 0..32 standard reply header (length in 32-bit +// units of the trailing buf) +// bytes 32..40 xDeviceResolutionState header: +// control(2)=1, length(2)=trailing-bytes, +// num_valuators(4) +// bytes 40.. 3 × num_valuators × CARD32 — resolutions, +// min_resolutions, max_resolutions. +// Xorg sizes and serializes this from `v->numAxes` +// (`Xi/getdctl.c:192-219`). +// xts5 ChangeDeviceControl-1/-2 set + read back via +// GetDeviceControl; without a real reply the test SEGFAULTs. +pub(super) fn handle_xi1_get_device_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let control = u16::from_le_bytes([*body.first().unwrap_or(&0), *body.get(1).unwrap_or(&0)]); + let dev = u16::from(*body.get(2).unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if control != 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(control), + minor, + ); + } + if !xi1_device_has_valuators(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + let num_axes = usize::from( + xi1_device_valuator_count(&state.xi_devices, dev).expect("validated valuator class"), + ); + let stored = state.xi1_resolution.get(&dev).cloned(); + let resolutions: Vec<[i32; 3]> = (0..num_axes) + .map(|i| { + stored + .as_ref() + .and_then(|v| v.get(i).copied()) + .unwrap_or([0, 0, 0]) + }) + .collect(); + // 8 bytes xDeviceResolutionState header + 3 × num_axes × 4 + let trailing_bytes = 8 + 3 * num_axes * 4; + let length_units = u32::try_from(trailing_bytes / 4).unwrap_or(u32::MAX); + let mut reply = x11::fixed_reply(byte_order, sequence, 0, length_units); + // Pad bytes 8..32 of the standard reply header. + reply.extend_from_slice(&[0u8; 24]); + // xDeviceResolutionState header + x11::write_u16(byte_order, &mut reply, 1); // control = DEVICE_RESOLUTION + #[allow(clippy::cast_possible_truncation)] + let ctl_len = trailing_bytes as u16; + x11::write_u16(byte_order, &mut reply, ctl_len); + x11::write_u32(byte_order, &mut reply, u32::try_from(num_axes).unwrap_or(0)); + // Three runs over axes: resolution, min_resolution, max_resolution. + for r in &resolutions { + x11::write_u32(byte_order, &mut reply, r[0].cast_unsigned()); + } + for r in &resolutions { + x11::write_u32(byte_order, &mut reply, r[1].cast_unsigned()); + } + for r in &resolutions { + x11::write_u32(byte_order, &mut reply, r[2].cast_unsigned()); + } + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// ChangeDeviceControl: { control, deviceid } + xDeviceCtl +// { control, length, first_valuator, num_valuators, pad2, +// resolutions[] }. +pub(super) fn handle_xi1_change_device_control( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let control = u16::from_le_bytes([body[0], body[1]]); + let dev = u16::from(body[2]); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if control != 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(control), + minor, + ); + } + // Embedded xDeviceCtl follows at body[4..]; its control id + // must agree with the request's (Xorg Xi/chgdctl.c → + // BadMatch on mismatch). + if body.len() >= 6 { + let ctl_control = u16::from_le_bytes([body[4], body[5]]); + if ctl_control != control { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + } + if !xi1_device_has_valuators(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // Xorg initializes relative axes without physical resolution + // metadata as resolution/min_resolution/max_resolution = 0/0/0 + // (`dix/devices.c::InitValuatorClassDeviceStruct`). Yserver's + // synthetic relative axes do the same, so zero is the sole valid + // value and round-trips through GetDeviceControl; nonzero values + // are correctly outside the advertised range. + let mut staged: Vec<(usize, i32)> = Vec::new(); + if body.len() >= 10 { + let first = body[8]; + let num = body[9]; + // Xorg rejects ranges past the current ValuatorClass + // (`Xi/chgdctl.c:157-160`). + let axis_count = xi1_device_valuator_count(&state.xi_devices, dev) + .expect("validated valuator class"); + if u16::from(first) + u16::from(num) > u16::from(axis_count) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(num), + minor, + ); + } + for i in 0..usize::from(num) { + let off = 12 + i * 4; + if off + 4 > body.len() { + break; + } + let res = + i32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + if res != 0 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + res.cast_unsigned(), + minor, + ); + } + staged.push((usize::from(first) + i, res)); + } + } + // Xorg `Xi/chgdctl.c::ProcXChangeDeviceControl` returns + // `AlreadyGrabbed` (status byte 8) when another client + // holds an active grab on the device — xts5 + // ChangeDeviceControl-10. + const ALREADY_GRABBED: u8 = 1; + let grabbed_elsewhere = state + .xi1_active_grabs + .get(&dev) + .is_some_and(|g| g.owner != client_id); + let status = if grabbed_elsewhere { + ALREADY_GRABBED + } else { + // Persist the validated resolutions so the matching + // `XGetDeviceControl` reports them. + if !staged.is_empty() { + let entry = state.xi1_resolution.entry(dev).or_insert_with(|| { + vec![ + [0, 0, 0]; + usize::from( + xi1_device_valuator_count(&state.xi_devices, dev) + .expect("validated valuator class") + ) + ] + }); + for (axis, value) in &staged { + if let Some(row) = entry.get_mut(*axis) { + row[0] = *value; + } + } + } + 0 + }; + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.push(status); + reply.extend_from_slice(&[0u8; 23]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/devices.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/devices.rs new file mode 100644 index 000000000..2978ecf01 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/devices.rs @@ -0,0 +1,666 @@ +use crate::{ + core_loop::process_request::{ + RequestOutcome, XI2_FIRST_ERROR, XI2_MAJOR_OPCODE, XI2_SERVER_MAJOR_VERSION, + XI2_SERVER_MINOR_VERSION, emit_x11_error_with_minor, + xi::{ + XI1_ERROR_BAD_DEVICE, XI1_KEY_MAX, XI1_KEY_MIN, dispatch::xi_write_reply, + record_xi2_client_version, xi1_device_has_keys, xi1_device_has_valuators, + xi1_device_is_master, xi1_device_valid, xi1_error, xi1_zero_reply, + }, + }, + server::{ServerState, XI_FIRST_EVENT}, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}, +}; + +pub(super) fn handle_xi1_get_extension_version( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XI GetExtensionVersion, as Xorg's ProcXGetExtensionVersion + // (Xi/getvers.c): the length must match `nbytes`, and the reply + // is the server's XI version (XIVersion, 2.4) with RepType = + // X_GetExtensionVersion. libXi reads this version to decide + // whether XI 2.2 fields (a raw event's sourceid) are valid. + debug!( + "client {} #{} XIGetExtensionVersion", + client_id.0, sequence.0 + ); + let nbytes = body + .get(0..2) + .map_or(0, |b| usize::from(u16::from_le_bytes([b[0], b[1]]))); + if usize::try_from(header.length_units).ok() != Some((8 + nbytes).div_ceil(4)) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + 1, + XI2_MAJOR_OPCODE, + ); + } + let mut reply = x11::fixed_reply(byte_order, sequence, 1, 0); + x11::write_u16(byte_order, &mut reply, XI2_SERVER_MAJOR_VERSION); + x11::write_u16(byte_order, &mut reply, XI2_SERVER_MINOR_VERSION); + reply.push(1); + reply.extend_from_slice(&[0; 19]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_set_client_pointer( + client_id: ClientId, + sequence: SequenceNumber, +) -> io::Result { + debug!("client {} #{} XISetClientPointer", client_id.0, sequence.0); + return Ok(RequestOutcome::Handled); +} + +pub(super) fn handle_xi_get_client_pointer( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIGetClientPointer reply layout (xXIGetClientPointerReply, + // X11/extensions/XI2proto.h): + // response_type(1) | pad0(1) | sequence(2) | length(4) + // | set:BOOL(1) | pad0(1) | deviceid(2) | pad1..5(20) + // Total = 32 bytes. NOTE: deviceid sits at byte 10 — only + // ONE pad byte follows `set`. Writing 3 pad bytes here pushed + // deviceid to byte 12, so clients read 0 (broke nemo's + // desktop rubber-band, which looks up its pointer device via + // this reply). + // + // Must reply `set=True`: libXi's `XIGetClientPointer` + // only writes the caller's `*deviceid` out-parameter + // when `reply.set == True`. With `set=False` it returns + // False and leaves the caller's variable uninitialized, + // which GDK then passes verbatim to `g_hash_table_lookup` + // on its device id_table — looking up garbage returns + // NULL, so GDK assigns `device=NULL` to any synthetic + // core ButtonPress/ButtonRelease/MotionNotify from + // XSendEvent (gdkdevicemanager-xi2.c::translate_event + // calls `get_client_pointer` to attribute the device), + // and the next `proxy_button_event` SEGVs at + // `pointer_info->toplevel_under_pointer`. mate-panel + // dies on every workspace-switch click because wnck-applet + // SendEvents a synthetic ButtonRelease into the panel + // when activating a workspace. + debug!( + "client {} #{} XIGetClientPointer -> set=1 deviceid=2", + client_id.0, sequence.0 + ); + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.push(1); // byte 8: set = True + reply.push(0); // byte 9: pad0 + // bytes 10-11: deviceid = master pointer (2). + x11::write_u16(byte_order, &mut reply, 2); + reply.extend_from_slice(&[0u8; 20]); // bytes 12-31: pad1..5 + debug_assert_eq!(reply.len(), 32); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +pub(super) fn handle_xi_query_version( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + debug!("client {} #{} XIQueryVersion", client_id.0, sequence.0); + let requested_major = body + .get(0..2) + .map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]])) + .unwrap_or(0); + let requested_minor = body + .get(2..4) + .map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]])) + .unwrap_or(0); + if requested_major < 2 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(requested_major), + 47, + XI2_MAJOR_OPCODE, + ); + } + let (reply_major, reply_minor) = if (requested_major, requested_minor) + < (XI2_SERVER_MAJOR_VERSION, XI2_SERVER_MINOR_VERSION) + { + (requested_major, requested_minor) + } else { + (XI2_SERVER_MAJOR_VERSION, XI2_SERVER_MINOR_VERSION) + }; + record_xi2_client_version(state, client_id, (reply_major, reply_minor)); + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + x11::write_u16(byte_order, &mut reply, reply_major); + x11::write_u16(byte_order, &mut reply, reply_minor); + reply.extend_from_slice(&[0; 20]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +pub(super) fn handle_xi_query_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIQueryDevice: 0 means all live devices, 1 means the master + // pair, and every other ID selects one exact registry entry. + debug!("client {} #{} XIQueryDevice", client_id.0, sequence.0); + if body.len() < 2 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + 48, + XI2_MAJOR_OPCODE, + ); + } + let request_device_id = match byte_order { + ClientByteOrder::LittleEndian => u16::from_le_bytes([body[0], body[1]]), + ClientByteOrder::BigEndian => u16::from_be_bytes([body[0], body[1]]), + }; + let devices = match state.xi_devices.query(request_device_id) { + Ok(devices) => devices, + Err(crate::xinput::XiQueryError::BadDevice(device_id)) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(device_id), + 48, + XI2_MAJOR_OPCODE, + ); + } + }; + let class_data = crate::xinput::query::XiQueryClassData { + button_labels: [ + state.atoms.intern("Button Left", false), + state.atoms.intern("Button Middle", false), + state.atoms.intern("Button Right", false), + state.atoms.intern("Button Wheel Up", false), + state.atoms.intern("Button Wheel Down", false), + state.atoms.intern("Button Horiz Wheel Left", false), + state.atoms.intern("Button Horiz Wheel Right", false), + ], + button_state: state.buttons_down, + axis_labels: [ + state.atoms.intern("Rel X", false), + state.atoms.intern("Rel Y", false), + state.atoms.intern("Rel Vert Scroll", false), + state.atoms.intern("Rel Horiz Scroll", false), + ], + pointer: ( + i32::from(state.randr.screen_width) / 2, + i32::from(state.randr.screen_height) / 2, + ), + // Xorg ListValuatorInfo reports the master pointer's + // current axisVal (Xi/xiquerydevice.c:369). This state is + // synchronized from the latest attached source in pointer + // fanout, rather than globally accumulating independent + // physical-device scroll counters. + scroll: state.scroll_axis_value, + }; + let reply = crate::xinput::query::encode_reply(byte_order, sequence, &devices, class_data)?; + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// XI 1.x ListInputDevices (minor 2). It selects the same live +// registry entries as XIQueryDevice. A previous empty-list stub +// crashed Chromium/Electron: Ozone-X11 cross-checks XI1's +// ListInputDevices against XI2's XIQueryDevice and fatal-CHECKs +// when XI2 has a master pointer but XI1 reports zero devices. +pub(super) fn handle_xi1_list_input_devices( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + debug!("client {} #{} XListInputDevices", client_id.0, sequence.0); + // Keep the same descriptor order as XIQueryDevice selector 0. + // XI1 has no enabled field. Match Xorg's None type for masters + // and XTEST devices while preserving each physical facet's type. + const PHYSICAL_POINTER_AXES: [(i32, i32); 4] = [(-1, -1), (-1, -1), (-1, 0), (-1, 0)]; + const CORE_POINTER_AXES: [(i32, i32); 2] = [(-1, -1), (-1, -1)]; + // XI1 copies `d->xinput_type` directly to the type atom + // (`Xi/listdev.c:171-173`). The server-created master and XTEST + // devices keep calloc's initial None value + // (`dix/devices.c:259-261`); physical types are assigned by the + // input driver (`Xi/extinit.c:1207-1210`). + let no_type_atom = x11::AtomId(0); + let mouse_atom = state.atoms.intern(crate::xinput::XI_ATOM_MOUSE, true); + let keyboard_atom = state.atoms.intern(crate::xinput::XI_ATOM_KEYBOARD, true); + let touchpad_atom = state.atoms.intern(crate::xinput::XI_ATOM_TOUCHPAD, true); + let listed_devices = state + .xi_devices + .query(0) + .expect("XIAllDevices selector is always valid"); + // Xorg ListInputDevices copies the live ButtonClass and + // ValuatorClass counts (`Xi/listdev.c:100-107, 143-155, + // 277-283`). Build each class vector from the same registry shape + // used by XIQueryDevice; the axis metadata remains shape-specific. + let class_storage: Vec>> = listed_devices + .iter() + .map(|device| { + let shape = device.class_shape; + let mut classes = Vec::with_capacity(3); + let button_count = shape.button_count(); + if button_count != 0 { + classes.push(x11::Xi1DeviceClass::Button { + num_buttons: u16::from(button_count), + }); + } + let valuator_count = usize::from(shape.valuator_count()); + if valuator_count != 0 { + let shape_axes: &[(i32, i32)] = match shape { + crate::xinput::XiClassShape::CorePointer => &CORE_POINTER_AXES, + crate::xinput::XiClassShape::PhysicalPointer => &PHYSICAL_POINTER_AXES, + crate::xinput::XiClassShape::Keyboard => &[], + }; + classes.push(x11::Xi1DeviceClass::Valuator { + mode: 0, + axes: &shape_axes[..valuator_count], + }); + } + if shape == crate::xinput::XiClassShape::Keyboard { + classes.push(x11::Xi1DeviceClass::Key { + min_keycode: XI1_KEY_MIN, + max_keycode: XI1_KEY_MAX, + num_keys: 248, + }); + } + classes + }) + .collect(); + let devices = listed_devices + .iter() + .zip(&class_storage) + .map(|(device, classes)| { + let (use_code, type_atom, classes) = match device.id { + crate::xinput::DEVICEID_MASTER_POINTER => (0, no_type_atom, &classes[..]), + crate::xinput::DEVICEID_MASTER_KEYBOARD => (1, no_type_atom, &classes[..]), + crate::xinput::DEVICEID_XTEST_POINTER => (4, no_type_atom, &classes[..]), + crate::xinput::DEVICEID_XTEST_KEYBOARD => (3, no_type_atom, &classes[..]), + _ => match device + .facet + .expect("registered physical XI device has a facet") + { + crate::xinput::XiFacetKind::PointerTouch => ( + 4, + if device.is_touchpad { + touchpad_atom + } else { + mouse_atom + }, + &classes[..], + ), + crate::xinput::XiFacetKind::Keyboard => (3, keyboard_atom, &classes[..]), + }, + }; + let attachment = match device.id { + crate::xinput::DEVICEID_MASTER_POINTER => { + crate::xinput::DEVICEID_MASTER_KEYBOARD + } + crate::xinput::DEVICEID_MASTER_KEYBOARD => { + crate::xinput::DEVICEID_MASTER_POINTER + } + _ => device.attached_master.unwrap_or(0), + }; + x11::Xi1DeviceDescriptor { + id: device.id, + use_code, + attachment, + type_atom, + name: &device.name, + classes, + } + }) + .collect::>(); + buf.extend_from_slice(&x11::encode_list_input_devices_reply( + byte_order, sequence, &devices, + )); + } + xi_write_reply(state, client_id, buf) +} + +// XI1 OpenDevice (minor 3). Xlib's `DevicePropertyNotify(dev, type, +// _class)` macro walks `XDevice->classes` (populated from this +// reply) for an `OtherClass(6)` entry, then computes +// type = entry.event_type_base + _propertyNotify(=6) +// _class = (deviceid << 8) | type +// and passes _class to `XSelectExtensionEvent`. An empty class +// list (our pre-fix stub) leaves _class = 0, and `xinput +// watch-props` silently subscribes to nothing. +// +// Verified against `mate-asahi-xorg.xtrace`: pointer devices return +// Button(1)/Valuator(2)/Feedback(3)/Other(6), while keyboards return +// Key(0)/Feedback(3)/Focus(5)/Other(6). The Other entry uses +// `event_type_base = 0x4c = 76`, and xinput's subsequent +// `SelectExtensionEvent` carries class `(deviceid<<8)|82`. +pub(super) fn handle_xi1_open_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // Xorg Xi/opendev.c: unknown IDs and master devices yield + // BadDevice. XOpenDevice opens the listed slave devices, + // including each live physical facet. + { + let deviceid = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, deviceid) + || xi1_device_is_master(&state.xi_devices, deviceid) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(deviceid), + u16::from(minor), + XI2_MAJOR_OPCODE, + ); + } + } + // Mirror Xorg's OpenDevice reply layout (verified in + // mate-asahi-xorg.xtrace line 142667): four XInputClassInfo + // entries in the order Button(1), Valuator(2), Feedback(3), + // Other(6) with `event_type_base` values that line up the + // XI1 wire event codes against `XI_FIRST_EVENT`. + // + // The Other entry is the load-bearing one for property + // notification: xinput's Xlib `DevicePropertyNotify(dev, + // type, _class)` macro walks `XDevice->classes`, finds the + // OtherClass entry, and computes + // type = entry.event_type_base + _propertyNotify(=6) + // _class = (deviceid << 8) | type + // and passes _class to `XSelectExtensionEvent`. An empty + // class list (our pre-fix stub) leaves _class = 0 and + // `xinput watch-props` silently subscribes to nothing. + // + // The Button/Valuator/Feedback entries carry only their + // (class, event_type_base) tags here — the OpenDevice + // reply itself never includes per-class trailing data + // (buttons / axes / feedback descriptors live in separate + // requests). Including them empty-shaped matches Xorg's + // wire byte-for-byte, which Xlib appears to need for the + // `XDevice` to register as fully usable even though only + // the OtherClass entry is consumed for property events. + // Class tags (XI.h) + event_type_base offsets relative to + // `XI_FIRST_EVENT` (= 66; Xorg `Xi/extinit.c::FixExtensionEvents`): + // Key(0) base + 1 = 0x43 Button(1) base + 3 = 0x45 + // Valuator(2) base + 5 = 0x47 Feedback(3) base 0 (no event) + // Focus(5) base + 6 = 0x48 Other(6) base + 10 = 0x4c + const KEY_CLASS: u8 = 0; + const BUTTON_CLASS: u8 = 1; + const VALUATOR_CLASS: u8 = 2; + const FEEDBACK_CLASS: u8 = 3; + const FOCUS_CLASS: u8 = 5; + const OTHER_CLASS: u8 = 6; + // The class set MUST match the device's use: a pointer reports + // Button/Valuator/Feedback/Other; a keyboard reports + // Key/Feedback/Focus/Other (verified against mate-xorg.xtrace + // OpenDevice replies). Returning pointer classes for a keyboard + // contradicts ListInputDevices and trips clients' device model. + let deviceid = u16::from(*body.first().unwrap_or(&0)); + let is_keyboard = xi1_device_has_keys(&state.xi_devices, deviceid); + let entries: [u8; 8] = if is_keyboard { + [ + KEY_CLASS, + XI_FIRST_EVENT + 1, + FEEDBACK_CLASS, + 0, + FOCUS_CLASS, + XI_FIRST_EVENT + 6, + OTHER_CLASS, + XI_FIRST_EVENT + 10, + ] + } else { + [ + BUTTON_CLASS, + XI_FIRST_EVENT + 3, + VALUATOR_CLASS, + XI_FIRST_EVENT + 5, + FEEDBACK_CLASS, + 0, + OTHER_CLASS, + XI_FIRST_EVENT + 10, + ] + }; + // CRITICAL: `num_classes` lives at byte 8 of xOpenDeviceReply + // (the first field after the 8-byte header), NOT the detail + // byte. Clients (Xlib XOpenDevice, Chromium's XI device init) + // read it there; the old code passed it as `fixed_reply`'s + // detail byte, leaving byte 8 = 0, so num_classes read as 0 on + // the wire and the class array below was invisible. That made + // OpenDevice contradict ListInputDevices' per-device class + // count → Chromium fatal CHECK / SIGTRAP on startup. + // length=2 = two extra 4-byte units (8 bytes of class entries). + let mut reply = x11::fixed_reply(byte_order, sequence, 3, 2); + reply.push(4); // byte 8: num_classes + reply.extend_from_slice(&[0u8; 23]); // bytes 9..=31: header pad + reply.extend_from_slice(&entries); + debug!( + "client {} #{} XI1 OpenDevice device={deviceid} -> {} classes", + client_id.0, sequence.0, 4 + ); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// ── XI 1.x minors with request validation ────────────────── +// +// Spec-error checks first (the XTS XI scenario's "Got Success, +// Expecting " family — BadDevice/BadValue/BadMatch/ +// BadWindow/BadMode/BadClass per the XInput 1.x protocol spec, +// cross-checked against Xorg Xi/*.c). Success behavior is described +// per request below; capability boundaries such as absent motion +// history and device-resolution ranges are explicit rather than a +// blanket zero-reply fallback. + +// CloseDevice (void): xCloseDeviceReq { deviceid }. +pub(super) fn handle_xi1_close_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + debug!( + "client {} #{} XI1 CloseDevice device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// SetDeviceMode: { deviceid, mode }. Mode changes only make +// sense for devices with valuators (Xorg Xi/setmode.c). +pub(super) fn handle_xi1_set_device_mode( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_valuators(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // Store the mode (Relative=0 / Absolute=1) — + // DeviceStateNotify reports it in the `classes_reported` + // bits above ModeBitsShift. Xorg + // `Xi/setmode.c::ProcXSetDeviceMode` returns + // `AlreadyGrabbed` (reply byte 8) when another client + // holds the device's active grab; in that case the mode + // is NOT updated. xts5 XSetDeviceMode-2. + const ALREADY_GRABBED: u8 = 1; + let grabbed_elsewhere = state + .xi1_active_grabs + .get(&dev) + .is_some_and(|g| g.owner != client_id); + let status = if grabbed_elsewhere { + ALREADY_GRABBED + } else { + let mode = *body.get(1).unwrap_or(&0); + if mode <= 1 { + state + .xi1_device_input_state + .entry(dev) + .or_default() + .valuator_mode = mode; + } + 0 + }; + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.push(status); + reply.extend_from_slice(&[0u8; 23]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// ChangeKeyboardDevice: { deviceid }. Needs a device with keys +// (Xorg Xi/chgkbd.c). xts5 expects: +// 1. ChangeDeviceNotify (request=1 = NewKeyboard) +// 2. core MappingNotify (request=1 = MappingKeyboard) +// 3. reply +// — in that order on the wire. +pub(super) fn handle_xi1_change_keyboard_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if !xi1_device_has_keys(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // 1. ChangeDeviceNotify for originator (if selected) + fanout. + if crate::core_loop::xi1_focus::xi1_client_wants_change_device_notify(state, client_id, dev) + { + let time = state.timestamp_now(); + #[allow(clippy::cast_possible_truncation)] + let device_byte = dev as u8; + crate::xinput::encode_xi1_change_device_notify( + &mut buf, + byte_order, + crate::server::XI_FIRST_EVENT + crate::xinput::XI_CHANGE_DEVICE_NOTIFY_OFFSET, + device_byte, + sequence, + time, + 1, // NewKeyboard + ); + } + crate::core_loop::xi1_focus::emit_change_device_notify(state, client_id, dev, 1); + // 2. core MappingNotify (request=1 = MappingKeyboard) to all + // clients, including originator inline so the wire order is + // ChangeDeviceNotify → MappingNotify → reply. + let _ = x11::write_mapping_notify_event(&mut buf, byte_order, sequence, 1, 0, 0); + let others: Vec = state + .clients + .keys() + .filter(|id| **id != client_id.0) + .map(|id| ClientId(*id)) + .collect(); + let _dropped = + crate::core_loop::fanout::fanout_event_to_clients(state, &others, |b, s, o| { + let _ = x11::write_mapping_notify_event(b, o, s, 1, 0, 0); + }); + // 3. reply. + buf.extend_from_slice(&xi1_zero_reply(byte_order, sequence)); + } + xi_write_reply(state, client_id, buf) +} + +// ChangePointerDevice is unsupported by Xorg 21.1.24: its handler +// returns BadDevice after request-size validation (Xi/chgptr.c:92-98). +#[allow(clippy::needless_return)] +pub(super) fn handle_xi1_change_pointer_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + minor: u8, +) -> io::Result { + return xi1_error(state, client_id, sequence, XI1_ERROR_BAD_DEVICE, 0, minor); +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/events.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/events.rs new file mode 100644 index 000000000..3f78b3884 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/events.rs @@ -0,0 +1,810 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::fanout_event_to_clients, + process_request::{ + RequestOutcome, XI2_FIRST_ERROR, XI2_MAJOR_OPCODE, emit_x11_error_with_minor, + xi::{ + XI1_ERROR_BAD_CLASS, XI1_ERROR_BAD_DEVICE, XI1_ERROR_BAD_MODE, + dispatch::xi_write_reply, emit_xi2_device_changed_bootstrap, xi1_device_valid, + xi1_error, xi1_event_class_device, xi1_send_extension_event_resolve_targets, + xi1_window_exists, xi2_first_invalid_mask_bit, + }, + }, + }, + resources::ROOT_WINDOW, + server::{ServerState, XI_FIRST_EVENT}, + xinput::{XI_DEVICE_KEY_PRESS_OFFSET, XI2_DEVICE_CHANGED_MASK}, +}; +use log::debug; +use std::{collections::HashSet, io}; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_select_events( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + debug!("client {} #{} XISelectEvents", client_id.0, sequence.0); + let mut send_device_changed_bootstrap = false; + if body.len() >= 8 { + let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let num_masks = u16::from_le_bytes([body[4], body[5]]) as usize; + // Xorg ProcXISelectEvents checks every mask before + // setting any, so a rejected request changes nothing. + let mut masks: Vec<(u16, u64)> = Vec::with_capacity(num_masks); + let mut pos = 8; + for _ in 0..num_masks { + if pos + 4 > body.len() { + break; + } + let deviceid = u16::from_le_bytes([body[pos], body[pos + 1]]); + let mask_len = u16::from_le_bytes([body[pos + 2], body[pos + 3]]) as usize; + pos += 4; + let byte_len = mask_len.saturating_mul(4); + if pos + byte_len > body.len() { + break; + } + let mask_bytes = &body[pos..pos + byte_len]; + // XICheckInvalidMaskBits: a bit past XI2LASTEVENT is + // BadValue with the bit number as errorValue. + if let Some(bit) = xi2_first_invalid_mask_bit(mask_bytes) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + bit, + 46, + header.opcode, + ); + } + let hierarchy_event = crate::xinput::XI2_HIERARCHY_CHANGED_EVENT_TYPE; + let selects_hierarchy = mask_bytes + .get((hierarchy_event / 8) as usize) + .is_some_and(|byte| byte & (1 << (hierarchy_event % 8)) != 0); + if deviceid != 0 && selects_hierarchy { + // Xorg Xi/xiselectev.c:186-193 permits this mask only + // on XIAllDevices. Preserve its lookup-before-mask + // validation order for concrete device ids. + if deviceid != 1 && state.xi_devices.device(deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 46, + header.opcode, + ); + } + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + hierarchy_event, + 46, + header.opcode, + ); + } + // The mask is a bit array (bit n in byte n/8), so the + // bytes are little-endian whatever the client order. + let mut word = [0u8; 8]; + let keep = byte_len.min(8); + word[..keep].copy_from_slice(&mask_bytes[..keep]); + masks.push((deviceid, u64::from_le_bytes(word))); + pos += byte_len; + } + if let Some(client) = state.clients.get_mut(&client_id.0) { + for (deviceid, mask) in masks { + debug!( + "client {} XISelectEvents window=0x{:x} deviceid={} mask=0x{:x}", + client_id.0, window.0, deviceid, mask + ); + if mask == 0 { + client.xi2_masks.remove(&(window, deviceid)); + } else { + client.xi2_masks.insert((window, deviceid), mask); + if window == ROOT_WINDOW + && matches!(deviceid, 0..=3) + && (mask & u64::from(XI2_DEVICE_CHANGED_MASK)) != 0 + { + send_device_changed_bootstrap = true; + } + } + } + } + } + if send_device_changed_bootstrap { + emit_xi2_device_changed_bootstrap( + state, + backend, + origin, + client_id, + sequence, + XI2_MAJOR_OPCODE, + )?; + } + return Ok(RequestOutcome::Handled); +} + +pub(super) fn handle_xi_get_selected_events( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + debug!("client {} #{} XIGetSelectedEvents", client_id.0, sequence.0); + if body.len() < 4 { + return Ok(RequestOutcome::Handled); + } + let window = ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + // Xorg ProcXIGetSelectedEvents: one xXIEventMask per device + // in device-id order, each trimmed to the words that hold set + // bits. deviceid/mask_len follow the client byte order; the + // mask itself is a bit array (bit n in byte n/8), written as + // little-endian bytes for every client. + let mut selected: Vec<(u16, u64)> = state + .clients + .get(&client_id.0) + .map(|client| { + client + .xi2_masks + .iter() + .filter(|&(&(win, _), &mask)| win == window && mask != 0) + .map(|(&(_, dev), &mask)| (dev, mask)) + .collect() + }) + .unwrap_or_default(); + selected.sort_unstable_by_key(|&(dev, _)| dev); + let mut masks = Vec::new(); + for &(dev, mask) in &selected { + let mask_len: u16 = if mask >> 32 == 0 { 1 } else { 2 }; + x11::write_u16(byte_order, &mut masks, dev); + x11::write_u16(byte_order, &mut masks, mask_len); + masks.extend_from_slice(&mask.to_le_bytes()[..4 * usize::from(mask_len)]); + } + let num_masks = u16::try_from(selected.len()).unwrap_or(u16::MAX); + let mut reply = x11::fixed_reply( + byte_order, + sequence, + 0, + x11::checked_units(masks.len())? as u32, + ); + x11::write_u16(byte_order, &mut reply, num_masks); + reply.extend_from_slice(&[0; 22]); + reply.extend_from_slice(&masks); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// XI 1.x SelectExtensionEvent (minor 6; xSelectExtensionEventReq, +// XIproto.h). Body after the 4-byte generic header: +// body[0..4] window (Window = CARD32), +// body[4..6] count (CARD16, number of XEventClass values), +// body[6..8] pad00 (CARD16), +// body[8..] count × XEventClass (CARD32). +// +// An XEventClass packs `(deviceid << 8) | event_code`. We only +// implement XI1 `DevicePropertyNotify` (event code 16 within +// the XInput block, i.e. low byte = `XI_FIRST_EVENT + 16` = 82 +// — yserver assigns XInput the contiguous block 66..=82), so +// classes for other XI1 events (motion / button / key / etc.) +// are accepted but ignored. We do NOT error on unknown classes: +// a single SelectExtensionEvent often selects multiple classes +// and Xorg silently drops the ones it can't service. +// +// Selection state is canonical per window, as in Xorg. Events such +// as DevicePropertyNotify carry no event-window field, so a separate +// aggregate is derived from the per-window state for delivery. +// +// Replace semantics: for every deviceid mentioned in the +// supplied class list, this client's prior selections for that +// deviceid on this window are dropped before the new set is +// installed. A client +// unsubscribes a given deviceid by passing at least one class +// for it whose low byte is not `DevicePropertyNotify` — the +// deviceid lands in `touched_devices` and its prior entries +// are cleared; the unsupported class itself is silently +// dropped. `count == 0` is a no-op (the existing selection +// survives unchanged), matching Xorg's behaviour. +#[allow(clippy::needless_return)] +pub(super) fn handle_xi1_select_extension_event( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + if body.len() < 8 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 16, // BadLength + 0, + 6, + XI2_MAJOR_OPCODE, + ); + } + let count = usize::from(u16::from_le_bytes([body[4], body[5]])); + let expected_len = 8usize.saturating_add(count.saturating_mul(4)); + if body.len() < expected_len { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 16, // BadLength + 0, + 6, + XI2_MAJOR_OPCODE, + ); + } + // Xorg Xi/selectev.c validates the window first (BadWindow), + // then rejects classes whose embedded deviceid names no + // device (BadClass) — XTS XSelectExtensionEvent-11/-13. + let sel_window = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if state.resources.window(ResourceId(sel_window)).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + sel_window, + u16::from(minor), + XI2_MAJOR_OPCODE, + ); + } + // Xorg's HandleDevicePresenceMask runs before ordinary XI1 + // class validation and removes every class whose device field + // is 256. Only its `_devicePresence` class selects a mask. + // Preserve that class separately: truncating the device field + // to eight bits would turn it into XIAllDevices (id 0). + let mut ordinary_classes = Vec::with_capacity(count); + let mut presence_selected = false; + for i in 0..count { + let off = 8 + i * 4; + let class = u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + if class >> 8 == 256 { + if class & 0xff == 0 { + presence_selected = true; + } + continue; + } + ordinary_classes.push(class); + } + if presence_selected && let Some(client) = state.clients.get_mut(&client_id.0) { + // Xorg installs DevicePresenceNotifyMask in + // HandleDevicePresenceMask before ordinary classes are + // validated. Preserve that ordering if a later class in + // this request reports BadClass. + client + .xi1_window_event_classes + .entry(ResourceId(sel_window)) + .or_default() + .insert(crate::xinput::XI1_DEVICE_PRESENCE_CLASS); + client.rebuild_xi1_global_event_classes(); + } + for class in &ordinary_classes { + if !xi1_device_valid(&state.xi_devices, xi1_event_class_device(*class)) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI1_ERROR_BAD_CLASS, + *class, + u16::from(minor), + XI2_MAJOR_OPCODE, + ); + } + } + // Decode the requested class list and collect the set of + // deviceids that appear (so we can drop the client's stale + // entries for *those* devices — Xorg's "replace per device" + // semantics, see Xi/selectev.c::ProcXSelectExtensionEvent). + let mut accepted_classes: Vec = Vec::with_capacity(ordinary_classes.len()); + let mut touched_devices: HashSet = HashSet::new(); + for class in ordinary_classes { + #[allow(clippy::cast_possible_truncation)] + let class_low = class as u8; // event code in the XInput block + #[allow(clippy::cast_possible_truncation)] + let dev_byte = (class >> 8) as u8; + touched_devices.insert(dev_byte); + // DevicePropertyNotify classes are device-scoped; the + // input-event classes (DeviceKeyPress..DeviceMotionNotify), + // the focus classes (DeviceFocusIn/Out, consumed by + // `xi1_focus::emit_device_focus`) and DeviceStateNotify + // (consumed by `xi1_state_notify::deliver_state_notify`) + // select per window like core input events and are + // recorded in `xi1_window_event_classes` below. Other + // classes are silently discarded, matching Xorg: it walks + // `xi_all_events` and skips entries it cannot service. + if crate::server::xi1_class_is_global_notification(class) { + // DevicePropertyNotify / DeviceMappingNotify / + // ChangeDeviceNotify are server-wide per-device + // events: Xorg `Xi/exevents.c::SendMappingNotify` / + // `SendDeviceNotify` fan them out by walking the + // global client list, NOT a per-window event-mask. + accepted_classes.push(class); + } else if (XI_FIRST_EVENT + XI_DEVICE_KEY_PRESS_OFFSET + ..=XI_FIRST_EVENT + crate::xinput::XI_DEVICE_FOCUS_OUT_OFFSET) + .contains(&class_low) + || class_low == XI_FIRST_EVENT + crate::xinput::XI_DEVICE_STATE_NOTIFY_OFFSET + { + accepted_classes.push(class); + } + } + debug!( + "client {} #{} XSelectExtensionEvent window=0x{:x} count={} accepted={} window_input={}", + client_id.0, + sequence.0, + sel_window, + count, + accepted_classes + .iter() + .filter(|class| crate::server::xi1_class_is_global_notification(**class)) + .count(), + accepted_classes + .iter() + .filter(|class| !crate::server::xi1_class_is_global_notification(**class)) + .count(), + ); + if let Some(client) = state.clients.get_mut(&client_id.0) { + // Selection state belongs to the request window. Drop stale + // entries for the named devices on that window only (Xorg + // replacement semantics), then install the accepted list. + if !touched_devices.is_empty() + && let Some(set) = client + .xi1_window_event_classes + .get_mut(&ResourceId(sel_window)) + { + set.retain(|c| { + if *c == crate::xinput::XI1_DEVICE_PRESENCE_CLASS { + return true; + } + #[allow(clippy::cast_possible_truncation)] + let dev_byte = (c >> 8) as u8; + !touched_devices.contains(&dev_byte) + }); + } + if !accepted_classes.is_empty() { + let set = client + .xi1_window_event_classes + .entry(ResourceId(sel_window)) + .or_default(); + for class in accepted_classes { + set.insert(class); + } + } + + // Keep the delivery-oriented aggregate in sync. Global XI1 + // notifications have no event-window field, but selecting + // them is still per-window protocol state. + client.rebuild_xi1_global_event_classes(); + } + return Ok(RequestOutcome::Handled); +} + +// GetSelectedExtensionEvents: { window }. The trailing payload is +// this client's classes followed by all clients' classes for the +// requested window (Xorg Xi/getselev.c). +pub(super) fn handle_xi1_get_selected_extension_events( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let win = u32::from_le_bytes([ + *body.first().unwrap_or(&0), + *body.get(1).unwrap_or(&0), + *body.get(2).unwrap_or(&0), + *body.get(3).unwrap_or(&0), + ]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let window = ResourceId(win); + let mut this_client: Vec = state + .clients + .get(&client_id.0) + .and_then(|client| client.xi1_window_event_classes.get(&window)) + .map(|classes| classes.iter().copied().collect()) + .unwrap_or_default(); + this_client.sort_unstable(); + + let mut all_clients: Vec = state + .clients + .values() + .filter_map(|client| client.xi1_window_event_classes.get(&window)) + .flat_map(|classes| classes.iter().copied()) + .collect(); + all_clients.sort_unstable(); + + let total_classes = this_client.len().saturating_add(all_clients.len()); + let length_words = u32::try_from(total_classes).unwrap_or(u32::MAX); + let this_count = u16::try_from(this_client.len()).unwrap_or(u16::MAX); + let all_count = u16::try_from(all_clients.len()).unwrap_or(u16::MAX); + let mut reply = x11::fixed_reply(byte_order, sequence, minor, length_words); + x11::write_u16(byte_order, &mut reply, this_count); + x11::write_u16(byte_order, &mut reply, all_count); + reply.extend_from_slice(&[0u8; 20]); + for class in this_client.into_iter().chain(all_clients) { + x11::write_u32(byte_order, &mut reply, class); + } + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// ChangeDeviceDontPropagateList (void): { window, count, mode }, +// classes follow. mode ∈ {AddToList=0, DeleteFromList=1}. +pub(super) fn handle_xi1_change_device_dont_propagate_list( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let mode = body[6]; + if mode > 1 { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_MODE, + u32::from(mode), + minor, + ); + } + let count = usize::from(u16::from_le_bytes([body[4], body[5]])); + let mut classes: Vec = Vec::with_capacity(count); + for i in 0..count { + let off = 8 + i * 4; + if off + 4 > body.len() { + break; + } + let class = + u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + if !xi1_device_valid(&state.xi_devices, xi1_event_class_device(class)) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_CLASS, + class, + minor, + ); + } + classes.push(class); + } + // mode 0 = AddToList, 1 = DeleteFromList. Xorg + // `Xi/chgdprop.c::ChangeDeviceDontPropagateList` applies the + // change to `OtherInputMasks.dontPropagateMask[deviceid]`; + // the deviceid is encoded in the high byte of each class so + // the per-device split is implicit in the class set. + let entry = state + .xi1_window_dont_propagate + .entry(ResourceId(win)) + .or_default(); + if mode == 0 { + for c in &classes { + entry.insert(*c); + } + } else { + for c in &classes { + entry.remove(c); + } + if entry.is_empty() { + state.xi1_window_dont_propagate.remove(&ResourceId(win)); + } + } + debug!( + "client {} #{} XI1 ChangeDeviceDontPropagateList win=0x{win:x} mode={mode} count={count}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// GetDeviceDontPropagateList: { window }. Reply layout +// (XIproto.h:`xGetDeviceDontPropagateListReply`): +// bytes 0..1 = reply opcode (1) + pad +// bytes 2..4 = sequence +// bytes 4..8 = length (32-bit units of trailing class array) +// bytes 8..10 = count (CARD16) +// bytes 10..32 = pad +// trailing `count` × XEventClass (CARD32) at byte 32 +pub(super) fn handle_xi1_get_device_dont_propagate_list( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let win = u32::from_le_bytes([ + *body.first().unwrap_or(&0), + *body.get(1).unwrap_or(&0), + *body.get(2).unwrap_or(&0), + *body.get(3).unwrap_or(&0), + ]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let classes: Vec = state + .xi1_window_dont_propagate + .get(&ResourceId(win)) + .map(|set| set.iter().copied().collect()) + .unwrap_or_default(); + #[allow(clippy::cast_possible_truncation)] + let count = classes.len() as u16; + let length_words = u32::try_from(classes.len()).unwrap_or(u32::MAX); + let mut reply = x11::fixed_reply(byte_order, sequence, 0, length_words); + x11::write_u16(byte_order, &mut reply, count); // bytes 8..10 + reply.extend_from_slice(&[0u8; 22]); // pad to 32 + for c in &classes { + x11::write_u32(byte_order, &mut reply, *c); + } + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// SendExtensionEvent (void): { destination, deviceid, propagate, +// count, num_events } + events (32 bytes each) + classes. +pub(super) fn handle_xi1_send_extension_event( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + { + if body.len() < 12 { + return Ok(RequestOutcome::Handled); + } + let dest = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + let dev = u16::from(body[4]); + let class_count = usize::from(u16::from_le_bytes([body[6], body[7]])); + let num_events = usize::from(body[8]); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + // Xorg Xi/sendexev.c order: device, then the class list + // (CreateMaskFromList → BadClass), and only then the + // destination window inside SendEvent — XTS + // XSendExtensionEvent-20 sends a stale window + bogus class + // and expects the BadClass. + let classes_off = 12 + num_events * 32; + // The XI swap table for minor 31 marks everything past the + // header as `OpaqueTail` because the per-event payload + // (the sender's byte order, like core SendEvent's xEvent + // template) must NOT be swapped. That leaves the trailing + // XEventClass[] in the client's native order; read each + // class with `byte_order` awareness rather than blind LE. + let read_class = |off: usize| -> Option { + let bytes = body.get(off..off + 4)?; + let arr = [bytes[0], bytes[1], bytes[2], bytes[3]]; + Some(match byte_order { + yserver_protocol::x11::ClientByteOrder::LittleEndian => u32::from_le_bytes(arr), + yserver_protocol::x11::ClientByteOrder::BigEndian => u32::from_be_bytes(arr), + }) + }; + for i in 0..class_count { + let off = classes_off + i * 4; + let Some(class) = read_class(off) else { + break; + }; + if !xi1_device_valid(&state.xi_devices, xi1_event_class_device(class)) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_CLASS, + class, + minor, + ); + } + } + // Like core SendEvent, destination accepts the specials + // PointerWindow (0) and InputFocus (1). + if !matches!(dest, 0 | 1) && !xi1_window_exists(state, dest) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + dest, + minor, + ); + } + // Per Xorg `Xi/sendexev.c::ProcXSendExtensionEvent` → + // `Xi/exevents.c::SendEvent`: resolve the destination, + // then deliver each supplied event to (a) clients whose + // XI1 selection on the destination window intersects the + // request's class list, and (b) the window's CREATOR when + // the per-device mask is empty (the `noextensioneventclass` + // case — Xorg `DeliverToWindowOwner` short-circuits on + // `filter == CantBeFiltered` = `NoEventMask` = 0). The + // class-intersection rule preserves XI1 event chains + // (DeviceKeyPress + DeviceValuator continuation), which + // the client selects via the head class only. + // Propagate semantics are not yet honoured — direct-window + // match only, like core SendEvent with propagate=False. + // + // Specials (xserver.git Xi/exevents.c:2915-2944): + // - PointerWindow → sprite window (deepest mapped window + // under the pointer); + // - InputFocus → device's focus window, with PointerRoot + // falling back to the sprite and FollowKeyboard chasing + // the core focus inside `resolve_focus`. + let dest_window: Option = match dest { + 0 => Some(crate::core_loop::key_fanout::deepest_window_at_pointer( + state, + )), + 1 => { + let focus = crate::core_loop::xi1_focus::device_focus(state, dev).focus; + match crate::core_loop::xi1_focus::resolve_focus(state, focus) { + crate::core_loop::xi1_focus::Xi1FocusTarget::None => None, + crate::core_loop::xi1_focus::Xi1FocusTarget::PointerRoot => Some( + crate::core_loop::key_fanout::deepest_window_at_pointer(state), + ), + crate::core_loop::xi1_focus::Xi1FocusTarget::Window(f) => { + // Xorg `effectiveFocus` rule (xserver.git + // Xi/exevents.c:2936-2941): if the focus is + // an ancestor of (or equal to) the sprite, + // deliver to the sprite — the focus + // bounds propagation but the deepest + // pointer window is the actual target. + // Otherwise the sprite is outside the focus + // subtree and delivery goes to the focus + // directly. xts5 XSendExtensionEvent-3 + // probes the inferior-of-focus case. + let sprite = crate::core_loop::key_fanout::deepest_window_at_pointer(state); + if f == sprite || crate::core_loop::xi1_focus::is_ancestor(state, f, sprite) + { + Some(sprite) + } else { + Some(f) + } + } + } + } + w => Some(ResourceId(w)), + }; + if let Some(dest_window) = dest_window { + // Collect the request's class list (already + // validated above for `xi1_device_valid`). Same + // byte-order reasoning as the BadClass loop above — + // classes are in the sender's native order because the + // XI swap table can't carve them out of the variable + // event payload that precedes them. + let mut request_classes: Vec = Vec::with_capacity(class_count); + for i in 0..class_count { + let off = classes_off + i * 4; + let Some(class) = read_class(off) else { + break; + }; + request_classes.push(class); + } + // Xorg `Xi/grabdev.c::CreateMaskFromList` walks the + // class list and OR's per-class mask bits into the + // per-device mask. `noextensioneventclass` (low byte + // `_noExtensionEvent = 9` per XI.h:260) has no + // associated mask bit, so it contributes nothing — + // a request whose only classes are noextensioneventclass + // entries (or an empty list) ends up with an + // all-zero mask, which `DeliverToWindowOwner` treats + // as `CantBeFiltered` and delivers to the window + // creator unconditionally. Without this fall-through + // xts5 XSendExtensionEvent 1–4 (which always pass + // `noextensioneventclass`) fail because the test + // process never calls XSelectExtensionEvent first. + const XI1_NO_EXTENSION_EVENT_OFFSET: u8 = 9; + #[allow(clippy::cast_possible_truncation)] + let mask_is_zero = request_classes.is_empty() + || request_classes + .iter() + .all(|c| (c & 0xff) as u8 == XI1_NO_EXTENSION_EVENT_OFFSET); + let propagate = matches!(body.get(5), Some(&p) if p != 0); + let targets = xi1_send_extension_event_resolve_targets( + state, + dest_window, + &request_classes, + mask_is_zero, + propagate, + ); + if !targets.is_empty() { + // Pre-snapshot all event bytes so the fanout + // closure can borrow them per-recipient. + let mut events_bytes: Vec<[u8; 32]> = Vec::with_capacity(num_events); + for i in 0..num_events { + let off = 12 + i * 32; + let Some(ev) = body.get(off..off + 32) else { + break; + }; + events_bytes.push(ev.try_into().expect("32-byte slice")); + } + let targets_vec: Vec = targets.into_iter().collect(); + let _dropped = fanout_event_to_clients(state, &targets_vec, |buf, seq, order| { + for ev_bytes in &events_bytes { + let mut out = *ev_bytes; + out[0] |= 0x80; // send_event + let seq_bytes = match order { + yserver_protocol::x11::ClientByteOrder::LittleEndian => { + seq.0.to_le_bytes() + } + yserver_protocol::x11::ClientByteOrder::BigEndian => { + seq.0.to_be_bytes() + } + }; + out[2] = seq_bytes[0]; + out[3] = seq_bytes[1]; + buf.extend_from_slice(&out); + } + }); + } + } + debug!( + "client {} #{} XI1 SendExtensionEvent device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/focus.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/focus.rs new file mode 100644 index 000000000..825633551 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/focus.rs @@ -0,0 +1,438 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::process_request::{ + RequestOutcome, XI2_MAJOR_OPCODE, emit_x11_error_with_minor, + xi::{ + XI1_ERROR_BAD_DEVICE, dispatch::xi_write_reply, xi1_device_has_keys, xi1_device_valid, + xi1_error, + }, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, ResourceId, SequenceNumber}, +}; + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_change_cursor( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // XIChangeCursor (XI2 opcode 42). Wire body after the + // request header: window(4), cursor(4), deviceid(2), pad(2). + // GTK4 (gnome-text-editor, modern GTK apps) sets per-widget + // cursors via this rather than core `XDefineCursor`, so + // pre-fix the I-beam never reached the backend and text + // areas kept showing the default arrow. Treat it as + // `XDefineCursor` for now — yserver doesn't yet route + // per-device cursors, but a single effective cursor on the + // window matches what XInput2 produces for AllMasterDevices + // and is what GTK relies on in practice. `cursor = None` + // (xid 0) means "clear" — same semantics as the CWA cursor + // path, see Xorg `dix/window.c:1487-1491`. + if body.len() < 8 { + debug!( + "client {} #{} XIChangeCursor (body too short: {})", + client_id.0, + sequence.0, + body.len() + ); + return Ok(RequestOutcome::Handled); + } + let window = ResourceId(u32::from_le_bytes(body[0..4].try_into().expect("4 bytes"))); + let cursor = ResourceId(u32::from_le_bytes(body[4..8].try_into().expect("4 bytes"))); + let host_window_raw = if window == ROOT_WINDOW { + Some(backend.window_id()) + } else { + state + .resources + .window(window) + .and_then(|w| w.host_xid) + .map(|h| h.as_raw()) + }; + let cursor_host_xid = if cursor.0 == 0 { + Some(0u32) + } else { + state.resources.cursor_host_xid(cursor) + }; + debug!( + "client {} #{} XIChangeCursor window=0x{:x} cursor=0x{:x}", + client_id.0, sequence.0, window.0, cursor.0 + ); + if let (Some(hw), Some(ch)) = (host_window_raw, cursor_host_xid) { + let _ = backend.define_cursor(origin, hw, ch); + } + return Ok(RequestOutcome::Handled); +} + +pub(super) fn handle_xi_query_pointer( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIQueryPointer: GDK calls this to fetch the current + // pointer position for gesture-drag anchors (caja-desktop + // marquee, mate-panel applet drags). Previously hardcoded + // every coordinate to 0, so every drag started from (0,0) + // regardless of the actual cursor position — caja then + // rubber-banded from screen origin to the click point on + // any single click. Wire the real cursor position through + // from the backend. + // XIQueryPointer body layout (per xinput.xml): + // bytes [0..4] window (WINDOW) + // bytes [4..6] deviceid (u16) + // bytes [6..8] pad + // Previously this read body[4..8], which is deviceid + pad + // — i.e. always interpreted as some sentinel xid (e.g. + // `0xfd820002`, `0xffff0002`). Then + // `window_absolute_position` couldn't find the bogus xid + // and returned `(0, 0)`, so the win-relative coords came + // out equal to the root-absolute coords. GTK popups in + // file managers (Thunar, Caja) place themselves at + // `(window_origin + win_xy + menu_offset)` — with our + // wrong reply they ended up offset by the window's own + // origin, and rubber-band drags anchored at root (0,0) + // instead of at the click point. + let queried_window = if body.len() >= 4 { + ResourceId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])) + } else { + ROOT_WINDOW + }; + let pointer = backend.query_pointer(origin).ok(); + let (root_x_int, root_y_int, mask, same_screen) = + if let Some(p) = pointer.filter(|p| p.same_screen) { + (p.win_x, p.win_y, p.mask, 1u8) + } else { + (0, 0, 0, 0u8) + }; + let (origin_x, origin_y) = state.resources.window_absolute_position(queried_window); + let win_x_int = + i16::try_from(i32::from(root_x_int).saturating_sub(origin_x)).unwrap_or(i16::MAX); + let win_y_int = + i16::try_from(i32::from(root_y_int).saturating_sub(origin_y)).unwrap_or(i16::MAX); + let child = state + .direct_child_at(queried_window, win_x_int, win_y_int) + .unwrap_or(ResourceId(0)); + debug!( + "client {} #{} XIQueryPointer window=0x{:x} -> root=({},{}) win=({},{}) child=0x{:x} mask=0x{:x}", + client_id.0, + sequence.0, + queried_window.0, + root_x_int, + root_y_int, + win_x_int, + win_y_int, + child.0, + mask, + ); + // Reply layout (length = 6 units = 24 bytes after the + // 8-byte header — total 32 + 24 = 56). FP1616 coords are + // (i32::from(coord) << 16) as u32. Per xinput.xml the + // BOOL `same_screen` is at offset 32 (NOT in the `pad0` + // slot at offset 1 — confirmed via x11trace 2026-05-15). + // GTK uses `same_screen` to pick popup-placement code + // paths; encoding it as pad0 left every client reading + // `same_screen=false` and routing through the "different + // screen" branch, which made Thunar's right-click popup + // appear at root+window_origin instead of near the click. + // XI2 button state: fold the KeyButMask button bits into the + // XI2 button bitmask (button N -> bit N). muffin's + // `_NET_WM_MOVERESIZE` move grab queries the pointer to learn + // whether the initiating button is still held — an empty mask + // makes it abort the move and the window never budges. + let mut button_mask: u32 = 0; + for (keybut_bit, button) in [ + (0x0100u16, 1u32), + (0x0200, 2), + (0x0400, 3), + (0x0800, 4), + (0x1000, 5), + ] { + if mask & keybut_bit != 0 { + button_mask |= 1 << button; + } + } + // length 7 units: 6 coord words + the same_screen/buttons_len/ + // ModifierInfo/GroupInfo block + a 1-unit button bitmask. + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 7); + x11::write_u32(byte_order, &mut reply, ROOT_WINDOW.0); + x11::write_u32(byte_order, &mut reply, child.0); + x11::write_u32(byte_order, &mut reply, (i32::from(root_x_int) << 16) as u32); + x11::write_u32(byte_order, &mut reply, (i32::from(root_y_int) << 16) as u32); + x11::write_u32(byte_order, &mut reply, (i32::from(win_x_int) << 16) as u32); + x11::write_u32(byte_order, &mut reply, (i32::from(win_y_int) << 16) as u32); + reply.push(same_screen); // byte 32: same_screen (BOOL) + reply.push(0); // byte 33: pad + x11::write_u16(byte_order, &mut reply, 1); // bytes 34-35: buttons_len (1 unit) + // ModifierInfo: 4× CARD32 = base / latched / locked / + // effective. `mask` carries the X11 KeyButMask snapshot + // from the backend: MODIFIERS in the low byte (Shift=0x1 … + // Mod5=0x80), buttons at 0x100+. Xorg fills `rep.mods` + // from the paired MASTER_KEYBOARD's XKB state + // (Xi/xiquerypointer.c:120,139) — base_mods must carry the + // modifier bits WITHOUT the button bits. Pre-fix base was + // hardcoded 0: cinnamon's alt-tab switcher polls + // `global.get_pointer()` (GDK → XIQueryPointer) right + // after pushModal to check Alt is still held; reading 0 it + // took the modifier-already-released branch + // (_activateSelected + destroy) and the switcher popup + // never appeared. `effective` keeps the full KeyButMask + // (mods + button bits) — GDK reads effective and the + // button bits are harmlessly idempotent with the XI2 + // buttons array below. + let mod_bits = u32::from(mask & 0x00ff); + x11::write_u32(byte_order, &mut reply, mod_bits); // base_mods + x11::write_u32(byte_order, &mut reply, 0); // latched_mods + x11::write_u32(byte_order, &mut reply, 0); // locked_mods + x11::write_u32(byte_order, &mut reply, u32::from(mask)); // effective_mods + reply.extend_from_slice(&[0u8; 4]); // group info + // XI2 button mask is a raw byte array indexed by + // `XIMaskIsSet(ptr, btn) = ptr[btn>>3] & (1 << (btn & 7))` + // (X11/extensions/XI2.h) — byte[0] holds buttons 0-7. It is + // NOT byte-swapped per client order (Xorg leaves the trailing + // mask bytes untouched in its reply swap), so emit + // little-endian unconditionally. + reply.extend_from_slice(&button_mask.to_le_bytes()); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// GetDeviceFocus: { deviceid }. Reply layout +// (xGetDeviceFocusReply, XIproto.h:709-721): focus CARD32 @8, +// time CARD32 @12, revertTo CARD8 @16, pad to 32. The focus +// field carries the raw stored value — None(0)/PointerRoot(1)/ +// FollowKeyboard(3) sentinels included (Xorg Xi/getfocus.c +// maps focus->win back to the sentinel, never resolving it). +pub(super) fn handle_xi1_get_device_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + let dev = u16::from(*body.first().unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + // NOTE: Xorg's `if (!dev->focus) return BadDevice` is NOT + // mirrored as a keyboard-only gate: real servers initialise + // a focus class on extension pointers too (XTS + // Miscellaneous-3..6 call SetDeviceFocus on Devs.Button / + // Devs.DvMod and expect Success). + let f = crate::core_loop::xi1_focus::device_focus(state, dev); + // Byte 1 = RepType = X_GetDeviceFocus (Xi/getfocus.c). + let mut reply = x11::fixed_reply(byte_order, sequence, minor, 0); + x11::write_u32(byte_order, &mut reply, f.focus); // bytes 8-11 + x11::write_u32(byte_order, &mut reply, f.time); // bytes 12-15 + reply.push(f.revert_to); // byte 16 + reply.extend_from_slice(&[0u8; 15]); // bytes 17-31: pad + debug!( + "client {} #{} XI1 GetDeviceFocus device={dev} -> focus=0x{:x} revert={}", + client_id.0, sequence.0, f.focus, f.revert_to + ); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// SetDeviceFocus (void): { focus, time, revertTo, device }. +// focus: None(0) / PointerRoot(1) / FollowKeyboard(3) / a valid +// viewable window. revertTo: RevertToNone(0)..FollowKeyboard(3). +// Mirrors Xorg Xi/setfocus.c → dix SetInputFocus +// (dix/events.c:4879): validate, then silently ignore stale / +// future timestamps, then store + emit DeviceFocusIn/Out. +pub(super) fn handle_xi1_set_device_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if body.len() < 10 { + return Ok(RequestOutcome::Handled); + } + let focus = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + let req_time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let revert_to = body[8]; + let dev = u16::from(body[9]); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if revert_to > 3 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(revert_to), + minor, + ); + } + if !matches!(focus, 0 | 1 | 3) { + let Some(window) = state.resources.window(ResourceId(focus)) else { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + focus, + minor, + ); + }; + if window.map_state != crate::resources::MapState::Viewable { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + } + // Timestamp gate (dix/events.c:4920-4922): CurrentTime(0) + // maps to the server clock; a time later than "now" or + // earlier than the last-focus-change time is a silent no-op. + let now = state.timestamp_now(); + let time = if req_time == 0 { now } else { req_time }; + let prev = crate::core_loop::xi1_focus::device_focus(state, dev); + if crate::core_loop::xi1_focus::time_after(time, now) + || crate::core_loop::xi1_focus::time_after(prev.time, time) + { + debug!( + "client {} #{} XI1 SetDeviceFocus device={dev} stale time {time} \ + (now={now} last={}) — ignored", + client_id.0, sequence.0, prev.time + ); + return Ok(RequestOutcome::Handled); + } + crate::core_loop::xi1_focus::set_device_focus(state, dev, focus, revert_to, time); + debug!( + "client {} #{} XI1 SetDeviceFocus device={dev} focus=0x{focus:x} \ + revert={revert_to} time={time}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +pub(super) fn handle_xi_get_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIGetFocus { deviceid:CARD16 } -> xXIGetFocusReply + // { focus:WINDOW @8, 20 bytes pad }. Xorg ProcXIGetFocus + // (Xi/xisetdevfocus.c) reports the device's raw focus (None=0 / + // PointerRoot=1 / FollowKeyboard=3 / window) without resolving + // the sentinels. Only keyboards have a focus class; pointers + // and unknown ids are BadDevice with no errorValue. The master + // keyboard's focus is the core focus; the slave keyboard's is + // its own (shared with XI1 GetDeviceFocus). + let dev = if body.len() >= 2 { + u16::from_le_bytes([body[0], body[1]]) + } else { + 0 + }; + if !xi1_device_has_keys(&state.xi_devices, dev) { + return xi1_error(state, client_id, sequence, XI1_ERROR_BAD_DEVICE, 0, minor); + } + let focus = + if state.xi_devices.role(dev) == Some(crate::xinput::XiDeviceRole::MasterKeyboard) { + state.core_focus.raw + } else { + crate::core_loop::xi1_focus::device_focus(state, dev).focus + }; + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + x11::write_u32(byte_order, &mut reply, focus); // bytes 8-11 + reply.extend_from_slice(&[0u8; 20]); // bytes 12-31 pad + debug!( + "client {} #{} XIGetFocus device={dev} -> focus=0x{focus:x}", + client_id.0, sequence.0 + ); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +pub(super) fn handle_xi_barrier_release_pointer( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + { + if let Some(entries) = x11::parse_xi_barrier_release(body) { + for (deviceid, barrier_id, event_id) in entries { + if !(deviceid == 0 || deviceid == 1 || deviceid == 2) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(deviceid), + 61, + XI2_MAJOR_OPCODE, + ); + } + let Some(barrier) = state.pointer_barriers.get_mut(&barrier_id) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + barrier_id, + 61, + XI2_MAJOR_OPCODE, + ); + }; + if barrier.owner != client_id { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + barrier_id, + 61, + XI2_MAJOR_OPCODE, + ); + } + if barrier.event_id == event_id { + barrier.release_event_id = event_id; + } + } + } + } + xi_write_reply(state, client_id, Vec::new()) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs new file mode 100644 index 000000000..bd8e6ba96 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs @@ -0,0 +1,1848 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::fanout_event_to_clients, + key_fanout::replay_frozen_key_to_focus, + pointer_fanout::replay_frozen_pointer_event_to_state, + process_request::{ + RequestOutcome, XI2_FIRST_ERROR, XI2_MAJOR_OPCODE, emit_x11_error_with_minor, + grabs::{ + apply_allow_events, apply_xi2_allow_events_for_slave, deactivate_core_pointer_grab, + deactivate_passive_pointer_grab_crossings, xi2_allow_mode_to_core, + }, + xi::{ + XI1_ERROR_BAD_CLASS, XI1_ERROR_BAD_DEVICE, XI1_KEY_MIN, XI1_USE_X_KEYBOARD, + dispatch::xi_write_reply, xi1_device_has_buttons, xi1_device_has_keys, + xi1_device_valid, xi1_error, xi1_event_class_device, xi1_modifiers_valid, + xi1_window_exists, + }, + }, + }, + resources::ROOT_WINDOW, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientByteOrder, ClientId, ResourceId, SequenceNumber}, +}; + +// XI2 grab opcodes (51-55). yserver wires these into the +// existing core X11 grab state (`state.active_pointer_grab`, +// `state.button_grabs`, +// `state.active_keyboard_grab`, `state.key_grabs`) which the +// pointer/key fanout already honours. The XI2 mask + per- +// device routing isn't fully implemented — every grab is +// mapped to the requested master slot or exact slave-device grab +// slot according to the registered device role. That matches what +// GTK relies on in practice (its uses of XIGrabDevice are equivalent +// to XGrabPointer/XGrabKeyboard for the master devices). +// +// Pre-fix all five handlers were no-ops that just sent +// Success replies — GTK then thought it owned the device but +// events still went to the normal pointer-window, so popups +// dismissed on the first stray motion event and `gtk_window_ +// present` looped re-mapping the popup at ~50 Hz (visible as +// brisk-menu's MapWindow remap storm pre-`MapWindow` +// no-op fix, and as subtle popup misbehavior elsewhere). +// +// Match Xorg `Xi/exevents.c::DeviceGrabDevice` / +// `ProcXIPassiveGrabDevice` for state-update intent. The +// status byte at reply offset 8 is always Success(0); a +// strict implementation would return AlreadyGrabbed(1) / +// NotViewable(3) / etc., but Xorg's permissive behaviour +// (set the grab and let later events sort it out) keeps GTK +// happy across pause/resume sleeps. +pub(super) fn handle_xi_grab_device( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIGrabDevice reply: 32 bytes (header + status at offset + // 8 + 23 pad). Wire body: window(4) + time(4) + cursor(4) + // + deviceid(2) + mode(1) + paired_device_mode(1) + + // owner_events(1) + pad(1) + mask_len(2) + ... + // XIGrabDevice body: window(4) time(4) cursor(4) + // deviceid(2) mode(1) paired(1) owner_events(1) pad(1) + // mask_len(2) mask... + let (grab_window, time, cursor, deviceid, owner_events) = if body.len() >= 17 { + ( + u32::from_le_bytes([body[0], body[1], body[2], body[3]]), + u32::from_le_bytes([body[4], body[5], body[6], body[7]]), + u32::from_le_bytes([body[8], body[9], body[10], body[11]]), + u16::from_le_bytes([body[12], body[13]]), + body[16] != 0, + ) + } else { + (0, 0, 0, 0, false) + }; + // The grab's XI2 event-type mask follows mask_len at body[18..20]. + // Keep the first two words represented by ActivePointerGrab's + // u64 mask; these cover all pointer event types currently routed. + let grab_xi2_mask = body + .get(18..20) + .map_or(0, |length| { + usize::from(u16::from_le_bytes([length[0], length[1]])) + }) + .saturating_mul(4) + .min(8) + .checked_add(20) + .and_then(|end| body.get(20..end)) + .map_or(0, |mask_bytes| { + let mut mask = [0u8; 8]; + mask[..mask_bytes.len()].copy_from_slice(mask_bytes); + u64::from_le_bytes(mask) + }); + let role = match state.xi_devices.role(deviceid) { + Some(role) => role, + None => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(deviceid), + 51, + XI2_MAJOR_OPCODE, + ); + } + }; + let is_keyboard = matches!( + role, + crate::xinput::XiDeviceRole::MasterKeyboard + | crate::xinput::XiDeviceRole::SlaveKeyboard + ); + let is_master = matches!( + role, + crate::xinput::XiDeviceRole::MasterKeyboard + | crate::xinput::XiDeviceRole::MasterPointer + ); + // Xorg `dix/events.c:5240` (GrabDevice): a device already + // grabbed by ANOTHER client → AlreadyGrabbed(1); do NOT + // overwrite the grab. Same-client re-grab still replaces + // (Xorg SameClient path, unchanged below). #94 Cinnamon + // click-swallow: muffin `XIGrabDevice`-stole the master + // pointer from Steam mid-click (both device=2), so the + // ButtonRelease was delivered to muffin and Steam's click + // never completed (cinnamon.xtrace conn 026 vs 105). The + // pointer slot covers implicit / passive-activated / explicit + // grabs alike — exactly Xorg's single `deviceGrab.grab`. + let grab_status: u8 = if is_keyboard && is_master { + u8::from( + state + .active_keyboard_grab + .is_some_and(|g| g.owner != client_id), + ) + } else if is_keyboard { + u8::from( + state + .xi2_keyboard_grabs + .get(&deviceid) + .is_some_and(|g| g.owner != client_id), + ) + } else if is_master { + u8::from( + state + .active_pointer_grab + .is_some_and(|grab| grab.owner != client_id), + ) + } else { + u8::from( + state + .xi2_pointer_grabs + .get(&deviceid) + .is_some_and(|grab| grab.owner != client_id), + ) + }; + if grab_status == 0 { + // Capture the previous grab window (if any, this client's) + // BEFORE we overwrite. Synthesised crossings need to send + // Leave on the previous grab window when transitioning to + // a different one. GTK3 popups grab the input-shadow + // window first, then re-grab the visible popup — without + // the Leave on the shadow window GTK3's menu-tracking + // never engages on the visible popup. + let prev_pointer_grab_window: Option = if is_keyboard { + None + } else if is_master { + state + .active_pointer_grab + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window) + } else { + state + .xi2_pointer_grabs + .get(&deviceid) + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window) + }; + let prev_keyboard_grab_window: Option = if is_keyboard && is_master { + state + .active_keyboard_grab + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window) + } else { + state + .xi2_keyboard_grabs + .get(&deviceid) + .filter(|g| g.owner == client_id) + .map(|g| g.grab_window) + }; + if is_keyboard { + let grab = crate::server::ActiveKeyboardGrab { + owner: client_id, + grab_window: ResourceId(grab_window), + source: crate::server::ActiveKeyboardGrabSource::Explicit, + owner_events, + via_xi2: true, + xi2_mask: u32::try_from(grab_xi2_mask & u64::from(u32::MAX)) + .expect("first XI2 mask word fits CARD32"), + }; + if is_master { + state.active_keyboard_grab = Some(grab); + } else { + state.xi2_keyboard_grabs.insert(deviceid, grab); + let _ = state.detach_xi2_slave(deviceid); + } + } else { + let grab = crate::server::ActivePointerGrab { + owner: client_id, + grab_window: ResourceId(grab_window), + event_mask: 0xFFFF, // core mask is unused for XI2 grabs + cursor: ResourceId(cursor), + time, + owner_events, + via_xi2: true, + implicit: false, + passive: false, + xi2_mask: grab_xi2_mask, + }; + if is_master { + state.set_pointer_grab(grab); + } else { + state.xi2_pointer_grabs.insert(deviceid, grab); + let _ = state.detach_xi2_slave(deviceid); + } + } + // Core↔XI bridge — Xorg `ActivateKeyboardGrab` / + // `ActivatePointerGrab` end with `CheckGrabForSyncs` + // (dix/events.c:1424): a SYNCHRONOUS grab freezes this + // device, an ASYNCHRONOUS grab THAWS it — including a + // freeze left behind by a sync passive-grab activation — + // and `ComputeFreezes` replays the withheld queues. The + // core GrabKeyboard/GrabPointer handlers already do this; + // pre-fix the XI2 path skipped it, so muffin's alt-tab + // (sync passive keybinding grab → ASYNC XIGrabDevice + // pushModal → XIUngrabDevice) left the keyboard + // FrozenNoEvent forever: one alt-tab killed all key input + // (the XIAllowEvents muffin sends after the ungrab is + // correctly a no-op — its grab is already gone). + // Wire: body[14]=grab_mode, body[15]=paired_device_mode; + // XI2 GrabModeSync=0 / GrabModeAsync=1. + let grab_mode = body.get(14).copied().unwrap_or(1); + let paired_mode = body.get(15).copied().unwrap_or(1); + crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( + state, + deviceid, + client_id, + grab_mode == 0, + paired_mode == 0, + ); + if grab_mode != 0 { + // The withheld sync-passive replay candidate was already + // delivered to the grab owner; an async grab forecloses + // Replay (Xorg drops the stored event on thaw). + state.xi1_frozen.entry(deviceid).or_default().stored = None; + } + debug!( + "client {} #{} XIGrabDevice window=0x{:x} deviceid={} cursor=0x{:x} -> Success", + client_id.0, sequence.0, grab_window, deviceid, cursor + ); + // Synthesised XI2 crossings on grab activation. Matches + // Xorg `Xi/exevents.c::ActivateKeyboardGrab` / + // `ActivatePointerGrab` (which call `DoEnterLeaveEvents` + // with `NotifyGrab`). Without these GTK3 popup state + // machines never engage their hover/click tracking — the + // menu is visible but items don't highlight or activate + // on click. Captured in `mate-xorg.xtrace` as the pair + // `XI_Leave(mode=Grab, detail=Nonlinear)` on the previous + // grab window followed by `XI_Enter(mode=Grab, + // detail=Nonlinear)` on the new grab window; keyboard + // grabs additionally get `XI_FocusIn(mode=Grab, + // detail=Nonlinear)`. NotifyGrab = 1, NotifyNonlinear = 3. + let pointer_xy = backend + .query_pointer(origin) + .ok() + .map(|p| (p.win_x, p.win_y)) + .unwrap_or((0, 0)); + let (root_x, root_y) = pointer_xy; + let server_time = state.timestamp_now(); + // Emit one XI2 crossing (Enter/Leave/FocusIn/FocusOut) on a + // single window with an explicit detail code, mode + // NotifyGrab. The keyboard-focus path drives this directly; + // the pointer path drives it from a crossing chain so the + // detail codes — and the `from == to` no-op — match Xorg's + // `DoEnterLeaveEvents`. + let emit_xi_crossing = |state: &mut ServerState, + evtype: u16, + target_window: ResourceId, + detail: u8| { + let (origin_x, origin_y) = state.resources.window_absolute_position(target_window); + let event_x = + i16::try_from(i32::from(root_x).saturating_sub(origin_x)).unwrap_or(i16::MAX); + let event_y = + i16::try_from(i32::from(root_y).saturating_sub(origin_y)).unwrap_or(i16::MAX); + let focus = !matches!(evtype, 9 | 10) && state.crossing_has_focus(target_window); + let _dropped = fanout_event_to_clients(state, &[client_id], |out, seq, order| { + x11::encode_xi2_crossing_event( + out, + order, + seq, + XI2_MAJOR_OPCODE, + evtype, + deviceid, + server_time, + ROOT_WINDOW, + target_window, + root_x, + root_y, + event_x, + event_y, + 0, + 1, // mode = NotifyGrab + detail, + deviceid, + focus, + ); + }); + }; + if is_keyboard { + // Keyboard grab → focus transitions (Xorg + // `ActivateKeyboardGrab` → `DoFocusEvents`). Unchanged. + if let Some(prev) = prev_keyboard_grab_window + && prev != ResourceId(grab_window) + { + emit_xi_crossing(state, 10, prev, 3); // XI_FocusOut + } + emit_xi_crossing(state, 9, ResourceId(grab_window), 3); // XI_FocusIn + } else { + // Pointer grab → Xorg `ActivatePointerGrab` → + // `DoEnterLeaveEvents(from, grab_window, NotifyGrab)` + // (dix/events.c). `from` is the previous grab window + // when replacing an active grab, else the window the + // pointer currently sits in (the sprite, resolved from + // the live position). `compute_crossing_chain` + // early-returns when `from == grab_window`, so grabbing + // the window already under the pointer emits nothing — + // matching Xorg. The pre-fix code emitted an + // unconditional `XI_Enter(NotifyGrab)` on the grab + // window, which desynced cinnamon's XEmbed-systray + // click-forward whenever muffin grabbed its own + // full-screen stage (pamac tray unclickable, 2026-06-22). + let from = prev_pointer_grab_window.unwrap_or_else(|| { + state + .root_pointer_target_at(root_x, root_y) + .map_or(ResourceId(grab_window), |h| h.0) + }); + let chain = + crate::crossings::implicit_grab_crossings(state, from, ResourceId(grab_window)); + for e in chain { + let evtype: u16 = match e.kind { + crate::crossings::CrossingKind::Enter => 7, + crate::crossings::CrossingKind::Leave => 8, + }; + emit_xi_crossing(state, evtype, e.window, e.detail); + } + } + } // end: mutate grab state + emit crossings only when granted + // XIGrabDevice reply carries the grab status at offset 8 + // (0 = Success, 1 = AlreadyGrabbed — Xorg dix/events.c:5240). + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + let mut grab_reply_body = [0u8; 24]; + grab_reply_body[0] = grab_status; + reply.extend_from_slice(&grab_reply_body); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_ungrab_device( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // XIUngrabDevice body: time(4) + deviceid(2) + pad(2). + let deviceid = if body.len() >= 6 { + u16::from_le_bytes([body[4], body[5]]) + } else { + 0 + }; + let role = match state.xi_devices.role(deviceid) { + Some(role) => role, + None => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(deviceid), + 52, + XI2_MAJOR_OPCODE, + ); + } + }; + let is_keyboard = matches!( + role, + crate::xinput::XiDeviceRole::MasterKeyboard | crate::xinput::XiDeviceRole::SlaveKeyboard + ); + let is_master = matches!( + role, + crate::xinput::XiDeviceRole::MasterKeyboard | crate::xinput::XiDeviceRole::MasterPointer + ); + deactivate_xi2_device_grab( + state, + backend, + origin, + client_id, + deviceid, + is_keyboard, + is_master, + ); + debug!( + "client {} #{} XIUngrabDevice deviceid={}", + client_id.0, sequence.0, deviceid + ); + return Ok(RequestOutcome::Handled); +} + +/// Deactivate `owner`'s XI2 grab on `deviceid`, if it holds one, and send the +/// owner the `NotifyUngrab` events (Xorg `DeactivatePointerGrab` / +/// `DeactivateKeyboardGrab`). XIUngrabDevice and window destroy. +pub(in crate::core_loop::process_request) fn deactivate_xi2_device_grab( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + owner: ClientId, + deviceid: u16, + is_keyboard: bool, + is_master: bool, +) { + // Capture grab_window BEFORE clearing — we synthesize the + // matching XI2 crossing with `NotifyUngrab` on the way out + // so the client's grab state machine pairs cleanly with + // its earlier NotifyGrab. Matches Xorg + // `Xi/exevents.c::DeactivateKeyboardGrab` / + // `DeactivatePointerGrab`. + let grab_window_for_event: Option = if is_keyboard && is_master { + state + .active_keyboard_grab + .filter(|g| g.owner == owner) + .map(|g| g.grab_window) + } else if is_keyboard { + state + .xi2_keyboard_grabs + .get(&deviceid) + .filter(|g| g.owner == owner) + .map(|g| g.grab_window) + } else if is_master { + state + .active_pointer_grab + .filter(|grab| grab.owner == owner) + .map(|grab| grab.grab_window) + } else { + state + .xi2_pointer_grabs + .get(&deviceid) + .filter(|grab| grab.owner == owner) + .map(|grab| grab.grab_window) + }; + if grab_window_for_event.is_some() { + if is_keyboard && is_master { + state.active_keyboard_grab = None; + } else if is_keyboard { + state.xi2_keyboard_grabs.remove(&deviceid); + } else if is_master { + state.clear_pointer_grab(); + } else { + state.xi2_pointer_grabs.remove(&deviceid); + } + state.xi1_frozen.entry(deviceid).or_default().stored = None; + crate::core_loop::pointer_fanout::xi1_core_grab_bridge_release(state, deviceid, owner); + if !is_master { + state.reattach_xi2_slave(deviceid); + } + if !is_keyboard { + // Clear any grab-cursor sprite override, as + // `deactivate_core_pointer_grab` does — a core + // XGrabPointer(cursor) torn down via XIUngrabDevice + // must not strand the grab cursor on the sprite. + let _ = backend.set_grab_cursor(None, None); + } + } + if let Some(grab_window) = grab_window_for_event { + let pointer_xy = backend + .query_pointer(origin) + .ok() + .map(|p| (p.win_x, p.win_y)) + .unwrap_or((0, 0)); + let (root_x, root_y) = pointer_xy; + let server_time = state.timestamp_now(); + let emit_xi_crossing = + |state: &mut ServerState, evtype: u16, target_window: ResourceId, detail: u8| { + let (origin_x, origin_y) = state.resources.window_absolute_position(target_window); + let event_x = + i16::try_from(i32::from(root_x).saturating_sub(origin_x)).unwrap_or(i16::MAX); + let event_y = + i16::try_from(i32::from(root_y).saturating_sub(origin_y)).unwrap_or(i16::MAX); + let focus = !matches!(evtype, 9 | 10) && state.crossing_has_focus(target_window); + let _dropped = fanout_event_to_clients(state, &[owner], |out, seq, order| { + x11::encode_xi2_crossing_event( + out, + order, + seq, + XI2_MAJOR_OPCODE, + evtype, + deviceid, + server_time, + ROOT_WINDOW, + target_window, + root_x, + root_y, + event_x, + event_y, + 0, + 2, // mode = NotifyUngrab + detail, + deviceid, + focus, + ); + }); + }; + if is_keyboard { + // Keyboard ungrab → focus restore. Unchanged. + emit_xi_crossing(state, 10, grab_window, 3); // XI_FocusOut + } else { + // Pointer ungrab → Xorg `DeactivatePointerGrab` → + // `DoEnterLeaveEvents(grab_window, sprite, NotifyUngrab)` + // (dix/events.c). Symmetric with the activation + // chain: `from == to` (sprite still inside the grab + // window) emits nothing. + let to = state + .root_pointer_target_at(root_x, root_y) + .map_or(grab_window, |h| h.0); + let chain = crate::crossings::implicit_grab_crossings(state, grab_window, to); + for e in chain { + let evtype: u16 = match e.kind { + crate::crossings::CrossingKind::Enter => 7, + crate::crossings::CrossingKind::Leave => 8, + }; + emit_xi_crossing(state, evtype, e.window, e.detail); + } + } + } +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_allow_events( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // XIAllowEvents body (per X11/extensions/XI2proto.h + // `xXIAllowEventsReq`): time(4) + deviceid(2) + mode(1) + + // pad(1). XI 2.2 extends with touchid(4) + grab_window(4) + // for touch grabs; we don't implement touch, so the + // extension fields are ignored. + // + // mutter/muffin/cinnamon install click-to-focus passive + // button grabs (sync) and keybinding key grabs (sync); on each + // press they examine it then call XIAllowEvents to thaw/replay. + // The mode (XIAsyncDevice/XISyncDevice/XIReplayDevice/…) + + // deviceid map onto a core AllowSome mode — see + // `xi2_allow_mode_to_core` — and run through the shared + // `apply_allow_events` below. + let (deviceid, mode) = if body.len() >= 8 { + (u16::from_le_bytes([body[4], body[5]]), body[6]) + } else { + (0, 0) + }; + let role = match state.xi_devices.role(deviceid) { + Some(role) => role, + None => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(deviceid), + 53, + XI2_MAJOR_OPCODE, + ); + } + }; + let is_keyboard = matches!( + role, + crate::xinput::XiDeviceRole::MasterKeyboard | crate::xinput::XiDeviceRole::SlaveKeyboard + ); + let is_master = matches!( + role, + crate::xinput::XiDeviceRole::MasterKeyboard | crate::xinput::XiDeviceRole::MasterPointer + ); + debug!( + "client {} #{} XIAllowEvents deviceid={} mode={}", + client_id.0, sequence.0, deviceid, mode + ); + let time = if body.len() >= 4 { + u32::from_le_bytes([body[0], body[1], body[2], body[3]]) + } else { + 0 + }; + // Map the XI2 mode + target deviceid onto the equivalent core + // AllowSome mode and run the SHARED `apply_allow_events`. This + // used to be a partial reimplementation that diverged from the + // core path and caused recurring freezes (desktop rubber-band = + // Async/Replay thaw gap; Cinnamon input freeze = XISyncDevice + // treated as a no-op). Touch modes (XIAcceptTouch/XIRejectTouch) + // are unsupported → no-op. + if is_master { + if let Some(core_mode) = xi2_allow_mode_to_core(mode, is_keyboard) { + return apply_allow_events(state, backend, client_id, sequence, core_mode, time); + } + } else { + return apply_xi2_allow_events_for_slave( + state, + backend, + client_id, + sequence, + deviceid, + is_keyboard, + mode, + time, + ); + } + return Ok(RequestOutcome::Handled); +} + +/// `XIAllDevices` (0) or `XIAllMasterDevices` (1): Xorg +/// `ProcXIPassiveGrabDevice` / `ProcXIPassiveUngrabDevice` +/// (Xi/xipassivegrab.c) take these without a device lookup. +fn is_xi2_device_wildcard(deviceid: u16) -> bool { + deviceid <= 1 +} + +/// The device a passive grab is stored under. `XIAllMasterDevices` becomes +/// the master of the grab's class, which the grab matching already treats +/// as "any device attached to it"; `XIAllDevices` stays 0, matched the same +/// way. Grab and ungrab map alike, so an ungrab finds its grab. +fn passive_grab_device(deviceid: u16, grab_type: u8) -> u16 { + match (deviceid, grab_type) { + (1, 0) => crate::xinput::DEVICEID_MASTER_POINTER, + (1, 1) => crate::xinput::DEVICEID_MASTER_KEYBOARD, + _ => deviceid, + } +} + +pub(super) fn handle_xi_passive_grab_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIPassiveGrabDevice body (per X11/extensions/XI2proto.h + // `xXIPassiveGrabDeviceReq`): time(4) + grab_window(4) + + // cursor(4) + detail(4) + deviceid(2) + num_modifiers(2) + // + mask_len(2) + grab_type(1) + grab_mode(1) + + // paired_device_mode(1) + owner_events(1) + pad1(2) + + // mask(mask_len*4) + modifiers(num_modifiers*4). + // + // GrabType: Button=0, Keycode=1, Enter=2, FocusIn=3, + // TouchBegin=4. Button and Keycode map onto core X11 + // PassiveButtonGrab / KeyGrab; the other three are no-ops + // for now (yserver doesn't synthesise core X11 Enter/ + // FocusIn passive grabs). + let ( + grab_window, + detail, + deviceid, + num_modifiers, + mask_len, + grab_type, + grab_mode, + paired_device_mode, + owner_events, + ) = if body.len() >= 25 { + ( + u32::from_le_bytes([body[4], body[5], body[6], body[7]]), + u32::from_le_bytes([body[12], body[13], body[14], body[15]]), + u16::from_le_bytes([body[16], body[17]]), + u16::from_le_bytes([body[18], body[19]]), + u16::from_le_bytes([body[20], body[21]]) as usize, + body[22], + body[23], + body[24], + body.get(25).copied().unwrap_or(0) != 0, + ) + } else { + (0, 0, 0, 0, 0, 0xff, 1, 1, false) + }; + if matches!(grab_type, 0 | 1) && !is_xi2_device_wildcard(deviceid) { + let role = state.xi_devices.role(deviceid); + let compatible = match grab_type { + 0 => matches!( + role, + Some( + crate::xinput::XiDeviceRole::MasterPointer + | crate::xinput::XiDeviceRole::SlavePointer + ) + ), + 1 => matches!( + role, + Some( + crate::xinput::XiDeviceRole::MasterKeyboard + | crate::xinput::XiDeviceRole::SlaveKeyboard + ) + ), + _ => true, + }; + if !compatible { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(deviceid), + 54, + XI2_MAJOR_OPCODE, + ); + } + } + let deviceid = passive_grab_device(deviceid, grab_type); + // Modifiers tail starts after the header (28) and the mask + // (mask_len * 4 bytes). + let mods_start = 28 + mask_len * 4; + // First mask word: event types 0..=31. + let grab_xi2_mask = if mask_len > 0 { + body.get(28..32) + .map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + } else { + 0 + }; + let mut modifier_masks: Vec = Vec::with_capacity(num_modifiers.max(1).into()); + if num_modifiers == 0 { + // "no modifiers" — single grab with modifier-mask 0. + modifier_masks.push(0); + } else { + for i in 0..usize::from(num_modifiers) { + let off = mods_start + i * 4; + if let Some(slice) = body.get(off..off + 4) { + let raw = u32::from_le_bytes(slice.try_into().unwrap()); + // XI2 `Any` = bit 31; map to core X11 AnyModifier (0x8000). + #[allow(clippy::cast_possible_truncation)] + let m = if raw & 0x8000_0000 != 0 { + 0x8000u16 + } else { + (raw & 0xFFFF) as u16 + }; + modifier_masks.push(m); + } + } + } + match grab_type { + 0 => { + // Button. detail = button number (0 == AnyButton). + let button = u8::try_from(detail).unwrap_or(0); + for modifiers in &modifier_masks { + state.button_grabs.retain(|g| { + !(g.owner == client_id + && g.via_xi2 + && g.device_id == deviceid + && g.grab_window.0 == grab_window + && g.button == button + && g.modifiers == *modifiers) + }); + state.button_grabs.push(crate::server::PassiveButtonGrab { + device_id: deviceid, + owner: client_id, + grab_window: ResourceId(grab_window), + button, + modifiers: *modifiers, + owner_events, + event_mask: 0xFFFF_FFFF, + pointer_mode: grab_mode, + keyboard_mode: 1, + confine_to: ResourceId(0), + via_xi2: true, + }); + } + } + 1 => { + // Keycode. detail = keycode (0 == AnyKey). + let keycode = u8::try_from(detail).unwrap_or(0); + for modifiers in &modifier_masks { + state.key_grabs.retain(|g| { + !(g.owner == client_id + && g.via_xi2 + && g.device_id == deviceid + && g.grab_window.0 == grab_window + && g.keycode == keycode + && g.modifiers == *modifiers) + }); + state.key_grabs.push(crate::server::KeyGrab { + device_id: deviceid, + owner: client_id, + grab_window: ResourceId(grab_window), + keycode, + modifiers: *modifiers, + owner_events, + pointer_mode: paired_device_mode, + keyboard_mode: grab_mode, + via_xi2: true, + xi2_mask: grab_xi2_mask, + }); + } + } + _ => { + // Enter/FocusIn/TouchBegin — yserver has no + // matching machinery yet; record the request in + // the debug log so a real repro shows up. + debug!( + "client {} #{} XIPassiveGrabDevice unsupported grab_type={} \ + (Enter/FocusIn/TouchBegin)", + client_id.0, sequence.0, grab_type + ); + } + } + debug!( + "client {} #{} XIPassiveGrabDevice window=0x{:x} detail=0x{:x} deviceid={} \ + grab_type={} num_modifiers={} -> Success", + client_id.0, sequence.0, grab_window, detail, deviceid, grab_type, num_modifiers, + ); + // Reply: num_modifiers(2) + pad(22). With 0 failed + // modifiers the client treats every requested combination + // as grabbed. + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.extend_from_slice(&[0u8; 24]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_passive_ungrab_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // XIPassiveUngrabDevice body: grab_window(4) + detail(4) + // + deviceid(2) + num_modifiers(2) + grab_type(1) + + // pad(3) + modifiers. + let (grab_window, detail, device_id, num_modifiers, grab_type) = if body.len() >= 13 { + ( + u32::from_le_bytes([body[0], body[1], body[2], body[3]]), + u32::from_le_bytes([body[4], body[5], body[6], body[7]]), + u16::from_le_bytes([body[8], body[9]]), + u16::from_le_bytes([body[10], body[11]]), + body[12], + ) + } else { + (0, 0, 0, 0, 0xff) + }; + if matches!(grab_type, 0 | 1) && !is_xi2_device_wildcard(device_id) { + let role = state.xi_devices.role(device_id); + let compatible = match grab_type { + 0 => matches!( + role, + Some( + crate::xinput::XiDeviceRole::MasterPointer + | crate::xinput::XiDeviceRole::SlavePointer + ) + ), + 1 => matches!( + role, + Some( + crate::xinput::XiDeviceRole::MasterKeyboard + | crate::xinput::XiDeviceRole::SlaveKeyboard + ) + ), + _ => true, + }; + if !compatible { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(device_id), + 55, + XI2_MAJOR_OPCODE, + ); + } + } + let device_id = passive_grab_device(device_id, grab_type); + let mods_start = 16; + let mut modifier_masks: Vec = Vec::with_capacity(num_modifiers.max(1).into()); + if num_modifiers == 0 { + modifier_masks.push(0); + } else { + for i in 0..usize::from(num_modifiers) { + let off = mods_start + i * 4; + if let Some(slice) = body.get(off..off + 4) { + let raw = u32::from_le_bytes(slice.try_into().unwrap()); + #[allow(clippy::cast_possible_truncation)] + let m = if raw & 0x8000_0000 != 0 { + 0x8000u16 + } else { + (raw & 0xFFFF) as u16 + }; + modifier_masks.push(m); + } + } + } + match grab_type { + 0 => { + let button = u8::try_from(detail).unwrap_or(0); + state.button_grabs.retain(|g| { + !(g.owner == client_id + && g.via_xi2 + && g.device_id == device_id + && g.grab_window.0 == grab_window + && (g.button == button || button == 0) + && modifier_masks + .iter() + .any(|m| g.modifiers == *m || *m == 0x8000)) + }); + } + 1 => { + let keycode = u8::try_from(detail).unwrap_or(0); + state.key_grabs.retain(|g| { + !(g.owner == client_id + && g.via_xi2 + && g.device_id == device_id + && g.grab_window.0 == grab_window + && (g.keycode == keycode || keycode == 0) + && modifier_masks + .iter() + .any(|m| g.modifiers == *m || *m == 0x8000)) + }); + } + _ => {} + } + debug!( + "client {} #{} XIPassiveUngrabDevice window=0x{:x} detail=0x{:x} grab_type={}", + client_id.0, sequence.0, grab_window, detail, grab_type + ); + return Ok(RequestOutcome::Handled); +} + +// GrabDevice: { grabWindow, time, event_count, this_device_mode, +// other_devices_mode, ownerEvents, deviceid } + classes. Classes +// must name the grabbed device (XTS XGrabDevice-4/-13). +pub(super) fn handle_xi1_grab_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, + minor: u8, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + if body.len() < 16 { + return Ok(RequestOutcome::Handled); + } + let dev = u16::from(body[13]); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let this_mode = body[10]; + let other_mode = body[11]; + let owner_events = body[12]; + if this_mode > 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(this_mode), + minor, + ); + } + if other_mode > 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(other_mode), + minor, + ); + } + if owner_events > 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(owner_events), + minor, + ); + } + let count = usize::from(u16::from_le_bytes([body[8], body[9]])); + for i in 0..count { + let off = 16 + i * 4; + if off + 4 > body.len() { + break; + } + let class = + u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + let class_dev = xi1_event_class_device(class); + if !xi1_device_valid(&state.xi_devices, class_dev) || class_dev != dev { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_CLASS, + class, + minor, + ); + } + } + // Establish the active device grab. Status values per X.h: + // GrabSuccess 0, AlreadyGrabbed 1, GrabInvalidTime 2, + // GrabNotViewable 3. + let time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.xi1_last_grab_time); + let viewable = state + .resources + .window(ResourceId(win)) + .is_some_and(|w| w.map_state == crate::resources::MapState::Viewable); + let status: u8 = if state + .xi1_active_grabs + .get(&dev) + .is_some_and(|g| g.owner != client_id) + { + 1 // AlreadyGrabbed + } else if !viewable { + 3 // GrabNotViewable + } else if time != 0 && (time < state.xi1_last_grab_time || time > now) { + 2 // GrabInvalidTime + } else { + state.xi1_active_grabs.insert( + dev, + crate::server::Xi1ActiveGrab { + owner: client_id, + deviceid: dev, + grab_window: ResourceId(win), + owner_events: owner_events != 0, + this_mode, + other_mode, + passive_detail: None, + }, + ); + state.xi1_last_grab_time = if time == 0 { now } else { time }; + // CheckGrabForSyncs: a sync this_mode freezes the + // device ONCE (FrozenNoEvent — no stored event, so + // Replay is a no-op on it); a sync other_mode holds + // the paired device on this grab's behalf. + crate::core_loop::pointer_fanout::xi1_check_grab_for_syncs( + state, + dev, + client_id, + this_mode == 0, + other_mode == 0, + ); + 0 // GrabSuccess + }; + debug!( + "client {} #{} XI1 GrabDevice device={dev} window=0x{win:x} status={status}", + client_id.0, sequence.0 + ); + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.push(status); + reply.extend_from_slice(&[0u8; 23]); + buf.extend_from_slice(&reply); + } + xi_write_reply(state, client_id, buf) +} + +// UngrabDevice (void): { time, deviceid }. Body: time at +// bytes 0..4, deviceid at byte 4 — `xUngrabDeviceReq`. +pub(super) fn handle_xi1_ungrab_device( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + let time = u32::from_le_bytes([ + *body.first().unwrap_or(&0), + *body.get(1).unwrap_or(&0), + *body.get(2).unwrap_or(&0), + *body.get(3).unwrap_or(&0), + ]); + let dev = u16::from(*body.get(4).unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + // Xorg `Xi/ungrdev.c::ProcXUngrabDevice` requires the + // request's time to be in `[grabTime, currentTime]` + // (CurrentTime = 0 passes both checks). Out-of-range + // timestamps silently skip the release — xts5 + // XUngrabDevice-2 asserts this. + let now = state.timestamp_now(); + let time_ok = time == 0 || (time >= state.xi1_last_grab_time && time <= now); + if time_ok + && state + .xi1_active_grabs + .get(&dev) + .is_some_and(|g| g.owner == client_id) + { + crate::core_loop::pointer_fanout::xi1_deactivate_device_grab(state, dev); + } + debug!( + "client {} #{} XI1 UngrabDevice device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// GrabDeviceKey (void): { grabWindow, event_count, modifiers, +// modifier_device, grabbed_device, key, this_device_mode, +// other_devices_mode, ownerEvents } + classes. (The XTS prose +// for XGrabDeviceKey-19/-20/-21 says "BadValue", but the test +// error traps accept only the XI extension BadDevice/BadClass +// codes — verified empirically; Xorg's dixLookupDevice agrees.) +pub(super) fn handle_xi1_grab_device_key( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if body.len() < 16 { + return Ok(RequestOutcome::Handled); + } + let mods = u16::from_le_bytes([body[6], body[7]]); + let mod_dev = u16::from(body[8]); + let dev = u16::from(body[9]); + let key = body[10]; + let this_mode = body[11]; + let other_mode = body[12]; + let owner_events = body[13]; + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(&state.xi_devices, mod_dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(mod_dev), + minor, + ); + } + if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(&state.xi_devices, mod_dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + // key: AnyKey (0) or within the advertised keycode range. + if key != 0 && key < XI1_KEY_MIN { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(key), + minor, + ); + } + if !xi1_modifiers_valid(mods) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mods), + minor, + ); + } + if this_mode > 1 || other_mode > 1 || owner_events > 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(this_mode.max(other_mode).max(owner_events)), + minor, + ); + } + let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let count = usize::from(u16::from_le_bytes([body[4], body[5]])); + for i in 0..count { + let off = 16 + i * 4; + if off + 4 > body.len() { + break; + } + let class = + u32::from_le_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + if !xi1_device_valid(&state.xi_devices, xi1_event_class_device(class)) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_CLASS, + class, + minor, + ); + } + } + // Conflicting grab by another client → BadAccess (XTS + // XGrabDeviceKey-16). + if state.xi1_passive_grabs.iter().any(|g| { + g.is_key + && g.owner != client_id + && g.deviceid == dev + && g.grab_window == ResourceId(win) + && (g.detail == key || g.detail == 0 || key == 0) + && (g.modifiers == mods || g.modifiers == 0x8000 || mods == 0x8000) + }) { + return xi1_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, minor); + } + state.xi1_passive_grabs.retain(|g| { + !(g.is_key + && g.owner == client_id + && g.deviceid == dev + && g.grab_window == ResourceId(win) + && g.detail == key + && g.modifiers == mods) + }); + state.xi1_passive_grabs.push(crate::server::Xi1PassiveGrab { + owner: client_id, + deviceid: dev, + grab_window: ResourceId(win), + detail: key, + modifiers: mods, + owner_events: owner_events != 0, + this_mode, + other_mode, + is_key: true, + }); + debug!( + "client {} #{} XI1 GrabDeviceKey device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// UngrabDeviceKey (void): { grabWindow, modifiers, +// modifier_device, key, grabbed_device }. +pub(super) fn handle_xi1_ungrab_device_key( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if body.len() < 9 { + return Ok(RequestOutcome::Handled); + } + let mods = u16::from_le_bytes([body[4], body[5]]); + let mod_dev = u16::from(body[6]); + let key = body[7]; + let dev = u16::from(body[8]); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(&state.xi_devices, mod_dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(mod_dev), + minor, + ); + } + if !xi1_device_has_keys(&state.xi_devices, dev) + || (mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(&state.xi_devices, mod_dev)) + { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + if key != 0 && key < XI1_KEY_MIN { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(key), + minor, + ); + } + if !xi1_modifiers_valid(mods) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mods), + minor, + ); + } + let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + state.xi1_passive_grabs.retain(|g| { + !(g.is_key + && g.owner == client_id + && g.deviceid == dev + && g.grab_window == ResourceId(win) + && (key == 0 || g.detail == key) + && (mods == 0x8000 || g.modifiers == mods)) + }); + debug!( + "client {} #{} XI1 UngrabDeviceKey device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// GrabDeviceButton (void): { grabWindow, grabbed_device, +// modifier_device, event_count, modifiers, this_device_mode, +// other_devices_mode, button, ownerEvents } + classes. +pub(super) fn handle_xi1_grab_device_button( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if body.len() < 16 { + return Ok(RequestOutcome::Handled); + } + let dev = u16::from(body[4]); + let mod_dev = u16::from(body[5]); + let mods = u16::from_le_bytes([body[8], body[9]]); + let this_mode = body[10]; + let other_mode = body[11]; + let owner_events = body[13]; + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(&state.xi_devices, mod_dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(mod_dev), + minor, + ); + } + if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(&state.xi_devices, mod_dev) { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + if !xi1_modifiers_valid(mods) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mods), + minor, + ); + } + if this_mode > 1 || other_mode > 1 || owner_events > 1 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(this_mode.max(other_mode).max(owner_events)), + minor, + ); + } + let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let button = body[12]; + // Validate the trailing XEventClass array (Xorg + // `Xi/grabdevb.c::ProcXGrabDeviceButton` → + // `CreateMaskFromList` → `BadClass`). Each class's high + // byte names a device id; any unknown deviceid is + // BadClass, including the `0xFFFFFFFF` sentinel xts5 + // GrabDeviceButton-21 builds. event_count lives at + // body[6..8] per `xGrabDeviceButtonReq`. + let event_count = usize::from(u16::from_le_bytes([body[6], body[7]])); + for i in 0..event_count { + let off = 16 + i * 4; + let Some(slice) = body.get(off..off + 4) else { + break; + }; + let class = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]); + if !xi1_device_valid(&state.xi_devices, xi1_event_class_device(class)) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_CLASS, + class, + minor, + ); + } + } + if state.xi1_passive_grabs.iter().any(|g| { + !g.is_key + && g.owner != client_id + && g.deviceid == dev + && g.grab_window == ResourceId(win) + && (g.detail == button || g.detail == 0 || button == 0) + && (g.modifiers == mods || g.modifiers == 0x8000 || mods == 0x8000) + }) { + return xi1_error(state, client_id, sequence, x11::error::BAD_ACCESS, 0, minor); + } + state.xi1_passive_grabs.retain(|g| { + !(!g.is_key + && g.owner == client_id + && g.deviceid == dev + && g.grab_window == ResourceId(win) + && g.detail == button + && g.modifiers == mods) + }); + state.xi1_passive_grabs.push(crate::server::Xi1PassiveGrab { + owner: client_id, + deviceid: dev, + grab_window: ResourceId(win), + detail: button, + modifiers: mods, + owner_events: owner_events != 0, + this_mode, + other_mode, + is_key: false, + }); + debug!( + "client {} #{} XI1 GrabDeviceButton device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// UngrabDeviceButton (void): { grabWindow, modifiers, +// modifier_device, button, grabbed_device }. +pub(super) fn handle_xi1_ungrab_device_button( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + if body.len() < 9 { + return Ok(RequestOutcome::Handled); + } + let mods = u16::from_le_bytes([body[4], body[5]]); + let mod_dev = u16::from(body[6]); + let dev = u16::from(body[8]); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_valid(&state.xi_devices, mod_dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(mod_dev), + minor, + ); + } + if !xi1_device_has_buttons(&state.xi_devices, dev) + || (mod_dev != XI1_USE_X_KEYBOARD && !xi1_device_has_keys(&state.xi_devices, mod_dev)) + { + return xi1_error(state, client_id, sequence, x11::error::BAD_MATCH, 0, minor); + } + if !xi1_modifiers_valid(mods) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mods), + minor, + ); + } + let win = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + if !xi1_window_exists(state, win) { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + win, + minor, + ); + } + let button = body[7]; + state.xi1_passive_grabs.retain(|g| { + !(!g.is_key + && g.owner == client_id + && g.deviceid == dev + && g.grab_window == ResourceId(win) + && (button == 0 || g.detail == button) + && (mods == 0x8000 || g.modifiers == mods)) + }); + debug!( + "client {} #{} XI1 UngrabDeviceButton device={dev}", + client_id.0, sequence.0 + ); + } + xi_write_reply(state, client_id, Vec::new()) +} + +// AllowDeviceEvents (void): { time, mode, deviceid }. Modes: +// AsyncThisDevice(0)..SyncAll(5). +pub(super) fn handle_xi1_allow_device_events( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + minor: u8, +) -> io::Result { + { + let mode = *body.get(4).unwrap_or(&0); + let dev = u16::from(*body.get(5).unwrap_or(&0)); + if !xi1_device_valid(&state.xi_devices, dev) { + return xi1_error( + state, + client_id, + sequence, + XI1_ERROR_BAD_DEVICE, + u32::from(dev), + minor, + ); + } + if mode > 5 { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(mode), + minor, + ); + } + // Port of Xorg `AllowSome` (dix/events.c:1823-1936) over + // the two-device model. Mode → newState mapping per + // Xi/allowev.c: AsyncThisDevice(0)→THAWED, + // SyncThisDevice(1)→FREEZE_NEXT_EVENT, + // ReplayThisDevice(2)→NOT_GRABBED, + // AsyncOtherDevices(3)→THAW_OTHERS, + // AsyncAll(4)→THAWED_BOTH, SyncAll(5)→FREEZE_BOTH_NEXT_EVENT. + use crate::{ + core_loop::pointer_fanout::{ + xi1_compute_freezes, xi1_deactivate_device_grab, xi1_device_grab_owner, + xi1_other_input_device, xi1_route_device_event, + }, + server::Xi1SyncState, + }; + let time = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + let other_dev = xi1_other_input_device(state, dev); + let sync_state = |state: &ServerState, d: u16| { + state + .xi1_frozen + .get(&d) + .map_or(Xi1SyncState::Thawed, |f| f.state) + }; + let sync_other = + |state: &ServerState, d: u16| state.xi1_frozen.get(&d).and_then(|f| f.other); + // thisGrabbed / otherGrabbed / thisSynced / othersFrozen + // (dix/events.c:1830-1851). `sync.other` stores the owning + // client, and deactivation clears it, so `== client` means + // "held on behalf of a live grab of this client". + let this_grabbed = xi1_device_grab_owner(state, dev) == Some(client_id); + let other_grabbed = + other_dev.is_some_and(|other| xi1_device_grab_owner(state, other) == Some(client_id)); + let this_synced = sync_other(state, dev) == Some(client_id) && other_grabbed; + let others_frozen = other_dev.is_some_and(|other| { + other_grabbed && sync_state(state, other) >= Xi1SyncState::FrozenNoEvent + }); + let this_frozen_by_grab = + this_grabbed && sync_state(state, dev) >= Xi1SyncState::FrozenNoEvent; + debug!( + "client {} #{} XI1 AllowDeviceEvents device={dev} mode={mode} \ + this_grabbed={this_grabbed} this_synced={this_synced} \ + others_frozen={others_frozen}", + client_id.0, sequence.0, + ); + // Gate 1: only act when this device is frozen by the + // client (directly or on another grab's behalf). + if !(this_frozen_by_grab || this_synced) { + return Ok(RequestOutcome::Handled); + } + // Gate 2: time validation — later than now or earlier than + // the client's last grab time → no effect. + let now = state + .timestamp_now() + .max(state.xi1_last_input_time) + .max(state.xi1_last_grab_time); + if time != 0 + && (crate::core_loop::xi1_focus::time_after(time, now) + || crate::core_loop::xi1_focus::time_after(state.xi1_last_grab_time, time)) + { + return Ok(RequestOutcome::Handled); + } + match mode { + // AsyncThisDevice → THAWED. + 0 => { + if this_grabbed && let Some(f) = state.xi1_frozen.get_mut(&dev) { + f.state = Xi1SyncState::Thawed; + } + if this_synced && let Some(f) = state.xi1_frozen.get_mut(&dev) { + f.other = None; + } + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); + } + // SyncThisDevice → FREEZE_NEXT_EVENT. + 1 => { + if this_grabbed { + state.xi1_frozen.entry(dev).or_default().state = Xi1SyncState::FreezeNextEvent; + if this_synced && let Some(f) = state.xi1_frozen.get_mut(&dev) { + f.other = None; + } + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); + } + } + // ReplayThisDevice → NOT_GRABBED: only for a grab + // frozen WITH a stored event; release the grab and + // reprocess that event as if the grab never took it + // (passive grabs get a fresh look at it). + 2 => { + if this_grabbed && sync_state(state, dev) == Xi1SyncState::FrozenWithEvent { + if this_synced && let Some(f) = state.xi1_frozen.get_mut(&dev) { + f.other = None; + } + let stored = state.xi1_frozen.get_mut(&dev).and_then(|f| f.stored.take()); + // Reprocessing masks out passive grabs at or + // above the released grab's window (Xorg + // syncEvents.replayWin → CheckDeviceGrabs). + let replay_floor = state.xi1_active_grabs.get(&dev).map(|g| g.grab_window); + if state.xi1_active_grabs.contains_key(&dev) { + xi1_deactivate_device_grab(state, dev); + } else if state.active_pointer_grab.is_some_and(|grab| grab.passive) { + // Xorg NOT_GRABBED → DeactivateGrab before the + // replay, passive flavor (mirrors + // apply_allow_events' passive NOT_GRABBED + // deactivation). + deactivate_passive_pointer_grab_crossings(state); + } else if state + .active_pointer_grab + .is_some_and(|g| g.owner == client_id) + { + // Explicit (or implicit) core grab: full + // deactivation (mirrors apply_allow_events' + // deactivate_core_pointer_grab call). + deactivate_core_pointer_grab(state, backend, client_id); + } + // Thaw dev after any deactivation. Arm A already + // thaws internally; re-thawing an already-thawed + // device is a no-op, and the no-core-grab case + // (previous behavior) simply thaws here. + if let Some(f) = state.xi1_frozen.get_mut(&dev) { + f.state = Xi1SyncState::Thawed; + } + if let Some(stored) = stored { + match stored { + crate::server::QueuedInputEvent::Xi1Routed(mut q) => { + q.replay_floor = replay_floor; + let _ = xi1_route_device_event(state, q, true); + } + crate::server::QueuedInputEvent::HostPointer(event) => { + let xid_map = backend.xid_map().clone(); + let _ = replay_frozen_pointer_event_to_state( + state, backend, &xid_map, event, + ); + } + crate::server::QueuedInputEvent::HostKey(event) => { + let _ = replay_frozen_key_to_focus(state, event); + } + crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + ) => { + let _ = crate::core_loop::key_fanout::replay_frozen_key_to_focus_after_transition( + state, + event, + master_transition_accepted, + ); + } + // Only a device event activates a grab, so + // the stored slot never holds a raw event; + // processing one is plain master delivery. + crate::server::QueuedInputEvent::RawKey(event) => { + let _ = crate::core_loop::key_fanout::deliver_raw_key_master( + state, event, + ); + } + } + } + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); + } + } + // AsyncOtherDevices → THAW_OTHERS: thaw every OTHER + // device held by this client (this device untouched). + 3 => { + if others_frozen && let Some(other) = other_dev { + if xi1_device_grab_owner(state, other) == Some(client_id) + && let Some(f) = state.xi1_frozen.get_mut(&other) + { + f.state = Xi1SyncState::Thawed; + } + if sync_other(state, other) == Some(client_id) + && let Some(f) = state.xi1_frozen.get_mut(&other) + { + f.other = None; + } + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); + } + } + // AsyncAll → THAWED_BOTH / SyncAll → FREEZE_BOTH_NEXT_EVENT: + // both REQUIRE the other devices to be frozen by the + // client (XTS XAllowDeviceEvents-16/-18); they act on + // every device the client grabbed or held. + 4 | 5 => { + if others_frozen { + let new_state = if mode == 4 { + Xi1SyncState::Thawed + } else { + Xi1SyncState::FreezeBothNextEvent + }; + for d in std::iter::once(dev).chain(other_dev) { + if xi1_device_grab_owner(state, d) == Some(client_id) { + state.xi1_frozen.entry(d).or_default().state = new_state; + } + if sync_other(state, d) == Some(client_id) + && let Some(f) = state.xi1_frozen.get_mut(&d) + { + f.other = None; + } + } + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); + } + } + _ => unreachable!("mode validated above"), + } + } + xi_write_reply(state, client_id, Vec::new()) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/props.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/props.rs new file mode 100644 index 000000000..a60ebc973 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/props.rs @@ -0,0 +1,666 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{ + RequestOutcome, XI2_FIRST_ERROR, XI2_MAJOR_OPCODE, emit_x11_error_with_minor, + props::{ + PropertyChangeOutcome, canonicalize_xi_property_data, dispatch_change_property, + emit_property_change, emit_property_dispatch_error, is_xtest_marker_property, + }, + xi::dispatch::xi_write_reply, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{AtomId, ClientByteOrder, ClientId, SequenceNumber}, +}; + +pub(super) fn handle_xi_list_properties( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIListProperties (xXIListPropertiesReq, XI2proto.h:742-749). + // body[0..2] = deviceid, body[2..4] = pad. + if body.len() < 2 { + return Ok(RequestOutcome::Handled); + } + let deviceid = u16::from_le_bytes([body[0], body[1]]); + debug!( + "client {} #{} XIListProperties deviceid={}", + client_id.0, sequence.0, deviceid + ); + let Some(device) = crate::xinput::find_device(&state.xi_devices, deviceid) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 56, + XI2_MAJOR_OPCODE, + ); + }; + buf.extend_from_slice(&crate::xinput::encode_list_properties_reply( + byte_order, sequence, device, + )); + } + xi_write_reply(state, client_id, buf) +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_change_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + // XIChangeProperty (xXIChangePropertyReq, XI2proto.h:769-780). + // Header struct: deviceid(2), mode(1), format(1), property(4), + // type(4), num_items(4); after stripping the 4-byte generic + // header `body` begins at deviceid: + // body[0..2] deviceid, body[2] mode, body[3] format, + // body[4..8] property, body[8..12] type, + // body[12..16] num_items, body[16..] value bytes. + if body.len() < 16 { + return Ok(RequestOutcome::Handled); + } + let deviceid = u16::from_le_bytes([body[0], body[1]]); + let mode = body[2]; + let format = body[3]; + let property = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let type_atom = AtomId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let num_items = u32::from_le_bytes([body[12], body[13], body[14], body[15]]) as usize; + debug!( + "client {} #{} XIChangeProperty deviceid={} mode={} format={} property={} type={} num_items={}", + client_id.0, sequence.0, deviceid, mode, format, property.0, type_atom.0, num_items + ); + // Device lookup FIRST (xserver ProcXIChangeProperty, + // xiproperty.c:1137-1141, does dixLookupDevice before the + // format/mode checks), so an unknown device yields BadDevice + // even when the format is also invalid. + if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 57, + XI2_MAJOR_OPCODE, + ); + } + // Validate mode (xiproperty.c check_change_property:325-329). + if mode != crate::xinput::XI_PROP_MODE_REPLACE + && mode != crate::xinput::XI_PROP_MODE_PREPEND + && mode != crate::xinput::XI_PROP_MODE_APPEND + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + u32::from(mode), + 57, + XI2_MAJOR_OPCODE, + ); + } + // Format must be 8/16/32 before we compute the value length. + if format != 8 && format != 16 && format != 32 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + u32::from(format), + 57, + XI2_MAJOR_OPCODE, + ); + } + let value_len = num_items.saturating_mul(usize::from(format / 8)); + let Some(data) = body.get(16..16 + value_len) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 16, // BadLength + 0, + 57, + XI2_MAJOR_OPCODE, + ); + }; + let data = canonicalize_xi_property_data(byte_order, format, data); + // T3 spec §D order is implemented by `dispatch_change_property`; + // both write arms (XI2 minor 57 + XI1 minor 37) share the same + // pipeline so T5/T6 only has to wire event emission in one place. + match dispatch_change_property( + state, backend, client_id, sequence, 57, deviceid, mode, format, property, type_atom, &data, + ) { + Ok(PropertyChangeOutcome::Changed(what)) => { + let _ = emit_property_change(state, deviceid, property, what); + return Ok(RequestOutcome::Handled); + } + Ok(PropertyChangeOutcome::Pending(request)) => { + return Ok(RequestOutcome::PendingXiConfig(request)); + } + Err(err) => { + return emit_property_dispatch_error(state, client_id, sequence, err, 57); + } + } +} + +#[allow(clippy::needless_return)] +pub(super) fn handle_xi_delete_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + // XIDeleteProperty (xXIDeletePropertyReq, XI2proto.h:785-793). + // body[0..2] deviceid, body[2..4] pad0, body[4..8] property. + if body.len() < 8 { + return Ok(RequestOutcome::Handled); + } + let deviceid = u16::from_le_bytes([body[0], body[1]]); + let property = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + debug!( + "client {} #{} XIDeleteProperty deviceid={} property={}", + client_id.0, sequence.0, deviceid, property.0 + ); + // T3: BadAtom guard (xserver ProcXIDeleteProperty, + // xiproperty.c). + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 5, // BadAtom + property.0, + 58, + XI2_MAJOR_OPCODE, + ); + } + if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 58, + XI2_MAJOR_OPCODE, + ); + } + if is_xtest_marker_property(state, deviceid, property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 10, // BadAccess: XTEST Device is protected by atom identity. + property.0, + 58, + XI2_MAJOR_OPCODE, + ); + } + if crate::xinput::find_device(&state.xi_devices, deviceid) + .and_then(|device| device.properties.get(&property)) + .is_some_and(|property| !property.deletable) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 10, // BadAccess: seeded driver properties are non-deletable. + property.0, + 58, + XI2_MAJOR_OPCODE, + ); + } + let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) + .expect("device existence verified above"); + if let Some(what) = crate::xinput::apply_delete_property(device, property) { + // Notify on a real removal only; a redundant delete of + // an absent property must stay silent — xiproperty.c + // does not call `send_property_event` in that case. + let _ = emit_property_change(state, deviceid, property, what); + } + return Ok(RequestOutcome::Handled); +} + +pub(super) fn handle_xi_get_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + // XIGetProperty (xXIGetPropertyReq, XI2proto.h:798-814). + // Struct: deviceid(2), delete(1), pad0(1), property(4), + // type(4), offset(4), len(4). After the 4-byte generic header + // `body` begins at deviceid: + // body[0..2] deviceid, body[2] delete, body[3] pad0, + // body[4..8] property, body[8..12] type, + // body[12..16] offset, body[16..20] len. + if body.len() < 20 { + return Ok(RequestOutcome::Handled); + } + let deviceid = u16::from_le_bytes([body[0], body[1]]); + let delete_raw = body[2]; + let property = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let req_type = AtomId(u32::from_le_bytes([body[8], body[9], body[10], body[11]])); + let offset = u32::from_le_bytes([body[12], body[13], body[14], body[15]]); + let len = u32::from_le_bytes([body[16], body[17], body[18], body[19]]); + debug!( + "client {} #{} XIGetProperty deviceid={} property={} type={} offset={} len={} delete={}", + client_id.0, sequence.0, deviceid, property.0, req_type.0, offset, len, delete_raw + ); + // T3: BadAtom guard before the device lookup so a bogus atom + // surfaces as BadAtom (xserver ProcXIGetProperty does it the + // same way via ValidAtom() before dixLookupDevice's payload + // path; the relative precedence vs. BadDevice never matters + // because clients always pair a valid atom with the deviceid + // they just learned from XIListProperties). + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 5, // BadAtom + property.0, + 59, + XI2_MAJOR_OPCODE, + ); + } + // Device lookup first (xserver dixLookupDevice precedes + // get_property, so BadDevice outranks the BadValue below). + if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 59, + XI2_MAJOR_OPCODE, + ); + } + // `delete` must be exactly 0 or 1; xserver's get_property + // (xiproperty.c:252-255) rejects anything else with BadValue. + if delete_raw > 1 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + u32::from(delete_raw), + 59, + XI2_MAJOR_OPCODE, + ); + } + let delete = delete_raw != 0; + // Re-acquire mutably now that both validations passed. + let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) + .expect("device existence verified above"); + let send_deleted = match crate::xinput::encode_get_property_reply( + byte_order, sequence, device, property, req_type, offset, len, delete, + ) { + Ok(reply) => { + let returned = x11::read_u32(byte_order, &reply[4..8]); + let bytes_after = x11::read_u32(byte_order, &reply[12..16]); + buf.extend_from_slice(&reply); + delete && returned != 0 && bytes_after == 0 + } + Err(crate::xinput::XiPropError::BadValue) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + offset, + 59, + XI2_MAJOR_OPCODE, + ); + } + Err(_) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, + offset, + 59, + XI2_MAJOR_OPCODE, + ); + } + }; + if send_deleted { + let _ = + emit_property_change(state, deviceid, property, crate::xinput::PropWhat::Deleted); + } + } + xi_write_reply(state, client_id, buf) +} + +// XI 1.x ListDeviceProperties (minor 36; xListDevicePropertiesReq, +// XIproto.h:1433-1440). Body after the 4-byte generic header: +// body[0] deviceid (CARD8), body[1] pad0, body[2..4] pad1. +// MATE's settings daemon enumerates a touchpad's libinput +// properties through this XI1 path (not the XI2 XIListProperties), +// so a real reply backed by `xi_devices` is required. +pub(super) fn handle_xi1_list_device_properties( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + if body.is_empty() { + return Ok(RequestOutcome::Handled); + } + let deviceid = u16::from(body[0]); + debug!( + "client {} #{} XListDeviceProperties deviceid={}", + client_id.0, sequence.0, deviceid + ); + let Some(device) = crate::xinput::find_device(&state.xi_devices, deviceid) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 36, + XI2_MAJOR_OPCODE, + ); + }; + buf.extend_from_slice(&crate::xinput::encode_xi1_list_properties_reply( + byte_order, sequence, device, + )); + } + xi_write_reply(state, client_id, buf) +} + +// XI 1.x ChangeDeviceProperty (minor 37; xChangeDevicePropertyReq, +// XIproto.h:1462-1473). Body after the 4-byte generic header: +// body[0..4] property (Atom), body[4..8] type (Atom), +// body[8] deviceid (CARD8), body[9] format, body[10] mode, +// body[11] pad, body[12..16] nUnits (CARD32), body[16..] value. +#[allow(clippy::needless_return)] +pub(super) fn handle_xi1_change_device_property( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + if body.len() < 16 { + return Ok(RequestOutcome::Handled); + } + let property = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let type_atom = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let deviceid = u16::from(body[8]); + let format = body[9]; + let mode = body[10]; + let num_items = u32::from_le_bytes([body[12], body[13], body[14], body[15]]) as usize; + debug!( + "client {} #{} XChangeDeviceProperty deviceid={} mode={} format={} property={} type={} num_items={}", + client_id.0, sequence.0, deviceid, mode, format, property.0, type_atom.0, num_items + ); + // Device lookup first, mirroring the XI2 path (xserver does + // dixLookupDevice before the mode/format checks). + if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 37, + XI2_MAJOR_OPCODE, + ); + } + if mode != crate::xinput::XI_PROP_MODE_REPLACE + && mode != crate::xinput::XI_PROP_MODE_PREPEND + && mode != crate::xinput::XI_PROP_MODE_APPEND + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + u32::from(mode), + 37, + XI2_MAJOR_OPCODE, + ); + } + if format != 8 && format != 16 && format != 32 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + u32::from(format), + 37, + XI2_MAJOR_OPCODE, + ); + } + let value_len = num_items.saturating_mul(usize::from(format / 8)); + let Some(data) = body.get(16..16 + value_len) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 16, // BadLength + 0, + 37, + XI2_MAJOR_OPCODE, + ); + }; + let data = canonicalize_xi_property_data(byte_order, format, data); + // The T3 spec §D pipeline is shared with the XI2 arm + // (minor 57) via `dispatch_change_property`; the same + // `emit_property_change` helper fans out + // `XI_PropertyEvent` here too — xserver's + // `send_property_event` fires from both XI1 and XI2 paths. + match dispatch_change_property( + state, backend, client_id, sequence, 37, deviceid, mode, format, property, type_atom, &data, + ) { + Ok(PropertyChangeOutcome::Changed(what)) => { + let _ = emit_property_change(state, deviceid, property, what); + return Ok(RequestOutcome::Handled); + } + Ok(PropertyChangeOutcome::Pending(request)) => { + return Ok(RequestOutcome::PendingXiConfig(request)); + } + Err(err) => { + return emit_property_dispatch_error(state, client_id, sequence, err, 37); + } + } +} + +// XI 1.x DeleteDeviceProperty (minor 38; xDeleteDevicePropertyReq, +// XIproto.h:1481-1489). Body after the 4-byte generic header: +// body[0..4] property (Atom), body[4] deviceid (CARD8), +// body[5] pad0, body[6..8] pad1. +#[allow(clippy::needless_return)] +pub(super) fn handle_xi1_delete_device_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + if body.len() < 5 { + return Ok(RequestOutcome::Handled); + } + let property = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let deviceid = u16::from(body[4]); + debug!( + "client {} #{} XDeleteDeviceProperty deviceid={} property={}", + client_id.0, sequence.0, deviceid, property.0 + ); + // T3: BadAtom guard (mirror of XI2 minor 58). + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 5, // BadAtom + property.0, + 38, + XI2_MAJOR_OPCODE, + ); + } + if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 38, + XI2_MAJOR_OPCODE, + ); + } + if is_xtest_marker_property(state, deviceid, property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 10, // BadAccess: XTEST Device is protected by atom identity. + property.0, + 38, + XI2_MAJOR_OPCODE, + ); + } + if crate::xinput::find_device(&state.xi_devices, deviceid) + .and_then(|device| device.properties.get(&property)) + .is_some_and(|property| !property.deletable) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 10, // BadAccess: seeded driver properties are non-deletable. + property.0, + 38, + XI2_MAJOR_OPCODE, + ); + } + let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) + .expect("device existence verified above"); + if let Some(what) = crate::xinput::apply_delete_property(device, property) { + // Same XI2 fan-out the minor-58 arm runs. + let _ = emit_property_change(state, deviceid, property, what); + } + return Ok(RequestOutcome::Handled); +} + +// XI 1.x GetDeviceProperty (minor 39; xGetDevicePropertyReq, +// XIproto.h:1497-1512). Body after the 4-byte generic header: +// body[0..4] property (Atom), body[4..8] type (Atom), +// body[8..12] longOffset (CARD32), body[12..16] longLength +// (CARD32), body[16] deviceid (CARD8), body[17] delete (BOOL), +// body[18..20] pad. +// This is the request MATE's settings daemon uses to read +// "libinput Tapping Enabled" etc. The reply echoes the requested +// deviceid (byte 21), unlike the XI2 reply (Task brief: the old +// zero-stub returned device=0 and MATE rejected the touchpad). +pub(super) fn handle_xi1_get_device_property( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], + byte_order: ClientByteOrder, +) -> io::Result { + let mut buf: Vec = Vec::with_capacity(64); + { + if body.len() < 18 { + return Ok(RequestOutcome::Handled); + } + let property = AtomId(u32::from_le_bytes([body[0], body[1], body[2], body[3]])); + let req_type = AtomId(u32::from_le_bytes([body[4], body[5], body[6], body[7]])); + let offset = u32::from_le_bytes([body[8], body[9], body[10], body[11]]); + let len = u32::from_le_bytes([body[12], body[13], body[14], body[15]]); + let deviceid = u16::from(body[16]); + let delete_raw = body[17]; + debug!( + "client {} #{} XGetDeviceProperty deviceid={} property={} type={} offset={} len={} delete={}", + client_id.0, sequence.0, deviceid, property.0, req_type.0, offset, len, delete_raw + ); + // T3: BadAtom guard (mirror of XI2 minor 59). + if !state.atoms.exists(property) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 5, // BadAtom + property.0, + 39, + XI2_MAJOR_OPCODE, + ); + } + if crate::xinput::find_device(&state.xi_devices, deviceid).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, // XI_BadDevice + u32::from(deviceid), + 39, + XI2_MAJOR_OPCODE, + ); + } + if delete_raw > 1 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + u32::from(delete_raw), + 39, + XI2_MAJOR_OPCODE, + ); + } + let delete = delete_raw != 0; + let device = crate::xinput::find_device_mut(&mut state.xi_devices, deviceid) + .expect("device existence verified above"); + let send_deleted = match crate::xinput::encode_xi1_get_property_reply( + byte_order, sequence, device, property, req_type, offset, len, delete, + ) { + Ok(reply) => { + let bytes_after = x11::read_u32(byte_order, &reply[12..16]); + buf.extend_from_slice(&reply); + delete && bytes_after == 0 + } + Err(_) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + 2, // BadValue + offset, + 39, + XI2_MAJOR_OPCODE, + ); + } + }; + if send_deleted { + let _ = + emit_property_change(state, deviceid, property, crate::xinput::PropWhat::Deleted); + } + } + xi_write_reply(state, client_id, buf) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/mod.rs b/crates/yserver-core/src/core_loop/process_request/xi/mod.rs new file mode 100644 index 000000000..39db6e762 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xi/mod.rs @@ -0,0 +1,607 @@ +mod dispatch; + +use crate::{ + backend::{Backend, OriginContext}, + core_loop::process_request::{ + RequestOutcome, XI2_MAJOR_OPCODE, emit_x11_error_with_minor, + focus_pointer::{apply_core_input_focus, core_focus_window_error}, + write_to_client, + }, + resources::ROOT_WINDOW, + server::ServerState, + xinput::XI2_DEVICE_CHANGED_MASK, +}; +pub(super) use dispatch::*; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, ResourceId, SequenceNumber}, +}; + +// ─── XI 1.x request validation (XTS XI scenario, the "Got Success, +// Expecting " family) ───────────────────────────────────────── +// +// XI extension error codes are offsets from the extension's first_error +// (157): BadDevice=+0, BadEvent=+1, BadMode=+2, DeviceBusy=+3, +// BadClass=+4 (XIproto.h). Error packets carry major=137 + the +// request's minor. +pub(super) const XI1_ERROR_BAD_DEVICE: u8 = crate::nested::XI2_FIRST_ERROR; +const XI1_ERROR_BAD_MODE: u8 = crate::nested::XI2_FIRST_ERROR + 2; +const XI1_ERROR_BAD_CLASS: u8 = crate::nested::XI2_FIRST_ERROR + 4; + +/// Keycode range advertised by ListInputDevices / XIQueryDevice. +const XI1_KEY_MIN: u8 = 8; +const XI1_KEY_MAX: u8 = 255; +/// XIproto `UseXKeyboard` — the "default modifier device" sentinel +/// accepted wherever a modifier_device byte is taken. +const XI1_USE_X_KEYBOARD: u16 = 255; + +/// An XI1 device is valid exactly while its ID is present in the shared +/// registry snapshot used by XI1 and XI2 enumeration. +fn xi1_device_valid(devices: &crate::xinput::XiRegistry, id: u16) -> bool { + devices.device(id).is_some() +} + +/// XI1 count fields and bounds come from the same current classes that +/// XIQueryDevice serializes, including copied master classes. +pub(super) fn xi1_device_button_count(devices: &crate::xinput::XiRegistry, id: u16) -> Option { + let device = devices.device(id)?; + let count = device.class_shape.button_count(); + (count != 0).then_some(count) +} + +fn xi1_device_valuator_count(devices: &crate::xinput::XiRegistry, id: u16) -> Option { + let device = devices.device(id)?; + let count = device.class_shape.valuator_count(); + (count != 0).then_some(count) +} + +/// Registry role decides whether a device ID names one of the two masters. +fn xi1_device_is_master(devices: &crate::xinput::XiRegistry, id: u16) -> bool { + matches!( + devices.role(id), + Some( + crate::xinput::XiDeviceRole::MasterPointer + | crate::xinput::XiDeviceRole::MasterKeyboard + ) + ) +} + +/// `XI2LASTEVENT` for XI 2.4 (`XI_GestureSwipeEnd`, XI2.h). +const XI2_LAST_EVENT: u32 = 32; + +/// Xorg `XICheckInvalidMaskBits` (Xi/xiselectev.c): the lowest set bit +/// above [`XI2_LAST_EVENT`] in an XI2 event mask (a bit array, bit n in +/// byte n/8), if any. +fn xi2_first_invalid_mask_bit(mask: &[u8]) -> Option { + mask.iter().enumerate().find_map(|(i, &byte)| { + let first_bit = u32::try_from(i * 8).ok()?; + (0..8u32) + .map(|b| first_bit + b) + .find(|&bit| bit > XI2_LAST_EVENT && byte & (1 << (bit - first_bit)) != 0) + }) +} + +/// Keyboard masters, XTEST keyboards, and registered keyboard facets carry +/// a KeyClass. +pub(crate) fn xi1_device_has_keys(devices: &crate::xinput::XiRegistry, id: u16) -> bool { + matches!( + devices.role(id), + Some( + crate::xinput::XiDeviceRole::MasterKeyboard + | crate::xinput::XiDeviceRole::SlaveKeyboard + ) + ) +} + +/// Pointer masters, XTEST pointer, and registered pointer facets carry +/// Button and Valuator classes. +pub(crate) fn xi1_device_has_buttons(devices: &crate::xinput::XiRegistry, id: u16) -> bool { + matches!( + devices.role(id), + Some( + crate::xinput::XiDeviceRole::MasterPointer | crate::xinput::XiDeviceRole::SlavePointer + ) + ) +} + +pub(crate) fn xi1_device_has_valuators(devices: &crate::xinput::XiRegistry, id: u16) -> bool { + xi1_device_has_buttons(devices, id) +} + +/// Core grab-modifier validity: any combination of the 8 modifier +/// masks, or AnyModifier (0x8000) alone. +fn xi1_modifiers_valid(modifiers: u16) -> bool { + modifiers == 0x8000 || modifiers & !0x00ff == 0 +} + +/// XI 1.x event classes pack the device id in the upper byte +/// (`deviceid << 8 | event_offset`). +fn xi1_event_class_device(class: u32) -> u16 { + u16::try_from((class >> 8) & 0xff).unwrap_or(u16::MAX) +} + +/// Standard 32-byte all-zero XI1 reply (status/count fields read as +/// Success / empty in every minor's reply layout). +fn xi1_zero_reply( + byte_order: yserver_protocol::x11::ClientByteOrder, + sequence: SequenceNumber, +) -> Vec { + let mut reply = x11::fixed_reply(byte_order, sequence, 0, 0); + reply.extend_from_slice(&[0u8; 24]); + reply +} + +/// Emit an X error for an XI 1.x request: major = 137, minor = the +/// request's minor opcode. +pub(super) fn xi1_error( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + code: u8, + value: u32, + minor: u8, +) -> io::Result { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + XI2_MAJOR_OPCODE, + ) +} + +fn xi1_window_exists(state: &ServerState, xid: u32) -> bool { + state.resources.window(ResourceId(xid)).is_some() +} + +/// Collect the set of XI1 clients receiving a `SendExtensionEvent` +/// dispatched to `dest_window`. Implements Xorg +/// `Xi/exevents.c::SendEvent` (xserver.git:2952-2965) selection + +/// propagation, with two simplifications from the canonical path: +/// +/// - per-window per-device do-not-propagate-mask is not yet modelled +/// (xts5 SendEvent 11/12 leave it empty), so the walk doesn't +/// trim classes as it ascends; +/// - `propagate` doesn't honour the `effectiveFocus` stop when +/// `dest_window` was resolved via `InputFocus` (the per-test +/// coverage there is XTS purposes 7-10, which all use +/// propagate=False). +/// +/// `mask_is_zero` reflects the `CreateMaskFromList` result: empty +/// when the only class in the list is `noextensioneventclass` +/// (`_noExtensionEvent = 9`). On a zero mask, delivery falls through +/// to the window's creator — Xorg's `DeliverToWindowOwner` short- +/// circuit on `filter == CantBeFiltered`. +fn xi1_send_extension_event_resolve_targets( + state: &ServerState, + dest_window: ResourceId, + request_classes: &[u32], + mask_is_zero: bool, + propagate: bool, +) -> std::collections::HashSet { + let mut current = dest_window; + // The active class set shrinks as the walk crosses windows whose + // do-not-propagate-list bans a class (Xorg + // `wOtherInputMasks(pWin)->dontPropagateMask[d->id]`). When the + // remaining set is empty, propagation stops without delivery — + // xts5 XSendExtensionEvent-8. + let mut active: std::collections::HashSet = request_classes.iter().copied().collect(); + for _ in 0..256 { + let mut targets: std::collections::HashSet = std::collections::HashSet::new(); + if mask_is_zero { + if let Some(owner) = state.resources.window_owner(current) { + targets.insert(owner); + } + } else { + for (cid, c) in &state.clients { + if let Some(set) = c.xi1_window_event_classes.get(¤t) + && active.iter().any(|cl| set.contains(cl)) + { + targets.insert(ClientId(*cid)); + } + } + } + if !targets.is_empty() || !propagate { + return targets; + } + // No selector at `current` — apply this window's + // do-not-propagate list to the active class set before walking + // up, then move to the parent. + if let Some(blocked) = state.xi1_window_dont_propagate.get(¤t) { + active.retain(|c| !blocked.contains(c)); + if active.is_empty() { + return std::collections::HashSet::new(); + } + } + match state.resources.parent_of(current) { + Some(parent) if parent != current => current = parent, + _ => return std::collections::HashSet::new(), + } + } + std::collections::HashSet::new() +} + +/// XISetFocus (XI 2.0 minor 49) — Xorg `ProcXISetFocus` +/// (Xi/xisetdevfocus.c): `SetInputFocus(dev, focus, RevertToParent, +/// time, followOK=TRUE)` on a device with a focus class, i.e. a keyboard. +/// Pointers and unknown ids are BadDevice (Xorg sets no errorValue). +/// +/// The master keyboard's focus is the core focus, so device 3 runs core +/// SetInputFocus. Slave keyboard facets keep their own focus +/// (`xi1_device_focus`, shared with XI1 SetDeviceFocus) and may follow +/// the keyboard. FollowKeyboard on the master keyboard itself would make +/// it follow itself: Xorg stores `FollowKeyboardWin` and then crashes +/// dereferencing it (Xvfb 21.1.24 segfaults at address 0x7), so yserver +/// answers BadValue instead. +fn handle_xi_set_focus( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + body: &[u8], +) -> io::Result { + use crate::core_loop::xi1_focus; + const MINOR: u8 = 49; + // Length is gated to at least 4 units above. + let focus = u32::from_le_bytes([body[0], body[1], body[2], body[3]]); + let req_time = u32::from_le_bytes([body[4], body[5], body[6], body[7]]); + let deviceid = u16::from_le_bytes([body[8], body[9]]); + let role = state.xi_devices.role(deviceid); + if !matches!( + role, + Some( + crate::xinput::XiDeviceRole::MasterKeyboard + | crate::xinput::XiDeviceRole::SlaveKeyboard + ) + ) { + return xi1_error(state, client_id, sequence, XI1_ERROR_BAD_DEVICE, 0, MINOR); + } + let revert_to = xi1_focus::REVERT_TO_PARENT; + if role == Some(crate::xinput::XiDeviceRole::MasterKeyboard) { + if focus == xi1_focus::FOCUS_FOLLOW_KEYBOARD { + return xi1_error( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + focus, + MINOR, + ); + } + if let Some((code, value)) = core_focus_window_error(state, ResourceId(focus)) { + return xi1_error(state, client_id, sequence, code, value, MINOR); + } + apply_core_input_focus( + state, + client_id, + sequence, + ResourceId(focus), + revert_to, + req_time, + ); + return Ok(RequestOutcome::Handled); + } + if focus != xi1_focus::FOCUS_FOLLOW_KEYBOARD + && let Some((code, value)) = core_focus_window_error(state, ResourceId(focus)) + { + return xi1_error(state, client_id, sequence, code, value, MINOR); + } + // Timestamp gate (dix/events.c:4920-4922), as XI1 SetDeviceFocus. + let now = state.timestamp_now(); + let time = if req_time == 0 { now } else { req_time }; + let prev = xi1_focus::device_focus(state, deviceid); + if xi1_focus::time_after(time, now) || xi1_focus::time_after(prev.time, time) { + debug!( + "client {} #{} XISetFocus device={deviceid} stale time {time} \ + (now={now} last={}) — ignored", + client_id.0, sequence.0, prev.time + ); + return Ok(RequestOutcome::Handled); + } + xi1_focus::set_device_focus(state, deviceid, focus, revert_to, time); + debug!( + "client {} #{} XISetFocus device={deviceid} focus=0x{focus:x}", + client_id.0, sequence.0 + ); + Ok(RequestOutcome::Handled) +} + +/// XIChangeHierarchy (XI 2.0 minor 43) — Xorg `ProcXIChangeHierarchy` +/// (Xi/xichangehierarchy.c) over yserver's fixed device set: masters 2/3 +/// (the virtual core pair) and one fixed slave each (4/5). +/// +/// The change list is walked exactly as Xorg walks it — same length +/// checks, unknown change types skipped, processing stops at the first +/// failing change — and every change gets the answer Xorg gives for the +/// same devices: +/// - RemoveMaster: return_mode must be Float/AttachToMaster (BadValue); +/// the virtual core pair can never be removed (BadDevice), and a slave +/// is not a master (BadDevice, errorValue = id). +/// - AttachSlave / DetachSlave: masters are BadDevice (errorValue = id); +/// yserver's slaves are fixed, which Xorg answers for its own fixed +/// slaves (the XTest devices, ids 4/5 on Xvfb) with BadDevice, +/// errorValue = id. +/// - AddMaster: Xorg creates a new pair; yserver can't add devices, so it +/// gives Xorg's answer when no device can be allocated (BadAlloc). +/// +/// Unknown device ids are BadDevice with errorValue 0 (dixLookupDevice +/// sets none). No change ever succeeds, so no HierarchyChanged event is +/// sent. The change records are opaque to the request swapper and are +/// read in the client's byte order (Xorg swaps only type/length/name_len +/// and reads the device ids unswapped — for a big-endian client on a +/// little-endian server that only changes the errorValue of the same +/// BadDevice error). +fn handle_xi_change_hierarchy( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + byte_order: yserver_protocol::x11::ClientByteOrder, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::ClientByteOrder; + const MINOR: u8 = 43; + const ADD_MASTER: u16 = 1; + const REMOVE_MASTER: u16 = 2; + const ATTACH_SLAVE: u16 = 3; + const DETACH_SLAVE: u16 = 4; + const ATTACH_TO_MASTER: u8 = 1; + const FLOATING: u8 = 2; + let rd16 = |o: usize| { + let b = [body[o], body[o + 1]]; + match byte_order { + ClientByteOrder::LittleEndian => u16::from_le_bytes(b), + ClientByteOrder::BigEndian => u16::from_be_bytes(b), + } + }; + let fail = |state: &mut ServerState, code: u8, value: u32| { + xi1_error(state, client_id, sequence, code, value, MINOR) + }; + // Length is gated to at least 2 units above: num_changes + pad. + let num_changes = body[0]; + let mut pos = 4usize; + for _ in 0..num_changes { + let len = body.len() - pos; + if len < 4 { + return fail(state, x11::error::BAD_LENGTH, 0); + } + let change_type = rd16(pos); + let change_bytes = usize::from(rd16(pos + 2)) * 4; + if len < change_bytes { + return fail(state, x11::error::BAD_LENGTH, 0); + } + // CHANGE_SIZE_MATCH: fixed-size records must state their own size. + let size_matches = |size: usize| len >= size && change_bytes == size; + match change_type { + ADD_MASTER => { + if len < 8 || usize::from(rd16(pos + 4)) > len - 8 { + return fail(state, x11::error::BAD_LENGTH, 0); + } + return fail(state, x11::error::BAD_ALLOC, 0); + } + REMOVE_MASTER => { + if !size_matches(12) { + return fail(state, x11::error::BAD_LENGTH, 0); + } + let return_mode = body[pos + 6]; + if return_mode != ATTACH_TO_MASTER && return_mode != FLOATING { + return fail(state, x11::error::BAD_VALUE, 0); + } + let deviceid = rd16(pos + 4); + // A slave is "not a master" (errorValue = id); the virtual + // core pair can't be removed and unknown ids don't exist + // (Xorg sets no errorValue for either). + let value = if xi1_device_valid(&state.xi_devices, deviceid) + && !xi1_device_is_master(&state.xi_devices, deviceid) + { + u32::from(deviceid) + } else { + 0 + }; + return fail(state, XI1_ERROR_BAD_DEVICE, value); + } + ATTACH_SLAVE | DETACH_SLAVE => { + if !size_matches(8) { + return fail(state, x11::error::BAD_LENGTH, 0); + } + let deviceid = rd16(pos + 4); + // Masters and the fixed slaves report their id; unknown + // ids report 0. + let value = if xi1_device_valid(&state.xi_devices, deviceid) { + u32::from(deviceid) + } else { + 0 + }; + return fail(state, XI1_ERROR_BAD_DEVICE, value); + } + _ => {} + } + pos += change_bytes; + } + debug!( + "client {} #{} XIChangeHierarchy: {num_changes} change(s), nothing to do", + client_id.0, sequence.0 + ); + Ok(RequestOutcome::Handled) +} + +/// Check the variable arrays that Xorg validates with `REQUEST_FIXED_SIZE` +/// or by walking XISelectEvents records. All typed count fields have been +/// swapped to little-endian by the reader before this production entry point. +fn xi2_request_has_complete_dynamic_tail(minor: u8, body: &[u8]) -> bool { + fn u16_at(body: &[u8], offset: usize) -> Option { + let bytes = body.get(offset..offset.checked_add(2)?)?; + Some(usize::from(u16::from_le_bytes([bytes[0], bytes[1]]))) + } + + fn words_fit(body: &[u8], start: usize, words: usize) -> Option { + let bytes = words.checked_mul(4)?; + let end = start.checked_add(bytes)?; + (end <= body.len()).then_some(end) + } + + match minor { + // SProcXISelectEvents checks each xXIEventMask header and mask_len + // region, returning BadLength before ProcXISelectEvents mutates masks. + 46 => { + let Some(num_masks) = u16_at(body, 4) else { + return false; + }; + let mut pos = 8usize; + for _ in 0..num_masks { + let Some(device_and_len_end) = pos.checked_add(4) else { + return false; + }; + if device_and_len_end > body.len() { + return false; + } + let Some(mask_words) = u16_at(body, pos + 2) else { + return false; + }; + let Some(mask_end) = words_fit(body, device_and_len_end, mask_words) else { + return false; + }; + pos = mask_end; + } + true + } + // ProcXIGrabDevice checks mask_len words after its 20-byte body + // prefix. Those words are byte masks and remain unswapped. + 51 => { + let Some(mask_len) = u16_at(body, 18) else { + return false; + }; + words_fit(body, 20, mask_len).is_some() + } + // SProcXIPassiveGrabDevice checks the mask and modifier spans together + // before its modifier CARD32 swap loop. + 54 => { + let (Some(num_modifiers), Some(mask_len)) = (u16_at(body, 18), u16_at(body, 20)) else { + return false; + }; + let Some(mask_end) = words_fit(body, 28, mask_len) else { + return false; + }; + words_fit(body, mask_end, num_modifiers).is_some() + } + // SProcXIPassiveUngrabDevice checks num_modifiers CARD32s after its + // 16-byte fixed body. + 55 => { + let Some(num_modifiers) = u16_at(body, 10) else { + return false; + }; + words_fit(body, 16, num_modifiers).is_some() + } + _ => true, + } +} + +/// Record a client's XI version the way Xorg `ProcXIQueryVersion` stores +/// it in `XIClientRec`: the first query sets it; a later query raises it +/// only when both the stored and the new version are 2.2 or newer +/// ("Peter promises to never again break backward compatibility"). +/// Otherwise the stored version stays — Xorg then answers a lower request +/// with BadValue and a higher one with the stored version; yserver keeps +/// answering with the negotiated version, so only the stored value (what +/// `FilterRawEvents` reads) follows Xorg here. +fn record_xi2_client_version(state: &mut ServerState, client_id: ClientId, version: (u16, u16)) { + match state.xi2_client_versions.get(&client_id) { + None => { + state.xi2_client_versions.insert(client_id, version); + } + Some(&stored) => { + if version >= (2, 2) && stored >= (2, 2) && version > stored { + state.xi2_client_versions.insert(client_id, version); + } + } + } +} + +fn emit_xi2_device_changed_bootstrap( + state: &mut ServerState, + _backend: &mut dyn Backend, + _origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + major_opcode: u8, +) -> io::Result<()> { + let time = state.timestamp_now(); + let Some((byte_order, selected_masters)) = state.clients.get(&client_id.0).map(|client| { + ( + client.byte_order, + [ + crate::xinput::DEVICEID_MASTER_POINTER, + crate::xinput::DEVICEID_MASTER_KEYBOARD, + ] + .into_iter() + .filter(|master_id| { + client + .xi2_masks + .iter() + .any(|(&(window, device_id), &mask)| { + window == ROOT_WINDOW + && (matches!(device_id, 0 | 1) || device_id == *master_id) + && (mask & u64::from(XI2_DEVICE_CHANGED_MASK)) != 0 + }) + }) + .collect::>(), + ) + }) else { + return Ok(()); + }; + let mut buf = Vec::new(); + for master_id in selected_masters { + // Xorg serializes the source ID retained by each copied class + // (`Xi/xiquerydevice.c:278,326`); it is independent of `lastSlave`, + // which may already have been cleared by disable/removal. + // + // Xorg sends no DeviceChanged on XISelectEvents at all + // (`Xi/xiselectev.c`): its only `XISlaveSwitch` is the one + // `dix/getevents.c:699` sends when an event comes from another + // slave than the last, naming that slave. This bootstrap stands for + // that event, so it goes only once a slave has driven the master + // and names that slave. A master that still carries its own + // classes has had no switch to report, and a SlaveSwitch naming + // the master itself is one no X server sends: Wine's winex11 opens + // a SlaveSwitch's source with XOpenDevice to read its button map, + // which is BadDevice for a master, and Xlib's default handler then + // ends the process. + let Some(sourceid) = state + .xi_devices + .device(master_id) + .map(|device| device.class_sourceid) + .filter(|&sourceid| sourceid != master_id) + else { + continue; + }; + let Some((classes, num_classes)) = + crate::xinput::hotplug::device_changed_class_block(state, master_id, byte_order) + else { + continue; + }; + let mut event_buf = Vec::new(); + x11::encode_xi2_device_changed_event( + &mut event_buf, + byte_order, + sequence, + major_opcode, + master_id, + time, + num_classes, + sourceid, + crate::xinput::hotplug::XiDeviceChangeReason::SlaveSwitch as u8, + &classes, + ); + buf.extend_from_slice(&event_buf); + } + if buf.is_empty() { + return Ok(()); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(()); + }; + let _outcome = write_to_client(client, client_id, &buf); + Ok(()) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xkb.rs b/crates/yserver-core/src/core_loop/process_request/xkb.rs new file mode 100644 index 000000000..faf0d5344 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xkb.rs @@ -0,0 +1,441 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + fanout::fanout_event_to_clients, + process_request::{ + RequestOutcome, X_KB_GET_CONTROLS, X_KB_SELECT_EVENTS, X_KB_SET_COMPAT_MAP, + X_KB_SET_CONTROLS, X_KB_SET_GEOMETRY, X_KB_SET_INDICATOR_MAP, X_KB_SET_MAP, + X_KB_SET_NAMES, X_KB_USE_EXTENSION, XKB_LAST_REQUEST, emit_x11_error_with_minor, + write_to_client, + }, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, SequenceNumber}, +}; + +#[allow(clippy::too_many_arguments)] +pub(super) fn handle_xkb_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let minor = header.data; + if minor > XKB_LAST_REQUEST { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(minor), + header.opcode, + ); + } + debug!( + "client {} #{} XkbProxy minor={}", + client_id.0, sequence.0, minor + ); + // Xorg's per-request order: the request size (REQUEST_AT_LEAST_SIZE, + // for the handlers ported so far), then BadAccess for a client that + // hasn't called XkbUseExtension (every XKB request but UseExtension). + let min_body = match minor { + X_KB_SELECT_EVENTS => 12, + 5 => 12, // LatchLockState + X_KB_SET_CONTROLS => 96, + X_KB_SET_MAP => 32, + X_KB_SET_COMPAT_MAP => 12, + X_KB_SET_INDICATOR_MAP => 8, + X_KB_SET_NAMES | X_KB_SET_GEOMETRY => 24, + _ => 0, + }; + if body.len() < min_body { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + header.opcode, + ); + } + if minor != X_KB_USE_EXTENSION + && !crate::core_loop::xkb_select::xkb_initialized(state, client_id) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + 0, + u16::from(minor), + header.opcode, + ); + } + let byte_order = state + .clients + .get(&client_id.0) + .map_or(x11::ClientByteOrder::LittleEndian, |c| c.byte_order); + if minor == X_KB_USE_EXTENSION { + // Whether the client is supported is the core loop's decision (it + // tracks the client's XKB state), and so is the reply, which must + // be in the client's byte order. The backend still sees the request: + // a nested backend initialises XKB on its host connection with it. + let supported = crate::core_loop::xkb_select::use_extension(state, client_id, body); + let _backend_reply = { + let atoms = &mut state.atoms; + let mut intern = |name: &str| atoms.intern(name, false).0; + backend.xkb_proxy(origin, minor, body, &mut intern) + }; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let mut buf = Vec::with_capacity(32); + x11::write_xkb_use_extension_reply(&mut buf, byte_order, sequence, supported)?; + return Ok(write_to_client(client, client_id, &buf)); + } + // SelectEvents is applied here; on success the request still reaches + // the backend (a nested backend forwards it to its host). + if minor == X_KB_SELECT_EVENTS + && let Err((code, value)) = + crate::core_loop::xkb_select::select_events(state, client_id, body) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + header.opcode, + ); + } + // SetControls: the repeat controls are core state for every backend. On + // success the request still reaches the backend (a nested backend + // forwards it to its host). + if minor == X_KB_SET_CONTROLS + && let Err((code, value)) = + crate::core_loop::xkb_controls::set_controls(state, &*backend, header.opcode, body) + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + header.opcode, + ); + } + // The Set* requests the backend's keyboard description implements (a + // port of Xorg's handler): its events, then its error. + let ancient = crate::core_loop::xkb_select::xkb_ancient(state, client_id); + let set_outcome = { + let atoms = &state.atoms; + let atom_name = |atom: u32| atoms.name(x11::AtomId(atom)).map(str::to_owned); + backend.xkb_set(minor, body, ancient, &atom_name) + }; + if let Some(outcome) = set_outcome { + crate::core_loop::xkb_layout::resync_xkb_announced(state, backend); + send_xkb_set_events(state, &*backend, header.opcode, minor, &outcome.events); + if let Some((code, value)) = outcome.error { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + header.opcode, + ); + } + return Ok(RequestOutcome::Handled); + } + // XkbLatchLockState (minor 5): a group lock switches the authoritative + // keyboard group, a modifier lock sets/clears real modifier locks (this + // is the path `numlockx` takes via XkbLockModifiers), and either one + // broadcasts XkbStateNotify to subscribed clients. When a request carries + // both, both are applied before one XkbStateNotify, as in Xorg. + // LatchLockState is a void request (no reply), so this runs in the + // pre-proxy region; the backend's xkb_proxy minor-5 returns None. + if minor == 5 { + // Xorg validates the whole request before applying any part of it. + if let Err((code, value)) = crate::core_loop::xkb_layout::check_latch_lock_state(body) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + header.opcode, + ); + } + // Modifier and group latches are validated but not applied yet. + if body[6] != 0 || body[9] != 0 { + debug!( + "client {} #{} XkbLatchLockState latches not applied: \ + affectModLatches={:#04x} latchGroup={}", + client_id.0, sequence.0, body[6], body[9] + ); + } + let requested_group = crate::core_loop::xkb_layout::parse_latch_lock_group(body); + let requested_mods = crate::core_loop::xkb_layout::parse_latch_lock_mods(body); + // Neither component present (e.g. a latch-only request): the state + // is left untouched and nothing is sent. + if requested_group.is_some() || requested_mods.is_some() { + // `changed` covers this request's change only. + crate::core_loop::xkb_layout::resync_xkb_announced(state, backend); + if let Some(group) = requested_group { + backend.set_locked_group(group); + } + if let Some((affect, values)) = requested_mods { + backend.set_locked_mods(affect, values); + } + crate::core_loop::xkb_layout::announce_xkb_state( + state, + backend, + crate::core_loop::xkb_layout::XkbStateCause { + keycode: 0, + event_type: 0, + request: (header.opcode, 5), + }, + ); + } + } + // XkbGetKbdByName (minor 23): a real keymap load + reply, NOT the + // minimal stub. The backend owns the keymap/rmlvo/atom-resolution, so it + // parses the body, loads the requested multi-group keymap, and assembles + // the nested-block reply; on a successful load it hands back the + // XkbNewKeyboardInfo this core loop broadcasts as XkbNewKeyboardNotify to + // ALL clients (Xorg ProcXkbGetKbdByName: XkbSendNewKeyboardNotify after + // the reply). The fanout lives here because the client tables do. + if minor == 23 { + let kbn = { + let atoms = &mut state.atoms; + let mut intern = |name: &str| atoms.intern(name, false).0; + backend.xkb_get_kbd_by_name(body, &mut intern) + }; + if let Some((mut bytes, notify)) = kbn { + crate::core_loop::xkb_layout::resync_xkb_announced(state, backend); + stamp_reply_sequence(&mut bytes, byte_order, sequence); + // Broadcast NewKeyboardNotify on a successful load, BEFORE writing + // the reply (Xorg order is reply-then-notify, but the notify fans + // out to a different client set; ordering across clients is + // independent, and emitting first keeps the reply write last so an + // early return can't drop it). + if let Some(info) = notify { + let base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); + let all: Vec = state.clients.keys().map(|id| ClientId(*id)).collect(); + // A full XkbGetKeyboardByName load replaces the whole + // key-symbol table in Xorg, so stale ChangeKeyboardMapping + // overrides must not keep shadowing it (see the identical + // fix + rationale in `apply_rules_names_change`). + state.keymap_overrides.clear(); + // Legacy core MappingNotify(Keyboard) + MappingNotify(Modifier) + // to ALL clients, mirroring Xorg's XkbSendLegacyMapNotify + // companion to XkbSendNewKeyboardNotify. XKB-unaware clients + // (any plain-X11 WM that never calls XkbSelectEvents — e.g. + // one that resolves keybinds via XKeysymToKeycode once at + // startup) never see XkbNewKeyboardNotify, so without this + // they keep grabbing the pre-switch keycodes forever: typing + // reflects the new layout (translation is per-keystroke) but + // WM keyboard shortcuts stay stuck on the old one, because + // nothing ever told the WM to re-resolve keysym→keycode and + // re-`GrabKey`. This is the same pair `apply_rules_names_change` + // sends for the `_XKB_RULES_NAMES`-ChangeProperty path; real + // `setxkbmap` goes through *this* XkbGetKbdByName path instead, + // so it needs the same legacy fanout here. + let count = info + .max_keycode + .saturating_sub(info.min_keycode) + .saturating_add(1); + let _dropped = fanout_event_to_clients(state, &all, |buf, seq, order| { + let _ = x11::write_mapping_notify_event( + buf, + order, + seq, + 1, + info.min_keycode, + count, + ); + }); + let _dropped = fanout_event_to_clients(state, &all, |buf, seq, order| { + let _ = x11::write_mapping_notify_event(buf, order, seq, 0, 0, 0); + }); + let _dropped = fanout_event_to_clients(state, &all, |buf, seq, order| { + let _ = x11::write_xkb_new_keyboard_notify( + buf, + order, + seq, + base, + 1, + info.min_keycode, + info.max_keycode, + info.old_min_keycode, + info.old_max_keycode, + 136, // requestMajor = XkbReqCode + 23, // requestMinor = X_kbGetKbdByName + info.changed, + ); + }); + // Refresh `_XKB_RULES_NAMES` on the root so it reflects the + // newly-loaded layout — Xorg keeps this property current on + // every keymap change (e.g. Cinnamon's runtime layout-add). + // `notify` is Some only when the keymap actually changed. + crate::core_loop::xkb_layout::publish_xkb_rules_names(state, &*backend); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &bytes)); + } + // Backend declined (no real keymap, e.g. test/v1 fixtures): fall + // through to the proxy's minimal-reply path below. + } + // Thread an atom interner so the backend can populate + // VirtualModNames in the GetNames reply (atoms live in the core + // loop's table; `backend` is a disjoint borrow from `state.atoms`). + let reply = { + let atoms = &mut state.atoms; + let mut intern = |name: &str| atoms.intern(name, false).0; + backend + .xkb_proxy(origin, minor, body, &mut intern) + .ok() + .flatten() + }; + if let Some(mut bytes) = reply { + stamp_reply_sequence(&mut bytes, byte_order, sequence); + // GetControls: the repeat controls are the core loop's (Xorg keeps + // XKB `per_key_repeat` and the feedback's `autoRepeats` in sync, and + // RepeatKeys with its global auto-repeat), not the backend's. + if minor == X_KB_GET_CONTROLS { + crate::core_loop::xkb_controls::patch_get_controls_reply(state, &mut bytes); + } + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + return Ok(write_to_client(client, client_id, &bytes)); + } + Ok(RequestOutcome::Handled) +} + +/// Write `sequence` into bytes 2..4 of a reply a backend built, in the +/// client's byte order. +fn stamp_reply_sequence( + bytes: &mut [u8], + byte_order: x11::ClientByteOrder, + sequence: SequenceNumber, +) { + if let Some(field) = bytes.get_mut(2..4) { + field.copy_from_slice(&match byte_order { + x11::ClientByteOrder::LittleEndian => sequence.0.to_le_bytes(), + x11::ClientByteOrder::BigEndian => sequence.0.to_be_bytes(), + }); + } +} + +/// Send what an XKB Set* request did, in Xorg's order: each +/// `XkbSendNewKeyboardNotify` / `XkbSendNotification` with its legacy core +/// MappingNotify, the per-key repeat re-derivation copied to the core +/// keyboard feedback, `_XkbSetCompatMap`'s CompatMapNotify and +/// `XkbApplyLedMapChanges`' indicator notifications. `major`/`minor` are the +/// request's (the events' cause). +fn send_xkb_set_events( + state: &mut ServerState, + backend: &dyn Backend, + major: u8, + minor: u8, + events: &[crate::backend::XkbSetEvent], +) { + use crate::{ + backend::XkbSetEvent, + core_loop::xkb_select::{self, LegacyCause}, + }; + let base = backend.xkb_info().map_or(0, |(_maj, ev, _err)| ev); + for event in events { + match event { + XkbSetEvent::NewKeyboard(info) => { + let recipients = xkb_select::new_keyboard_recipients(state, info.changed); + let _dropped = fanout_event_to_clients(state, &recipients, |buf, seq, order| { + let _ = x11::write_xkb_new_keyboard_notify( + buf, + order, + seq, + base, + 1, + info.min_keycode, + info.max_keycode, + info.old_min_keycode, + info.old_max_keycode, + major, + minor, + info.changed, + ); + }); + let num = info + .max_keycode + .wrapping_sub(info.min_keycode) + .wrapping_add(1); + xkb_select::send_legacy_map_notify( + state, + LegacyCause::NewKeyboardNotify, + info.changed, + info.min_keycode, + num, + ); + } + XkbSetEvent::Notification(change) => { + let m = change.map_notify; + if m.changed != 0 { + crate::core_loop::xkb_layout::send_xkb_map_notify(state, base, m); + xkb_select::send_legacy_map_notify( + state, + LegacyCause::MapNotify, + m.changed, + m.first_key_sym, + m.n_key_syms, + ); + } + crate::core_loop::xkb_layout::send_keyboard_mapping_followups( + state, + base, + change, + (major, minor), + ); + } + XkbSetEvent::Repeats(repeats) => { + let _ = crate::core_loop::xkb_layout::apply_repeats_to_core(state, repeats); + } + XkbSetEvent::CompatMap(notify) => { + crate::core_loop::xkb_layout::send_xkb_compat_map_notify(state, base, *notify); + } + XkbSetEvent::IndicatorMaps(change) => { + crate::core_loop::xkb_layout::send_indicator_maps_change(state, base, change); + } + XkbSetEvent::Names(notify) => { + crate::core_loop::xkb_layout::send_xkb_names_notify(state, base, *notify); + } + XkbSetEvent::IndicatorNames { + leds_defined, + state: lit, + } => { + crate::core_loop::xkb_layout::send_indicator_names_change( + state, + base, + *leds_defined, + *lit, + ); + } + } + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/xshm.rs b/crates/yserver-core/src/core_loop/process_request/xshm.rs new file mode 100644 index 000000000..4a9c4eb84 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xshm.rs @@ -0,0 +1,885 @@ +use crate::{ + backend::{Backend, OriginContext}, + core_loop::{ + damage_fanout::accumulate_damage_to_state, + fanout::fanout_event_to_clients, + process_request::{ + RequestOutcome, drawing::zpixmap_row_stride, emit_x11_error_with_minor, + send_reply_with_fd, supported_pixmap_depth, validate_drawable_and_gc, write_to_client, + zpixmap_expected_len, + }, + }, + server::ServerState, +}; +use log::debug; +use std::{ + io, + os::fd::{IntoRawFd, OwnedFd}, +}; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +#[allow(clippy::too_many_arguments)] +pub(super) fn handle_mit_shm_request( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], + attached_fd: Option, +) -> io::Result { + use yserver_protocol::x11::mit_shm as shm; + const MIT_SHM_MAJOR_OPCODE: u8 = 130; + let minor = header.data; + debug!( + "client {} #{} MIT-SHM dispatch minor={minor} body_len={}", + client_id.0, + sequence.0, + body.len() + ); + match minor { + shm::QUERY_VERSION => { + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + // Xorg reports the server's effective uid/gid, stored in the + // 16-bit wire fields (truncating, as the C assignment does). + // SAFETY: geteuid/getegid take no arguments and cannot fail. + let (euid, egid) = unsafe { (libc::geteuid(), libc::getegid()) }; + #[allow(clippy::cast_possible_truncation)] + let reply = shm::encode_query_version_reply( + byte_order, + sequence, + false, + euid as u16, + egid as u16, + ); + return Ok(write_to_client(client, client_id, &reply)); + } + shm::ATTACH => { + let Some(req) = shm::parse_attach(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + match crate::server::MitShmSegment::from_shmid(client_id, req.shmid, req.read_only) { + Ok(segment) => { + state.mit_shm_segments.insert(req.shmseg, segment); + debug!( + "client {} #{} MIT-SHM::Attach shmseg=0x{:x} shmid=0x{:x}", + client_id.0, sequence.0, req.shmseg, req.shmid + ); + } + Err(_) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + } + } + } + shm::ATTACH_FD => { + let Some(req) = shm::parse_attach_fd(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let Some(fd) = attached_fd else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + // OwnedFd carries an automatic close-on-drop; from_fd takes + // raw and assumes ownership transfer. + let raw = std::os::fd::IntoRawFd::into_raw_fd(fd); + match crate::server::MitShmSegment::from_fd(client_id, raw, req.read_only) { + Ok(segment) => { + state.mit_shm_segments.insert(req.shmseg, segment); + } + Err(_) => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + } + } + } + shm::DETACH => { + if let Some(shmseg) = shm::parse_detach(body) { + state.mit_shm_segments.remove(&shmseg); + } + } + shm::CREATE_PIXMAP => { + let Some(req) = shm::parse_create_pixmap(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + return handle_mit_shm_create_pixmap(state, backend, origin, client_id, sequence, req); + } + shm::PUT_IMAGE => { + let Some(req) = shm::parse_put_image(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + return handle_mit_shm_put_image(state, backend, origin, client_id, sequence, req); + } + shm::GET_IMAGE => { + let Some(req) = shm::parse_get_image(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + return handle_mit_shm_get_image(state, backend, origin, client_id, sequence, req); + } + shm::CREATE_SEGMENT => { + let Some(req) = shm::parse_create_segment(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(minor), + MIT_SHM_MAJOR_OPCODE, + ); + }; + return handle_mit_shm_create_segment(state, client_id, sequence, req); + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + MIT_SHM_MAJOR_OPCODE, + ); + } + } + Ok(RequestOutcome::Handled) +} + +fn handle_mit_shm_create_pixmap( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + req: yserver_protocol::x11::mit_shm::CreatePixmapRequest, +) -> io::Result { + const MIT_SHM_MAJOR_OPCODE: u8 = 130; + use yserver_protocol::x11::mit_shm as shm; + debug!( + "client {} #{} MIT-SHM::CreatePixmap pid=0x{:x} drawable=0x{:x} {}x{} d{}", + client_id.0, sequence.0, req.pid, req.drawable, req.width, req.height, req.depth, + ); + let validation_failed = { + let handle = state.clients.get(&client_id.0).expect("client registered"); + let owned = crate::server::IdAllocator::validate_owned( + req.pid, + handle.resource_id_base, + handle.resource_id_mask, + ); + let in_use = state.xid_occupied(req.pid); + !owned || in_use + }; + let drawable_exists = state.resources.window(ResourceId(req.drawable)).is_some() + || state.resources.pixmap(ResourceId(req.drawable)).is_some(); + if validation_failed { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ID_CHOICE, + req.pid, + u16::from(shm::CREATE_PIXMAP), + MIT_SHM_MAJOR_OPCODE, + ); + } + if !drawable_exists { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable, + u16::from(shm::CREATE_PIXMAP), + MIT_SHM_MAJOR_OPCODE, + ); + } + if !supported_pixmap_depth(req.depth) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(req.depth), + u16::from(shm::CREATE_PIXMAP), + MIT_SHM_MAJOR_OPCODE, + ); + } + let Some(expected_len) = zpixmap_expected_len(req.width, req.height, req.depth) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(shm::CREATE_PIXMAP), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let host_xid = match backend.create_pixmap(origin, req.depth, req.width, req.height) { + Ok(handle) => Some(handle), + Err(err) => { + log::warn!( + "client {} MIT-SHM::CreatePixmap host CreatePixmap failed: {err}", + client_id.0 + ); + None + } + }; + let snapshot: Vec = { + let Some(segment) = state.mit_shm_segments.get(&req.shmseg) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(shm::CREATE_PIXMAP), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let bytes = segment.as_slice(); + let start = req.offset as usize; + let end = start.saturating_add(expected_len); + if end > bytes.len() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.offset, + u16::from(shm::CREATE_PIXMAP), + MIT_SHM_MAJOR_OPCODE, + ); + } + bytes[start..end].to_vec() + }; + if let Some(host_xid) = host_xid { + // The new pixmap takes the segment's bytes as they are: no client + // GC, so not the function or plane mask the last draw left behind. + let copy_gc = crate::backend::DrawState::default(); + let _ = backend + .apply_clip_state(origin, ©_gc.clip) + .and_then(|()| backend.apply_draw_state(origin, ©_gc)); + if let Err(err) = backend.put_image( + origin, + host_xid.as_raw(), + req.depth, + req.width, + req.height, + 0, + 0, + &snapshot, + ) { + log::warn!( + "client {} MIT-SHM::CreatePixmap put_image failed: {err}", + client_id.0 + ); + } + } + state.resources.create_pixmap( + client_id, + x11::CreatePixmapRequest { + depth: req.depth, + pixmap: ResourceId(req.pid), + drawable: ResourceId(req.drawable), + width: req.width, + height: req.height, + }, + ); + if let Some(xid) = host_xid { + let updated = state + .resources + .set_pixmap_host_xid(ResourceId(req.pid), xid); + debug_assert!(updated, "pixmap was just inserted above"); + } + Ok(RequestOutcome::Handled) +} + +pub(super) fn handle_mit_shm_put_image( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + req: yserver_protocol::x11::mit_shm::PutImageRequest, +) -> io::Result { + const MIT_SHM_MAJOR_OPCODE: u8 = 130; + use yserver_protocol::x11::mit_shm as shm; + // MIT-SHM PutImage perf-cliff diagnostic (2026-05-28 cinnamon + // telemetry: single op130 calls at 100-128ms blocking the core + // loop for ~6-8 vsync intervals). Section-time so we can pin + // which step dominates. Threshold-gated at exit; steady-state + // healthy calls (sub-100µs) stay silent. + let t_entry = std::time::Instant::now(); + debug!( + "client {} #{} MIT-SHM::PutImage drawable=0x{:x} {}x{} d{}", + client_id.0, sequence.0, req.drawable, req.src_width, req.src_height, req.depth + ); + let drawable = ResourceId(req.drawable); + let gc = ResourceId(req.gc); + if let Err((code, bad_value)) = validate_drawable_and_gc( + state, + client_id, + crate::access::RequestOpcodes { + major: MIT_SHM_MAJOR_OPCODE, + minor: shm::PUT_IMAGE, + }, + drawable, + gc, + None, + None, + ) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + bad_value, + u16::from(shm::PUT_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + } + let draw_state = state.resources.resolve_draw_state(gc).unwrap_or_default(); + let target = state.resources.host_drawable_target(drawable); + let Some(target) = target else { + return Ok(RequestOutcome::Handled); + }; + let Some(segment) = state.mit_shm_segments.get(&req.shmseg) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(shm::PUT_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let Some(snapshot) = extract_shm_zpixmap_region( + segment.as_slice(), + req.offset, + req.total_width, + req.total_height, + req.src_x, + req.src_y, + req.src_width, + req.src_height, + req.depth, + ) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.offset, + u16::from(shm::PUT_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let t_after_extract = t_entry.elapsed(); + let snapshot_borrowed = matches!(snapshot, std::borrow::Cow::Borrowed(_)); + let snapshot_bytes = snapshot.len(); + backend.apply_clip_state(origin, &draw_state.clip)?; + backend.apply_draw_state(origin, &draw_state)?; + let t_after_apply_state = t_entry.elapsed(); + backend.put_image( + origin, + target.host_xid(), + req.depth, + req.src_width, + req.src_height, + req.dst_x, + req.dst_y, + &snapshot, + )?; + let t_after_put_image = t_entry.elapsed(); + let _dropped = accumulate_damage_to_state( + state, + ResourceId(req.drawable), + req.dst_x, + req.dst_y, + req.src_width, + req.src_height, + ); + // ShmPutImage with send_event=true obligates a ShmCompletion event + // once the transfer is done (shmproto.h). GTK/GDK pools SHM segments + // and blocks the next frame until the completion frees one — without + // this the render loop stalls after the pool is exhausted (the + // cinnamon-settings repaint freeze). MIT-SHM first-event base is 65; + // ShmCompletion offset is 0. + if req.send_event { + const MIT_SHM_FIRST_EVENT: u8 = 65; + let _dropped = fanout_event_to_clients(state, &[client_id], |buf, seq, order| { + x11::encode_shm_completion_event( + buf, + order, + seq, + MIT_SHM_FIRST_EVENT, + ResourceId(req.drawable), + u16::from(shm::PUT_IMAGE), + MIT_SHM_MAJOR_OPCODE, + req.shmseg, + req.offset, + ); + }); + } + let total = t_entry.elapsed(); + // 5ms threshold matches the suspected cliff territory; healthy + // PutImage steady-state is sub-100µs per call so threshold- + // gating keeps the log quiet. + if total >= std::time::Duration::from_millis(5) { + // CALLING client (the one issuing PutImage) is `client_id` — + // that's what we want to attribute the hot-path activity to. + // The drawable's OWNER (high bits of `req.drawable`) is a + // separate, less-actionable identity — typically a pixmap + // whose creator may have disconnected with the resource kept + // alive via X11 RetainTemporary / Permanent / SaveSet. So + // log the caller's WM_CLASS as the primary attribution and + // include the drawable XID for cross-reference. + let caller_class = state + .client_wm_class + .get(&client_id.0) + .map(String::as_str) + .unwrap_or(""); + log::debug!( + "MIT-SHM PutImage perf: total={total_us}us \ + [extract={ext_us}us apply_state+={state_us}us put_image+={pi_us}us] \ + {w}x{h} depth={depth} bytes={bytes} borrowed={borrowed} \ + drawable=0x{drawable:x} caller=client{caller_id}/{caller_class:?}", + total_us = total.as_micros(), + ext_us = t_after_extract.as_micros(), + state_us = t_after_apply_state + .saturating_sub(t_after_extract) + .as_micros(), + pi_us = t_after_put_image + .saturating_sub(t_after_apply_state) + .as_micros(), + w = req.src_width, + h = req.src_height, + depth = req.depth, + bytes = snapshot_bytes, + borrowed = snapshot_borrowed, + drawable = req.drawable, + caller_id = client_id.0, + ); + } + Ok(RequestOutcome::Handled) +} + +fn handle_mit_shm_get_image( + state: &mut ServerState, + backend: &mut dyn Backend, + origin: Option, + client_id: ClientId, + sequence: SequenceNumber, + req: yserver_protocol::x11::mit_shm::GetImageRequest, +) -> io::Result { + use yserver_protocol::x11::mit_shm as shm; + const MIT_SHM_MAJOR_OPCODE: u8 = 130; + { + let Some(segment) = state.mit_shm_segments.get(&req.shmseg) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + if segment.read_only { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + req.shmseg, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + } + } + let target = state + .resources + .host_drawable_target(ResourceId(req.drawable)); + let Some(target) = target else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let host_bytes = backend + .get_image( + origin, + target.host_xid(), + req.format, + req.x, + req.y, + req.width, + req.height, + req.plane_mask, + ) + .ok() + .flatten(); + let Some(host_reply_bytes) = host_bytes else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_DRAWABLE, + req.drawable, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let pixel_data: Vec = host_reply_bytes.get(32..).unwrap_or(&[]).to_vec(); + { + let Some(segment) = state.mit_shm_segments.get_mut(&req.shmseg) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let Some(buf) = segment.as_mut_slice() else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ACCESS, + req.shmseg, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + }; + let start = req.offset as usize; + let end = start.saturating_add(pixel_data.len()); + if end > buf.len() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.offset, + u16::from(shm::GET_IMAGE), + MIT_SHM_MAJOR_OPCODE, + ); + } + buf[start..end].copy_from_slice(&pixel_data); + } + let depth = host_reply_bytes.first().copied().unwrap_or(24); + let visual = crate::resources::ROOT_VISUAL.0; + #[allow(clippy::cast_possible_truncation)] + let size = pixel_data.len() as u32; + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let reply = shm::encode_get_image_reply(byte_order, sequence, depth, visual, size); + Ok(write_to_client(client, client_id, &reply)) +} + +fn handle_mit_shm_create_segment( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + req: yserver_protocol::x11::mit_shm::CreateSegmentRequest, +) -> io::Result { + const MIT_SHM_MAJOR_OPCODE: u8 = 130; + use yserver_protocol::x11::mit_shm as shm; + if req.size == 0 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + req.shmseg, + u16::from(shm::CREATE_SEGMENT), + MIT_SHM_MAJOR_OPCODE, + ); + } + let Ok(fd) = crate::anon_shm::create_anon_shm(c"yserver-shm").map(IntoRawFd::into_raw_fd) + else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.shmseg, + u16::from(shm::CREATE_SEGMENT), + MIT_SHM_MAJOR_OPCODE, + ); + }; + if unsafe { libc::ftruncate(fd, libc::off_t::from(req.size as i32)) } < 0 { + unsafe { libc::close(fd) }; + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.shmseg, + u16::from(shm::CREATE_SEGMENT), + MIT_SHM_MAJOR_OPCODE, + ); + } + let fd_for_client = unsafe { libc::dup(fd) }; + if fd_for_client < 0 { + unsafe { libc::close(fd) }; + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.shmseg, + u16::from(shm::CREATE_SEGMENT), + MIT_SHM_MAJOR_OPCODE, + ); + } + let segment = match crate::server::MitShmSegment::from_fd(client_id, fd, req.read_only) { + Ok(s) => s, + Err(_) => { + unsafe { libc::close(fd_for_client) }; + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.shmseg, + u16::from(shm::CREATE_SEGMENT), + MIT_SHM_MAJOR_OPCODE, + ); + } + }; + state.mit_shm_segments.insert(req.shmseg, segment); + let send_res = match state.clients.get_mut(&client_id.0) { + Some(client) => { + let reply = yserver_protocol::x11::mit_shm::encode_create_segment_reply( + client.byte_order, + sequence, + ); + send_reply_with_fd(client, &reply, fd_for_client) + } + None => Ok(()), + }; + unsafe { libc::close(fd_for_client) }; + if send_res.is_err() { + // Xorg's `ProcShmCreateSegment` (`Xext/shm.c:1323`): + // + // if (WriteFdToClient(client, fd, TRUE) < 0) { + // FreeResource(stuff->shmseg, X11_RESTYPE_NONE); + // close(fd); + // return BadAlloc; + // } + // + // Both halves matter. Propagating the I/O error instead left the + // segment in `mit_shm_segments` with no client able to reach it, + // and sent no protocol reply at all — the client saw a request that + // neither succeeded nor failed. The dispatch gate above should mean + // this is now unreachable for the transport reason; it stays + // because a short write is not the only way to get here. + state.mit_shm_segments.remove(&req.shmseg); + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_ALLOC, + req.shmseg, + u16::from(shm::CREATE_SEGMENT), + MIT_SHM_MAJOR_OPCODE, + ); + } + Ok(RequestOutcome::Handled) +} + +/// Extract a tightly-packed `src_width × src_height × bpp(depth)` +/// region from an MIT-SHM ZPixmap buffer laid out as `total_width × +/// total_height` with the server's standard scanline padding. The +/// caller passes the full shm segment in `bytes`; `offset` is the +/// byte offset to the START of the image (not the region). +/// +/// Returns `None` if any computed offset would exceed `bytes.len()`, +/// or the depth is unsupported, or any required arithmetic +/// overflows. For `depth == 1` (bit-packed), `src_x` must be a +/// multiple of 8 — non-byte-aligned bit extraction is not +/// implemented; in practice all known clients use `src_x = 0` for +/// bitmasks. +pub(super) fn extract_shm_zpixmap_region( + bytes: &[u8], + offset: u32, + total_width: u16, + total_height: u16, + src_x: i16, + src_y: i16, + src_width: u16, + src_height: u16, + depth: u8, +) -> Option> { + if src_x < 0 || src_y < 0 { + return None; + } + let src_x = u32::try_from(src_x).ok()?; + let src_y = u32::try_from(src_y).ok()?; + // The region must fit inside the declared total image. + let src_x_end = src_x.checked_add(u32::from(src_width))?; + let src_y_end = src_y.checked_add(u32::from(src_height))?; + if src_x_end > u32::from(total_width) || src_y_end > u32::from(total_height) { + return None; + } + + let total_stride = zpixmap_row_stride(total_width, depth)?; + let src_stride = zpixmap_row_stride(src_width, depth)?; + + // Per-row leading-byte offset within the source row. + let src_x_bytes: usize = match depth { + 1 => { + if src_x % 8 != 0 { + return None; + } + (src_x / 8) as usize + } + 4 => { + if src_x % 2 != 0 { + return None; + } + (src_x / 2) as usize + } + 8 => src_x as usize, + 24 | 32 => (src_x as usize).checked_mul(4)?, + _ => return None, + }; + + let base = usize::try_from(offset).ok()?; + // Bytes-per-source-row that actually carry image data (no trailing pad). + let row_bytes: usize = match depth { + 24 | 32 => (src_width as usize).checked_mul(4)?, + 8 => src_width as usize, + 4 => (src_width as usize).div_ceil(2), + 1 => (src_width as usize).div_ceil(8), + _ => return None, + }; + if row_bytes > src_stride { + return None; + } + + // Fast path: full-frame extract (src origin = (0,0), src dims = total + // dims) AND no trailing per-row pad gap (`row_bytes == src_stride == + // total_stride`). The wanted bytes are contiguous in the SHM segment + // starting at `offset` — borrow directly instead of per-row memcpy + // into a fresh Vec. 2026-05-28 cinnamon telemetry showed 28MB full- + // frame extracts at ~8-10ms each; this fast path drops them to a + // bounds-check + slice. The slow per-row path stays for partial + // regions (src offset != 0 or src dims != total dims) and for depths + // where `row_bytes < src_stride` (padding fills required). + if src_x == 0 + && src_y == 0 + && src_width == total_width + && src_height == total_height + && row_bytes == src_stride + { + let total_bytes = src_stride.checked_mul(usize::from(src_height))?; + let end = base.checked_add(total_bytes)?; + if end > bytes.len() { + return None; + } + return Some(std::borrow::Cow::Borrowed(&bytes[base..end])); + } + + let mut out = Vec::with_capacity(src_stride.checked_mul(usize::from(src_height))?); + for r in 0..usize::from(src_height) { + let row_y = (src_y as usize).checked_add(r)?; + let row_start = base + .checked_add(row_y.checked_mul(total_stride)?)? + .checked_add(src_x_bytes)?; + let row_end = row_start.checked_add(row_bytes)?; + if row_end > bytes.len() { + return None; + } + out.extend_from_slice(&bytes[row_start..row_end]); + // Pad scanline to 32-bit boundary if needed (d1/d4/d8 with + // width not a multiple of the pad unit). Output buffer's + // row stride is `src_stride`; pad with zeros so downstream + // consumers see the standard ZPixmap layout. + if src_stride > row_bytes { + out.resize(out.len() + (src_stride - row_bytes), 0); + } + } + Some(std::borrow::Cow::Owned(out)) +} diff --git a/crates/yserver-core/src/core_loop/process_request/xtest.rs b/crates/yserver-core/src/core_loop/process_request/xtest.rs new file mode 100644 index 000000000..5f6e2e24c --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/xtest.rs @@ -0,0 +1,624 @@ +use crate::{ + backend::Backend, + core_loop::process_request::{ + RequestOutcome, XI2_FIRST_ERROR, emit_x11_error_with_minor, write_to_client, + xi::{ + xi1_device_button_count, xi1_device_has_buttons, xi1_device_has_keys, + xi1_device_has_valuators, + }, + }, + server::ServerState, +}; +use log::debug; +use std::io; +use yserver_protocol::{ + x11, + x11::{ClientId, RequestHeader, ResourceId, SequenceNumber}, +}; + +fn effective_window_cursor(state: &ServerState, mut window: ResourceId) -> Option { + for _ in 0..256 { + let current = state.resources.window(window)?; + if let Some(cursor) = current.cursor { + return (cursor.0 != 0).then_some(cursor); + } + if current.parent == window { + break; + } + window = current.parent; + } + None +} + +fn current_pointer_cursor(state: &ServerState) -> Option { + if let Some(grab) = state.active_pointer_grab + && grab.cursor.0 != 0 + { + return Some(grab.cursor); + } + let pointer_window = crate::core_loop::key_fanout::deepest_window_at_pointer(state); + effective_window_cursor(state, pointer_window) +} + +pub(super) fn handle_xtest_request( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + use yserver_protocol::x11::xtest as x11xtest; + let minor = header.data; + match minor { + x11xtest::GET_VERSION => { + let (cmaj, cmin) = x11xtest::parse_get_version(body).unwrap_or(( + u8::try_from(x11xtest::MAJOR_VERSION).unwrap_or(2), + x11xtest::MINOR_VERSION, + )); + debug!( + "client {} #{} XTEST::GetVersion client={cmaj}.{cmin} -> {}.{}", + client_id.0, + sequence.0, + x11xtest::MAJOR_VERSION, + x11xtest::MINOR_VERSION, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let byte_order = client.byte_order; + let reply = x11xtest::encode_get_version_reply( + byte_order, + sequence, + u8::try_from(x11xtest::MAJOR_VERSION).unwrap_or(2), + x11xtest::MINOR_VERSION, + ); + return Ok(write_to_client(client, client_id, &reply)); + } + x11xtest::COMPARE_CURSOR => { + let byte_order = state + .clients + .get(&client_id.0) + .map_or(x11::ClientByteOrder::LittleEndian, |client| { + client.byte_order + }); + let read_u32 = |slice: &[u8]| match byte_order { + x11::ClientByteOrder::LittleEndian => { + u32::from_le_bytes(slice.try_into().expect("four bytes")) + } + x11::ClientByteOrder::BigEndian => { + u32::from_be_bytes(slice.try_into().expect("four bytes")) + } + }; + let window = ResourceId(read_u32(&body[0..4])); + let cursor = ResourceId(read_u32(&body[4..8])); + if state.resources.window(window).is_none() { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_WINDOW, + window.0, + u16::from(minor), + header.opcode, + ); + } + let comparison = if cursor.0 == 0 { + None + } else if cursor.0 == 1 { + current_pointer_cursor(state) + } else if state.resources.cursor_exists(cursor) { + Some(cursor) + } else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_CURSOR, + cursor.0, + u16::from(minor), + header.opcode, + ); + }; + // Xorg compares cursor objects: after XFIXES ChangeCursor two + // XIDs can name the same cursor, so compare their host handles. + let effective = effective_window_cursor(state, window); + let same = effective == comparison + || matches!((effective, comparison), (Some(a), Some(b)) + if state.resources.cursor_host_xid(a).is_some() + && state.resources.cursor_host_xid(a) + == state.resources.cursor_host_xid(b)); + debug!( + "client {} #{} XTEST::CompareCursor window=0x{:x} cursor=0x{:x} same={same}", + client_id.0, sequence.0, window.0, cursor.0, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + let reply = x11xtest::encode_compare_cursor_reply(byte_order, sequence, same); + return Ok(write_to_client(client, client_id, &reply)); + } + x11xtest::FAKE_INPUT => { + let Some(fi) = x11xtest::parse_fake_input(body) else { + debug!( + "client {} #{} XTEST::FakeInput body too short ({} bytes), dropping", + client_id.0, + sequence.0, + body.len() + ); + return Ok(RequestOutcome::Handled); + }; + debug!( + "client {} #{} XTEST::FakeInput type={} detail={} root_xy=({},{})", + client_id.0, sequence.0, fi.event_type, fi.detail, fi.root_x, fi.root_y + ); + return dispatch_fake_input_with_body( + state, backend, client_id, sequence, header, fi, body, + ); + } + x11xtest::GRAB_CONTROL => { + debug!( + "client {} #{} XTEST::GrabControl (no-op)", + client_id.0, sequence.0 + ); + } + other => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_REQUEST, + 0, + u16::from(other), + header.opcode, + ); + } + } + Ok(RequestOutcome::Handled) +} + +/// `body` is the FakeInput request body (the 32-byte first xEvent plus +/// any follow-up events) — needed for the XI 1.x *device* fakes, where +/// libXtst packs the deviceid into byte 31 of the first event and +/// device-motion axes into trailing deviceValuator events (Xorg +/// Xext/xtest.c ProcXTestFakeInput). +#[allow(clippy::too_many_lines)] +fn dispatch_fake_input_with_body( + state: &mut ServerState, + backend: &mut dyn Backend, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + fi: yserver_protocol::x11::xtest::FakeInput, + body: &[u8], +) -> io::Result { + use crate::{core_loop::HostInputEvent, host_x11::HostKeyEvent}; + use yserver_protocol::x11::xtest as x11xtest; + + let xi_first = crate::server::XI_FIRST_EVENT; + let event_type = fi.event_type & 0x7f; + let xi_device_event = event_type >= xi_first; + let xi_offset = if xi_device_event { + Some(event_type - xi_first) + } else { + None + }; + let target_device_id = if xi_device_event { + // ProcXTestFakeInput first validates that the request contains full + // xEvents, then masks the device id's MORE_EVENTS bit and looks it up + // (Xext/xtest.c:170-186). + if body.len() < 32 || !body.len().is_multiple_of(32) { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + header.opcode, + ); + } + let Some(device_id) = fake_input_device_id(body) else { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + header.opcode, + ); + }; + if state.xi_devices.device(device_id).is_none() { + // XI_BadDevice is the XInput extension's first error. + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + u32::from(device_id), + u16::from(header.data), + header.opcode, + ); + } + + // Check the event's device class before the DeviceMotion valuator + // pairing, as Xorg does at xtest.c:189-226. Class failures carry the + // original event type in errorValue. + let class_ok = match xi_offset { + Some(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET) + | Some(crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET) => { + xi1_device_has_keys(&state.xi_devices, device_id) + } + Some(crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET) + | Some(crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET) => { + xi1_device_has_buttons(&state.xi_devices, device_id) + } + Some(crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET) => { + xi1_device_has_valuators(&state.xi_devices, device_id) + } + _ => false, + }; + if !class_ok { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.event_type), + u16::from(header.data), + header.opcode, + ); + } + if xi_offset == Some(crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET) && body.len() == 32 { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_LENGTH, + 0, + u16::from(header.data), + header.opcode, + ); + } + + match xi_offset { + Some(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET) + | Some(crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET) + if !fake_input_keycode_valid(fi.detail) => + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.detail), + u16::from(header.data), + header.opcode, + ); + } + Some(crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET) + | Some(crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET) + if !fake_input_button_valid(&state.xi_devices, device_id, fi.detail) => + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.detail), + u16::from(header.data), + header.opcode, + ); + } + _ => {} + } + device_id + } else { + // Core FakeInput selects the XTEST keyboard or pointer from the event + // type before checking its class/detail (xtest.c:282-326, 357-410). + let device_id = match event_type { + x11xtest::FAKE_KEY_PRESS | x11xtest::FAKE_KEY_RELEASE => { + crate::xinput::DEVICEID_XTEST_KEYBOARD + } + x11xtest::FAKE_BUTTON_PRESS + | x11xtest::FAKE_BUTTON_RELEASE + | x11xtest::FAKE_MOTION_NOTIFY => crate::xinput::DEVICEID_XTEST_POINTER, + _ => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.event_type), + u16::from(header.data), + header.opcode, + ); + } + }; + let class_ok = match event_type { + x11xtest::FAKE_KEY_PRESS | x11xtest::FAKE_KEY_RELEASE => { + xi1_device_has_keys(&state.xi_devices, device_id) + } + x11xtest::FAKE_BUTTON_PRESS | x11xtest::FAKE_BUTTON_RELEASE => { + xi1_device_has_buttons(&state.xi_devices, device_id) + } + x11xtest::FAKE_MOTION_NOTIFY => xi1_device_has_valuators(&state.xi_devices, device_id), + _ => false, + }; + if !class_ok { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + XI2_FIRST_ERROR, + 0, + u16::from(header.data), + header.opcode, + ); + } + match event_type { + x11xtest::FAKE_KEY_PRESS | x11xtest::FAKE_KEY_RELEASE + if !fake_input_keycode_valid(fi.detail) => + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.detail), + u16::from(header.data), + header.opcode, + ); + } + x11xtest::FAKE_BUTTON_PRESS | x11xtest::FAKE_BUTTON_RELEASE + if !fake_input_button_valid(&state.xi_devices, device_id, fi.detail) => + { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.detail), + u16::from(header.data), + header.opcode, + ); + } + x11xtest::FAKE_MOTION_NOTIFY if fi.detail != 0 && fi.detail != 1 => { + return emit_x11_error_with_minor( + state, + client_id, + sequence, + x11::error::BAD_VALUE, + u32::from(fi.detail), + u16::from(header.data), + header.opcode, + ); + } + _ => {} + } + device_id + }; + + let fi = yserver_protocol::x11::xtest::FakeInput { event_type, ..fi }; + let origin = crate::core_loop::InputOrigin::XTest(target_device_id); + + if let Some(offset) = xi_offset { + match offset { + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET + | crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => { + let pressed = offset == crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET; + backend.on_host_input( + state, + HostInputEvent::Key(HostKeyEvent { + origin, + pressed, + keycode: fi.detail, + time: fi.time, + root_x: 0, + root_y: 0, + event_x: 0, + event_y: 0, + state: 0, + }), + ); + } + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET + | crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => { + let pressed = offset == crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; + let button = fake_input_button_code(fi.detail) + .expect("validated XI device button number has an input code"); + backend.on_host_input( + state, + HostInputEvent::PointerButton { + origin, + button, + pressed, + time: fi.time, + }, + ); + } + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET => { + // Device-motion fakes are DEVICE-coordinate space and do + // NOT move the sprite — Xorg uses POINTER_ABSOLUTE without + // POINTER_DESKTOP (Xext/xtest.c:265). + let mut axes = crate::server::Xi1MotionAxes { + first: 0, + count: 0, + values: [0; 6], + }; + let mut chunk = 32; + let mut got_first = false; + while let Some(dv) = body.get(chunk..chunk + 32) { + let num = usize::from(dv[6].min(6)); + if !got_first { + axes.first = dv[7]; + got_first = true; + } + for i in 0..num { + let off = 8 + i * 4; + let slot = usize::from(axes.count); + if slot >= 6 { + break; + } + axes.values[slot] = + i32::from_le_bytes([dv[off], dv[off + 1], dv[off + 2], dv[off + 3]]); + #[allow(clippy::cast_possible_truncation)] + { + axes.count += 1; + } + } + chunk += 32; + } + let target = crate::core_loop::key_fanout::deepest_window_at_pointer(state); + let (root_x, root_y) = state.pointer_root; + let _ = crate::core_loop::pointer_fanout::xi1_route_device_event( + state, + crate::server::Xi1QueuedEvent { + deviceid: target_device_id, + evcode: crate::server::XI_FIRST_EVENT + + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, + detail: 0, + time: fi.time, + root_x, + root_y, + state_mask: 0, + natural_target: target, + focus_route: crate::server::Xi1FocusRoute::Walk, + axes: (axes.count != 0).then_some(axes), + replay_floor: None, + }, + true, + ); + } + _ => unreachable!("XI event type was validated before injection"), + } + return Ok(RequestOutcome::Handled); + } + + match fi.event_type { + x11xtest::FAKE_KEY_PRESS | x11xtest::FAKE_KEY_RELEASE => { + let pressed = fi.event_type == x11xtest::FAKE_KEY_PRESS; + backend.on_host_input( + state, + HostInputEvent::Key(HostKeyEvent { + origin, + pressed, + keycode: fi.detail, + time: fi.time, + root_x: fi.root_x, + root_y: fi.root_y, + event_x: 0, + event_y: 0, + state: 0, + }), + ); + } + x11xtest::FAKE_BUTTON_PRESS | x11xtest::FAKE_BUTTON_RELEASE => { + let pressed = fi.event_type == x11xtest::FAKE_BUTTON_PRESS; + // Xorg's XTEST pointer has 10 buttons (dix/devices.c:655-700); + // ProcXTestFakeInput validates 1..numButtons and passes the detail + // unchanged to GetPointerEvents (Xext/xtest.c:401-425). BTN_FORWARD + // (0x115) maps to X button 10 via libinput's btn_linux2xorg + // (xf86-input-libinput/src/xf86libinput.c:253-272). + let linux_code = fake_input_button_code(fi.detail) + .expect("validated core button number has an input code"); + backend.on_host_input( + state, + HostInputEvent::PointerButton { + origin, + button: linux_code, + pressed, + time: fi.time, + }, + ); + } + x11xtest::FAKE_MOTION_NOTIFY => { + // detail 0 = absolute, detail 1 = relative (Xorg xtest.c: rootX/ + // rootY become the valuators, POINTER_ABSOLUTE only for 0). A + // relative fake moves the sprite by the delta from its current + // position, unaccelerated (XTEST doesn't set POINTER_ACCELERATE); + // the backend clips to the screen. The delta also rides as the + // raw relative motion, so XI2 RawMotion reports it. + let motion = if fi.detail == 0 { + HostInputEvent::PointerMotion { + origin, + x: i32::from(fi.root_x), + y: i32::from(fi.root_y), + time: fi.time, + relative: false, + dx: 0, + dy: 0, + motion_delta: None, + } + } else { + let (x, y) = state.pointer_root; + let (dx, dy) = (i32::from(fi.root_x), i32::from(fi.root_y)); + HostInputEvent::PointerMotion { + origin, + x: i32::from(x) + dx, + y: i32::from(y) + dy, + time: fi.time, + relative: true, + dx, + dy, + motion_delta: None, + } + }; + backend.on_host_input(state, motion); + // Like WarpPointer: the physical-input tracker must continue + // from the faked position, or the next real motion jumps back. + backend.resync_input_position(); + } + other => { + unreachable!("core FakeInput event type was validated: {other}"); + } + } + Ok(RequestOutcome::Handled) +} + +fn fake_input_keycode_valid(keycode: u8) -> bool { + // QueryDevice's KeyClass is shared by the master, XTEST, and physical + // keyboard facets: keycodes 8..=255 (xinput/query.rs:259-272). + keycode >= 8 +} + +fn fake_input_button_count(devices: &crate::xinput::XiRegistry, device_id: u16) -> Option { + if !xi1_device_has_buttons(devices, device_id) { + return None; + } + xi1_device_button_count(devices, device_id) +} + +fn fake_input_button_valid( + devices: &crate::xinput::XiRegistry, + device_id: u16, + button: u8, +) -> bool { + button != 0 && fake_input_button_count(devices, device_id).is_some_and(|count| button <= count) +} + +fn fake_input_button_code(button: u8) -> Option { + Some(match button { + 1 => 0x110, // BTN_LEFT + 2 => 0x112, // BTN_MIDDLE + 3 => 0x111, // BTN_RIGHT + 4 => 0x180, // SYNTH_SCROLL_UP + 5 => 0x181, // SYNTH_SCROLL_DOWN + 6 => 0x182, // SYNTH_SCROLL_LEFT + 7 => 0x183, // SYNTH_SCROLL_RIGHT + 8 => 0x113, // BTN_SIDE + 9 => 0x114, // BTN_EXTRA + 10 => 0x115, // BTN_FORWARD -> X 10 via btn_linux2xorg (xf86-input-libinput/src/xf86libinput.c:253-272) + _ => return None, + }) +} + +fn fake_input_device_id(body: &[u8]) -> Option { + if body.first().copied()? & 0x7f < crate::server::XI_FIRST_EVENT { + return None; + } + // XI1 reserves the top device-byte bit for MORE_EVENTS. Keep a missing or + // unknown device distinct from a core FakeInput's default 4/5 target. + body.get(31).map(|device_id| u16::from(device_id & 0x7f)) +} diff --git a/crates/yserver-core/src/core_loop/record.rs b/crates/yserver-core/src/core_loop/record.rs new file mode 100644 index 000000000..ea4cbaba4 --- /dev/null +++ b/crates/yserver-core/src/core_loop/record.rs @@ -0,0 +1,2327 @@ +//! RECORD extension 1.13 (Xorg `record/record.c`, `record/set.c`). +//! +//! A context is a server-wide XID resource owned by its creator; any client +//! may register on, query, enable, disable or free it. `EnableContext` +//! turns the enabling connection into the context's data connection: it +//! stops dispatching that client's requests (Xorg `IgnoreClient`, here via +//! `run.rs` `client_runnable`) and streams every recorded element to it as +//! replies carrying the Enable request's sequence number, until another +//! client disables or frees the context. +//! +//! Phase 1 records core device events (KeyPress..MotionNotify), ClientStarted +//! and ClientDied. Request, reply, error and delivered-event ranges are +//! validated, stored and reported by `GetContext`, but not recorded yet. +//! Each element goes out as its own reply; Xorg batches elements of one +//! category and client per flush, and clients must accept either. + +use std::{collections::BTreeMap, io}; + +use yserver_protocol::x11::{ + self, ClientByteOrder, ClientId, RequestHeader, SequenceNumber, + record::{self as x11rec, Range}, +}; + +use crate::{ + core_loop::{ + client_io::{self, WriteOutcome}, + process_request::{RequestOutcome, emit_x11_error_with_minor, write_to_client}, + }, + nested::{RECORD_FIRST_ERROR, RECORD_MAJOR_OPCODE}, + resources::ROOT_WINDOW, + server::ServerState, +}; + +/// Xorg `LimitClients` default: the ceiling on a request's client count. +const LIMIT_CLIENTS: u32 = 256; + +/// A set of opcodes / event types as sorted, merged, non-abutting +/// intervals — the members Xorg's bit-vector or interval-list set holds. +type Set = Vec<(u16, u16)>; + +fn make_set(mut intervals: Vec<(u16, u16)>) -> Set { + intervals.sort_by_key(|interval| interval.0); + let mut set: Set = Vec::with_capacity(intervals.len()); + for (first, last) in intervals { + match set.last_mut() { + Some(prev) if u32::from(prev.1) + 1 >= u32::from(first) => prev.1 = prev.1.max(last), + _ => set.push((first, last)), + } + } + set +} + +fn set_contains(set: &Set, member: u16) -> bool { + set.iter() + .any(|&(first, last)| (first..=last).contains(&member)) +} + +/// The set's intervals with members above `max` dropped (Xorg +/// `RecordConvertSetToRanges`' `imax`). +fn capped(set: &Set, max: u16) -> impl Iterator + '_ { + set.iter() + .take_while(move |interval| interval.0 <= max) + .map(move |&(first, last)| (first, last.min(max))) +} + +/// Minor-opcode set for one extension major-opcode interval. +#[derive(Debug)] +struct MinorSets { + major: (u8, u8), + minors: Set, +} + +/// Xorg `RecordClientsAndProtocolRec`: the clients and protocol of one +/// CreateContext / RegisterClients. +#[derive(Debug, Default)] +struct Rcap { + /// Client resource-id bases, or `FUTURE_CLIENTS`. + clients: Vec, + /// Core and extension major request opcodes. + requests: Set, + request_minors: Vec, + replies: Set, + reply_minors: Vec, + delivered_events: Set, + device_events: Set, + errors: Set, + client_started: bool, + client_died: bool, +} + +impl Rcap { + /// Xorg `RecordRegisterClients` / `RecordConvertRangesToIntervals`. + fn from_ranges(clients: Vec, ranges: &[Range]) -> Self { + fn core(ranges: &[Range], pick: impl Fn(&Range) -> (u8, u8)) -> Vec<(u16, u16)> { + ranges + .iter() + .map(pick) + .filter(|&(first, last)| first != 0 || last != 0) + .map(|(first, last)| (u16::from(first), u16::from(last))) + .collect() + } + fn ext( + ranges: &[Range], + majors: &mut Vec<(u16, u16)>, + pick: impl Fn(&Range) -> ((u8, u8), (u16, u16)), + ) -> Vec { + let mut groups: Vec = Vec::new(); + for (major, minor) in ranges.iter().map(pick) { + if major == (0, 0) { + continue; + } + majors.push((u16::from(major.0), u16::from(major.1))); + match groups.iter_mut().find(|g| g.major == major) { + Some(group) => group.minors.push(minor), + None => groups.push(MinorSets { + major, + minors: vec![minor], + }), + } + } + for group in &mut groups { + group.minors = make_set(std::mem::take(&mut group.minors)); + } + groups + } + let mut requests = core(ranges, |r| r.core_requests); + let request_minors = ext(ranges, &mut requests, |r| { + (r.ext_requests_major, r.ext_requests_minor) + }); + let mut replies = core(ranges, |r| r.core_replies); + let reply_minors = ext(ranges, &mut replies, |r| { + (r.ext_replies_major, r.ext_replies_minor) + }); + Self { + clients, + requests: make_set(requests), + request_minors, + replies: make_set(replies), + reply_minors, + delivered_events: make_set(core(ranges, |r| r.delivered_events)), + device_events: make_set(core(ranges, |r| r.device_events)), + errors: make_set(core(ranges, |r| r.errors)), + client_started: ranges.iter().any(|r| r.client_started != 0), + client_died: ranges.iter().any(|r| r.client_died != 0), + } + } + + /// The ranges GetContext reports (Xorg `ProcRecordGetContext`): each + /// kind fills slots from 0 independently, so kinds share ranges. + fn to_ranges(&self) -> Vec { + fn slot(ranges: &mut Vec, index: usize) -> &mut Range { + if ranges.len() <= index { + ranges.resize(index + 1, Range::default()); + } + &mut ranges[index] + } + #[allow(clippy::cast_possible_truncation)] + fn fill(ranges: &mut Vec, set: &Set, max: u16, put: fn(&mut Range, (u8, u8))) { + for (index, (first, last)) in capped(set, max).enumerate() { + put(slot(ranges, index), (first as u8, last as u8)); + } + } + fn fill_ext( + ranges: &mut Vec, + groups: &[MinorSets], + put: fn(&mut Range, (u8, u8), (u16, u16)), + ) { + let mut index = 0; + for group in groups { + for minor in capped(&group.minors, u16::MAX) { + put(slot(ranges, index), group.major, minor); + index += 1; + } + } + } + let mut ranges = Vec::new(); + fill(&mut ranges, &self.requests, 127, |r, v| r.core_requests = v); + fill(&mut ranges, &self.replies, 127, |r, v| r.core_replies = v); + fill(&mut ranges, &self.delivered_events, 255, |r, v| { + r.delivered_events = v; + }); + fill(&mut ranges, &self.device_events, 255, |r, v| { + r.device_events = v; + }); + fill(&mut ranges, &self.errors, 255, |r, v| r.errors = v); + fill_ext(&mut ranges, &self.request_minors, |r, major, minor| { + r.ext_requests_major = major; + r.ext_requests_minor = minor; + }); + fill_ext(&mut ranges, &self.reply_minors, |r, major, minor| { + r.ext_replies_major = major; + r.ext_replies_minor = minor; + }); + if self.client_started || self.client_died { + let first = slot(&mut ranges, 0); + first.client_started = u8::from(self.client_started); + first.client_died = u8::from(self.client_died); + } + ranges + } +} + +#[derive(Clone, Copy, Debug)] +struct Recorder { + client: ClientId, + /// The EnableContext request's sequence number; every reply of the + /// stream carries it. + sequence: SequenceNumber, +} + +#[derive(Debug)] +struct RecordContext { + owner: ClientId, + recorder: Option, + element_header: u8, + /// Index 0 is the head of Xorg's `pListOfRCAP` (newest first). + rcaps: Vec, +} + +impl RecordContext { + /// Xorg `RecordFindClientOnContext`: (rcap index, position). + fn find_client(&self, spec: u32) -> Option<(usize, usize)> { + self.rcaps.iter().enumerate().find_map(|(index, rcap)| { + rcap.clients + .iter() + .position(|c| *c == spec) + .map(|pos| (index, pos)) + }) + } + + /// Xorg `RecordDeleteClientFromContext`: the last client moves into the + /// vacated slot, and an RCAP left with no clients goes away. + fn delete_client(&mut self, spec: u32) { + if let Some((index, pos)) = self.find_client(spec) { + let rcap = &mut self.rcaps[index]; + rcap.clients.swap_remove(pos); + if rcap.clients.is_empty() { + self.rcaps.remove(index); + } + } + } +} + +/// Every RECORD context, keyed by XID. +#[derive(Debug, Default)] +pub struct RecordState { + contexts: BTreeMap, + /// Data connections whose stream write failed, awaiting disconnect. + failed: Vec, +} + +impl RecordState { + /// Owner of the live RECORD context named by `id`. + #[must_use] + pub(crate) fn owner(&self, id: u32) -> Option { + self.contexts.get(&id).map(|context| context.owner) + } + + #[must_use] + pub fn contains(&self, id: u32) -> bool { + self.contexts.contains_key(&id) + } + + pub fn ids(&self) -> impl Iterator + '_ { + self.contexts.keys().copied() + } + + #[cfg(test)] + pub(crate) fn fail_recorder_for_test(&mut self, client: ClientId) { + self.failed.push(client); + } + + #[cfg(test)] + pub(crate) fn insert_for_test(&mut self, id: u32, owner: ClientId) { + self.contexts.insert( + id, + RecordContext { + owner, + recorder: None, + element_header: 0, + rcaps: Vec::new(), + }, + ); + } +} + +/// Whether `client` is the data connection of an enabled context, whose +/// requests are not dispatched until the context is disabled. +#[must_use] +pub fn client_is_recording(state: &ServerState, client: ClientId) -> bool { + state + .record + .contexts + .values() + .any(|ctx| ctx.recorder.is_some_and(|r| r.client == client)) +} + +/// Whether `client`'s queued requests must wait: it records an enabled +/// context, or its stream write failed and it awaits disconnect (its queued +/// requests must never run). +#[must_use] +pub fn client_blocks_requests(state: &ServerState, client: ClientId) -> bool { + client_is_recording(state, client) || state.record.failed.contains(&client) +} + +/// The running client whose XID range holds `xid`: (id, base, mask). +fn owning_client(state: &ServerState, xid: u32) -> Option<(ClientId, u32, u32)> { + state + .clients + .iter() + .find(|(_, c)| (xid & !c.resource_id_mask) == c.resource_id_base) + .map(|(id, c)| (ClientId(*id), c.resource_id_base, c.resource_id_mask)) +} + +fn client_base(state: &ServerState, client: ClientId) -> Option { + state.clients.get(&client.0).map(|c| c.resource_id_base) +} + +/// An X error to send back: (code, value). +type Error = (u8, u32); + +/// Xorg `RecordSanityCheckClientSpecifiers`. `recorder` is the enabled +/// context's data connection, which may not be named. +fn check_client_specs( + state: &ServerState, + specs: &[u32], + recorder: Option, +) -> Result<(), Error> { + let recorder = recorder.and_then(|r| state.clients.get(&r.0)); + for &spec in specs { + if matches!( + spec, + x11rec::CURRENT_CLIENTS | x11rec::FUTURE_CLIENTS | x11rec::ALL_CLIENTS + ) { + continue; + } + if recorder.is_some_and(|r| (spec & !r.resource_id_mask) == r.resource_id_base) { + return Err((x11::error::BAD_MATCH, 0)); + } + match owning_client(state, spec) { + Some((_, base, _)) if spec == base => {} + Some(_) if state.xid_occupied(spec) => {} + Some(_) => return Err((x11::error::BAD_VALUE, spec)), + None => return Err((x11::error::BAD_MATCH, 0)), + } + } + Ok(()) +} + +/// Xorg `RecordCanonicalizeClientSpecifiers`: XIDs become their client's +/// base, duplicates go, and the first All/Current expands to every running +/// client but `exclude` (All adds FutureClients) and replaces the list. +fn canonicalize(state: &ServerState, specs: &[u32], exclude: Option) -> Vec { + let mut specs: Vec = specs + .iter() + .map(|&spec| { + if spec > x11rec::ALL_CLIENTS { + owning_client(state, spec).map_or(spec, |(_, base, _)| base) + } else { + spec + } + }) + .collect(); + let mut n = specs.len(); + let mut i = 0; + while i < n { + if matches!(specs[i], x11rec::ALL_CLIENTS | x11rec::CURRENT_CLIENTS) { + let mut bases: Vec = state + .clients + .values() + .map(|c| c.resource_id_base) + .filter(|base| Some(*base) != exclude) + .collect(); + // Xorg walks clients by index, i.e. by base. + bases.sort_unstable(); + if specs[i] == x11rec::ALL_CLIENTS { + bases.push(x11rec::FUTURE_CLIENTS); + } + return bases; + } + let mut j = i + 1; + while j < n { + if specs[i] == specs[j] { + specs[j] = specs[n - 1]; + n -= 1; + } else { + j += 1; + } + } + i += 1; + } + specs.truncate(n); + specs +} + +/// Xorg `RecordSanityCheckRegisterClients` for a CreateContext / +/// RegisterClients body: the client specs and ranges, or the error. +fn check_register( + state: &ServerState, + byte_order: ClientByteOrder, + body: &[u8], + head: &x11rec::RegisterHeader, + recorder: Option, +) -> Result<(Vec, Vec), Error> { + if head.n_clients > LIMIT_CLIENTS { + return Err((x11::error::BAD_VALUE, 0)); + } + let max_ranges = (i64::from(i32::MAX) - 4 * i64::from(head.n_clients)) / 24; + if i64::from(head.n_ranges) > max_ranges { + return Err((x11::error::BAD_VALUE, 0)); + } + let n_clients = head.n_clients as usize; + let n_ranges = head.n_ranges as usize; + if body.len() - x11rec::REGISTER_FIXED_BODY != 4 * n_clients + x11rec::RANGE_SIZE * n_ranges { + return Err((x11::error::BAD_LENGTH, 0)); + } + if head.element_header + & !(x11rec::FROM_SERVER_TIME | x11rec::FROM_CLIENT_TIME | x11rec::FROM_CLIENT_SEQUENCE) + != 0 + { + return Err((x11::error::BAD_VALUE, u32::from(head.element_header))); + } + let specs: Vec = (0..n_clients) + .map(|i| x11rec::read_list_u32(byte_order, body, x11rec::REGISTER_FIXED_BODY, i)) + .collect(); + check_client_specs(state, &specs, recorder)?; + let ranges_at = x11rec::REGISTER_FIXED_BODY + 4 * n_clients; + let ranges: Vec = (0..n_ranges) + .map(|i| Range::parse(byte_order, &body[ranges_at + x11rec::RANGE_SIZE * i..])) + .collect(); + for r in &ranges { + check_range(r)?; + } + Ok((specs, ranges)) +} + +/// Xorg's per-range checks, in its order; the value is the offending +/// interval's first field. +fn check_range(r: &Range) -> Result<(), Error> { + let bad = |v: u32| Err((x11::error::BAD_VALUE, v)); + let bad_major = |(first, last): (u8, u8)| { + (first != 0 || last != 0) && (first < 128 || last < 128 || first > last) + }; + let bad_event = |(first, last): (u8, u8)| { + (first != 0 || last != 0) && (first < 2 || last < 2 || first > last) + }; + if r.core_requests.0 > r.core_requests.1 { + return bad(r.core_requests.0.into()); + } + if r.core_replies.0 > r.core_replies.1 { + return bad(r.core_replies.0.into()); + } + if bad_major(r.ext_requests_major) { + return bad(r.ext_requests_major.0.into()); + } + if r.ext_requests_minor.0 > r.ext_requests_minor.1 { + return bad(r.ext_requests_minor.0.into()); + } + if bad_major(r.ext_replies_major) { + return bad(r.ext_replies_major.0.into()); + } + if r.ext_replies_minor.0 > r.ext_replies_minor.1 { + return bad(r.ext_replies_minor.0.into()); + } + if bad_event(r.delivered_events) { + return bad(r.delivered_events.0.into()); + } + if bad_event(r.device_events) { + return bad(r.device_events.0.into()); + } + if r.errors.0 > r.errors.1 { + return bad(r.errors.0.into()); + } + if r.client_started > 1 { + return bad(r.client_started.into()); + } + if r.client_died > 1 { + return bad(r.client_died.into()); + } + Ok(()) +} + +/// Xorg `SwapCreateRegister`'s length checks, which a byte-swapped client +/// hits before anything else in the request. +fn check_swapped_register_length(body: &[u8], head: &x11rec::RegisterHeader) -> Result<(), Error> { + let words = ((body.len() + 4) / 4) as u64; + let avail = words.saturating_sub(5); + if u64::from(head.n_clients) > avail + || u64::from(head.n_ranges) > (avail - u64::from(head.n_clients)) / 6 + { + return Err((x11::error::BAD_LENGTH, 0)); + } + Ok(()) +} + +/// Xorg `RecordRegisterClients` after its sanity checks. +fn register_clients( + state: &mut ServerState, + context: u32, + element_header: u8, + specs: &[u32], + ranges: &[Range], +) { + let exclude = state.record.contexts[&context] + .recorder + .and_then(|r| client_base(state, r.client)); + let canon = if specs.is_empty() { + Vec::new() + } else { + canonicalize(state, specs, exclude) + }; + let ctx = state + .record + .contexts + .get_mut(&context) + .expect("context exists"); + ctx.element_header = element_header; + if specs.is_empty() { + return; + } + for &spec in &canon { + ctx.delete_client(spec); + } + ctx.rcaps.insert(0, Rcap::from_ranges(canon, ranges)); +} + +/// Send one reply to a context's data connection. A recorder whose write +/// fails (peer gone, or `OUTBOUND_CAP` reached) stops recording at once, as +/// its stream can no longer be whole, and is queued for the core loop to +/// disconnect (`take_failed_recorders`): this can run inside another +/// client's disconnect, so it never disconnects inline. +fn send_to_recorder(state: &mut ServerState, recorder: ClientId, bytes: &[u8]) { + if state.record.failed.contains(&recorder) { + return; + } + let Some(client) = state.clients.get_mut(&recorder.0) else { + return; + }; + crate::core_loop::fanout::record_outbound_telemetry(recorder, client.byte_order, bytes); + if matches!( + client_io::write_or_buffer(client, bytes), + Ok(WriteOutcome::Done | WriteOutcome::WouldBlock) + ) { + return; + } + log::warn!( + "record: data connection {} cannot take its stream; disconnecting it", + recorder.0 + ); + for ctx in state.record.contexts.values_mut() { + if ctx.recorder.is_some_and(|r| r.client == recorder) { + ctx.recorder = None; + } + } + state.record.failed.push(recorder); +} + +/// RECORD data connections whose stream write failed, for the core loop to +/// disconnect. +pub(crate) fn take_failed_recorders(state: &mut ServerState) -> Vec { + std::mem::take(&mut state.record.failed) +} + +/// Recording client's byte order, if it is still connected. +fn recorder_order(state: &ServerState, recorder: Recorder) -> Option { + state.clients.get(&recorder.client.0).map(|c| c.byte_order) +} + +/// A StartOfData / EndOfData reply (no client, no data). +fn send_marker(state: &mut ServerState, recorder: Recorder, element_header: u8, category: u8) { + let Some(order) = recorder_order(state, recorder) else { + return; + }; + let reply = x11rec::encode_enable_context_header( + order, + recorder.sequence, + category, + 0, + element_header, + order == ClientByteOrder::BigEndian, + 0, + state.timestamp_now(), + 0, + ); + send_to_recorder(state, recorder.client, &reply); +} + +/// Xorg `RecordDisableContext`: EndOfData unless `recorder_gone`, and the +/// data connection's requests run again. +fn disable_context(state: &mut ServerState, context: u32, recorder_gone: bool) { + let Some(ctx) = state.record.contexts.get_mut(&context) else { + return; + }; + let Some(recorder) = ctx.recorder.take() else { + return; + }; + let element_header = ctx.element_header; + log::debug!( + "record: context 0x{context:x} disabled, client {} resumes", + recorder.client.0 + ); + if !recorder_gone { + send_marker(state, recorder, element_header, x11rec::END_OF_DATA); + } +} + +/// Xorg `RecordDeleteContext`. +fn free_context(state: &mut ServerState, context: u32) { + disable_context(state, context, false); + state.record.contexts.remove(&context); +} + +pub(crate) fn handle_record_request( + state: &mut ServerState, + client_id: ClientId, + sequence: SequenceNumber, + header: RequestHeader, + body: &[u8], +) -> io::Result { + let minor = header.data; + let Some(byte_order) = state.clients.get(&client_id.0).map(|c| c.byte_order) else { + return Ok(RequestOutcome::Handled); + }; + let error = |state: &mut ServerState, (code, value): Error| { + emit_x11_error_with_minor( + state, + client_id, + sequence, + code, + value, + u16::from(minor), + RECORD_MAJOR_OPCODE, + ) + }; + let bad_context = |state: &mut ServerState, id: u32| { + error(state, (RECORD_FIRST_ERROR + x11rec::BAD_CONTEXT, id)) + }; + let exact = |len: usize| body.len() == len; + match minor { + x11rec::QUERY_VERSION => { + if !exact(4) { + return error(state, (x11::error::BAD_LENGTH, 0)); + } + let reply = x11rec::encode_query_version_reply(byte_order, sequence); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &reply)) + } + x11rec::CREATE_CONTEXT | x11rec::REGISTER_CLIENTS => { + let Some(head) = x11rec::parse_register_header(byte_order, body) else { + return error(state, (x11::error::BAD_LENGTH, 0)); + }; + if byte_order == ClientByteOrder::BigEndian + && let Err(err) = check_swapped_register_length(body, &head) + { + return error(state, err); + } + let recorder = if minor == x11rec::CREATE_CONTEXT { + let base = client_base(state, client_id).unwrap_or(0); + let mask = state + .clients + .get(&client_id.0) + .map_or(0, |c| c.resource_id_mask); + if (head.context & !mask) != base || state.xid_occupied(head.context) { + return error(state, (x11::error::BAD_ID_CHOICE, head.context)); + } + None + } else { + let Some(ctx) = state.record.contexts.get(&head.context) else { + return bad_context(state, head.context); + }; + ctx.recorder.map(|r| r.client) + }; + let (specs, ranges) = match check_register(state, byte_order, body, &head, recorder) { + Ok(parsed) => parsed, + Err(err) => return error(state, err), + }; + if minor == x11rec::CREATE_CONTEXT { + state.record.contexts.insert( + head.context, + RecordContext { + owner: client_id, + recorder: None, + element_header: 0, + rcaps: Vec::new(), + }, + ); + } + register_clients(state, head.context, head.element_header, &specs, &ranges); + log::debug!( + "client {} #{} RECORD {} context 0x{:x} clients={specs:x?} ranges={}", + client_id.0, + sequence.0, + if minor == x11rec::CREATE_CONTEXT { + "CreateContext" + } else { + "RegisterClients" + }, + head.context, + ranges.len(), + ); + Ok(RequestOutcome::Handled) + } + x11rec::UNREGISTER_CLIENTS => { + if body.len() < x11rec::UNREGISTER_FIXED_BODY { + return error(state, (x11::error::BAD_LENGTH, 0)); + } + let context = x11rec::read_body_u32(byte_order, body, 0); + let n_clients = x11rec::read_body_u32(byte_order, body, 4); + if u64::from(n_clients) * 4 != (body.len() - x11rec::UNREGISTER_FIXED_BODY) as u64 { + return error(state, (x11::error::BAD_LENGTH, 0)); + } + if !state.record.contains(context) { + return bad_context(state, context); + } + let specs: Vec = (0..n_clients as usize) + .map(|i| x11rec::read_list_u32(byte_order, body, x11rec::UNREGISTER_FIXED_BODY, i)) + .collect(); + if let Err(err) = check_client_specs(state, &specs, None) { + return error(state, err); + } + let canon = canonicalize(state, &specs, None); + let ctx = state + .record + .contexts + .get_mut(&context) + .expect("context exists"); + for spec in canon { + ctx.delete_client(spec); + } + Ok(RequestOutcome::Handled) + } + x11rec::GET_CONTEXT => { + if !exact(4) { + return error(state, (x11::error::BAD_LENGTH, 0)); + } + let context = x11rec::read_body_u32(byte_order, body, 0); + let Some(ctx) = state.record.contexts.get(&context) else { + return bad_context(state, context); + }; + let per_rcap: Vec<(&Rcap, Vec)> = + ctx.rcaps.iter().map(|r| (r, r.to_ranges())).collect(); + let infos: Vec<(u32, &[Range])> = per_rcap + .iter() + .flat_map(|(rcap, ranges)| { + rcap.clients + .iter() + .map(move |client| (*client, ranges.as_slice())) + }) + .collect(); + let reply = x11rec::encode_get_context_reply( + byte_order, + sequence, + ctx.recorder.is_some(), + ctx.element_header, + &infos, + ); + let Some(client) = state.clients.get_mut(&client_id.0) else { + return Ok(RequestOutcome::Handled); + }; + Ok(write_to_client(client, client_id, &reply)) + } + x11rec::ENABLE_CONTEXT => { + if !exact(4) { + return error(state, (x11::error::BAD_LENGTH, 0)); + } + let context = x11rec::read_body_u32(byte_order, body, 0); + let Some(ctx) = state.record.contexts.get(&context) else { + return bad_context(state, context); + }; + if ctx.recorder.is_some() { + return error(state, (x11::error::BAD_MATCH, 0)); + } + let base = client_base(state, client_id).unwrap_or(0); + let recorder = Recorder { + client: client_id, + sequence, + }; + let ctx = state + .record + .contexts + .get_mut(&context) + .expect("context exists"); + ctx.recorder = Some(recorder); + // The data connection never records itself. + ctx.delete_client(base); + let element_header = ctx.element_header; + log::debug!( + "client {} #{} RECORD EnableContext 0x{context:x}: requests suspended", + client_id.0, + sequence.0, + ); + send_marker(state, recorder, element_header, x11rec::START_OF_DATA); + Ok(RequestOutcome::Handled) + } + x11rec::DISABLE_CONTEXT | x11rec::FREE_CONTEXT => { + if !exact(4) { + return error(state, (x11::error::BAD_LENGTH, 0)); + } + let context = x11rec::read_body_u32(byte_order, body, 0); + if !state.record.contains(context) { + return bad_context(state, context); + } + if minor == x11rec::DISABLE_CONTEXT { + disable_context(state, context, false); + } else { + free_context(state, context); + } + Ok(RequestOutcome::Handled) + } + other => { + log::debug!("client {} RECORD minor {other} -> BadRequest", client_id.0); + error(state, (x11::error::BAD_REQUEST, 0)) + } + } +} + +/// A core device event as the RECORD device-event hook sees it: the event +/// as clients get it, before grabs and delivery. +#[derive(Clone, Copy, Debug)] +pub struct RecordedDeviceEvent { + /// Core event code, KeyPress (2) through MotionNotify (6). + pub event_type: u8, + pub detail: u8, + /// A server-generated autorepeat press. + pub repeat: bool, + pub time: u32, + pub root_x: i16, + pub root_y: i16, + /// Key/button state before the event. + pub state: u16, +} + +/// Xorg `RecordADeviceEvent` for a master-device core event: every enabled +/// context's every RCAP whose device-event set holds the type records it, +/// whichever client caused it. +pub fn record_device_event(state: &mut ServerState, event: RecordedDeviceEvent) { + let mut targets: Vec<(Recorder, u8)> = Vec::new(); + for ctx in state.record.contexts.values() { + let Some(recorder) = ctx.recorder else { + continue; + }; + for rcap in &ctx.rcaps { + if set_contains(&rcap.device_events, u16::from(event.event_type)) { + targets.push((recorder, ctx.element_header)); + } + } + } + for (recorder, element_header) in targets { + let Some(order) = recorder_order(state, recorder) else { + continue; + }; + let now = state.timestamp_now(); + let mut data = Vec::with_capacity(36); + if element_header & x11rec::FROM_SERVER_TIME != 0 { + x11::write_u32(order, &mut data, now); + } + // Xorg records a root window only for motion (exevents.c). + let root = if event.event_type == 6 { + ROOT_WINDOW.0 + } else { + 0 + }; + data.extend_from_slice(&x11rec::encode_core_device_event( + order, + event.event_type, + event.detail, + event.repeat, + event.time, + root, + event.root_x, + event.root_y, + event.state, + )); + let mut reply = x11rec::encode_enable_context_header( + order, + recorder.sequence, + x11rec::FROM_SERVER, + u32::try_from(data.len() / 4).unwrap_or(0), + element_header, + false, + 0, + now, + 0, + ); + reply.extend_from_slice(&data); + send_to_recorder(state, recorder.client, &reply); + } +} + +/// Xorg's ClientStateRunning callback: every context holding FutureClients +/// registers the new client on that RCAP; enabled ones whose RCAP selects +/// clientStarted record the setup reply the client received. +pub(crate) fn client_started(state: &mut ServerState, client: ClientId, setup_reply: &[u8]) { + let Some((base, order)) = state + .clients + .get(&client.0) + .map(|c| (c.resource_id_base, c.byte_order)) + else { + return; + }; + let mut announce: Vec<(Recorder, u8)> = Vec::new(); + for ctx in state.record.contexts.values_mut() { + let Some((index, _)) = ctx.find_client(x11rec::FUTURE_CLIENTS) else { + continue; + }; + let rcap = &mut ctx.rcaps[index]; + rcap.clients.push(base); + if let Some(recorder) = ctx.recorder + && rcap.client_started + { + announce.push((recorder, ctx.element_header)); + } + } + for (recorder, element_header) in announce { + let Some(recorder_order) = recorder_order(state, recorder) else { + continue; + }; + let mut reply = x11rec::encode_enable_context_header( + recorder_order, + recorder.sequence, + x11rec::CLIENT_STARTED, + u32::try_from(setup_reply.len() / 4).unwrap_or(0), + element_header, + order != recorder_order, + base, + state.timestamp_now(), + 0, + ); + reply.extend_from_slice(setup_reply); + send_to_recorder(state, recorder.client, &reply); + } +} + +/// Xorg's ClientStateGone callback followed by the client's resource +/// teardown: contexts it was recording stop without EndOfData, it leaves +/// every context (ClientDied where selected), and contexts it created are +/// freed. Runs while the client is still in `state.clients`. +pub(crate) fn client_disconnected(state: &mut ServerState, client: ClientId) { + state.record.failed.retain(|c| *c != client); + if state.record.contexts.is_empty() { + return; + } + let Some((base, order, last_sequence)) = state.clients.get(&client.0).map(|c| { + ( + c.resource_id_base, + c.byte_order, + c.last_sequence.load(std::sync::atomic::Ordering::Relaxed), + ) + }) else { + return; + }; + let ids: Vec = state.record.ids().collect(); + for &id in &ids { + if state.record.contexts[&id] + .recorder + .is_some_and(|r| r.client == client) + { + disable_context(state, id, true); + } + let ctx = state.record.contexts.get_mut(&id).expect("context exists"); + let Some((index, _)) = ctx.find_client(base) else { + continue; + }; + let died = ctx.recorder.filter(|_| ctx.rcaps[index].client_died); + let element_header = ctx.element_header; + ctx.delete_client(base); + if let Some(recorder) = died + && let Some(recorder_order) = recorder_order(state, recorder) + { + let mut data = Vec::new(); + if element_header & x11rec::FROM_CLIENT_SEQUENCE != 0 { + x11::write_u32(recorder_order, &mut data, u32::from(last_sequence)); + } + let mut reply = x11rec::encode_enable_context_header( + recorder_order, + recorder.sequence, + x11rec::CLIENT_DIED, + u32::try_from(data.len() / 4).unwrap_or(0), + element_header, + order != recorder_order, + base, + state.timestamp_now(), + u32::from(last_sequence), + ); + reply.extend_from_slice(&data); + send_to_recorder(state, recorder.client, &reply); + } + } + for id in ids { + if state + .record + .contexts + .get(&id) + .is_some_and(|ctx| ctx.owner == client) + { + free_context(state, id); + } + } +} + +/// Goldens are Xvfb 21.1.24 captures from `tools/record-probe.c`, run with +/// `RECORD_PROBE_HEX=1` (raw bytes) or decoded; the scenario is named on +/// each test. Clients get Xvfb's resource bases (0x200000, 0x400000, +/// 0x600000, mask 0x1fffff) so ids compare byte for byte. Differences that +/// are not ours to match: Xvfb's major opcode 146 and first error 154 +/// (yserver 154 / 189), its root window 0x39f, the uninitialised pad bytes +/// of its EnableContext replies (zero here), and its batching of several +/// FromServer elements into one reply (one reply per element here). +#[cfg(test)] +mod tests { + use std::{ + collections::{HashMap, HashSet, VecDeque}, + io::Read, + os::unix::net::UnixStream, + sync::{ + Arc, Mutex, + atomic::{AtomicU16, Ordering}, + }, + }; + + use yserver_protocol::x11::ClientByteOrder::{BigEndian, LittleEndian}; + + use super::*; + use crate::{ + backend::recording::RecordingBackend, core_loop::process_request::process_request, + server::ClientState, + }; + + const REC: u32 = 1; + const CTL: u32 = 2; + const C3: u32 = 3; + const REC_BASE: u32 = 0x0020_0000; + const CTL_BASE: u32 = 0x0040_0000; + const C3_BASE: u32 = 0x0060_0000; + const MASK: u32 = 0x001F_FFFF; + const BAD_CONTEXT: u8 = RECORD_FIRST_ERROR; + + fn install(state: &mut ServerState, id: u32, base: u32, order: ClientByteOrder) -> UnixStream { + let (a, b) = UnixStream::pair().unwrap(); + b.set_nonblocking(true).unwrap(); + state.clients.insert( + id, + ClientState { + admission: crate::access::Admission::Internal, + writer: Arc::new(Mutex::new(crate::transport::Transport::Unix(a))), + byte_order: order, + last_sequence: Arc::new(AtomicU16::new(0)), + resource_id_base: base, + resource_id_mask: MASK, + event_masks: HashMap::new(), + save_set: HashSet::new(), + big_requests_enabled: false, + xi2_masks: HashMap::new(), + xi1_event_classes: HashSet::new(), + xi1_window_event_classes: HashMap::new(), + outbound: VecDeque::new(), + outbound_fds: Default::default(), + watching_writable: false, + write_failed: false, + gone: false, + focused_window: ROOT_WINDOW, + reader_control: None, + is_local: true, + fd_passing: true, + internal: false, + peer: crate::peer::PeerIdentity::unknown_unix(), + }, + ); + b + } + + fn read_all(peer: &mut UnixStream) -> Vec { + let mut out = Vec::new(); + let mut buf = [0u8; 4096]; + while let Ok(n) = peer.read(&mut buf) { + if n == 0 { + break; + } + out.extend_from_slice(&buf[..n]); + } + out + } + + fn send(state: &mut ServerState, client: u32, seq: u16, minor: u8, body: &[u8]) { + process_request( + state, + &mut RecordingBackend::new(), + ClientId(client), + SequenceNumber(seq), + RequestHeader { + opcode: RECORD_MAJOR_OPCODE, + data: minor, + length_units: u32::try_from(1 + body.len() / 4).unwrap(), + }, + body, + None, + ) + .expect("RECORD request"); + } + + fn order_of(state: &ServerState, client: u32) -> ClientByteOrder { + state.clients[&client].byte_order + } + + fn put32(order: ClientByteOrder, out: &mut Vec, v: u32) { + x11::write_u32(order, out, v); + } + + fn register_body( + order: ClientByteOrder, + ctx: u32, + ehdr: u8, + specs: &[u32], + ranges: &[Range], + ) -> Vec { + let mut out = Vec::new(); + put32(order, &mut out, ctx); + out.extend_from_slice(&[ehdr, 0, 0, 0]); + put32(order, &mut out, u32::try_from(specs.len()).unwrap()); + put32(order, &mut out, u32::try_from(ranges.len()).unwrap()); + for spec in specs { + put32(order, &mut out, *spec); + } + for range in ranges { + range.encode(order, &mut out); + } + out + } + + fn words(order: ClientByteOrder, values: &[u32]) -> Vec { + let mut out = Vec::new(); + for v in values { + put32(order, &mut out, *v); + } + out + } + + fn create( + state: &mut ServerState, + client: u32, + seq: u16, + ctx: u32, + ehdr: u8, + specs: &[u32], + ranges: &[Range], + ) { + let body = register_body(order_of(state, client), ctx, ehdr, specs, ranges); + send(state, client, seq, x11rec::CREATE_CONTEXT, &body); + } + + fn ctx_request(state: &mut ServerState, client: u32, seq: u16, minor: u8, ctx: u32) { + let body = words(order_of(state, client), &[ctx]); + send(state, client, seq, minor, &body); + } + + /// "01000300 1c000000 …" as bytes. + fn hex(s: &str) -> Vec { + let digits: Vec = s.bytes().filter(u8::is_ascii_hexdigit).collect(); + digits + .chunks(2) + .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()) + .collect() + } + + /// Split a byte stream into X replies / errors. + fn packets(order: ClientByteOrder, bytes: &[u8]) -> Vec> { + let mut out = Vec::new(); + let mut at = 0; + while at < bytes.len() { + let extra = if bytes[at] == 1 { + 4 * x11::read_u32(order, &bytes[at + 4..at + 8]) as usize + } else { + 0 + }; + out.push(bytes[at..at + 32 + extra].to_vec()); + at += 32 + extra; + } + out + } + + /// (code, value, minor) of an error packet, checking it is RECORD's. + fn error_of(order: ClientByteOrder, packet: &[u8]) -> (u8, u32, u16) { + assert_eq!(packet[0], 0, "expected an error, got {packet:02x?}"); + assert_eq!(packet[10], RECORD_MAJOR_OPCODE); + let minor = match order { + LittleEndian => u16::from_le_bytes([packet[8], packet[9]]), + BigEndian => u16::from_be_bytes([packet[8], packet[9]]), + }; + (packet[1], x11::read_u32(order, &packet[4..8]), minor) + } + + type ErrorCase = (&'static str, u8, Vec, u8, Option); + + fn check_errors( + state: &mut ServerState, + rec: &mut UnixStream, + order: ClientByteOrder, + seq: &mut u16, + cases: Vec, + ) { + for (name, minor, body, code, value) in cases { + *seq += 1; + send(state, REC, *seq, minor, &body); + let got = read_all(rec); + assert_eq!(got.len(), 32, "{order:?} {name}: one error"); + let (got_code, got_value, got_minor) = error_of(order, &got); + assert_eq!(got_code, code, "{order:?} {name}"); + assert_eq!(got_minor, u16::from(minor), "{order:?} {name}"); + if let Some(value) = value { + assert_eq!(got_value, value, "{order:?} {name}"); + } + } + } + + /// Client resources a GetContext reply lists, in order. + fn get_context_clients(order: ClientByteOrder, reply: &[u8]) -> Vec { + let n = x11::read_u32(order, &reply[12..16]) as usize; + let mut at = 32; + let mut out = Vec::new(); + for _ in 0..n { + out.push(x11::read_u32(order, &reply[at..at + 4])); + let ranges = x11::read_u32(order, &reply[at + 4..at + 8]) as usize; + at += 8 + 24 * ranges; + } + out + } + + /// Patch the time words of an expected EnableContext reply from the + /// reply actually sent: header `server_time` and every word listed. + fn with_times(mut expected: Vec, got: &[u8], word_offsets: &[usize]) -> Vec { + for &at in [16].iter().chain(word_offsets) { + expected[at..at + 4].copy_from_slice(&got[at..at + 4]); + } + expected + } + + fn device_range() -> Range { + Range { + device_events: (2, 6), + client_started: 1, + client_died: 1, + ..Range::default() + } + } + + /// `record-probe ranges l`: kinds share range slots, abutting intervals + /// merge, core request/reply columns stop at 127, extension minors are + /// grouped per major interval, and a duplicate client spec is dropped. + #[test] + fn get_context_merges_ranges_like_xorg() { + let mut state = ServerState::new(); + let mut rec = install(&mut state, REC, REC_BASE, LittleEndian); + let _ctl = install(&mut state, CTL, CTL_BASE, LittleEndian); + let ranges = [ + Range { + core_requests: (10, 20), + core_replies: (5, 5), + ext_requests_major: (150, 150), + ext_requests_minor: (3, 7), + device_events: (2, 3), + errors: (1, 4), + client_started: 1, + ..Range::default() + }, + Range { + core_requests: (21, 30), + ext_requests_major: (150, 150), + ext_requests_minor: (8, 9), + delivered_events: (12, 14), + device_events: (5, 6), + client_died: 1, + ..Range::default() + }, + Range { + core_requests: (100, 200), + core_replies: (1, 2), + ext_requests_major: (160, 170), + ext_replies_major: (140, 141), + ext_replies_minor: (1, 2), + ..Range::default() + }, + ]; + let ctx = REC_BASE + 1; + create( + &mut state, + REC, + 2, + ctx, + 0, + &[CTL_BASE, CTL_BASE, 2], + &ranges, + ); + ctx_request(&mut state, REC, 3, x11rec::GET_CONTEXT, ctx); + let rcap1 = "0a1e0102 96960300 09008c8d 01000200 0c0e0203 01040101 \ + 647f0505 a0aa0000 00000000 00000000 00000506 00000000"; + assert_eq!( + read_all(&mut rec), + hex(&format!( + "01000300 1c000000 00000000 02000000 00000000 00000000 00000000 00000000 \ + 00004000 02000000 {rcap1} 02000000 02000000 {rcap1}" + )) + ); + + // The context's own XID names its owner; the new RCAP goes first. + let dev4 = Range { + device_events: (4, 4), + ..Range::default() + }; + let body = register_body(LittleEndian, ctx, 1, &[ctx], &[dev4]); + send(&mut state, REC, 4, x11rec::REGISTER_CLIENTS, &body); + ctx_request(&mut state, REC, 5, x11rec::GET_CONTEXT, ctx); + let rcap2 = "00002000 01000000 00000000 00000000 00000000 00000000 00000404 00000000"; + assert_eq!( + read_all(&mut rec), + hex(&format!( + "01000500 24000000 01000000 03000000 00000000 00000000 00000000 00000000 \ + {rcap2} 00004000 02000000 {rcap1} 02000000 02000000 {rcap1}" + )) + ); + + // No clients: only the element header changes. + let body = register_body(LittleEndian, ctx, 5, &[], &[dev4]); + send(&mut state, REC, 6, x11rec::REGISTER_CLIENTS, &body); + ctx_request(&mut state, REC, 7, x11rec::GET_CONTEXT, ctx); + assert_eq!( + read_all(&mut rec), + hex(&format!( + "01000700 24000000 05000000 03000000 00000000 00000000 00000000 00000000 \ + {rcap2} 00004000 02000000 {rcap1} 02000000 02000000 {rcap1}" + )) + ); + + let unregister = |state: &mut ServerState, seq, spec| { + send( + state, + REC, + seq, + x11rec::UNREGISTER_CLIENTS, + &words(LittleEndian, &[ctx, 1, spec]), + ); + }; + unregister(&mut state, 8, x11rec::FUTURE_CLIENTS); + ctx_request(&mut state, REC, 9, x11rec::GET_CONTEXT, ctx); + let reply = read_all(&mut rec); + assert_eq!( + get_context_clients(LittleEndian, &reply), + [REC_BASE, CTL_BASE] + ); + // CurrentClients expands to every running client; emptied RCAPs go. + unregister(&mut state, 10, x11rec::CURRENT_CLIENTS); + ctx_request(&mut state, REC, 11, x11rec::GET_CONTEXT, ctx); + assert_eq!( + read_all(&mut rec), + hex("01000b00 00000000 05000000 00000000 00000000 00000000 00000000 00000000") + ); + + // AllClients replaces the whole spec list with its expansion. + let body = register_body( + LittleEndian, + ctx, + 0, + &[CTL_BASE, x11rec::ALL_CLIENTS, REC_BASE], + &[device_range()], + ); + send(&mut state, REC, 12, x11rec::REGISTER_CLIENTS, &body); + ctx_request(&mut state, REC, 13, x11rec::GET_CONTEXT, ctx); + let reply = read_all(&mut rec); + assert_eq!( + get_context_clients(LittleEndian, &reply), + [REC_BASE, CTL_BASE, x11rec::FUTURE_CLIENTS] + ); + + let ctx2 = REC_BASE + 2; + create( + &mut state, + REC, + 14, + ctx2, + 0, + &[x11rec::CURRENT_CLIENTS], + &[dev4], + ); + ctx_request(&mut state, REC, 15, x11rec::GET_CONTEXT, ctx2); + let reply = read_all(&mut rec); + assert_eq!( + get_context_clients(LittleEndian, &reply), + [REC_BASE, CTL_BASE] + ); + crate::core_loop::process_disconnect::process_disconnect( + &mut state, + &mut RecordingBackend::new(), + ClientId(CTL), + ); + ctx_request(&mut state, REC, 16, x11rec::GET_CONTEXT, ctx2); + let reply = read_all(&mut rec); + assert_eq!(get_context_clients(LittleEndian, &reply), [REC_BASE]); + } + + /// `record-probe errors l` and `errors B`. `None` marks an error value + /// Xorg leaves stale (not set by the failing check). + #[test] + fn request_errors_match_xvfb() { + for order in [LittleEndian, BigEndian] { + let mut state = ServerState::new(); + let mut rec = install(&mut state, REC, REC_BASE, order); + let _ctl = install(&mut state, CTL, CTL_BASE, LittleEndian); + state.resources.create_cursor( + ClientId(CTL), + yserver_protocol::x11::ResourceId(CTL_BASE + 1), + ); + let ctx = REC_BASE + 1; + let bogus = REC_BASE + 0x32; + let all = [x11rec::ALL_CLIENTS]; + let reg = |ctx: u32, ehdr: u8, specs: &[u32], ranges: &[Range]| { + register_body(order, ctx, ehdr, specs, ranges) + }; + let raw = |n_clients: u32, extra: usize| { + let mut body = words(order, &[ctx, 0, n_clients, 0]); + body.resize(16 + extra, 0); + body + }; + let big = order == BigEndian; + let range = |r: Range| reg(ctx, 0, &all, &[r]); + let cases: Vec = vec![ + ("short", 1, vec![0; 12], x11::error::BAD_LENGTH, None), + ( + "foreign id", + 1, + reg(CTL_BASE + 1, 0, &all, &[device_range()]), + x11::error::BAD_ID_CHOICE, + Some(CTL_BASE + 1), + ), + ( + "foreign id + ehdr 8", + 1, + reg(CTL_BASE + 1, 8, &all, &[device_range()]), + x11::error::BAD_ID_CHOICE, + Some(CTL_BASE + 1), + ), + // Swapped clients fail SwapCreateRegister's length check first. + ( + "nClients=1000", + 1, + raw(1000, 0), + if big { + x11::error::BAD_LENGTH + } else { + x11::error::BAD_VALUE + }, + None, + ), + ( + "nClients=300", + 1, + raw(300, 4), + if big { + x11::error::BAD_LENGTH + } else { + x11::error::BAD_VALUE + }, + None, + ), + ( + "length mismatch", + 1, + { + let mut b = raw(1, 4); + b.extend_from_slice(&[0; 4]); + b + }, + x11::error::BAD_LENGTH, + None, + ), + ( + "ehdr 8", + 1, + reg(ctx, 8, &all, &[device_range()]), + x11::error::BAD_VALUE, + Some(8), + ), + ( + "spec 4", + 1, + reg(ctx, 0, &[4], &[device_range()]), + x11::error::BAD_MATCH, + None, + ), + ( + "spec root", + 1, + reg(ctx, 0, &[ROOT_WINDOW.0], &[device_range()]), + x11::error::BAD_MATCH, + None, + ), + ( + "spec ctl+77", + 1, + reg(ctx, 0, &[CTL_BASE + 0x77], &[device_range()]), + x11::error::BAD_VALUE, + Some(CTL_BASE + 0x77), + ), + ( + "spec 0x1ff00000", + 1, + reg(ctx, 0, &[0x1ff0_0000], &[device_range()]), + x11::error::BAD_MATCH, + None, + ), + ( + "spec rec+5", + 1, + reg(ctx, 0, &[REC_BASE + 5], &[device_range()]), + x11::error::BAD_VALUE, + Some(REC_BASE + 5), + ), + ( + "core req 5-4", + 1, + range(Range { + core_requests: (5, 4), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(5), + ), + ( + "core rep 9-8", + 1, + range(Range { + core_replies: (9, 8), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(9), + ), + ( + "ext req 100-100", + 1, + range(Range { + ext_requests_major: (100, 100), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(100), + ), + ( + "ext req 200-150", + 1, + range(Range { + ext_requests_major: (200, 150), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(200), + ), + ( + "ext req minor 3-2", + 1, + range(Range { + ext_requests_minor: (3, 2), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(3), + ), + ( + "ext rep 128-127", + 1, + range(Range { + ext_replies_major: (128, 127), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(128), + ), + ( + "ext rep minor 7-1", + 1, + range(Range { + ext_replies_minor: (7, 1), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(7), + ), + ( + "delivered 2-1", + 1, + range(Range { + delivered_events: (2, 1), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(2), + ), + ( + "delivered 0-5", + 1, + range(Range { + delivered_events: (0, 5), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(0), + ), + ( + "device 1-6", + 1, + range(Range { + device_events: (1, 6), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(1), + ), + ( + "errors 9-3", + 1, + range(Range { + errors: (9, 3), + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(9), + ), + ( + "clientStarted 2", + 1, + range(Range { + client_started: 2, + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(2), + ), + ( + "clientDied 7", + 1, + range(Range { + client_died: 7, + ..Range::default() + }), + x11::error::BAD_VALUE, + Some(7), + ), + ( + "register bogus", + 2, + reg(bogus, 0, &all, &[device_range()]), + BAD_CONTEXT, + Some(bogus), + ), + ( + "unregister bogus", + 3, + words(order, &[bogus, 1, 3]), + BAD_CONTEXT, + Some(bogus), + ), + ( + "get length 3", + 4, + words(order, &[ctx, 0]), + x11::error::BAD_LENGTH, + None, + ), + ( + "query length 1", + 0, + Vec::new(), + x11::error::BAD_LENGTH, + None, + ), + ( + "enable length 1", + 5, + Vec::new(), + x11::error::BAD_LENGTH, + None, + ), + ( + "enable bogus", + 5, + words(order, &[bogus]), + BAD_CONTEXT, + Some(bogus), + ), + ( + "disable bogus", + 6, + words(order, &[bogus]), + BAD_CONTEXT, + Some(bogus), + ), + ( + "free bogus", + 7, + words(order, &[bogus]), + BAD_CONTEXT, + Some(bogus), + ), + ("minor 9", 9, Vec::new(), x11::error::BAD_REQUEST, None), + ]; + // After a successful create: a duplicate id and Unregister checks. + let after: Vec = vec![ + ( + "dup id", + 1, + reg(ctx, 0, &all, &[device_range()]), + x11::error::BAD_ID_CHOICE, + Some(ctx), + ), + ( + "unregister length", + 3, + words(order, &[ctx, 2, 3]), + x11::error::BAD_LENGTH, + None, + ), + ( + "unregister spec 4", + 3, + words(order, &[ctx, 1, 4]), + x11::error::BAD_MATCH, + None, + ), + ( + "unregister ctl+77", + 3, + words(order, &[ctx, 1, CTL_BASE + 0x77]), + x11::error::BAD_VALUE, + Some(CTL_BASE + 0x77), + ), + ]; + let mut seq = 1; + check_errors(&mut state, &mut rec, order, &mut seq, cases); + // A spec naming an existing resource of a running client is fine. + send( + &mut state, + REC, + 100, + 1, + ®(ctx, 0, &[CTL_BASE + 1], &[device_range()]), + ); + send( + &mut state, + REC, + 101, + x11rec::FREE_CONTEXT, + &words(order, &[ctx]), + ); + send( + &mut state, + REC, + 102, + 1, + ®(ctx, 0, &all, &[device_range()]), + ); + assert!(read_all(&mut rec).is_empty(), "{order:?}: valid requests"); + let mut seq = 102; + check_errors(&mut state, &mut rec, order, &mut seq, after); + } + } + + /// `record-probe basic B 7`: a big-endian recorder with every element + /// header, a little-endian control client and a little-endian client + /// that connects and leaves while recording. + #[test] + fn stream_to_byte_swapped_recorder_matches_xvfb() { + let mut state = ServerState::new(); + let mut rec = install(&mut state, REC, REC_BASE, BigEndian); + let ctx = REC_BASE + 1; + create( + &mut state, + REC, + 3, + ctx, + 7, + &[x11rec::ALL_CLIENTS], + &[device_range()], + ); + let mut ctl = install(&mut state, CTL, CTL_BASE, LittleEndian); + client_started(&mut state, ClientId(CTL), &[]); + ctx_request(&mut state, REC, 6, x11rec::ENABLE_CONTEXT, ctx); + assert!(client_is_recording(&state, ClientId(REC))); + let got = read_all(&mut rec); + assert_eq!( + got, + with_times( + hex("01040006 00000000 07010000 00000000 00000000 00000000 00000000 00000000"), + &got, + &[] + ) + ); + + // ctl sees the recorder gone from the context, FutureClients moved + // into its slot (swap-remove). + let range = "00000000 00000000 00000000 00000000 00000206 00000101"; + ctx_request(&mut state, CTL, 3, x11rec::GET_CONTEXT, ctx); + assert_eq!( + read_all(&mut ctl), + hex(&format!( + "01010300 10000000 07000000 02000000 00000000 00000000 00000000 00000000 \ + 00004000 01000000 {range} 02000000 01000000 {range}" + )) + ); + ctx_request(&mut state, CTL, 4, x11rec::ENABLE_CONTEXT, ctx); + let body = register_body(LittleEndian, ctx, 0, &[REC_BASE], &[Range::default()]); + send(&mut state, CTL, 5, x11rec::REGISTER_CLIENTS, &body); + let errors = packets(LittleEndian, &read_all(&mut ctl)); + assert_eq!(errors.len(), 2); + assert_eq!(error_of(LittleEndian, &errors[0]).0, x11::error::BAD_MATCH); + assert_eq!(error_of(LittleEndian, &errors[1]).0, x11::error::BAD_MATCH); + + // Xvfb sent these five elements in one reply (length 0x2d); each + // element is a time header then the event: + // 014cccda 06000000 014cccda 0000039f 00000000 00000000 00640032 00000000 00000000 + // 014cccda 02260000 014cccda 00000000 00000000 00000000 00640032 00000000 00000000 + // … 03260000 … 04010000 … 05010000 … 00640032 00000000 01000000 + let events = [ + ( + 6, + 0, + 0, + "06000000 00000064 00000000 00000000 00000000 00640032 00000000 00000000", + ), + ( + 2, + 38, + 0, + "02260000 00000064 00000000 00000000 00000000 00640032 00000000 00000000", + ), + ( + 3, + 38, + 0, + "03260000 00000064 00000000 00000000 00000000 00640032 00000000 00000000", + ), + ( + 4, + 1, + 0, + "04010000 00000064 00000000 00000000 00000000 00640032 00000000 00000000", + ), + ( + 5, + 1, + 0x100, + "05010000 00000064 00000000 00000000 00000000 00640032 00000000 01000000", + ), + ]; + for (event_type, detail, key_state, bytes) in events { + record_device_event( + &mut state, + RecordedDeviceEvent { + event_type, + detail, + repeat: false, + time: 0x64, + root_x: 100, + root_y: 50, + state: key_state, + }, + ); + let got = read_all(&mut rec); + let mut expected = hex(&format!( + "01000006 00000009 07000000 00000000 00000000 00000000 00000000 00000000 \ + 00000000 {bytes}" + )); + if event_type == 6 { + expected[44..48].copy_from_slice(&ROOT_WINDOW.0.to_be_bytes()); + } + assert_eq!(got, with_times(expected, &got, &[32]), "event {event_type}"); + assert_eq!(got[16..20], got[32..36], "element time is the reply's"); + } + + // c3 connects: ClientStarted carries its setup bytes verbatim. + let _c3 = install(&mut state, C3, C3_BASE, LittleEndian); + let setup = hex("01000b00 00000100 a0a5b800"); + client_started(&mut state, ClientId(C3), &setup); + let got = read_all(&mut rec); + assert_eq!( + got, + with_times( + hex( + "01020006 00000003 07010000 00600000 00000000 00000000 00000000 00000000 \ + 01000b00 00000100 a0a5b800" + ), + &got, + &[] + ) + ); + // …and leaves after one request: `01030006 00000001 0701… + // 00600000